idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
7,200
private void addJavaAgent ( Config . AgentMode junitMode ) throws MojoExecutionException { try { URL agentJarURL = Types . extractJarURL ( EkstaziAgent . class ) ; if ( agentJarURL == null ) { throw new MojoExecutionException ( "Unable to locate Ekstazi agent" ) ; } Properties properties = project . getProperties ( ) ; String oldValue = properties . getProperty ( ARG_LINE_PARAM_NAME ) ; properties . setProperty ( ARG_LINE_PARAM_NAME , prepareEkstaziOptions ( agentJarURL , junitMode ) + " " + ( oldValue == null ? "" : oldValue ) ) ; } catch ( IOException ex ) { throw new MojoExecutionException ( "Unable to set path to agent" , ex ) ; } catch ( URISyntaxException ex ) { throw new MojoExecutionException ( "Unable to set path to agent" , ex ) ; } }
Sets property to pass Ekstazi agent to surefire plugin .
213
14
7,201
private void appendExcludesListToExcludesFile ( Plugin plugin , List < String > nonAffectedClasses ) throws MojoExecutionException { String excludesFileName = extractParamValue ( plugin , EXCLUDES_FILE_PARAM_NAME ) ; File excludesFileFile = new File ( excludesFileName ) ; // First restore file in case it has been modified by this // plugin before (if 'restore' was not run, or VM crashed). restoreExcludesFile ( plugin ) ; PrintWriter pw = null ; try { // Have to restore original file (on shutdown); see // RestoreMojo. pw = new PrintWriter ( new FileOutputStream ( excludesFileFile , true ) , true ) ; pw . println ( EKSTAZI_LINE_MARKER ) ; for ( String exclude : nonAffectedClasses ) { pw . println ( exclude ) ; } // If "exclude(s)" is not present, we also have to add default value to exclude inner classes. if ( ! isAtLeastOneExcludePresent ( plugin ) ) { pw . println ( "**/*$*" ) ; } } catch ( IOException ex ) { throw new MojoExecutionException ( "Could not access excludesFile" , ex ) ; } finally { if ( pw != null ) { pw . close ( ) ; } } }
Appends list of classes that should be excluded to the given file .
294
14
7,202
private boolean isParallelOn ( Plugin plugin ) throws MojoExecutionException { String value = extractParamValue ( plugin , PARALLEL_PARAM_NAME ) ; // If value is set and it is not an empty string. return value != null && ! value . equals ( "" ) ; }
Returns true if parallel parameter is ON false otherwise . This parameter is ON if the value is different from NULL .
64
22
7,203
private boolean isForkMode ( Plugin plugin ) throws MojoExecutionException { String reuseForksValue = extractParamValue ( plugin , REUSE_FORKS_PARAM_NAME ) ; return reuseForksValue != null && reuseForksValue . equals ( "false" ) ; }
Returns true if there each test class is executed in its own process .
62
14
7,204
private boolean isForkDisabled ( Plugin plugin ) throws MojoExecutionException { String forkCountValue = extractParamValue ( plugin , FORK_COUNT_PARAM_NAME ) ; String forkModeValue = extractParamValue ( plugin , FORK_MODE_PARAM_NAME ) ; return ( forkCountValue != null && forkCountValue . equals ( "0" ) ) || ( forkModeValue != null && forkModeValue . equals ( "never" ) ) ; }
Returns true if fork is disabled i . e . if we cannot set the agent .
103
17
7,205
private void checkParameters ( Plugin plugin ) throws MojoExecutionException { // Fail if 'parallel' parameter is used. if ( isParallelOn ( plugin ) ) { throw new MojoExecutionException ( "Ekstazi currently does not support parallel parameter" ) ; } // Fail if fork is disabled. if ( isForkDisabled ( plugin ) ) { throw new MojoExecutionException ( "forkCount has to be at least 1" ) ; } }
Checks that all parameters are set as expected .
101
10
7,206
@ Nonnull public static < T extends IHCNode > T getPreparedNode ( @ Nonnull final T aNode , @ Nonnull final IHCHasChildrenMutable < ? , ? super IHCNode > aTargetNode , @ Nonnull final IHCConversionSettingsToNode aConversionSettings ) { // Run the global customizer aNode . customizeNode ( aConversionSettings . getCustomizer ( ) , aConversionSettings . getHTMLVersion ( ) , aTargetNode ) ; // finalize the node aNode . finalizeNodeState ( aConversionSettings , aTargetNode ) ; // Consistency check aNode . consistencyCheck ( aConversionSettings ) ; // No forced registration here final boolean bForcedResourceRegistration = false ; aNode . registerExternalResources ( aConversionSettings , bForcedResourceRegistration ) ; return aNode ; }
Prepare and return a single node .
185
8
7,207
public static void prepareForConversion ( @ Nonnull final IHCNode aStartNode , @ Nonnull final IHCHasChildrenMutable < ? , ? super IHCNode > aGlobalTargetNode , @ Nonnull final IHCConversionSettingsToNode aConversionSettings ) { ValueEnforcer . notNull ( aStartNode , "NodeToBeCustomized" ) ; ValueEnforcer . notNull ( aGlobalTargetNode , "TargetNode" ) ; ValueEnforcer . notNull ( aConversionSettings , "ConversionSettings" ) ; final IHCCustomizer aCustomizer = aConversionSettings . getCustomizer ( ) ; final EHTMLVersion eHTMLVersion = aConversionSettings . getHTMLVersion ( ) ; // Customize all elements before extracting out-of-band nodes, in case the // customizer adds some out-of-band nodes as well // Than finalize and register external resources final IHCIteratorNonBreakableCallback aCB = ( aParentNode , aChildNode ) -> { // If the parent node is suitable, use it, else use the global target // node IHCHasChildrenMutable < ? , ? super IHCNode > aRealTargetNode ; if ( aParentNode instanceof IHCHasChildrenMutable < ? , ? > ) { // Unchecked conversion aRealTargetNode = GenericReflection . uncheckedCast ( aParentNode ) ; } else aRealTargetNode = aGlobalTargetNode ; final int nTargetNodeChildren = aRealTargetNode . getChildCount ( ) ; // Run the global customizer aChildNode . customizeNode ( aCustomizer , eHTMLVersion , aRealTargetNode ) ; // finalize the node aChildNode . finalizeNodeState ( aConversionSettings , aRealTargetNode ) ; // Consistency check aChildNode . consistencyCheck ( aConversionSettings ) ; // No forced registration here final boolean bForcedResourceRegistration = false ; aChildNode . registerExternalResources ( aConversionSettings , bForcedResourceRegistration ) ; // Something was added? if ( aRealTargetNode . getChildCount ( ) > nTargetNodeChildren ) { // Recursive call on the target node only. // It's important to scan the whole tree, as a hierarchy of nodes may // have been added! prepareForConversion ( aRealTargetNode , aRealTargetNode , aConversionSettings ) ; } } ; HCHelper . iterateTreeNonBreakable ( aStartNode , aCB ) ; }
Customize the passed base node and all child nodes recursively .
534
14
7,208
@ Nullable public static IMicroNode getAsNode ( @ Nonnull final IHCNode aHCNode ) { return getAsNode ( aHCNode , HCSettings . getConversionSettings ( ) ) ; }
Convert the passed HC node to a micro node using the default conversion settings .
46
16
7,209
@ SuppressWarnings ( "unchecked" ) @ Nullable public static IMicroNode getAsNode ( @ Nonnull final IHCNode aSrcNode , @ Nonnull final IHCConversionSettingsToNode aConversionSettings ) { IHCNode aConvertNode = aSrcNode ; // Special case for HCHtml - must have been done separately because the // extraction of the OOB nodes must happen before the HTML HEAD is filled if ( ! ( aSrcNode instanceof HCHtml ) ) { // Determine the target node to use final boolean bSrcNodeCanHaveChildren = aSrcNode instanceof IHCHasChildrenMutable < ? , ? > ; IHCHasChildrenMutable < ? , IHCNode > aTempNode ; if ( bSrcNodeCanHaveChildren ) { // Passed node can handle it aTempNode = ( IHCHasChildrenMutable < ? , IHCNode > ) aSrcNode ; } else { aTempNode = new HCNodeList ( ) ; aTempNode . addChild ( aSrcNode ) ; } // customize, finalize and extract resources prepareForConversion ( aTempNode , aTempNode , aConversionSettings ) ; // NOTE: no OOB extraction here, because it is unclear what would happen // to the nodes. // Select node to convert to MicroDOM - if something was extracted, use // the temp node if ( ! bSrcNodeCanHaveChildren && aTempNode . getChildCount ( ) > 1 ) aConvertNode = aTempNode ; } final IMicroNode aMicroNode = aConvertNode . convertToMicroNode ( aConversionSettings ) ; return aMicroNode ; }
Convert the passed HC node to a micro node using the provided conversion settings .
367
16
7,210
@ Nonnull public static String getAsHTMLString ( @ Nonnull final IHCNode aHCNode ) { return getAsHTMLString ( aHCNode , HCSettings . getConversionSettings ( ) ) ; }
Convert the passed HC node to an HTML string using the default conversion settings .
46
16
7,211
@ Nonnull public static String getAsHTMLString ( @ Nonnull final IHCNode aHCNode , @ Nonnull final IHCConversionSettings aConversionSettings ) { final IMicroNode aMicroNode = getAsNode ( aHCNode , aConversionSettings ) ; if ( aMicroNode == null ) return "" ; return MicroWriter . getNodeAsString ( aMicroNode , aConversionSettings . getXMLWriterSettings ( ) ) ; }
Convert the passed node to it s HTML representation . First this HC - node is converted to a micro node which is than
98
25
7,212
public static int readRawUntil ( final StringBuilder out , final String in , final int start , final char end ) { int pos = start ; while ( pos < in . length ( ) ) { final char ch = in . charAt ( pos ) ; if ( ch == end ) break ; out . append ( ch ) ; pos ++ ; } return ( pos == in . length ( ) ) ? - 1 : pos ; }
Reads characters until the end character is encountered ignoring escape sequences .
89
13
7,213
@ Nonnull public ELoginResult loginUser ( @ Nullable final String sLoginName , @ Nullable final String sPlainTextPassword ) { return loginUser ( sLoginName , sPlainTextPassword , ( Iterable < String > ) null ) ; }
Login the passed user without much ado .
56
8
7,214
@ Nonnull public EChange logoutUser ( @ Nullable final String sUserID ) { LoginInfo aInfo ; m_aRWLock . writeLock ( ) . lock ( ) ; try { aInfo = m_aLoggedInUsers . remove ( sUserID ) ; if ( aInfo == null ) { AuditHelper . onAuditExecuteSuccess ( "logout" , sUserID , "user-not-logged-in" ) ; return EChange . UNCHANGED ; } // Ensure that the SessionUser is empty. This is only relevant if user is // manually logged out without destructing the underlying session final InternalSessionUserHolder aSUH = InternalSessionUserHolder . _getInstanceIfInstantiatedInScope ( aInfo . getSessionScope ( ) ) ; if ( aSUH != null ) aSUH . _reset ( ) ; // Set logout time - in case somebody has a strong reference to the // LoginInfo object aInfo . setLogoutDTNow ( ) ; } finally { m_aRWLock . writeLock ( ) . unlock ( ) ; } if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( "Logged out " + _getUserIDLogText ( sUserID ) + " after " + Duration . between ( aInfo . getLoginDT ( ) , aInfo . getLogoutDT ( ) ) . toString ( ) ) ; AuditHelper . onAuditExecuteSuccess ( "logout" , sUserID ) ; // Execute callback as the very last action m_aUserLogoutCallbacks . forEach ( aCB -> aCB . onUserLogout ( aInfo ) ) ; return EChange . CHANGED ; }
Manually log out the specified user
370
7
7,215
@ Nullable public LoginInfo getLoginInfo ( @ Nullable final String sUserID ) { return m_aRWLock . readLocked ( ( ) -> m_aLoggedInUsers . get ( sUserID ) ) ; }
Get the login details of the specified user .
51
9
7,216
public static void loadConfig ( String options , boolean force ) { if ( sIsInitialized && ! force ) return ; sIsInitialized = true ; Properties commandProperties = unpackOptions ( options ) ; String userHome = getUserHome ( ) ; File userHomeDir = new File ( userHome , Names . EKSTAZI_CONFIG_FILE ) ; Properties homeProperties = getProperties ( userHomeDir ) ; File userDir = new File ( System . getProperty ( "user.dir" ) , Names . EKSTAZI_CONFIG_FILE ) ; Properties userProperties = getProperties ( userDir ) ; loadProperties ( homeProperties ) ; loadProperties ( userProperties ) ; loadProperties ( commandProperties ) ; // Init Log before any print of config/debug. Log . init ( DEBUG_MODE_V == DebugMode . SCREEN || DEBUG_MODE_V == DebugMode . EVERYWHERE , DEBUG_MODE_V == DebugMode . FILE || DEBUG_MODE_V == DebugMode . EVERYWHERE , createFileNameInCoverageDir ( "debug.log" ) ) ; // Print configuration. printVerbose ( userHomeDir , userDir ) ; }
Load configuration from properties .
261
5
7,217
protected static boolean checkNamesOfProperties ( Properties props ) { Set < String > names = getAllOptionNames ( Config . class ) ; for ( Object key : props . keySet ( ) ) { if ( ! ( key instanceof String ) || ! names . contains ( key ) ) { return false ; } } return true ; }
Checks if properties have correct names . A property has a correct name if it is one of the configuration options .
70
23
7,218
protected static int getNumOfNonExperimentalOptions ( Class < ? > clz ) { Field [ ] options = getAllOptions ( clz ) ; int count = 0 ; for ( Field option : options ) { count += option . getName ( ) . startsWith ( "X_" ) ? 0 : 1 ; } return count ; }
Returns the number of non experimental options for the given class .
72
12
7,219
public static void main ( String [ ] args ) { DEBUG_MODE_V = DebugMode . SCREEN ; Log . initScreen ( ) ; printVerbose ( null , null ) ; }
Prints configuration options .
42
5
7,220
@ Nonnull public final IMPLTYPE setWidth ( final int nWidth ) { if ( nWidth >= 0 ) m_sWidth = Integer . toString ( nWidth ) ; return thisAsT ( ) ; }
Set the width in pixel
46
5
7,221
@ Nonnull public HCConversionSettings setCSSWriterSettings ( @ Nonnull final ICSSWriterSettings aCSSWriterSettings ) { ValueEnforcer . notNull ( aCSSWriterSettings , "CSSWriterSettings" ) ; m_aCSSWriterSettings = new CSSWriterSettings ( aCSSWriterSettings ) ; return this ; }
Set the CSS writer settings to be used .
68
9
7,222
@ Nonnull public HCConversionSettings setJSWriterSettings ( @ Nonnull final IJSWriterSettings aJSWriterSettings ) { ValueEnforcer . notNull ( aJSWriterSettings , "JSWriterSettings" ) ; m_aJSWriterSettings = new JSWriterSettings ( aJSWriterSettings ) ; return this ; }
Set the JS formatter settings to be used .
76
10
7,223
@ Nonnull public static ESuccess check ( @ Nonnull @ Nonempty final String sServerSideKey , @ Nullable final String sReCaptchaResponse ) { ValueEnforcer . notEmpty ( sServerSideKey , "ServerSideKey" ) ; if ( StringHelper . hasNoText ( sReCaptchaResponse ) ) return ESuccess . SUCCESS ; final HttpClientFactory aHCFactory = new HttpClientFactory ( ) ; // For proxy etc aHCFactory . setUseSystemProperties ( true ) ; try ( HttpClientManager aMgr = new HttpClientManager ( aHCFactory ) ) { final HttpPost aPost = new HttpPost ( new SimpleURL ( "https://www.google.com/recaptcha/api/siteverify" ) . add ( "secret" , sServerSideKey ) . add ( "response" , sReCaptchaResponse ) . getAsURI ( ) ) ; final ResponseHandlerJson aRH = new ResponseHandlerJson ( ) ; final IJson aJson = aMgr . execute ( aPost , aRH ) ; if ( aJson != null && aJson . isObject ( ) ) { final boolean bSuccess = aJson . getAsObject ( ) . getAsBoolean ( "success" , false ) ; if ( GlobalDebug . isDebugMode ( ) ) LOGGER . info ( "ReCpatcha Response for '" + sReCaptchaResponse + "': " + aJson . getAsJsonString ( ) ) ; return ESuccess . valueOf ( bSuccess ) ; } } catch ( final IOException ex ) { LOGGER . warn ( "Error checking ReCaptcha response" , ex ) ; } return ESuccess . FAILURE ; }
Check if the response of a RecCaptcha is valid or not .
381
14
7,224
@ Nonnull public SimpleURL getInvocationURL ( @ Nonnull final String sBasePath ) { ValueEnforcer . notNull ( sBasePath , "BasePath" ) ; return new SimpleURL ( sBasePath + m_sPath ) ; }
Get the invocation URL of this API path .
54
9
7,225
@ Nullable public final String getHiddenFieldName ( ) { final String sFieldName = getName ( ) ; if ( StringHelper . hasNoText ( sFieldName ) ) return null ; return HIDDEN_FIELD_PREFIX + sFieldName ; }
Get the hidden field name for this checkbox .
57
10
7,226
public void addHandler ( @ Nonnull final EJSEvent eJSEvent , @ Nonnull final IHasJSCode aNewHandler ) { ValueEnforcer . notNull ( eJSEvent , "JSEvent" ) ; ValueEnforcer . notNull ( aNewHandler , "NewHandler" ) ; CollectingJSCodeProvider aCode = m_aEvents . get ( eJSEvent ) ; if ( aCode == null ) { aCode = new CollectingJSCodeProvider ( ) ; m_aEvents . put ( eJSEvent , aCode ) ; } aCode . appendFlattened ( aNewHandler ) ; }
Add an additional handler for the given JS event . If an existing handler is present the new handler is appended at the end .
142
26
7,227
public void prependHandler ( @ Nonnull final EJSEvent eJSEvent , @ Nonnull final IHasJSCode aNewHandler ) { ValueEnforcer . notNull ( eJSEvent , "JSEvent" ) ; ValueEnforcer . notNull ( aNewHandler , "NewHandler" ) ; CollectingJSCodeProvider aCode = m_aEvents . get ( eJSEvent ) ; if ( aCode == null ) { aCode = new CollectingJSCodeProvider ( ) ; m_aEvents . put ( eJSEvent , aCode ) ; } aCode . prepend ( aNewHandler ) ; }
Add an additional handler for the given JS event . If an existing handler is present the new handler is appended at front .
141
25
7,228
public void setHandler ( @ Nonnull final EJSEvent eJSEvent , @ Nonnull final IHasJSCode aNewHandler ) { ValueEnforcer . notNull ( eJSEvent , "JSEvent" ) ; ValueEnforcer . notNull ( aNewHandler , "NewHandler" ) ; // Set only the new handler and remove any existing handler m_aEvents . put ( eJSEvent , new CollectingJSCodeProvider ( ) . appendFlattened ( aNewHandler ) ) ; }
Set a handler for the given JS event . If an existing handler is present it is automatically overridden .
113
21
7,229
@ Override public List < FileSource > createSources ( String srcName ) { final File dirOrFile = new File ( srcName ) ; final File [ ] files = dirOrFile . listFiles ( FILTER ) ; if ( files != null ) { final List < FileSource > sources = new ArrayList < FileSource > ( files . length ) ; for ( File file : files ) { sources . add ( new FileSource ( file ) ) ; } return sources ; } else { return Util . list ( new FileSource ( dirOrFile ) ) ; } }
Return sa list of FileSources based on the name . If the name is a directory then it returns all the files in that directory ending with . jadt . Otherwise it is assumed that the name is a file .
120
44
7,230
@ Nonnull public static AccessToken createAccessTokenValidFromNow ( @ Nullable final String sTokenString ) { // Length 66 so that the Base64 encoding does not add the "==" signs // Length must be dividable by 3 final String sRealTokenString = StringHelper . hasText ( sTokenString ) ? sTokenString : createNewTokenString ( 66 ) ; return new AccessToken ( sRealTokenString , PDTFactory . getCurrentLocalDateTime ( ) , null , new RevocationStatus ( ) ) ; }
Create a new access token that is valid from now on for an infinite amount of time .
112
18
7,231
@ Nullable public static EFamFamFlagIcon getFlagFromLocale ( @ Nullable final Locale aFlagLocale ) { if ( aFlagLocale != null ) { final String sCountry = aFlagLocale . getCountry ( ) ; if ( StringHelper . hasText ( sCountry ) ) return EFamFamFlagIcon . getFromIDOrNull ( sCountry ) ; } return null ; }
Get the flag from the passed locale
89
7
7,232
private void checkIfEkstaziDirCanBeCreated ( ) throws MojoExecutionException { File ekstaziDir = Config . createRootDir ( parentdir ) ; // If .ekstazi does not exist and cannot be created, let them // know. (We also remove directory if successfully created.) if ( ! ekstaziDir . exists ( ) && ( ! ekstaziDir . mkdirs ( ) || ! ekstaziDir . delete ( ) ) ) { throw new MojoExecutionException ( "Cannot create Ekstazi directory in " + parentdir ) ; } }
Checks if . ekstazi directory can be created . For example the problems can happen if there is no sufficient permission .
131
26
7,233
@ Nonnull public EChange setSystemMessage ( @ Nonnull final ESystemMessageType eMessageType , @ Nullable final String sMessage ) { ValueEnforcer . notNull ( eMessageType , "MessageType" ) ; if ( m_eMessageType . equals ( eMessageType ) && EqualsHelper . equals ( m_sMessage , sMessage ) ) return EChange . UNCHANGED ; internalSetMessageType ( eMessageType ) ; internalSetMessage ( sMessage ) ; setLastUpdate ( PDTFactory . getCurrentLocalDateTime ( ) ) ; return EChange . CHANGED ; }
Set the system message type and text and update the last modification date .
131
14
7,234
public String createChallenge ( String request ) throws IllegalArgumentException , ProtocolVersionException { String userName ; userName = CrtAuthCodec . deserializeRequest ( request ) ; Fingerprint fingerprint ; try { fingerprint = new Fingerprint ( getKeyForUser ( userName ) ) ; } catch ( KeyNotFoundException e ) { log . info ( "No public key found for user {}, creating fake fingerprint" , userName ) ; fingerprint = createFakeFingerprint ( userName ) ; } byte [ ] uniqueData = new byte [ Challenge . UNIQUE_DATA_LENGTH ] ; UnsignedInteger timeNow = timeSupplier . getTime ( ) ; random . nextBytes ( uniqueData ) ; Challenge challenge = Challenge . newBuilder ( ) . setFingerprint ( fingerprint ) . setUniqueData ( uniqueData ) . setValidFromTimestamp ( timeNow . minus ( CLOCK_FUDGE ) ) . setValidToTimestamp ( timeNow . plus ( RESPONSE_TIMEOUT ) ) . setServerName ( serverName ) . setUserName ( userName ) . build ( ) ; return encode ( CrtAuthCodec . serialize ( challenge , secret ) ) ; }
Create a challenge to authenticate a given user . The userName needs to be provided at this stage to encode a fingerprint of the public key stored in the server encoded in the challenge . This is required because a client can hold more than one private key and would need this information to pick the right key to sign the response . If the keyProvider fails to retrieve the public key a fake Fingerprint is generated so that the presence of a challenge doesn t reveal whether a user key is present on the server or not .
257
103
7,235
private RSAPublicKey getKeyForUser ( String userName ) throws KeyNotFoundException { RSAPublicKey key = null ; for ( final KeyProvider keyProvider : keyProviders ) { try { key = keyProvider . getKey ( userName ) ; break ; } catch ( KeyNotFoundException e ) { // that's fine, try the next provider } } if ( key == null ) { throw new KeyNotFoundException ( ) ; } return key ; }
Get the public key for a user by iterating through all key providers . The first matching key will be returned .
99
23
7,236
private Fingerprint createFakeFingerprint ( String userName ) { byte [ ] usernameHmac = CrtAuthCodec . getAuthenticationCode ( this . secret , userName . getBytes ( Charsets . UTF_8 ) ) ; return new Fingerprint ( Arrays . copyOfRange ( usernameHmac , 0 , 6 ) ) ; }
Generate a fake real looking fingerprint for a non - existent user .
75
15
7,237
public String createToken ( String response ) throws IllegalArgumentException , ProtocolVersionException { final Response decodedResponse ; final Challenge challenge ; decodedResponse = CrtAuthCodec . deserializeResponse ( decode ( response ) ) ; challenge = CrtAuthCodec . deserializeChallengeAuthenticated ( decodedResponse . getPayload ( ) , secret ) ; if ( ! challenge . getServerName ( ) . equals ( serverName ) ) { throw new IllegalArgumentException ( "Got challenge with the wrong server_name encoded." ) ; } PublicKey publicKey ; try { publicKey = getKeyForUser ( challenge . getUserName ( ) ) ; } catch ( KeyNotFoundException e ) { // If the user requesting authentication doesn't have a public key, we throw an // InvalidInputException. This normally shouldn't happen, since at this stage a challenge // should have already been sent, which in turn requires knowledge of the user's public key. throw new IllegalArgumentException ( e ) ; } boolean signatureVerified ; try { Signature signature = Signature . getInstance ( SIGNATURE_ALGORITHM ) ; signature . initVerify ( publicKey ) ; signature . update ( decodedResponse . getPayload ( ) ) ; signatureVerified = signature . verify ( decodedResponse . getSignature ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } if ( challenge . isExpired ( timeSupplier ) ) { throw new IllegalArgumentException ( "The challenge is out of its validity period" ) ; } if ( ! signatureVerified ) { throw new IllegalArgumentException ( "Client did not provide proof that it controls the " + "secret key." ) ; } UnsignedInteger validFrom = timeSupplier . getTime ( ) . minus ( CLOCK_FUDGE ) ; UnsignedInteger validTo = timeSupplier . getTime ( ) . plus ( tokenLifetimeSeconds ) ; Token token = new Token ( validFrom . intValue ( ) , validTo . intValue ( ) , challenge . getUserName ( ) ) ; return encode ( CrtAuthCodec . serialize ( token , secret ) ) ; }
Given the response to a previous challenge produce a token used by the client to authenticate .
467
18
7,238
public String validateToken ( String token ) throws IllegalArgumentException , TokenExpiredException , ProtocolVersionException { final Token deserializedToken = CrtAuthCodec . deserializeTokenAuthenticated ( decode ( token ) , secret ) ; if ( deserializedToken . isExpired ( timeSupplier ) ) { throw new TokenExpiredException ( ) ; } if ( deserializedToken . getValidTo ( ) - deserializedToken . getValidFrom ( ) > MAX_VALIDITY ) { throw new TokenExpiredException ( "Overly long token lifetime." ) ; } return deserializedToken . getUserName ( ) ; }
Verify that a given token is valid i . e . that it has been produced by the current authenticator and that it hasn t expired .
139
29
7,239
public Optional < Object > lookupLexer ( PyGateway gateway , String alias ) { Object result = lexerCache . get ( alias ) ; if ( result == null ) { result = evalLookupLexer ( gateway , alias , NULL ) ; lexerCache . put ( alias , result ) ; } if ( result == NULL ) { return Optional . absent ( ) ; } else { return Optional . of ( result ) ; } }
Lookup a Pygments lexer by an alias .
91
11
7,240
@ Nonnull public static ESuccess execute ( @ Nonnull final IJSchSessionProvider aSessionProvider , final int nChannelConnectTimeoutMillis , @ Nonnull final IChannelSftpRunnable aRunnable ) throws JSchException { ValueEnforcer . notNull ( aSessionProvider , "SessionProvider" ) ; ValueEnforcer . notNull ( aRunnable , "Runnable" ) ; Session aSession = null ; Channel aChannel = null ; ChannelSftp aSFTPChannel = null ; try { // get session from pool aSession = aSessionProvider . createSession ( ) ; if ( aSession == null ) throw new IllegalStateException ( "Failed to create JSch session from provider" ) ; // Open the SFTP channel aChannel = aSession . openChannel ( "sftp" ) ; // Set connection timeout aChannel . connect ( nChannelConnectTimeoutMillis ) ; aSFTPChannel = ( ChannelSftp ) aChannel ; // call callback aRunnable . execute ( aSFTPChannel ) ; return ESuccess . SUCCESS ; } catch ( final SftpException ex ) { LOGGER . error ( "Error peforming SFTP action: " + aRunnable . getDisplayName ( ) , ex ) ; return ESuccess . FAILURE ; } finally { // end SFTP session if ( aSFTPChannel != null ) aSFTPChannel . quit ( ) ; // close channel if ( aChannel != null && aChannel . isConnected ( ) ) aChannel . disconnect ( ) ; // destroy session if ( aSession != null ) JSchSessionFactory . destroySession ( aSession ) ; } }
Upload a file to the server .
358
7
7,241
public static void setPasswordConstraintList ( @ Nonnull final IPasswordConstraintList aPasswordConstraintList ) { ValueEnforcer . notNull ( aPasswordConstraintList , "PasswordConstraintList" ) ; // Create a copy final IPasswordConstraintList aRealPasswordConstraints = aPasswordConstraintList . getClone ( ) ; s_aRWLock . writeLocked ( ( ) -> { s_aPasswordConstraintList = aRealPasswordConstraints ; } ) ; LOGGER . info ( "Set global password constraints to " + aRealPasswordConstraints ) ; }
Set the global password constraint list .
139
7
7,242
private CoverageClassVisitor createCoverageClassVisitor ( String className , ClassWriter cv , boolean isRedefined ) { // We cannot change classfiles if class is being redefined. return new CoverageClassVisitor ( className , cv ) ; }
Creates class visitor to instrument for coverage based on configuration options .
55
13
7,243
private boolean isMonitorAccessibleFromClassLoader ( ClassLoader loader ) { if ( loader == null ) { return false ; } boolean isMonitorAccessible = true ; InputStream monitorInputStream = null ; try { monitorInputStream = loader . getResourceAsStream ( COVERAGE_MONITOR_RESOURCE ) ; if ( monitorInputStream == null ) { isMonitorAccessible = false ; } } catch ( Exception ex1 ) { isMonitorAccessible = false ; try { if ( monitorInputStream != null ) { monitorInputStream . close ( ) ; } } catch ( IOException ex2 ) { // do nothing } } return isMonitorAccessible ; }
LoaderMethodVisitor and LoaderMonitor .
139
9
7,244
@ SuppressWarnings ( "unused" ) private void saveClassfileBufferForDebugging ( String className , byte [ ] classfileBuffer ) { try { if ( className . contains ( "CX" ) ) { java . io . DataOutputStream tmpout = new java . io . DataOutputStream ( new java . io . FileOutputStream ( "out" ) ) ; tmpout . write ( classfileBuffer , 0 , classfileBuffer . length ) ; tmpout . close ( ) ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; } }
This method is for debugging purposes . So far one of the best way to debug instrumentation was to actually look at the instrumented code . This method let us choose which class to print .
128
38
7,245
private static byte [ ] instrumentClassFile ( byte [ ] classfileBuffer ) { String className = new ClassReader ( classfileBuffer ) . getClassName ( ) . replace ( "/" , "." ) ; ClassLoader currentClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; byte [ ] newClassfileBuffer = new EkstaziCFT ( ) . transform ( currentClassLoader , className , null , null , classfileBuffer ) ; return newClassfileBuffer ; }
Support for static instrumentation .
107
6
7,246
@ Nonnull public CollectingJSCodeProvider addAt ( @ Nonnegative final int nIndex , @ Nullable final IHasJSCode aProvider ) { if ( aProvider != null ) m_aList . add ( nIndex , aProvider ) ; return this ; }
Add JS code at the specified index .
59
8
7,247
@ Nonnull public JSFunction name ( @ Nonnull @ Nonempty final String sName ) { if ( ! JSMarshaller . isJSIdentifier ( sName ) ) throw new IllegalArgumentException ( "The name '" + sName + "' is not a legal JS identifier!" ) ; m_sName = sName ; return this ; }
Changes the name of the function .
77
7
7,248
@ Nonnull public static TypeaheadEditSelection getSelectionForRequiredObject ( @ Nonnull final IWebPageExecutionContext aWPEC , @ Nullable final String sEditFieldName , @ Nullable final String sHiddenFieldName ) { ValueEnforcer . notNull ( aWPEC , "WPEC" ) ; String sEditValue = aWPEC . params ( ) . getAsString ( sEditFieldName ) ; String sHiddenFieldValue = aWPEC . params ( ) . getAsString ( sHiddenFieldName ) ; if ( StringHelper . hasText ( sHiddenFieldValue ) ) { if ( StringHelper . hasNoText ( sEditValue ) ) { // The content of the edit field was deleted after a valid item was once // selected sHiddenFieldValue = null ; } } else { if ( StringHelper . hasText ( sEditValue ) ) { // No ID but a text -> no object selected but only a string typed sEditValue = null ; } } return new TypeaheadEditSelection ( sEditValue , sHiddenFieldValue ) ; }
Get the current selection in the case that it is mandatory to select an available object .
230
17
7,249
@ Nullable @ OverrideOnDemand protected IHCNode createPageHeader ( @ Nonnull final ISimpleWebExecutionContext aSWEC , @ Nullable final IHCNode aPageTitle ) { return BootstrapPageHeader . createOnDemand ( aPageTitle ) ; }
Create the text above the login form .
59
8
7,250
@ Nonnull public static JSInvocation createEventTrackingCode ( @ Nonnull final String sCategory , @ Nonnull final String sAction , @ Nullable final String sLabel , @ Nullable final Integer aValue ) { final JSArray aArray = new JSArray ( ) . add ( "_trackEvent" ) . add ( sCategory ) . add ( sAction ) ; if ( StringHelper . hasText ( sLabel ) ) aArray . add ( sLabel ) ; if ( aValue != null ) aArray . add ( aValue . intValue ( ) ) ; return JSExpr . ref ( "_gaq" ) . invoke ( "push" ) . arg ( aArray ) ; }
Set this in the onclick events of links to track them
148
12
7,251
public static Collection < String > sanitiseSemanticTypes ( final Collection < String > semanticTypes ) { if ( semanticTypes == null ) return ImmutableList . of ( ) ; // check that each of the given types are in the map we have, otherwise throw it away final Set < String > s = new LinkedHashSet <> ( semanticTypes ) ; return s . retainAll ( SEMANTIC_TYPES_CODE_TO_DESCRIPTION . keySet ( ) ) ? s : semanticTypes ; }
Sanitise semantic types from user input .
110
9
7,252
public static String printComments ( String indent , List < JavaComment > comments ) { final StringBuilder builder = new StringBuilder ( ) ; for ( JavaComment comment : comments ) { builder . append ( print ( indent , comment ) ) ; builder . append ( "\n" ) ; } return builder . toString ( ) ; }
Prints a list of comments pretty much unmolested except to add \ n s
68
17
7,253
public static String print ( final String indent , JavaComment comment ) { return comment . match ( new JavaComment . MatchBlock < String > ( ) { @ Override public String _case ( JavaDocComment x ) { final StringBuilder builder = new StringBuilder ( indent ) ; builder . append ( x . start ) ; for ( JDToken token : x . generalSection ) { builder . append ( print ( indent , token ) ) ; } for ( JDTagSection tagSection : x . tagSections ) { for ( JDToken token : tagSection . tokens ) { builder . append ( print ( indent , token ) ) ; } } builder . append ( x . end ) ; return builder . toString ( ) ; } @ Override public String _case ( JavaBlockComment comment ) { final StringBuilder builder = new StringBuilder ( indent ) ; for ( List < BlockToken > line : comment . lines ) { for ( BlockToken token : line ) { builder . append ( token . match ( new BlockToken . MatchBlock < String > ( ) { @ Override public String _case ( BlockWord x ) { return x . word ; } @ Override public String _case ( BlockWhiteSpace x ) { return x . ws ; } @ Override public String _case ( BlockEOL x ) { return x . content + indent ; } } ) ) ; } } return builder . toString ( ) ; } @ Override public String _case ( JavaEOLComment x ) { return x . comment ; } } ) ; }
Prints a single comment pretty much unmolested
325
10
7,254
public static String print ( Arg arg ) { return printArgModifiers ( arg . modifiers ) + print ( arg . type ) + " " + arg . name ; }
prints an arg as type name
35
6
7,255
public static String printArgModifiers ( List < ArgModifier > modifiers ) { final StringBuilder builder = new StringBuilder ( ) ; if ( modifiers . contains ( ArgModifier . _Final ( ) ) ) { builder . append ( print ( ArgModifier . _Final ( ) ) ) ; builder . append ( " " ) ; } if ( modifiers . contains ( ArgModifier . _Transient ( ) ) ) { builder . append ( print ( ArgModifier . _Transient ( ) ) ) ; builder . append ( " " ) ; } if ( modifiers . contains ( ArgModifier . _Volatile ( ) ) ) { builder . append ( print ( ArgModifier . _Volatile ( ) ) ) ; builder . append ( " " ) ; } return builder . toString ( ) ; }
Prints a list of arg modifiers
170
7
7,256
public static String print ( Type type ) { return type . match ( new Type . MatchBlock < String > ( ) { @ Override public String _case ( Ref x ) { return print ( x . type ) ; } @ Override public String _case ( Primitive x ) { return print ( x . type ) ; } } ) ; }
Prints a type as either a ref type or a primitive
72
12
7,257
public static String print ( RefType type ) { return type . match ( new RefType . MatchBlock < String > ( ) { @ Override public String _case ( ClassType x ) { final StringBuilder builder = new StringBuilder ( x . baseName ) ; if ( ! x . typeArguments . isEmpty ( ) ) { builder . append ( "<" ) ; boolean first = true ; for ( RefType typeArgument : x . typeArguments ) { if ( first ) { first = false ; } else { builder . append ( ", " ) ; } builder . append ( print ( typeArgument ) ) ; } builder . append ( ">" ) ; } return builder . toString ( ) ; } @ Override public String _case ( ArrayType x ) { return print ( x . heldType ) + "[]" ; } } ) ; }
Prints a type as either an array or class type .
180
12
7,258
public static String print ( PrimitiveType type ) { return type . match ( new PrimitiveType . MatchBlock < String > ( ) { @ Override public String _case ( BooleanType x ) { return "boolean" ; } @ Override public String _case ( ByteType x ) { return "byte" ; } @ Override public String _case ( CharType x ) { return "char" ; } @ Override public String _case ( DoubleType x ) { return "double" ; } @ Override public String _case ( FloatType x ) { return "float" ; } @ Override public String _case ( IntType x ) { return "int" ; } @ Override public String _case ( LongType x ) { return "long" ; } @ Override public String _case ( ShortType x ) { return "short" ; } } ) ; }
Prints a primitive type as boolean | char | short | int | long | float | double
186
19
7,259
public static String print ( ArgModifier modifier ) { return modifier . match ( new ArgModifier . MatchBlock < String > ( ) { @ Override public String _case ( Final x ) { return "final" ; } @ Override public String _case ( Volatile x ) { return "volatile" ; } @ Override public String _case ( Transient x ) { return "transient" ; } } ) ; }
Print arg modifier
91
3
7,260
private static String print ( final String indent , JDToken token ) { return token . match ( new JDToken . MatchBlock < String > ( ) { @ Override public String _case ( JDAsterisk x ) { return "*" ; } @ Override public String _case ( JDEOL x ) { return x . content + indent ; } @ Override public String _case ( JDTag x ) { return x . name ; } @ Override public String _case ( JDWord x ) { return x . word ; } @ Override public String _case ( JDWhiteSpace x ) { return x . ws ; } } ) ; }
Print a single JavaDoc token
140
6
7,261
public static String print ( final Literal literal ) { return literal . match ( new Literal . MatchBlock < String > ( ) { @ Override public String _case ( StringLiteral x ) { return x . content ; } @ Override public String _case ( FloatingPointLiteral x ) { return x . content ; } @ Override public String _case ( IntegerLiteral x ) { return x . content ; } @ Override public String _case ( CharLiteral x ) { return x . content ; } @ Override public String _case ( BooleanLiteral x ) { return x . content ; } @ Override public String _case ( NullLiteral x ) { return "null" ; } } ) ; }
Print a single literal
159
4
7,262
public static String print ( Expression expression ) { return expression . match ( new Expression . MatchBlock < String > ( ) { @ Override public String _case ( LiteralExpression x ) { return print ( x . literal ) ; } @ Override public String _case ( VariableExpression x ) { return x . selector . match ( new Optional . MatchBlock < Expression , String > ( ) { @ Override public String _case ( Some < Expression > x ) { return print ( x . value ) + "." ; } @ Override public String _case ( None < Expression > x ) { return "" ; } } ) + x . identifier ; } @ Override public String _case ( NestedExpression x ) { return "( " + print ( x . expression ) + " )" ; } @ Override public String _case ( ClassReference x ) { return print ( x . type ) + ".class" ; } @ Override public String _case ( TernaryExpression x ) { return print ( x . cond ) + " ? " + print ( x . trueExpression ) + " : " + print ( x . falseExpression ) ; } @ Override public String _case ( BinaryExpression x ) { return print ( x . left ) + " " + print ( x . op ) + " " + print ( x . right ) ; } } ) ; }
Print an expression
292
3
7,263
@ Nonnull public BootstrapSpacingBuilder property ( @ Nonnull final EBootstrapSpacingPropertyType eProperty ) { ValueEnforcer . notNull ( eProperty , "Property" ) ; m_eProperty = eProperty ; return this ; }
Set the property type . Default is margin .
53
9
7,264
@ Nonnull public BootstrapSpacingBuilder side ( @ Nonnull final EBootstrapSpacingSideType eSide ) { ValueEnforcer . notNull ( eSide , "Side" ) ; m_eSide = eSide ; return this ; }
Set the edge type . Default is all .
53
9
7,265
@ Nonnull @ SuppressFBWarnings ( "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE" ) public EChange registerState ( @ Nonnull @ Nonempty final String sStateID , @ Nonnull final IHasUIState aNewState ) { ValueEnforcer . notEmpty ( sStateID , "StateID" ) ; ValueEnforcer . notNull ( aNewState , "NewState" ) ; final ObjectType aOT = aNewState . getObjectType ( ) ; if ( aOT == null ) throw new IllegalStateException ( "Object has no typeID: " + aNewState ) ; return m_aRWLock . writeLocked ( ( ) -> { final Map < String , IHasUIState > aMap = m_aMap . computeIfAbsent ( aOT , k -> new CommonsHashMap <> ( ) ) ; if ( LOGGER . isDebugEnabled ( ) && aMap . containsKey ( sStateID ) ) LOGGER . debug ( "Overwriting " + aOT . getName ( ) + " with ID " + sStateID + " with new object" ) ; aMap . put ( sStateID , aNewState ) ; return EChange . CHANGED ; } ) ; }
Registers a new control for the passed tree ID
275
10
7,266
@ Nonnull public EChange registerState ( @ Nonnull final IHCElement < ? > aNewElement ) { ValueEnforcer . notNull ( aNewElement , "NewElement" ) ; if ( aNewElement . hasNoID ( ) ) LOGGER . warn ( "Registering the state for an object that has no ID - creating a new ID now!" ) ; return registerState ( aNewElement . ensureID ( ) . getID ( ) , aNewElement ) ; }
Register a state for the passed HC element using the internal ID of the element .
104
16
7,267
@ Nonnull public FineUploader5Chunking setPartSize ( @ Nonnegative final long nPartSize ) { ValueEnforcer . isGT0 ( nPartSize , "PartSize" ) ; m_nChunkingPartSize = nPartSize ; return this ; }
The maximum size of each chunk in bytes .
60
9
7,268
@ Nonnull public FineUploader5Chunking setParamNameChunkSize ( @ Nonnull @ Nonempty final String sParamNameChunkSize ) { ValueEnforcer . notEmpty ( sParamNameChunkSize , "ParamNameChunkSize" ) ; m_sChunkingParamNamesChunkSize = sParamNameChunkSize ; return this ; }
Name of the parameter passed with a chunked request that specifies the size in bytes of the associated chunk .
80
21
7,269
@ Nonnull public FineUploader5Chunking setParamNamePartByteOffset ( @ Nonnull @ Nonempty final String sParamNamePartByteOffset ) { ValueEnforcer . notEmpty ( sParamNamePartByteOffset , "ParamNamePartByteOffset" ) ; m_sChunkingParamNamesPartByteOffset = sParamNamePartByteOffset ; return this ; }
Name of the parameter passed with a chunked request that specifies the starting byte of the associated chunk .
80
20
7,270
@ Nonnull public FineUploader5Chunking setParamNamePartIndex ( @ Nonnull @ Nonempty final String sParamNamePartIndex ) { ValueEnforcer . notEmpty ( sParamNamePartIndex , "ParamNamePartIndex" ) ; m_sChunkingParamNamesPartIndex = sParamNamePartIndex ; return this ; }
Name of the parameter passed with a chunked request that specifies the index of the associated partition .
74
19
7,271
@ Nonnull public FineUploader5Chunking setParamNameTotalParts ( @ Nonnull @ Nonempty final String sParamNameTotalParts ) { ValueEnforcer . notEmpty ( sParamNameTotalParts , "ParamNameTotalParts" ) ; m_sChunkingParamNamesTotalParts = sParamNameTotalParts ; return this ; }
Name of the parameter passed with a chunked request that specifies the total number of chunks associated with the File or Blob .
74
25
7,272
public static byte [ ] removeDebugInfo ( byte [ ] bytes ) { if ( bytes . length >= 4 ) { // Check magic number. int magic = ( ( bytes [ 0 ] & 0xff ) << 24 ) | ( ( bytes [ 1 ] & 0xff ) << 16 ) | ( ( bytes [ 2 ] & 0xff ) << 8 ) | ( bytes [ 3 ] & 0xff ) ; if ( magic != 0xCAFEBABE ) return bytes ; } else { return bytes ; } // We set the initial size as it cannot exceed that value (but note that // this may not be the final size). ByteArrayOutputStream baos = new ByteArrayOutputStream ( bytes . length ) ; DataOutputStream dos = new DataOutputStream ( baos ) ; try { ClassReader classReader = new ClassReader ( bytes ) ; CleanClass cleanClass = new CleanClass ( dos ) ; classReader . accept ( cleanClass , ClassReader . SKIP_DEBUG ) ; if ( cleanClass . isFiltered ( ) ) { return FILTERED_BYTECODE ; } } catch ( Exception ex ) { return bytes ; } return baos . toByteArray ( ) ; }
Removes debug info from the given class file . If the file is not java class file the given byte array is returned without any change .
250
28
7,273
@ Nonnull public final HCSWFObject addFlashVar ( @ Nonnull final String sName , final Object aValue ) { if ( ! JSMarshaller . isJSIdentifier ( sName ) ) throw new IllegalArgumentException ( "The name '" + sName + "' is not a legal JS identifier!" ) ; if ( m_aFlashVars == null ) m_aFlashVars = new CommonsLinkedHashMap <> ( ) ; m_aFlashVars . put ( sName , aValue ) ; return this ; }
Add a parameter to be passed to the Flash object
120
10
7,274
@ Nonnull public final HCSWFObject removeFlashVar ( @ Nullable final String sName ) { if ( m_aFlashVars != null ) m_aFlashVars . remove ( sName ) ; return this ; }
Remove a flash variable
50
4
7,275
public static Instrumentation initAgentAtRuntimeAndReportSuccess ( ) { try { setSystemClassLoaderClassPath ( ) ; } catch ( Exception e ) { Log . e ( "Could not set classpath. Tool will be off." , e ) ; return null ; } try { return addClassfileTransformer ( ) ; } catch ( Exception e ) { Log . e ( "Could not add transformer. Tool will be off." , e ) ; return null ; } }
Initializes an agent at runtime and adds it to VM . Returns true if the initialization was successful false otherwise .
98
22
7,276
private static void setSystemClassLoaderClassPath ( ) throws Exception { Log . d ( "Setting classpath" ) ; // We use agent class as we do not extract this class in newly created // jar (otherwise we may end up creating one -magic jar from another); // also it will exist even without JUnit classes). URL url = EkstaziAgent . class . getResource ( EkstaziAgent . class . getSimpleName ( ) + ".class" ) ; String origPath = url . getFile ( ) . replace ( "file:" , "" ) . replaceAll ( ".jar!.*" , ".jar" ) ; File junitJar = new File ( origPath ) ; File xtsJar = new File ( origPath . replaceAll ( ".jar" , "-magic.jar" ) ) ; boolean isCreated = false ; // If extracted (Tool) jar is newer than junit*.jar, there is no reason // to extract files again, so just return in that case. if ( FileUtil . isSecondNewerThanFirst ( junitJar , xtsJar ) ) { // We cannot return here, as we have to include jar on the path. isCreated = true ; } else { // Extract new jar as junit.jar is newer. String [ ] includePrefixes = { Names . EKSTAZI_PACKAGE_BIN } ; String [ ] excludePrefixes = { EkstaziAgent . class . getName ( ) } ; isCreated = JarXtractor . extract ( junitJar , xtsJar , includePrefixes , excludePrefixes ) ; } // Add jar to classpath if it was successfully created, otherwise throw // an exception. if ( isCreated ) { addURL ( xtsJar . toURI ( ) . toURL ( ) ) ; } else { throw new RuntimeException ( "Could not extract Tool classes in separate jar." ) ; } }
Set paths from the current class loader to the path of system class loader . This method should be invoked only once .
414
23
7,277
private static void addURL ( URL url ) throws Exception { URLClassLoader sysloader = ( URLClassLoader ) ClassLoader . getSystemClassLoader ( ) ; Class < ? > sysclass = URLClassLoader . class ; Method method = sysclass . getDeclaredMethod ( "addURL" , new Class [ ] { URL . class } ) ; method . setAccessible ( true ) ; method . invoke ( sysloader , new Object [ ] { url } ) ; }
Adds URL to system ClassLoader . This is not a nice approach as we use reflection but it seems the only available in Java . This will be gone if we decided to go with javaagent and boot classloader .
99
43
7,278
public static void t ( Class < ? > clz ) { // Must be non null and type of interest. if ( clz == null || ClassesCache . check ( clz ) || Types . isIgnorable ( clz ) ) { return ; } // Check and assign id to this class (this must be synchronized). try { sLock . lock ( ) ; if ( ! sClasses . add ( clz ) ) { return ; } } finally { sLock . unlock ( ) ; } String className = clz . getName ( ) ; String resourceName = className . substring ( className . lastIndexOf ( "." ) + 1 ) . concat ( ".class" ) ; URL url = null ; try { // Find resource for the class (URL that we will use to extract // the path). url = clz . getResource ( resourceName ) ; } catch ( SecurityException ex ) { Log . w ( "Unable to obtain resource because of security reasons." ) ; } // If no URL obtained, return. if ( url == null ) { return ; } recordURL ( url . toExternalForm ( ) ) ; }
Touch method . Instrumented code invokes this method to collect class coverage .
242
15
7,279
public static void t ( Class < ? > clz , int probeId ) { if ( clz != null ) { int index = probeId & PROBE_SIZE_MASK ; if ( PROBE_ARRAY [ index ] != clz ) { PROBE_ARRAY [ index ] = clz ; t ( clz ) ; } } }
Touch method which also accepts probe id . The id can be used to optimize execution .
78
17
7,280
public static void addFileURL ( File f ) { String absolutePath = f . getAbsolutePath ( ) ; if ( ! filterFile ( absolutePath ) ) { try { recordURL ( f . toURI ( ) . toURL ( ) . toExternalForm ( ) ) ; } catch ( MalformedURLException e ) { // Never expected. } } }
Records the given file as a dependency after some filtering .
78
12
7,281
protected static void recordURL ( String externalForm ) { if ( filterURL ( externalForm ) ) { return ; } if ( isWellKnownUrl ( externalForm ) ) { // Ignore JUnit classes if specified in configuration. if ( Config . DEPENDENCIES_INCLUDE_WELLKNOWN_V ) { safeRecordURL ( externalForm ) ; } } else { safeRecordURL ( externalForm ) ; } }
Records the given external form of URL as a dependency after checking if it should be filtered .
90
19
7,282
private static void safeRecordURL ( String externalForm ) { try { sLock . lock ( ) ; sURLs . add ( externalForm ) ; } finally { sLock . unlock ( ) ; } }
Records the given external form of URL as a dependency .
43
12
7,283
public static final void c ( String msg ) { if ( msg . replaceAll ( "\\s+" , "" ) . equals ( "" ) ) { println ( CONF_TEXT ) ; } else { println ( CONF_TEXT + ": " + msg ) ; } }
Printing configuration options .
59
5
7,284
@ Nonnull public PathMatchingResult matchesParts ( @ Nonnull final List < String > aPathParts ) { ValueEnforcer . notNull ( aPathParts , "PathParts" ) ; final int nPartCount = m_aPathParts . size ( ) ; if ( aPathParts . size ( ) != nPartCount ) { // Size must match return PathMatchingResult . NO_MATCH ; } final ICommonsOrderedMap < String , String > aVariableValues = new CommonsLinkedHashMap <> ( ) ; for ( int i = 0 ; i < nPartCount ; ++ i ) { final PathDescriptorPart aPart = m_aPathParts . get ( i ) ; final String sPathPart = aPathParts . get ( i ) ; if ( ! aPart . matches ( sPathPart ) ) { // Current part does not match - full error return PathMatchingResult . NO_MATCH ; } // Matching variable part? if ( aPart . isVariable ( ) ) aVariableValues . put ( aPart . getName ( ) , sPathPart ) ; } // We've got it! return PathMatchingResult . createSuccess ( aVariableValues ) ; }
Check if this path descriptor matches the provided path parts . This requires that this path descriptor and the provided collection have the same number of elements and that all static and variable parts match .
259
36
7,285
@ Nonnull public FineUploader5Retry setAutoAttemptDelay ( @ Nonnegative final int nAutoAttemptDelay ) { ValueEnforcer . isGE0 ( nAutoAttemptDelay , "AutoAttemptDelay" ) ; m_nRetryAutoAttemptDelay = nAutoAttemptDelay ; return this ; }
The number of seconds to wait between auto retry attempts .
70
12
7,286
@ Nonnull public FineUploader5Retry setMaxAutoAttempts ( @ Nonnegative final int nMaxAutoAttempts ) { ValueEnforcer . isGE0 ( nMaxAutoAttempts , "MaxAutoAttempts" ) ; m_nRetryMaxAutoAttempts = nMaxAutoAttempts ; return this ; }
The maximum number of times to attempt to retry a failed upload .
64
14
7,287
@ Nonnull public FineUploader5Retry setPreventRetryResponseProperty ( @ Nonnull @ Nonempty final String sPreventRetryResponseProperty ) { ValueEnforcer . notEmpty ( sPreventRetryResponseProperty , "PreventRetryResponseProperty" ) ; m_sRetryPreventRetryResponseProperty = sPreventRetryResponseProperty ; return this ; }
This property will be looked for in the server response and if found and true will indicate that no more retries should be attempted for this item .
84
29
7,288
public void markRevoked ( @ Nonnull @ Nonempty final String sRevocationUserID , @ Nonnull final LocalDateTime aRevocationDT , @ Nonnull @ Nonempty final String sRevocationReason ) { ValueEnforcer . notEmpty ( sRevocationUserID , "RevocationUserID" ) ; ValueEnforcer . notNull ( aRevocationDT , "RevocationDT" ) ; ValueEnforcer . notEmpty ( sRevocationReason , "RevocationReason" ) ; if ( m_bRevoked ) throw new IllegalStateException ( "This object is already revoked!" ) ; m_bRevoked = true ; m_sRevocationUserID = sRevocationUserID ; m_aRevocationDT = aRevocationDT ; m_sRevocationReason = sRevocationReason ; }
Mark the owning item as revoked .
175
7
7,289
@ GET @ Produces ( MediaType . TEXT_PLAIN ) public InputStream doc ( ) throws IOException { //noinspection ConstantConditions return getClass ( ) . getClassLoader ( ) . getResource ( "SnomedCoderService_help.txt" ) . openStream ( ) ; }
Return some docs about how to call this webservice
65
11
7,290
@ POST @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( { MediaType . APPLICATION_JSON , MediaType . TEXT_XML } ) public static Collection < Utterance > mapTextWithOptions ( final AnalysisRequest r ) throws IOException , InterruptedException , JAXBException , SQLException , ParserConfigurationException , SAXException { System . out . println ( r ) ; // metamap options final Collection < Option > opts = new ArrayList <> ( ) ; final Set < String > optionNames = new HashSet <> ( ) ; for ( final String o : r . getOptions ( ) ) { final Option opt = MetaMapOptions . strToOpt ( o ) ; if ( opt != null ) { optionNames . add ( opt . name ( ) ) ; if ( ! opt . useProcessorDefault ( ) ) opts . add ( opt ) ; } } // always make sure we have a restrict_to_sources option if ( ! optionNames . contains ( new RestrictToSources ( ) . name ( ) ) ) opts . add ( new RestrictToSources ( ) ) ; // tmp files for metamap in/out final File infile = File . createTempFile ( "metamap-input-" , ".txt" ) ; final File outfile = File . createTempFile ( "metamap-output-" , ".xml" ) ; final String s = r . getText ( ) + ( r . getText ( ) . endsWith ( "\n" ) ? "" : "\n" ) ; final String ascii = MetaMap . decomposeToAscii ( URLDecoder . decode ( s , "UTF-8" ) ) ; Files . write ( ascii , infile , Charsets . UTF_8 ) ; // we don't want too much data for a free service if ( infile . length ( ) > MAX_DATA_BYTES ) { throw new WebApplicationException ( Response . status ( Responses . NOT_ACCEPTABLE ) . entity ( "Too much data, currently limited to " + MAX_DATA_BYTES + " bytes." ) . type ( "text/plain" ) . build ( ) ) ; } // process the data with MetaMap final MetaMap metaMap = new MetaMap ( PUBLIC_MM_DIR , opts ) ; if ( ! metaMap . process ( infile , outfile ) ) { throw new WebApplicationException ( Response . status ( INTERNAL_SERVER_ERROR ) . entity ( "Processing failed, aborting." ) . type ( "text/plain" ) . build ( ) ) ; } // look up the SNOMED codes from the UMLS CUI code/description combinations returned by MetaMap final MMOs root = JaxbLoader . loadXml ( outfile ) ; try ( final SnomedLookup snomedLookup = new SnomedLookup ( DB_PATH ) ) { snomedLookup . enrichXml ( root ) ; } //noinspection ResultOfMethodCallIgnored infile . delete ( ) ; //noinspection ResultOfMethodCallIgnored outfile . delete ( ) ; return destructiveFilter ( root ) ; }
Accepts a JSON object with text and possible options for the analysis .
689
14
7,291
private static Collection < Utterance > destructiveFilter ( final MMOs root ) { final Collection < Utterance > utterances = new ArrayList <> ( ) ; for ( final MMO mmo : root . getMMO ( ) ) { for ( final Utterance utterance : mmo . getUtterances ( ) . getUtterance ( ) ) { // clear candidates to save heaps of bytes for ( final Phrase phrase : utterance . getPhrases ( ) . getPhrase ( ) ) { phrase . setCandidates ( null ) ; } utterances . add ( utterance ) ; } } return utterances ; }
Beware! Destructive filtering of things we are not interested in in the JAXB data structure .
137
22
7,292
private static void _initialFillSet ( @ Nonnull final ICommonsOrderedSet < String > aSet , @ Nullable final String sItemList , final boolean bUnify ) { ValueEnforcer . notNull ( aSet , "Set" ) ; if ( ! aSet . isEmpty ( ) ) throw new IllegalArgumentException ( "The provided set must be empty, but it is not: " + aSet ) ; if ( StringHelper . hasText ( sItemList ) ) { // Perform some default replacements to avoid updating all references at // once before splitting final String sRealItemList = StringHelper . replaceAll ( sItemList , EXTENSION_MACRO_WEB_DEFAULT , "js,css,png,jpg,jpeg,gif,eot,svg,ttf,woff,woff2,map" ) ; for ( final String sItem : StringHelper . getExploded ( ' ' , sRealItemList ) ) { String sRealItem = sItem . trim ( ) ; if ( bUnify ) sRealItem = getUnifiedItem ( sRealItem ) ; // Add only non-empty items if ( StringHelper . hasText ( sRealItem ) ) aSet . add ( sRealItem ) ; } } }
Helper function to convert the configuration string to a collection .
274
11
7,293
public List < Page > extractText ( InputStream src ) throws IOException { List < Page > pages = Lists . newArrayList ( ) ; PdfReader reader = new PdfReader ( src ) ; RenderListener listener = new InternalListener ( ) ; PdfContentStreamProcessor processor = new PdfContentStreamProcessor ( listener ) ; for ( int i = 1 ; i <= reader . getNumberOfPages ( ) ; i ++ ) { pages . add ( currentPage = new Page ( ) ) ; PdfDictionary pageDic = reader . getPageN ( i ) ; PdfDictionary resourcesDic = pageDic . getAsDict ( PdfName . RESOURCES ) ; processor . processContent ( ContentByteUtils . getContentBytesForPage ( reader , i ) , resourcesDic ) ; } reader . close ( ) ; return pages ; }
Extracts text from a PDF document .
188
9
7,294
public String createResponse ( String challenge ) throws IllegalArgumentException , KeyNotFoundException , ProtocolVersionException { byte [ ] decodedChallenge = decode ( challenge ) ; Challenge deserializedChallenge = CrtAuthCodec . deserializeChallenge ( decodedChallenge ) ; if ( ! deserializedChallenge . getServerName ( ) . equals ( serverName ) ) { throw new IllegalArgumentException ( String . format ( "Server name mismatch (%s != %s). Possible MITM attack." , deserializedChallenge . getServerName ( ) , serverName ) ) ; } byte [ ] signature = signer . sign ( decodedChallenge , deserializedChallenge . getFingerprint ( ) ) ; return encode ( CrtAuthCodec . serialize ( new Response ( decodedChallenge , signature ) ) ) ; }
Generate a response String using the Signer of this instance additionally verifying that the embedded serverName matches the serverName of this instance .
183
27
7,295
private static boolean initSingleCoverageMode ( final String runName , Instrumentation instrumentation ) { // Check if run is affected and if not start coverage. if ( Ekstazi . inst ( ) . checkIfAffected ( runName ) ) { Ekstazi . inst ( ) . startCollectingDependencies ( runName ) ; // End coverage when VM ends execution. Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { @ Override public void run ( ) { Ekstazi . inst ( ) . finishCollectingDependencies ( runName ) ; } } ) ; return true ; } else { instrumentation . addTransformer ( new RemoveMainCFT ( ) ) ; return false ; } }
Initialize SingleMode run . We first check if run is affected and only in that case start coverage otherwise we remove bodies of all main methods to avoid any execution .
157
33
7,296
@ OverrideOnDemand protected void addMetaElements ( @ Nonnull final IRequestWebScopeWithoutResponse aRequestScope , @ Nonnull final HCHead aHead ) { final ICommonsList < IMetaElement > aMetaElements = new CommonsArrayList <> ( ) ; { // add special meta element at the beginning final IMimeType aMimeType = PhotonHTMLHelper . getMimeType ( aRequestScope ) ; aMetaElements . add ( EStandardMetaElement . CONTENT_TYPE . getAsMetaElement ( aMimeType . getAsString ( ) ) ) ; } PhotonMetaElements . getAllRegisteredMetaElementsForGlobal ( aMetaElements ) ; PhotonMetaElements . getAllRegisteredMetaElementsForThisRequest ( aMetaElements ) ; for ( final IMetaElement aMetaElement : aMetaElements ) for ( final Map . Entry < Locale , String > aEntry : aMetaElement . getContent ( ) ) { final HCMeta aMeta = new HCMeta ( ) ; if ( aMetaElement . isHttpEquiv ( ) ) aMeta . setHttpEquiv ( aMetaElement . getName ( ) ) ; else aMeta . setName ( aMetaElement . getName ( ) ) ; aMeta . setContent ( aEntry . getValue ( ) ) ; final Locale aContentLocale = aEntry . getKey ( ) ; if ( aContentLocale != null && ! LocaleHelper . isSpecialLocale ( aContentLocale ) ) aMeta . setLanguage ( aContentLocale . toString ( ) ) ; aHead . metaElements ( ) . add ( aMeta ) ; } }
Add all meta elements to the HTML head element .
363
10
7,297
@ Nonnull public FineUploader5Core setMaxConnections ( @ Nonnegative final int nMaxConnections ) { ValueEnforcer . isGT0 ( nMaxConnections , "MaxConnections" ) ; m_nCoreMaxConnections = nMaxConnections ; return this ; }
Maximum allowable concurrent requests
62
4
7,298
@ Nonnull public JSFormatter outdentAlways ( ) { if ( m_nIndentLevel == 0 ) throw new IllegalStateException ( "Nothing left to outdent!" ) ; m_nIndentLevel -- ; m_sIndentCache = m_sIndentCache . substring ( 0 , m_nIndentLevel * m_aSettings . getIndent ( ) . length ( ) ) ; return this ; }
Decrement the indentation level .
95
7
7,299
@ Nonnull @ CodingStyleguideUnaware public JSDefinedClass _extends ( @ Nonnull final AbstractJSClass aSuperClass ) { m_aSuperClass = ValueEnforcer . notNull ( aSuperClass , "SuperClass" ) ; return this ; }
This class extends the specified class .
60
7