idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
7,200
public DataTablesDom addCustom ( final String sStr ) { ValueEnforcer . notEmpty ( sStr , "Str" ) ; _internalAdd ( sStr ) ; return this ; }
Add a custom element
7,201
public FineUploader5Validation setItemLimit ( final int nItemLimit ) { ValueEnforcer . isGE0 ( nItemLimit , "ItemLimit" ) ; m_nValidationItemLimit = nItemLimit ; return this ; }
Maximum number of items that can be potentially uploaded in this session . Will reject all items that are added or retried after this limit is reached .
7,202
public FineUploader5Validation setMinSizeLimit ( final int nMinSizeLimit ) { ValueEnforcer . isGE0 ( nMinSizeLimit , "MinSizeLimit" ) ; m_nValidationMinSizeLimit = nMinSizeLimit ; return this ; }
The minimum allowable size in bytes for an item .
7,203
public FineUploader5Validation setSizeLimit ( final int nSizeLimit ) { ValueEnforcer . isGE0 ( nSizeLimit , "SizeLimit" ) ; m_nValidationSizeLimit = nSizeLimit ; return this ; }
The maximum allowable size in bytes for an item .
7,204
private void sendTextToServer ( ) { statusLabel . setText ( "" ) ; conceptList . clear ( ) ; final String text = mainTextArea . getText ( ) ; if ( text . length ( ) < 1 ) { statusLabel . setText ( messages . pleaseEnterTextLabel ( ) ) ; return ; } glassPanel . setPositionAndShow ( ) ; final JSONArray options = new JSONArray ( ) ; setSemanticTypesOption ( types , options ) ; options . set ( options . size ( ) , new JSONString ( "word_sense_disambiguation" ) ) ; options . set ( options . size ( ) , new JSONString ( "composite_phrases 8" ) ) ; options . set ( options . size ( ) , new JSONString ( "no_derivational_variants" ) ) ; options . set ( options . size ( ) , new JSONString ( "strict_model" ) ) ; options . set ( options . size ( ) , new JSONString ( "ignore_word_order" ) ) ; options . set ( options . size ( ) , new JSONString ( "allow_large_n" ) ) ; options . set ( options . size ( ) , new JSONString ( "restrict_to_sources SNOMEDCT_US" ) ) ; final JSONObject analysisRequest = new JSONObject ( ) ; analysisRequest . put ( "text" , new JSONString ( text ) ) ; analysisRequest . put ( "options" , options ) ; final RequestBuilder builder = new RequestBuilder ( RequestBuilder . POST , webserviceUrl ) ; builder . setHeader ( "Content-Type" , MediaType . APPLICATION_JSON ) ; builder . setRequestData ( analysisRequest . toString ( ) ) ; builder . setCallback ( new SnomedRequestCallback ( conceptList , statusLabel , glassPanel , typeCodeToDescription ) ) ; try { builder . send ( ) ; } catch ( final RequestException e ) { statusLabel . setText ( messages . problemPerformingAnalysisLabel ( ) ) ; GWT . log ( "There was a problem performing the analysis: " + e . getMessage ( ) , e ) ; glassPanel . hide ( ) ; } }
send the text from the mainTextArea to the server and accept an async response
7,205
public ParseResult parse ( Source source ) { if ( ! testSrcInfo . equals ( source . getSrcInfo ( ) ) ) { throw new RuntimeException ( "testSrcInfo and source.getSrcInfo were not equal. testSrcInfo = " + testSrcInfo + ", source.getSrcInfo = " + source . getSrcInfo ( ) ) ; } try { BufferedReader reader = source . createReader ( ) ; try { if ( ! testString . equals ( reader . readLine ( ) ) ) { throw new RuntimeException ( "testString and reader.readLine() were not equal" ) ; } final String secondLine = reader . readLine ( ) ; if ( secondLine != null ) { throw new RuntimeException ( "got a second line '" + secondLine + "' from the reader" ) ; } } finally { reader . close ( ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } return testResult ; }
When called this examines the source to make sure the scrcInfo and data are the expected testSrcInfo and testString . It then produces the testDoc as a result
7,206
public void registerPasswordHashCreator ( final IPasswordHashCreator aPasswordHashCreator ) { ValueEnforcer . notNull ( aPasswordHashCreator , "PasswordHashCreator" ) ; final String sAlgorithmName = aPasswordHashCreator . getAlgorithmName ( ) ; if ( StringHelper . hasNoText ( sAlgorithmName ) ) throw new IllegalArgumentException ( "PasswordHashCreator algorithm '" + aPasswordHashCreator + "' is empty!" ) ; m_aRWLock . writeLocked ( ( ) -> { if ( m_aPasswordHashCreators . containsKey ( sAlgorithmName ) ) throw new IllegalArgumentException ( "Another PasswordHashCreator for algorithm '" + sAlgorithmName + "' is already registered!" ) ; m_aPasswordHashCreators . put ( sAlgorithmName , aPasswordHashCreator ) ; } ) ; if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Registered password hash creator algorithm '" + sAlgorithmName + "' to " + aPasswordHashCreator ) ; }
Register a new password hash creator . No other password hash creator with the same algorithm name may be registered .
7,207
public IPasswordHashCreator getPasswordHashCreatorOfAlgorithm ( final String sAlgorithmName ) { return m_aRWLock . readLocked ( ( ) -> m_aPasswordHashCreators . get ( sAlgorithmName ) ) ; }
Get the password hash creator of the specified algorithm name .
7,208
private List < SemanticError > check ( DataType dataType ) { logger . finer ( "Checking semantic constraints on datatype " + dataType . name ) ; final List < SemanticError > errors = new ArrayList < SemanticError > ( ) ; final Set < String > constructorNames = new HashSet < String > ( ) ; for ( Constructor constructor : dataType . constructors ) { logger . finest ( "Checking semantic constraints on constructor " + constructor . name + " in datatype " + dataType . name ) ; if ( dataType . constructors . size ( ) > 1 && dataType . name . equals ( constructor . name ) ) { logger . info ( "Constructor with same name as its data type " + dataType . name + "." ) ; errors . add ( _ConstructorDataTypeConflict ( dataType . name ) ) ; } if ( constructorNames . contains ( constructor . name ) ) { logger . info ( "Two constructors with same name " + constructor . name + " in data type " + dataType . name + "." ) ; errors . add ( _DuplicateConstructor ( dataType . name , constructor . name ) ) ; } else { constructorNames . add ( constructor . name ) ; } errors . addAll ( check ( dataType , constructor ) ) ; } return errors ; }
Checks a data type for duplicate constructor names or constructors having the same name as the data type
7,209
private List < SemanticError > check ( DataType dataType , Constructor constructor ) { logger . finer ( "Checking semantic constraints on data type " + dataType . name + ", constructor " + constructor . name ) ; final List < SemanticError > errors = new ArrayList < SemanticError > ( ) ; final Set < String > argNames = new HashSet < String > ( ) ; for ( Arg arg : constructor . args ) { if ( argNames . contains ( arg . name ) ) { errors . add ( _DuplicateArgName ( dataType . name , constructor . name , arg . name ) ) ; } else { argNames . add ( arg . name ) ; } errors . addAll ( check ( dataType , constructor , arg ) ) ; } return errors ; }
Check a constructor to make sure it does not duplicate any args and that no arg duplicates any modifiers
7,210
private List < SemanticError > check ( DataType dataType , Constructor constructor , Arg arg ) { logger . finest ( "Checking semantic constraints on data type " + dataType . name + ", constructor " + constructor . name ) ; final List < SemanticError > errors = new ArrayList < SemanticError > ( ) ; final Set < ArgModifier > modifiers = new HashSet < ArgModifier > ( ) ; for ( ArgModifier modifier : arg . modifiers ) { if ( modifiers . contains ( modifier ) ) { final String modName = ASTPrinter . print ( modifier ) ; errors . add ( _DuplicateModifier ( dataType . name , constructor . name , arg . name , modName ) ) ; } else { modifiers . add ( modifier ) ; } } return errors ; }
Checkt to make sure an arg doesn t have duplicate modifiers
7,211
@ SuppressWarnings ( "resource" ) protected CSVWriter createCSVWriter ( final OutputStream aOS ) { return new CSVWriter ( new OutputStreamWriter ( aOS , m_aCharset ) ) . setSeparatorChar ( m_cSeparatorChar ) . setQuoteChar ( m_cQuoteChar ) . setEscapeChar ( m_cEscapeChar ) . setLineEnd ( m_sLineEnd ) . setAvoidFinalLineEnd ( m_bAvoidFinalLineEnd ) ; }
Create a new CSV writer .
7,212
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 .
7,213
private void appendExcludesListToExcludesFile ( Plugin plugin , List < String > nonAffectedClasses ) throws MojoExecutionException { String excludesFileName = extractParamValue ( plugin , EXCLUDES_FILE_PARAM_NAME ) ; File excludesFileFile = new File ( excludesFileName ) ; restoreExcludesFile ( plugin ) ; PrintWriter pw = null ; try { pw = new PrintWriter ( new FileOutputStream ( excludesFileFile , true ) , true ) ; pw . println ( EKSTAZI_LINE_MARKER ) ; for ( String exclude : nonAffectedClasses ) { pw . println ( exclude ) ; } 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 .
7,214
private boolean isParallelOn ( Plugin plugin ) throws MojoExecutionException { String value = extractParamValue ( plugin , PARALLEL_PARAM_NAME ) ; 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 .
7,215
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 .
7,216
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 .
7,217
private void checkParameters ( Plugin plugin ) throws MojoExecutionException { if ( isParallelOn ( plugin ) ) { throw new MojoExecutionException ( "Ekstazi currently does not support parallel parameter" ) ; } if ( isForkDisabled ( plugin ) ) { throw new MojoExecutionException ( "forkCount has to be at least 1" ) ; } }
Checks that all parameters are set as expected .
7,218
public static < T extends IHCNode > T getPreparedNode ( final T aNode , final IHCHasChildrenMutable < ? , ? super IHCNode > aTargetNode , final IHCConversionSettingsToNode aConversionSettings ) { aNode . customizeNode ( aConversionSettings . getCustomizer ( ) , aConversionSettings . getHTMLVersion ( ) , aTargetNode ) ; aNode . finalizeNodeState ( aConversionSettings , aTargetNode ) ; aNode . consistencyCheck ( aConversionSettings ) ; final boolean bForcedResourceRegistration = false ; aNode . registerExternalResources ( aConversionSettings , bForcedResourceRegistration ) ; return aNode ; }
Prepare and return a single node .
7,219
public static void prepareForConversion ( final IHCNode aStartNode , final IHCHasChildrenMutable < ? , ? super IHCNode > aGlobalTargetNode , 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 ( ) ; final IHCIteratorNonBreakableCallback aCB = ( aParentNode , aChildNode ) -> { IHCHasChildrenMutable < ? , ? super IHCNode > aRealTargetNode ; if ( aParentNode instanceof IHCHasChildrenMutable < ? , ? > ) { aRealTargetNode = GenericReflection . uncheckedCast ( aParentNode ) ; } else aRealTargetNode = aGlobalTargetNode ; final int nTargetNodeChildren = aRealTargetNode . getChildCount ( ) ; aChildNode . customizeNode ( aCustomizer , eHTMLVersion , aRealTargetNode ) ; aChildNode . finalizeNodeState ( aConversionSettings , aRealTargetNode ) ; aChildNode . consistencyCheck ( aConversionSettings ) ; final boolean bForcedResourceRegistration = false ; aChildNode . registerExternalResources ( aConversionSettings , bForcedResourceRegistration ) ; if ( aRealTargetNode . getChildCount ( ) > nTargetNodeChildren ) { prepareForConversion ( aRealTargetNode , aRealTargetNode , aConversionSettings ) ; } } ; HCHelper . iterateTreeNonBreakable ( aStartNode , aCB ) ; }
Customize the passed base node and all child nodes recursively .
7,220
public static IMicroNode getAsNode ( final IHCNode aHCNode ) { return getAsNode ( aHCNode , HCSettings . getConversionSettings ( ) ) ; }
Convert the passed HC node to a micro node using the default conversion settings .
7,221
@ SuppressWarnings ( "unchecked" ) public static IMicroNode getAsNode ( final IHCNode aSrcNode , final IHCConversionSettingsToNode aConversionSettings ) { IHCNode aConvertNode = aSrcNode ; if ( ! ( aSrcNode instanceof HCHtml ) ) { final boolean bSrcNodeCanHaveChildren = aSrcNode instanceof IHCHasChildrenMutable < ? , ? > ; IHCHasChildrenMutable < ? , IHCNode > aTempNode ; if ( bSrcNodeCanHaveChildren ) { aTempNode = ( IHCHasChildrenMutable < ? , IHCNode > ) aSrcNode ; } else { aTempNode = new HCNodeList ( ) ; aTempNode . addChild ( aSrcNode ) ; } prepareForConversion ( aTempNode , aTempNode , aConversionSettings ) ; 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 .
7,222
public static String getAsHTMLString ( final IHCNode aHCNode ) { return getAsHTMLString ( aHCNode , HCSettings . getConversionSettings ( ) ) ; }
Convert the passed HC node to an HTML string using the default conversion settings .
7,223
public static String getAsHTMLString ( final IHCNode aHCNode , 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
7,224
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 .
7,225
public ELoginResult loginUser ( final String sLoginName , final String sPlainTextPassword ) { return loginUser ( sLoginName , sPlainTextPassword , ( Iterable < String > ) null ) ; }
Login the passed user without much ado .
7,226
public EChange logoutUser ( 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 ; } final InternalSessionUserHolder aSUH = InternalSessionUserHolder . _getInstanceIfInstantiatedInScope ( aInfo . getSessionScope ( ) ) ; if ( aSUH != null ) aSUH . _reset ( ) ; 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 ) ; m_aUserLogoutCallbacks . forEach ( aCB -> aCB . onUserLogout ( aInfo ) ) ; return EChange . CHANGED ; }
Manually log out the specified user
7,227
public LoginInfo getLoginInfo ( final String sUserID ) { return m_aRWLock . readLocked ( ( ) -> m_aLoggedInUsers . get ( sUserID ) ) ; }
Get the login details of the specified user .
7,228
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 ) ; 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" ) ) ; printVerbose ( userHomeDir , userDir ) ; }
Load configuration from properties .
7,229
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 .
7,230
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 .
7,231
public static void main ( String [ ] args ) { DEBUG_MODE_V = DebugMode . SCREEN ; Log . initScreen ( ) ; printVerbose ( null , null ) ; }
Prints configuration options .
7,232
public final IMPLTYPE setWidth ( final int nWidth ) { if ( nWidth >= 0 ) m_sWidth = Integer . toString ( nWidth ) ; return thisAsT ( ) ; }
Set the width in pixel
7,233
public HCConversionSettings setCSSWriterSettings ( final ICSSWriterSettings aCSSWriterSettings ) { ValueEnforcer . notNull ( aCSSWriterSettings , "CSSWriterSettings" ) ; m_aCSSWriterSettings = new CSSWriterSettings ( aCSSWriterSettings ) ; return this ; }
Set the CSS writer settings to be used .
7,234
public HCConversionSettings setJSWriterSettings ( final IJSWriterSettings aJSWriterSettings ) { ValueEnforcer . notNull ( aJSWriterSettings , "JSWriterSettings" ) ; m_aJSWriterSettings = new JSWriterSettings ( aJSWriterSettings ) ; return this ; }
Set the JS formatter settings to be used .
7,235
public static ESuccess check ( final String sServerSideKey , final String sReCaptchaResponse ) { ValueEnforcer . notEmpty ( sServerSideKey , "ServerSideKey" ) ; if ( StringHelper . hasNoText ( sReCaptchaResponse ) ) return ESuccess . SUCCESS ; final HttpClientFactory aHCFactory = new HttpClientFactory ( ) ; 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 .
7,236
public SimpleURL getInvocationURL ( final String sBasePath ) { ValueEnforcer . notNull ( sBasePath , "BasePath" ) ; return new SimpleURL ( sBasePath + m_sPath ) ; }
Get the invocation URL of this API path .
7,237
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 .
7,238
public void addHandler ( final EJSEvent eJSEvent , 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 .
7,239
public void prependHandler ( final EJSEvent eJSEvent , 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 .
7,240
public void setHandler ( final EJSEvent eJSEvent , final IHasJSCode aNewHandler ) { ValueEnforcer . notNull ( eJSEvent , "JSEvent" ) ; ValueEnforcer . notNull ( aNewHandler , "NewHandler" ) ; 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 .
7,241
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 .
7,242
public static AccessToken createAccessTokenValidFromNow ( final String sTokenString ) { 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 .
7,243
public static EFamFamFlagIcon getFlagFromLocale ( 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
7,244
private void checkIfEkstaziDirCanBeCreated ( ) throws MojoExecutionException { File ekstaziDir = Config . createRootDir ( parentdir ) ; 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 .
7,245
public EChange setSystemMessage ( final ESystemMessageType eMessageType , 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 .
7,246
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 .
7,247
private RSAPublicKey getKeyForUser ( String userName ) throws KeyNotFoundException { RSAPublicKey key = null ; for ( final KeyProvider keyProvider : keyProviders ) { try { key = keyProvider . getKey ( userName ) ; break ; } catch ( KeyNotFoundException e ) { } } 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 .
7,248
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 .
7,249
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 ) { 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 .
7,250
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 .
7,251
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 .
7,252
public static ESuccess execute ( final IJSchSessionProvider aSessionProvider , final int nChannelConnectTimeoutMillis , final IChannelSftpRunnable aRunnable ) throws JSchException { ValueEnforcer . notNull ( aSessionProvider , "SessionProvider" ) ; ValueEnforcer . notNull ( aRunnable , "Runnable" ) ; Session aSession = null ; Channel aChannel = null ; ChannelSftp aSFTPChannel = null ; try { aSession = aSessionProvider . createSession ( ) ; if ( aSession == null ) throw new IllegalStateException ( "Failed to create JSch session from provider" ) ; aChannel = aSession . openChannel ( "sftp" ) ; aChannel . connect ( nChannelConnectTimeoutMillis ) ; aSFTPChannel = ( ChannelSftp ) aChannel ; aRunnable . execute ( aSFTPChannel ) ; return ESuccess . SUCCESS ; } catch ( final SftpException ex ) { LOGGER . error ( "Error peforming SFTP action: " + aRunnable . getDisplayName ( ) , ex ) ; return ESuccess . FAILURE ; } finally { if ( aSFTPChannel != null ) aSFTPChannel . quit ( ) ; if ( aChannel != null && aChannel . isConnected ( ) ) aChannel . disconnect ( ) ; if ( aSession != null ) JSchSessionFactory . destroySession ( aSession ) ; } }
Upload a file to the server .
7,253
public static void setPasswordConstraintList ( final IPasswordConstraintList aPasswordConstraintList ) { ValueEnforcer . notNull ( aPasswordConstraintList , "PasswordConstraintList" ) ; 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 .
7,254
private CoverageClassVisitor createCoverageClassVisitor ( String className , ClassWriter cv , boolean isRedefined ) { return new CoverageClassVisitor ( className , cv ) ; }
Creates class visitor to instrument for coverage based on configuration options .
7,255
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 ) { } } return isMonitorAccessible ; }
LoaderMethodVisitor and LoaderMonitor .
7,256
@ 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 .
7,257
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 .
7,258
public CollectingJSCodeProvider addAt ( final int nIndex , final IHasJSCode aProvider ) { if ( aProvider != null ) m_aList . add ( nIndex , aProvider ) ; return this ; }
Add JS code at the specified index .
7,259
public JSFunction name ( 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 .
7,260
public static TypeaheadEditSelection getSelectionForRequiredObject ( final IWebPageExecutionContext aWPEC , final String sEditFieldName , 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 ) ) { sHiddenFieldValue = null ; } } else { if ( StringHelper . hasText ( sEditValue ) ) { sEditValue = null ; } } return new TypeaheadEditSelection ( sEditValue , sHiddenFieldValue ) ; }
Get the current selection in the case that it is mandatory to select an available object .
7,261
protected IHCNode createPageHeader ( final ISimpleWebExecutionContext aSWEC , final IHCNode aPageTitle ) { return BootstrapPageHeader . createOnDemand ( aPageTitle ) ; }
Create the text above the login form .
7,262
public static JSInvocation createEventTrackingCode ( final String sCategory , final String sAction , final String sLabel , 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
7,263
public static Collection < String > sanitiseSemanticTypes ( final Collection < String > semanticTypes ) { if ( semanticTypes == null ) return ImmutableList . of ( ) ; final Set < String > s = new LinkedHashSet < > ( semanticTypes ) ; return s . retainAll ( SEMANTIC_TYPES_CODE_TO_DESCRIPTION . keySet ( ) ) ? s : semanticTypes ; }
Sanitise semantic types from user input .
7,264
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
7,265
public static String print ( final String indent , JavaComment comment ) { return comment . match ( new JavaComment . MatchBlock < String > ( ) { 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 ( ) ; } 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 > ( ) { public String _case ( BlockWord x ) { return x . word ; } public String _case ( BlockWhiteSpace x ) { return x . ws ; } public String _case ( BlockEOL x ) { return x . content + indent ; } } ) ) ; } } return builder . toString ( ) ; } public String _case ( JavaEOLComment x ) { return x . comment ; } } ) ; }
Prints a single comment pretty much unmolested
7,266
public static String print ( Arg arg ) { return printArgModifiers ( arg . modifiers ) + print ( arg . type ) + " " + arg . name ; }
prints an arg as type name
7,267
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
7,268
public static String print ( Type type ) { return type . match ( new Type . MatchBlock < String > ( ) { public String _case ( Ref x ) { return print ( x . type ) ; } public String _case ( Primitive x ) { return print ( x . type ) ; } } ) ; }
Prints a type as either a ref type or a primitive
7,269
public static String print ( RefType type ) { return type . match ( new RefType . MatchBlock < String > ( ) { 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 ( ) ; } public String _case ( ArrayType x ) { return print ( x . heldType ) + "[]" ; } } ) ; }
Prints a type as either an array or class type .
7,270
public static String print ( PrimitiveType type ) { return type . match ( new PrimitiveType . MatchBlock < String > ( ) { public String _case ( BooleanType x ) { return "boolean" ; } public String _case ( ByteType x ) { return "byte" ; } public String _case ( CharType x ) { return "char" ; } public String _case ( DoubleType x ) { return "double" ; } public String _case ( FloatType x ) { return "float" ; } public String _case ( IntType x ) { return "int" ; } public String _case ( LongType x ) { return "long" ; } public String _case ( ShortType x ) { return "short" ; } } ) ; }
Prints a primitive type as boolean | char | short | int | long | float | double
7,271
public static String print ( ArgModifier modifier ) { return modifier . match ( new ArgModifier . MatchBlock < String > ( ) { public String _case ( Final x ) { return "final" ; } public String _case ( Volatile x ) { return "volatile" ; } public String _case ( Transient x ) { return "transient" ; } } ) ; }
Print arg modifier
7,272
private static String print ( final String indent , JDToken token ) { return token . match ( new JDToken . MatchBlock < String > ( ) { public String _case ( JDAsterisk x ) { return "*" ; } public String _case ( JDEOL x ) { return x . content + indent ; } public String _case ( JDTag x ) { return x . name ; } public String _case ( JDWord x ) { return x . word ; } public String _case ( JDWhiteSpace x ) { return x . ws ; } } ) ; }
Print a single JavaDoc token
7,273
public static String print ( final Literal literal ) { return literal . match ( new Literal . MatchBlock < String > ( ) { public String _case ( StringLiteral x ) { return x . content ; } public String _case ( FloatingPointLiteral x ) { return x . content ; } public String _case ( IntegerLiteral x ) { return x . content ; } public String _case ( CharLiteral x ) { return x . content ; } public String _case ( BooleanLiteral x ) { return x . content ; } public String _case ( NullLiteral x ) { return "null" ; } } ) ; }
Print a single literal
7,274
public static String print ( Expression expression ) { return expression . match ( new Expression . MatchBlock < String > ( ) { public String _case ( LiteralExpression x ) { return print ( x . literal ) ; } public String _case ( VariableExpression x ) { return x . selector . match ( new Optional . MatchBlock < Expression , String > ( ) { public String _case ( Some < Expression > x ) { return print ( x . value ) + "." ; } public String _case ( None < Expression > x ) { return "" ; } } ) + x . identifier ; } public String _case ( NestedExpression x ) { return "( " + print ( x . expression ) + " )" ; } public String _case ( ClassReference x ) { return print ( x . type ) + ".class" ; } public String _case ( TernaryExpression x ) { return print ( x . cond ) + " ? " + print ( x . trueExpression ) + " : " + print ( x . falseExpression ) ; } public String _case ( BinaryExpression x ) { return print ( x . left ) + " " + print ( x . op ) + " " + print ( x . right ) ; } } ) ; }
Print an expression
7,275
public BootstrapSpacingBuilder property ( final EBootstrapSpacingPropertyType eProperty ) { ValueEnforcer . notNull ( eProperty , "Property" ) ; m_eProperty = eProperty ; return this ; }
Set the property type . Default is margin .
7,276
public BootstrapSpacingBuilder side ( final EBootstrapSpacingSideType eSide ) { ValueEnforcer . notNull ( eSide , "Side" ) ; m_eSide = eSide ; return this ; }
Set the edge type . Default is all .
7,277
@ SuppressFBWarnings ( "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE" ) public EChange registerState ( final String sStateID , 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
7,278
public EChange registerState ( 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 .
7,279
public FineUploader5Chunking setPartSize ( final long nPartSize ) { ValueEnforcer . isGT0 ( nPartSize , "PartSize" ) ; m_nChunkingPartSize = nPartSize ; return this ; }
The maximum size of each chunk in bytes .
7,280
public FineUploader5Chunking setParamNameChunkSize ( 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 .
7,281
public FineUploader5Chunking setParamNamePartByteOffset ( 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 .
7,282
public FineUploader5Chunking setParamNamePartIndex ( 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 .
7,283
public FineUploader5Chunking setParamNameTotalParts ( 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 .
7,284
public static byte [ ] removeDebugInfo ( byte [ ] bytes ) { if ( bytes . length >= 4 ) { 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 ; } 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 .
7,285
public final HCSWFObject addFlashVar ( 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
7,286
public final HCSWFObject removeFlashVar ( final String sName ) { if ( m_aFlashVars != null ) m_aFlashVars . remove ( sName ) ; return this ; }
Remove a flash variable
7,287
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 .
7,288
private static void setSystemClassLoaderClassPath ( ) throws Exception { Log . d ( "Setting classpath" ) ; 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 ( FileUtil . isSecondNewerThanFirst ( junitJar , xtsJar ) ) { isCreated = true ; } else { String [ ] includePrefixes = { Names . EKSTAZI_PACKAGE_BIN } ; String [ ] excludePrefixes = { EkstaziAgent . class . getName ( ) } ; isCreated = JarXtractor . extract ( junitJar , xtsJar , includePrefixes , excludePrefixes ) ; } 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 .
7,289
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 .
7,290
public static void t ( Class < ? > clz ) { if ( clz == null || ClassesCache . check ( clz ) || Types . isIgnorable ( clz ) ) { return ; } 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 { url = clz . getResource ( resourceName ) ; } catch ( SecurityException ex ) { Log . w ( "Unable to obtain resource because of security reasons." ) ; } if ( url == null ) { return ; } recordURL ( url . toExternalForm ( ) ) ; }
Touch method . Instrumented code invokes this method to collect class coverage .
7,291
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 .
7,292
public static void addFileURL ( File f ) { String absolutePath = f . getAbsolutePath ( ) ; if ( ! filterFile ( absolutePath ) ) { try { recordURL ( f . toURI ( ) . toURL ( ) . toExternalForm ( ) ) ; } catch ( MalformedURLException e ) { } } }
Records the given file as a dependency after some filtering .
7,293
protected static void recordURL ( String externalForm ) { if ( filterURL ( externalForm ) ) { return ; } if ( isWellKnownUrl ( externalForm ) ) { 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 .
7,294
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 .
7,295
public static final void c ( String msg ) { if ( msg . replaceAll ( "\\s+" , "" ) . equals ( "" ) ) { println ( CONF_TEXT ) ; } else { println ( CONF_TEXT + ": " + msg ) ; } }
Printing configuration options .
7,296
public PathMatchingResult matchesParts ( final List < String > aPathParts ) { ValueEnforcer . notNull ( aPathParts , "PathParts" ) ; final int nPartCount = m_aPathParts . size ( ) ; if ( aPathParts . size ( ) != nPartCount ) { 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 ) ) { return PathMatchingResult . NO_MATCH ; } if ( aPart . isVariable ( ) ) aVariableValues . put ( aPart . getName ( ) , sPathPart ) ; } 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 .
7,297
public FineUploader5Retry setAutoAttemptDelay ( final int nAutoAttemptDelay ) { ValueEnforcer . isGE0 ( nAutoAttemptDelay , "AutoAttemptDelay" ) ; m_nRetryAutoAttemptDelay = nAutoAttemptDelay ; return this ; }
The number of seconds to wait between auto retry attempts .
7,298
public FineUploader5Retry setMaxAutoAttempts ( final int nMaxAutoAttempts ) { ValueEnforcer . isGE0 ( nMaxAutoAttempts , "MaxAutoAttempts" ) ; m_nRetryMaxAutoAttempts = nMaxAutoAttempts ; return this ; }
The maximum number of times to attempt to retry a failed upload .
7,299
public FineUploader5Retry setPreventRetryResponseProperty ( 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 .