idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
151,500
private static OkHttpClient getUnsafeOkHttpClient ( ) { try { // Create a trust manager that does not validate certificate chains final TrustManager [ ] trustAllCerts = new TrustManager [ ] { new X509TrustManager ( ) { @ Override public void checkClientTrusted ( java . security . cert . X509Certificate [ ] chain , String authType ) throws CertificateException { } @ Override public void checkServerTrusted ( java . security . cert . X509Certificate [ ] chain , String authType ) throws CertificateException { } @ Override public java . security . cert . X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } } } ; // Install the all-trusting trust manager final SSLContext sslContext = SSLContext . getInstance ( "SSL" ) ; sslContext . init ( null , trustAllCerts , new java . security . SecureRandom ( ) ) ; // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext . getSocketFactory ( ) ; OkHttpClient okHttpClient = new OkHttpClient ( ) ; okHttpClient . setSslSocketFactory ( sslSocketFactory ) ; okHttpClient . setHostnameVerifier ( new HostnameVerifier ( ) { @ Override public boolean verify ( String hostname , SSLSession session ) { return true ; } } ) ; return okHttpClient ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Returns a OkHttpClient that ignores SSL cert errors
327
10
151,501
public void cleanup ( ) { synchronized ( _sslMap ) { for ( SslRelayOdo relay : _sslMap . values ( ) ) { if ( relay . getHttpServer ( ) != null && relay . isStarted ( ) ) { relay . getHttpServer ( ) . removeListener ( relay ) ; } } sslRelays . clear ( ) ; } }
Cleanup function to remove all allocated listeners
80
8
151,502
public void removeOverride ( int overrideId , int pathId , Integer ordinal , String clientUUID ) { // TODO: reorder priorities after removal PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { int enabledId = getEnabledEndpoint ( pathId , overrideId , ordinal , clientUUID ) . getId ( ) ; statement = sqlConnection . prepareStatement ( "DELETE FROM " + Constants . DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; statement . setInt ( 1 , enabledId ) ; statement . executeUpdate ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Remove specified override id from enabled overrides for path
194
10
151,503
public void increasePriority ( int overrideId , int ordinal , int pathId , String clientUUID ) { logger . info ( "Increase priority" ) ; int origPriority = - 1 ; int newPriority = - 1 ; int origId = 0 ; int newId = 0 ; PreparedStatement statement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { results = null ; statement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants . ENABLED_OVERRIDES_PATH_ID + " = ?" + " AND " + Constants . GENERIC_CLIENT_UUID + " = ?" + " ORDER BY " + Constants . ENABLED_OVERRIDES_PRIORITY ) ; statement . setInt ( 1 , pathId ) ; statement . setString ( 2 , clientUUID ) ; results = statement . executeQuery ( ) ; int ordinalCount = 0 ; while ( results . next ( ) ) { if ( results . getInt ( Constants . ENABLED_OVERRIDES_OVERRIDE_ID ) == overrideId ) { ordinalCount ++ ; if ( ordinalCount == ordinal ) { origPriority = results . getInt ( Constants . ENABLED_OVERRIDES_PRIORITY ) ; origId = results . getInt ( Constants . GENERIC_ID ) ; break ; } } newPriority = results . getInt ( Constants . ENABLED_OVERRIDES_PRIORITY ) ; newId = results . getInt ( Constants . GENERIC_ID ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } try ( Connection sqlConnection = sqlService . getConnection ( ) ) { // update priorities if ( origPriority != - 1 && newPriority != - 1 ) { statement = sqlConnection . prepareStatement ( "UPDATE " + Constants . DB_TABLE_ENABLED_OVERRIDE + " SET " + Constants . ENABLED_OVERRIDES_PRIORITY + "=?" + " WHERE " + Constants . GENERIC_ID + "=?" ) ; statement . setInt ( 1 , origPriority ) ; statement . setInt ( 2 , newId ) ; statement . executeUpdate ( ) ; statement . close ( ) ; statement = sqlConnection . prepareStatement ( "UPDATE " + Constants . DB_TABLE_ENABLED_OVERRIDE + " SET " + Constants . ENABLED_OVERRIDES_PRIORITY + "=?" + " WHERE " + Constants . GENERIC_ID + "=?" ) ; statement . setInt ( 1 , newPriority ) ; statement . setInt ( 2 , origId ) ; statement . executeUpdate ( ) ; } } catch ( Exception e ) { } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Increase the priority of an overrideId
722
7
151,504
private static String preparePlaceHolders ( int length ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < length ; ) { builder . append ( "?" ) ; if ( ++ i < length ) { builder . append ( "," ) ; } } return builder . toString ( ) ; }
Creates a list of placeholders for use in a PreparedStatement
70
14
151,505
public void disableAllOverrides ( int pathID , String clientUUID ) { PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "DELETE FROM " + Constants . DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants . ENABLED_OVERRIDES_PATH_ID + " = ? " + " AND " + Constants . GENERIC_CLIENT_UUID + " = ? " ) ; statement . setInt ( 1 , pathID ) ; statement . setString ( 2 , clientUUID ) ; statement . execute ( ) ; statement . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Disable all overrides for a specified path
198
8
151,506
public void disableAllOverrides ( int pathID , String clientUUID , int overrideType ) { PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { ArrayList < Integer > enabledOverrides = new ArrayList < Integer > ( ) ; enabledOverrides . add ( Constants . PLUGIN_REQUEST_HEADER_OVERRIDE_ADD ) ; enabledOverrides . add ( Constants . PLUGIN_REQUEST_HEADER_OVERRIDE_REMOVE ) ; enabledOverrides . add ( Constants . PLUGIN_REQUEST_OVERRIDE_CUSTOM ) ; enabledOverrides . add ( Constants . PLUGIN_REQUEST_OVERRIDE_CUSTOM_POST_BODY ) ; String overridePlaceholders = preparePlaceHolders ( enabledOverrides . size ( ) ) ; statement = sqlConnection . prepareStatement ( "DELETE FROM " + Constants . DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants . ENABLED_OVERRIDES_PATH_ID + " = ? " + " AND " + Constants . GENERIC_CLIENT_UUID + " = ? " + " AND " + Constants . ENABLED_OVERRIDES_OVERRIDE_ID + ( overrideType == Constants . OVERRIDE_TYPE_RESPONSE ? " NOT" : "" ) + " IN ( " + overridePlaceholders + " )" ) ; statement . setInt ( 1 , pathID ) ; statement . setString ( 2 , clientUUID ) ; for ( int i = 3 ; i <= enabledOverrides . size ( ) + 2 ; ++ i ) { statement . setInt ( i , enabledOverrides . get ( i - 3 ) ) ; } statement . execute ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Disable all overrides for a specified path with overrideType
453
11
151,507
public List < EnabledEndpoint > getEnabledEndpoints ( int pathId , String clientUUID , String [ ] filters ) throws Exception { ArrayList < EnabledEndpoint > enabledOverrides = new ArrayList < EnabledEndpoint > ( ) ; PreparedStatement query = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { query = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants . ENABLED_OVERRIDES_PATH_ID + "=?" + " AND " + Constants . GENERIC_CLIENT_UUID + "=?" + " ORDER BY " + Constants . ENABLED_OVERRIDES_PRIORITY ) ; query . setInt ( 1 , pathId ) ; query . setString ( 2 , clientUUID ) ; results = query . executeQuery ( ) ; while ( results . next ( ) ) { EnabledEndpoint endpoint = this . getPartialEnabledEndpointFromResultset ( results ) ; com . groupon . odo . proxylib . models . Method m = PathOverrideService . getInstance ( ) . getMethodForOverrideId ( endpoint . getOverrideId ( ) ) ; // this is an errant entry.. perhaps a method got deleted from a plugin // we'll also remove it from the endpoint if ( m == null ) { PathOverrideService . getInstance ( ) . removeOverride ( endpoint . getOverrideId ( ) ) ; continue ; } // check filters and see if any match boolean addOverride = false ; if ( filters != null ) { for ( String filter : filters ) { if ( m . getMethodType ( ) . endsWith ( filter ) ) { addOverride = true ; break ; } } } else { // if there are no filters then we assume that the requester wants all enabled overrides addOverride = true ; } if ( addOverride ) { enabledOverrides . add ( endpoint ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( query != null ) { query . close ( ) ; } } catch ( Exception e ) { } } // now go through the ArrayList and get the method for all of the endpoints // have to do this so we don't have overlapping SQL queries ArrayList < EnabledEndpoint > enabledOverridesWithMethods = new ArrayList < EnabledEndpoint > ( ) ; for ( EnabledEndpoint endpoint : enabledOverrides ) { if ( endpoint . getOverrideId ( ) >= 0 ) { com . groupon . odo . proxylib . models . Method m = PathOverrideService . getInstance ( ) . getMethodForOverrideId ( endpoint . getOverrideId ( ) ) ; endpoint . setMethodInformation ( m ) ; } enabledOverridesWithMethods . add ( endpoint ) ; } return enabledOverridesWithMethods ; }
Returns an array of the enabled endpoints as Integer IDs
656
11
151,508
public int getCurrentMethodOrdinal ( int overrideId , int pathId , String clientUUID , String [ ] filters ) throws Exception { int currentOrdinal = 0 ; List < EnabledEndpoint > enabledEndpoints = getEnabledEndpoints ( pathId , clientUUID , filters ) ; for ( EnabledEndpoint enabledEndpoint : enabledEndpoints ) { if ( enabledEndpoint . getOverrideId ( ) == overrideId ) { currentOrdinal ++ ; } } return currentOrdinal ; }
Get the ordinal value for the last of a particular override on a path
104
15
151,509
private EnabledEndpoint getPartialEnabledEndpointFromResultset ( ResultSet result ) throws Exception { EnabledEndpoint endpoint = new EnabledEndpoint ( ) ; endpoint . setId ( result . getInt ( Constants . GENERIC_ID ) ) ; endpoint . setPathId ( result . getInt ( Constants . ENABLED_OVERRIDES_PATH_ID ) ) ; endpoint . setOverrideId ( result . getInt ( Constants . ENABLED_OVERRIDES_OVERRIDE_ID ) ) ; endpoint . setPriority ( result . getInt ( Constants . ENABLED_OVERRIDES_PRIORITY ) ) ; endpoint . setRepeatNumber ( result . getInt ( Constants . ENABLED_OVERRIDES_REPEAT_NUMBER ) ) ; endpoint . setResponseCode ( result . getString ( Constants . ENABLED_OVERRIDES_RESPONSE_CODE ) ) ; ArrayList < Object > args = new ArrayList < Object > ( ) ; try { JSONArray arr = new JSONArray ( result . getString ( Constants . ENABLED_OVERRIDES_ARGUMENTS ) ) ; for ( int x = 0 ; x < arr . length ( ) ; x ++ ) { args . add ( arr . get ( x ) ) ; } } catch ( Exception e ) { // ignore it.. this means the entry was null/corrupt } endpoint . setArguments ( args . toArray ( new Object [ 0 ] ) ) ; return endpoint ; }
This only gets half of the EnabledEndpoint from a JDBC ResultSet Getting the method for the override id requires an additional SQL query and needs to be called after the SQL connection is released
334
38
151,510
public Integer getOverrideIdForMethod ( String className , String methodName ) { Integer overrideId = null ; PreparedStatement query = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { query = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_OVERRIDE + " WHERE " + Constants . OVERRIDE_CLASS_NAME + " = ?" + " AND " + Constants . OVERRIDE_METHOD_NAME + " = ?" ) ; query . setString ( 1 , className ) ; query . setString ( 2 , methodName ) ; results = query . executeQuery ( ) ; if ( results . next ( ) ) { overrideId = results . getInt ( Constants . GENERIC_ID ) ; } } catch ( SQLException e ) { e . printStackTrace ( ) ; return null ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( query != null ) { query . close ( ) ; } } catch ( Exception e ) { } } return overrideId ; }
Gets an overrideID for a class name method name
255
11
151,511
public List < Client > findAllClients ( int profileId ) throws Exception { ArrayList < Client > clients = new ArrayList < Client > ( ) ; PreparedStatement query = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { query = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_CLIENT + " WHERE " + Constants . GENERIC_PROFILE_ID + " = ?" ) ; query . setInt ( 1 , profileId ) ; results = query . executeQuery ( ) ; while ( results . next ( ) ) { clients . add ( this . getClientFromResultSet ( results ) ) ; } } catch ( Exception e ) { throw e ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( query != null ) { query . close ( ) ; } } catch ( Exception e ) { } } return clients ; }
Return all Clients for a profile
219
7
151,512
public Client getClient ( int clientId ) throws Exception { Client client = null ; PreparedStatement statement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { String queryString = "SELECT * FROM " + Constants . DB_TABLE_CLIENT + " WHERE " + Constants . GENERIC_ID + " = ?" ; statement = sqlConnection . prepareStatement ( queryString ) ; statement . setInt ( 1 , clientId ) ; results = statement . executeQuery ( ) ; if ( results . next ( ) ) { client = this . getClientFromResultSet ( results ) ; } } catch ( Exception e ) { throw e ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } return client ; }
Returns a client object for a clientId
204
8
151,513
public Client findClient ( String clientUUID , Integer profileId ) throws Exception { Client client = null ; /* ERROR CODE: 500 WHEN TRYING TO DELETE A SERVER GROUP. THIS APPEARS TO BE BECAUSE CLIENT UUID IS NULL. */ /* CODE ADDED TO PREVENT NULL POINTERS. */ if ( clientUUID == null ) { clientUUID = "" ; } // first see if the clientUUID is actually a uuid.. it might be a friendlyName and need conversion /* A UUID IS A UNIVERSALLY UNIQUE IDENTIFIER. */ if ( clientUUID . compareTo ( Constants . PROFILE_CLIENT_DEFAULT_ID ) != 0 && ! clientUUID . matches ( "[\\w]{8}-[\\w]{4}-[\\w]{4}-[\\w]{4}-[\\w]{12}" ) ) { Client tmpClient = this . findClientFromFriendlyName ( profileId , clientUUID ) ; // if we can't find a client then fall back to the default ID if ( tmpClient == null ) { clientUUID = Constants . PROFILE_CLIENT_DEFAULT_ID ; } else { return tmpClient ; } } PreparedStatement statement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { String queryString = "SELECT * FROM " + Constants . DB_TABLE_CLIENT + " WHERE " + Constants . CLIENT_CLIENT_UUID + " = ?" ; if ( profileId != null ) { queryString += " AND " + Constants . GENERIC_PROFILE_ID + "=?" ; } statement = sqlConnection . prepareStatement ( queryString ) ; statement . setString ( 1 , clientUUID ) ; if ( profileId != null ) { statement . setInt ( 2 , profileId ) ; } results = statement . executeQuery ( ) ; if ( results . next ( ) ) { client = this . getClientFromResultSet ( results ) ; } } catch ( Exception e ) { throw e ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } return client ; }
Returns a Client object for a clientUUID and profileId
509
12
151,514
private Client getClientFromResultSet ( ResultSet result ) throws Exception { Client client = new Client ( ) ; client . setId ( result . getInt ( Constants . GENERIC_ID ) ) ; client . setUUID ( result . getString ( Constants . CLIENT_CLIENT_UUID ) ) ; client . setFriendlyName ( result . getString ( Constants . CLIENT_FRIENDLY_NAME ) ) ; client . setProfile ( ProfileService . getInstance ( ) . findProfile ( result . getInt ( Constants . GENERIC_PROFILE_ID ) ) ) ; client . setIsActive ( result . getBoolean ( Constants . CLIENT_IS_ACTIVE ) ) ; client . setActiveServerGroup ( result . getInt ( Constants . CLIENT_ACTIVESERVERGROUP ) ) ; return client ; }
Returns a client model from a ResultSet
183
8
151,515
public Client setFriendlyName ( int profileId , String clientUUID , String friendlyName ) throws Exception { // first see if this friendlyName is already in use Client client = this . findClientFromFriendlyName ( profileId , friendlyName ) ; if ( client != null && ! client . getUUID ( ) . equals ( clientUUID ) ) { throw new Exception ( "Friendly name already in use" ) ; } PreparedStatement statement = null ; int rowsAffected = 0 ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "UPDATE " + Constants . DB_TABLE_CLIENT + " SET " + Constants . CLIENT_FRIENDLY_NAME + " = ?" + " WHERE " + Constants . CLIENT_CLIENT_UUID + " = ?" + " AND " + Constants . GENERIC_PROFILE_ID + " = ?" ) ; statement . setString ( 1 , friendlyName ) ; statement . setString ( 2 , clientUUID ) ; statement . setInt ( 3 , profileId ) ; rowsAffected = statement . executeUpdate ( ) ; } catch ( Exception e ) { } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } if ( rowsAffected == 0 ) { return null ; } return this . findClient ( clientUUID , profileId ) ; }
Set a friendly name for a client
316
7
151,516
public void updateActive ( int profileId , String clientUUID , Boolean active ) throws Exception { PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "UPDATE " + Constants . DB_TABLE_CLIENT + " SET " + Constants . CLIENT_IS_ACTIVE + "= ?" + " WHERE " + Constants . GENERIC_CLIENT_UUID + "= ? " + " AND " + Constants . GENERIC_PROFILE_ID + "= ?" ) ; statement . setBoolean ( 1 , active ) ; statement . setString ( 2 , clientUUID ) ; statement . setInt ( 3 , profileId ) ; statement . executeUpdate ( ) ; } catch ( Exception e ) { // ok to swallow this.. just means there wasn't any } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
disables the current active id enables the new one selected
216
11
151,517
public void reset ( int profileId , String clientUUID ) throws Exception { PreparedStatement statement = null ; // TODO: need a better way to do this than brute force.. but the iterative approach is too slow try ( Connection sqlConnection = sqlService . getConnection ( ) ) { // first remove all enabled overrides with this client uuid String queryString = "DELETE FROM " + Constants . DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants . GENERIC_CLIENT_UUID + "= ? " + " AND " + Constants . GENERIC_PROFILE_ID + " = ?" ; statement = sqlConnection . prepareStatement ( queryString ) ; statement . setString ( 1 , clientUUID ) ; statement . setInt ( 2 , profileId ) ; statement . executeUpdate ( ) ; statement . close ( ) ; // clean up request response table for this uuid queryString = "UPDATE " + Constants . DB_TABLE_REQUEST_RESPONSE + " SET " + Constants . REQUEST_RESPONSE_CUSTOM_REQUEST + "=?, " + Constants . REQUEST_RESPONSE_CUSTOM_RESPONSE + "=?, " + Constants . REQUEST_RESPONSE_REPEAT_NUMBER + "=-1, " + Constants . REQUEST_RESPONSE_REQUEST_ENABLED + "=0, " + Constants . REQUEST_RESPONSE_RESPONSE_ENABLED + "=0 " + "WHERE " + Constants . GENERIC_CLIENT_UUID + "=? " + " AND " + Constants . GENERIC_PROFILE_ID + "=?" ; statement = sqlConnection . prepareStatement ( queryString ) ; statement . setString ( 1 , "" ) ; statement . setString ( 2 , "" ) ; statement . setString ( 3 , clientUUID ) ; statement . setInt ( 4 , profileId ) ; statement . executeUpdate ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } this . updateActive ( profileId , clientUUID , false ) ; }
Resets all override settings for the clientUUID and disables it
511
14
151,518
public String getProfileIdFromClientId ( int id ) { return ( String ) sqlService . getFromTable ( Constants . CLIENT_PROFILE_ID , Constants . GENERIC_ID , id , Constants . DB_TABLE_CLIENT ) ; }
gets the profile_name associated with a specific id
57
10
151,519
@ RequestMapping ( value = "/scripts" , method = RequestMethod . GET ) public String scriptView ( Model model ) throws Exception { return "script" ; }
Returns script view
35
3
151,520
@ RequestMapping ( value = "/api/scripts" , method = RequestMethod . GET ) public @ ResponseBody HashMap < String , Object > getScripts ( Model model , @ RequestParam ( required = false ) Integer type ) throws Exception { Script [ ] scripts = ScriptService . getInstance ( ) . getScripts ( type ) ; return Utils . getJQGridJSON ( scripts , "scripts" ) ; }
Returns all scripts
90
3
151,521
@ RequestMapping ( value = "/api/scripts" , method = RequestMethod . POST ) public @ ResponseBody Script addScript ( Model model , @ RequestParam ( required = true ) String name , @ RequestParam ( required = true ) String script ) throws Exception { return ScriptService . getInstance ( ) . addScript ( name , script ) ; }
Add a new script
74
4
151,522
@ RequestMapping ( value = "group" , method = RequestMethod . GET ) public String newGroupGet ( Model model ) { model . addAttribute ( "groups" , pathOverrideService . findAllGroups ( ) ) ; return "groups" ; }
Redirect to page
55
4
151,523
protected void createKeystore ( ) { java . security . cert . Certificate signingCert = null ; PrivateKey caPrivKey = null ; if ( _caCert == null || _caPrivKey == null ) { try { log . debug ( "Keystore or signing cert & keypair not found. Generating..." ) ; KeyPair caKeypair = getRSAKeyPair ( ) ; caPrivKey = caKeypair . getPrivate ( ) ; signingCert = CertificateCreator . createTypicalMasterCert ( caKeypair ) ; log . debug ( "Done generating signing cert" ) ; log . debug ( signingCert ) ; _ks . load ( null , _keystorepass ) ; _ks . setCertificateEntry ( _caCertAlias , signingCert ) ; _ks . setKeyEntry ( _caPrivKeyAlias , caPrivKey , _keypassword , new java . security . cert . Certificate [ ] { signingCert } ) ; File caKsFile = new File ( root , _caPrivateKeystore ) ; OutputStream os = new FileOutputStream ( caKsFile ) ; _ks . store ( os , _keystorepass ) ; log . debug ( "Wrote JKS keystore to: " + caKsFile . getAbsolutePath ( ) ) ; // also export a .cer that can be imported as a trusted root // to disable all warning dialogs for interception File signingCertFile = new File ( root , EXPORTED_CERT_NAME ) ; FileOutputStream cerOut = new FileOutputStream ( signingCertFile ) ; byte [ ] buf = signingCert . getEncoded ( ) ; log . debug ( "Wrote signing cert to: " + signingCertFile . getAbsolutePath ( ) ) ; cerOut . write ( buf ) ; cerOut . flush ( ) ; cerOut . close ( ) ; _caCert = ( X509Certificate ) signingCert ; _caPrivKey = caPrivKey ; } catch ( Exception e ) { log . error ( "Fatal error creating/storing keystore or signing cert." , e ) ; throw new Error ( e ) ; } } else { log . debug ( "Successfully loaded keystore." ) ; log . debug ( _caCert ) ; } }
Creates writes and loads a new keystore and CA root certificate .
481
14
151,524
public synchronized void addCertAndPrivateKey ( String hostname , final X509Certificate cert , final PrivateKey privKey ) throws KeyStoreException , CertificateException , NoSuchAlgorithmException { // String alias = ThumbprintUtil.getThumbprint(cert); _ks . deleteEntry ( hostname ) ; _ks . setCertificateEntry ( hostname , cert ) ; _ks . setKeyEntry ( hostname , privKey , _keypassword , new java . security . cert . Certificate [ ] { cert } ) ; if ( persistImmediately ) { persist ( ) ; } }
Stores a new certificate and its associated private key in the keystore .
126
15
151,525
public synchronized X509Certificate getCertificateByHostname ( final String hostname ) throws KeyStoreException , CertificateParsingException , InvalidKeyException , CertificateExpiredException , CertificateNotYetValidException , SignatureException , CertificateException , NoSuchAlgorithmException , NoSuchProviderException , UnrecoverableKeyException { String alias = _subjectMap . get ( getSubjectForHostname ( hostname ) ) ; if ( alias != null ) { return ( X509Certificate ) _ks . getCertificate ( alias ) ; } return getMappedCertificateForHostname ( hostname ) ; }
Returns the aliased certificate . Certificates are aliased by their hostname .
128
17
151,526
public synchronized X509Certificate getMappedCertificate ( final X509Certificate cert ) throws CertificateEncodingException , InvalidKeyException , CertificateException , CertificateNotYetValidException , NoSuchAlgorithmException , NoSuchProviderException , SignatureException , KeyStoreException , UnrecoverableKeyException { String thumbprint = ThumbprintUtil . getThumbprint ( cert ) ; String mappedCertThumbprint = _certMap . get ( thumbprint ) ; if ( mappedCertThumbprint == null ) { // Check if we've already mapped this public key from a KeyValue PublicKey mappedPk = getMappedPublicKey ( cert . getPublicKey ( ) ) ; PrivateKey privKey ; if ( mappedPk == null ) { PublicKey pk = cert . getPublicKey ( ) ; String algo = pk . getAlgorithm ( ) ; KeyPair kp ; if ( algo . equals ( "RSA" ) ) { kp = getRSAKeyPair ( ) ; } else if ( algo . equals ( "DSA" ) ) { kp = getDSAKeyPair ( ) ; } else { throw new InvalidKeyException ( "Key algorithm " + algo + " not supported." ) ; } mappedPk = kp . getPublic ( ) ; privKey = kp . getPrivate ( ) ; mapPublicKeys ( cert . getPublicKey ( ) , mappedPk ) ; } else { privKey = getPrivateKey ( mappedPk ) ; } X509Certificate replacementCert = CertificateCreator . mitmDuplicateCertificate ( cert , mappedPk , getSigningCert ( ) , getSigningPrivateKey ( ) ) ; addCertAndPrivateKey ( null , replacementCert , privKey ) ; mappedCertThumbprint = ThumbprintUtil . getThumbprint ( replacementCert ) ; _certMap . put ( thumbprint , mappedCertThumbprint ) ; _certMap . put ( mappedCertThumbprint , thumbprint ) ; _subjectMap . put ( replacementCert . getSubjectX500Principal ( ) . getName ( ) , thumbprint ) ; if ( persistImmediately ) { persist ( ) ; } return replacementCert ; } return getCertificateByAlias ( mappedCertThumbprint ) ; }
This method returns the duplicated certificate mapped to the passed in cert or creates and returns one if no mapping has yet been performed . If a naked public key has already been mapped that matches the key in the cert the already mapped keypair will be reused for the mapped cert .
492
55
151,527
public X509Certificate getMappedCertificateForHostname ( String hostname ) throws CertificateParsingException , InvalidKeyException , CertificateExpiredException , CertificateNotYetValidException , SignatureException , CertificateException , NoSuchAlgorithmException , NoSuchProviderException , KeyStoreException , UnrecoverableKeyException { String subject = getSubjectForHostname ( hostname ) ; String thumbprint = _subjectMap . get ( subject ) ; if ( thumbprint == null ) { KeyPair kp = getRSAKeyPair ( ) ; X509Certificate newCert = CertificateCreator . generateStdSSLServerCertificate ( kp . getPublic ( ) , getSigningCert ( ) , getSigningPrivateKey ( ) , subject ) ; addCertAndPrivateKey ( hostname , newCert , kp . getPrivate ( ) ) ; thumbprint = ThumbprintUtil . getThumbprint ( newCert ) ; _subjectMap . put ( subject , thumbprint ) ; if ( persistImmediately ) { persist ( ) ; } return newCert ; } return getCertificateByAlias ( thumbprint ) ; }
This method returns the mapped certificate for a hostname or generates a standard SSL server certificate issued by the CA to the supplied subject if no mapping has been created . This is not a true duplication just a shortcut method that is adequate for web browsers .
243
49
151,528
public synchronized PrivateKey getPrivateKeyForLocalCert ( final X509Certificate cert ) throws CertificateEncodingException , KeyStoreException , UnrecoverableKeyException , NoSuchAlgorithmException { String thumbprint = ThumbprintUtil . getThumbprint ( cert ) ; return ( PrivateKey ) _ks . getKey ( thumbprint , _keypassword ) ; }
For a cert we have generated return the private key .
79
11
151,529
public synchronized void mapPublicKeys ( final PublicKey original , final PublicKey substitute ) { _mappedPublicKeys . put ( original , substitute ) ; if ( persistImmediately ) { persistPublicKeyMap ( ) ; } }
Stores a public key mapping .
47
7
151,530
public Script getScript ( int id ) { PreparedStatement statement = null ; ResultSet results = null ; try ( Connection sqlConnection = SQLService . getInstance ( ) . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_SCRIPT + " WHERE id = ?" ) ; statement . setInt ( 1 , id ) ; results = statement . executeQuery ( ) ; if ( results . next ( ) ) { return scriptFromSQLResult ( results ) ; } } catch ( Exception e ) { } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } return null ; }
Get the script for a given ID
177
7
151,531
public Script [ ] getScripts ( Integer type ) { ArrayList < Script > returnData = new ArrayList <> ( ) ; PreparedStatement statement = null ; ResultSet results = null ; try ( Connection sqlConnection = SQLService . getInstance ( ) . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_SCRIPT + " ORDER BY " + Constants . GENERIC_ID ) ; if ( type != null ) { statement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_SCRIPT + " WHERE " + Constants . SCRIPT_TYPE + "= ?" + " ORDER BY " + Constants . GENERIC_ID ) ; statement . setInt ( 1 , type ) ; } logger . info ( "Query: {}" , statement ) ; results = statement . executeQuery ( ) ; while ( results . next ( ) ) { returnData . add ( scriptFromSQLResult ( results ) ) ; } } catch ( Exception e ) { } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } return returnData . toArray ( new Script [ 0 ] ) ; }
Return all scripts of a given type
296
7
151,532
public Script updateName ( int id , String name ) throws Exception { PreparedStatement statement = null ; try ( Connection sqlConnection = SQLService . getInstance ( ) . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "UPDATE " + Constants . DB_TABLE_SCRIPT + " SET " + Constants . SCRIPT_NAME + " = ? " + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; statement . setString ( 1 , name ) ; statement . setInt ( 2 , id ) ; statement . executeUpdate ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } return this . getScript ( id ) ; }
Update the name of a script
185
6
151,533
public void removeScript ( int id ) throws Exception { PreparedStatement statement = null ; try ( Connection sqlConnection = SQLService . getInstance ( ) . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "DELETE FROM " + Constants . DB_TABLE_SCRIPT + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; statement . setInt ( 1 , id ) ; statement . executeUpdate ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Remove script for a given ID
149
6
151,534
@ Override public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { final ServletRequest r1 = request ; chain . doFilter ( request , new HttpServletResponseWrapper ( ( HttpServletResponse ) response ) { @ SuppressWarnings ( "unchecked" ) public void setHeader ( String name , String value ) { ArrayList < String > headersToRemove = new ArrayList < String > ( ) ; if ( r1 . getAttribute ( "com.groupon.odo.removeHeaders" ) != null ) headersToRemove = ( ArrayList < String > ) r1 . getAttribute ( "com.groupon.odo.removeHeaders" ) ; boolean removeHeader = false ; // need to loop through removeHeaders to make things case insensitive for ( String headerToRemove : headersToRemove ) { if ( headerToRemove . toLowerCase ( ) . equals ( name . toLowerCase ( ) ) ) { removeHeader = true ; break ; } } if ( ! removeHeader ) { super . setHeader ( name , value ) ; } } } ) ; }
This looks at the servlet attributes to get the list of response headers to remove while the response object gets created by the servlet
247
26
151,535
public static int [ ] arrayFromStringOfIntegers ( String str ) throws IllegalArgumentException { StringTokenizer tokenizer = new StringTokenizer ( str , "," ) ; int n = tokenizer . countTokens ( ) ; int [ ] list = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { String token = tokenizer . nextToken ( ) ; list [ i ] = Integer . parseInt ( token ) ; } return list ; }
Split string of comma - delimited ints into an a int array
104
14
151,536
public static File copyResourceToLocalFile ( String sourceResource , String destFileName ) throws Exception { try { Resource keystoreFile = new ClassPathResource ( sourceResource ) ; InputStream in = keystoreFile . getInputStream ( ) ; File outKeyStoreFile = new File ( destFileName ) ; FileOutputStream fop = new FileOutputStream ( outKeyStoreFile ) ; byte [ ] buf = new byte [ 512 ] ; int num ; while ( ( num = in . read ( buf ) ) != - 1 ) { fop . write ( buf , 0 , num ) ; } fop . flush ( ) ; fop . close ( ) ; in . close ( ) ; return outKeyStoreFile ; } catch ( IOException ioe ) { throw new Exception ( "Could not copy keystore file: " + ioe . getMessage ( ) ) ; } }
Copies file from a resource to a local temp file
186
11
151,537
public static int getSystemPort ( String portIdentifier ) { int defaultPort = 0 ; if ( portIdentifier . compareTo ( Constants . SYS_API_PORT ) == 0 ) { defaultPort = Constants . DEFAULT_API_PORT ; } else if ( portIdentifier . compareTo ( Constants . SYS_DB_PORT ) == 0 ) { defaultPort = Constants . DEFAULT_DB_PORT ; } else if ( portIdentifier . compareTo ( Constants . SYS_FWD_PORT ) == 0 ) { defaultPort = Constants . DEFAULT_FWD_PORT ; } else if ( portIdentifier . compareTo ( Constants . SYS_HTTP_PORT ) == 0 ) { defaultPort = Constants . DEFAULT_HTTP_PORT ; } else if ( portIdentifier . compareTo ( Constants . SYS_HTTPS_PORT ) == 0 ) { defaultPort = Constants . DEFAULT_HTTPS_PORT ; } else { return defaultPort ; } String portStr = System . getenv ( portIdentifier ) ; return ( portStr == null || portStr . isEmpty ( ) ) ? defaultPort : Integer . valueOf ( portStr ) ; }
Returns the port as configured by the system variables fallback is the default port value
262
16
151,538
public static String getPublicIPAddress ( ) throws Exception { final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z" ; String ipAddr = null ; Enumeration e = NetworkInterface . getNetworkInterfaces ( ) ; while ( e . hasMoreElements ( ) ) { NetworkInterface n = ( NetworkInterface ) e . nextElement ( ) ; Enumeration ee = n . getInetAddresses ( ) ; while ( ee . hasMoreElements ( ) ) { InetAddress i = ( InetAddress ) ee . nextElement ( ) ; // Pick the first non loop back address if ( ( ! i . isLoopbackAddress ( ) && i . isSiteLocalAddress ( ) ) || i . getHostAddress ( ) . matches ( IPV4_REGEX ) ) { ipAddr = i . getHostAddress ( ) ; break ; } } if ( ipAddr != null ) { break ; } } return ipAddr ; }
This function returns the first external IP address encountered
271
9
151,539
public Configuration getConfiguration ( String name ) { Configuration [ ] values = getConfigurations ( name ) ; if ( values == null ) { return null ; } return values [ 0 ] ; }
Get the value for a particular configuration property
39
8
151,540
public Configuration [ ] getConfigurations ( String name ) { ArrayList < Configuration > valuesList = new ArrayList < Configuration > ( ) ; logger . info ( "Getting data for {}" , name ) ; PreparedStatement statement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { String queryString = "SELECT * FROM " + Constants . DB_TABLE_CONFIGURATION ; if ( name != null ) { queryString += " WHERE " + Constants . DB_TABLE_CONFIGURATION_NAME + "=?" ; } statement = sqlConnection . prepareStatement ( queryString ) ; if ( name != null ) { statement . setString ( 1 , name ) ; } results = statement . executeQuery ( ) ; while ( results . next ( ) ) { Configuration config = new Configuration ( ) ; config . setValue ( results . getString ( Constants . DB_TABLE_CONFIGURATION_VALUE ) ) ; config . setKey ( results . getString ( Constants . DB_TABLE_CONFIGURATION_NAME ) ) ; config . setId ( results . getInt ( Constants . GENERIC_ID ) ) ; logger . info ( "the configValue is = {}" , config . getValue ( ) ) ; valuesList . add ( config ) ; } } catch ( SQLException sqe ) { logger . info ( "Exception in sql" ) ; sqe . printStackTrace ( ) ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } if ( valuesList . size ( ) == 0 ) { return null ; } return valuesList . toArray ( new Configuration [ 0 ] ) ; }
Get the values for a particular configuration property
400
8
151,541
@ RequestMapping ( value = "api/edit/disableAll" , method = RequestMethod . POST ) public @ ResponseBody String disableAll ( Model model , int profileID , @ RequestParam ( defaultValue = Constants . PROFILE_CLIENT_DEFAULT_ID ) String clientUUID ) { editService . disableAll ( profileID , clientUUID ) ; return null ; }
Disables all the overrides for a specific profile
83
10
151,542
@ RequestMapping ( value = "api/edit/repeatNumber" , method = RequestMethod . POST ) public @ ResponseBody String updateRepeatNumber ( Model model , int newNum , int path_id , @ RequestParam ( defaultValue = Constants . PROFILE_CLIENT_DEFAULT_ID ) String clientUUID ) throws Exception { logger . info ( "want to update repeat number of path_id={}, to newNum={}" , path_id , newNum ) ; editService . updateRepeatNumber ( newNum , path_id , clientUUID ) ; return null ; }
Calls a method from editService to update the repeat number for a path
126
15
151,543
@ RequestMapping ( value = "api/edit/enable/custom" , method = RequestMethod . POST ) public @ ResponseBody String enableCustomResponse ( Model model , String custom , int path_id , @ RequestParam ( defaultValue = Constants . PROFILE_CLIENT_DEFAULT_ID ) String clientUUID ) throws Exception { if ( custom . equals ( "undefined" ) ) return null ; editService . enableCustomResponse ( custom , path_id , clientUUID ) ; return null ; }
Enables a custom response
110
5
151,544
@ RequestMapping ( value = "api/edit/disable" , method = RequestMethod . POST ) public @ ResponseBody String disableResponses ( Model model , int path_id , @ RequestParam ( defaultValue = Constants . PROFILE_CLIENT_DEFAULT_ID ) String clientUUID ) throws Exception { OverrideService . getInstance ( ) . disableAllOverrides ( path_id , clientUUID ) ; //TODO also need to disable custom override if there is one of those editService . removeCustomOverride ( path_id , clientUUID ) ; return null ; }
disables the responses for a given pathname and user id
129
12
151,545
public void startServer ( ) throws Exception { if ( ! externalDatabaseHost ) { try { this . port = Utils . getSystemPort ( Constants . SYS_DB_PORT ) ; server = Server . createTcpServer ( "-tcpPort" , String . valueOf ( port ) , "-tcpAllowOthers" ) . start ( ) ; } catch ( SQLException e ) { if ( e . toString ( ) . contains ( "java.net.UnknownHostException" ) ) { logger . error ( "Startup failure. Potential bug in OSX & Java7. Workaround: add name of local machine to '/etc/hosts.'" ) ; logger . error ( "Example: 127.0.0.1 MacBook" ) ; throw e ; } } } }
Only meant to be called once
169
6
151,546
public void stopServer ( ) throws Exception { if ( ! externalDatabaseHost ) { try ( Connection sqlConnection = getConnection ( ) ) { sqlConnection . prepareStatement ( "SHUTDOWN" ) . execute ( ) ; } catch ( Exception e ) { } try { server . stop ( ) ; } catch ( Exception e ) { } } }
Shutdown the server
72
4
151,547
public static SQLService getInstance ( ) throws Exception { if ( _instance == null ) { _instance = new SQLService ( ) ; _instance . startServer ( ) ; // default pool size is 20 // can be overriden by env variable int dbPool = 20 ; if ( Utils . getEnvironmentOptionValue ( Constants . SYS_DATABASE_POOL_SIZE ) != null ) { dbPool = Integer . valueOf ( Utils . getEnvironmentOptionValue ( Constants . SYS_DATABASE_POOL_SIZE ) ) ; } // initialize connection pool PoolProperties p = new PoolProperties ( ) ; String connectString = "jdbc:h2:tcp://" + _instance . databaseHost + ":" + String . valueOf ( _instance . port ) + "/" + _instance . databaseName + "/proxydb;MULTI_THREADED=true;AUTO_RECONNECT=TRUE;AUTOCOMMIT=ON" ; p . setUrl ( connectString ) ; p . setDriverClassName ( "org.h2.Driver" ) ; p . setUsername ( "sa" ) ; p . setJmxEnabled ( true ) ; p . setTestWhileIdle ( false ) ; p . setTestOnBorrow ( true ) ; p . setValidationQuery ( "SELECT 1" ) ; p . setTestOnReturn ( false ) ; p . setValidationInterval ( 5000 ) ; p . setTimeBetweenEvictionRunsMillis ( 30000 ) ; p . setMaxActive ( dbPool ) ; p . setInitialSize ( 5 ) ; p . setMaxWait ( 30000 ) ; p . setRemoveAbandonedTimeout ( 60 ) ; p . setMinEvictableIdleTimeMillis ( 30000 ) ; p . setMinIdle ( 10 ) ; p . setLogAbandoned ( true ) ; p . setRemoveAbandoned ( true ) ; _instance . datasource = new DataSource ( ) ; _instance . datasource . setPoolProperties ( p ) ; } return _instance ; }
Obtain instance of the SQL Service
463
7
151,548
public void updateSchema ( String migrationPath ) { try { logger . info ( "Updating schema... " ) ; int current_version = 0 ; // first check the current schema version HashMap < String , Object > configuration = getFirstResult ( "SELECT * FROM " + Constants . DB_TABLE_CONFIGURATION + " WHERE " + Constants . DB_TABLE_CONFIGURATION_NAME + " = \'" + Constants . DB_TABLE_CONFIGURATION_DATABASE_VERSION + "\'" ) ; if ( configuration == null ) { logger . info ( "Creating configuration table.." ) ; // create configuration table executeUpdate ( "CREATE TABLE " + Constants . DB_TABLE_CONFIGURATION + " (" + Constants . GENERIC_ID + " INTEGER IDENTITY," + Constants . DB_TABLE_CONFIGURATION_NAME + " VARCHAR(256)," + Constants . DB_TABLE_CONFIGURATION_VALUE + " VARCHAR(1024));" ) ; executeUpdate ( "INSERT INTO " + Constants . DB_TABLE_CONFIGURATION + "(" + Constants . DB_TABLE_CONFIGURATION_NAME + "," + Constants . DB_TABLE_CONFIGURATION_VALUE + ")" + " VALUES (\'" + Constants . DB_TABLE_CONFIGURATION_DATABASE_VERSION + "\', '0');" ) ; } else { logger . info ( "Getting current schema version.." ) ; // get current version current_version = new Integer ( configuration . get ( "VALUE" ) . toString ( ) ) ; logger . info ( "Current schema version is {}" , current_version ) ; } // loop through until we get up to the right schema version while ( current_version < Constants . DB_CURRENT_SCHEMA_VERSION ) { current_version ++ ; // look for a schema file for this version logger . info ( "Updating to schema version {}" , current_version ) ; String currentFile = migrationPath + "/schema." + current_version ; Resource migFile = new ClassPathResource ( currentFile ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( migFile . getInputStream ( ) ) ) ; String str ; while ( ( str = in . readLine ( ) ) != null ) { // execute each line if ( str . length ( ) > 0 ) { executeUpdate ( str ) ; } } in . close ( ) ; } // update the configuration table with the correct version executeUpdate ( "UPDATE " + Constants . DB_TABLE_CONFIGURATION + " SET " + Constants . DB_TABLE_CONFIGURATION_VALUE + "='" + current_version + "' WHERE " + Constants . DB_TABLE_CONFIGURATION_NAME + "='" + Constants . DB_TABLE_CONFIGURATION_DATABASE_VERSION + "';" ) ; } catch ( Exception e ) { logger . info ( "Error in executeUpdate" ) ; e . printStackTrace ( ) ; } }
Update database schema
678
3
151,549
public int executeUpdate ( String query ) throws Exception { int returnVal = 0 ; Statement queryStatement = null ; try ( Connection sqlConnection = getConnection ( ) ) { queryStatement = sqlConnection . createStatement ( ) ; returnVal = queryStatement . executeUpdate ( query ) ; } catch ( Exception e ) { } finally { try { if ( queryStatement != null ) { queryStatement . close ( ) ; } } catch ( Exception e ) { } } return returnVal ; }
Wrapped version of standard jdbc executeUpdate Pays attention to DB locked exception and waits up to 1s
100
23
151,550
public HashMap < String , Object > getFirstResult ( String query ) throws Exception { HashMap < String , Object > result = null ; Statement queryStatement = null ; ResultSet results = null ; try ( Connection sqlConnection = getConnection ( ) ) { queryStatement = sqlConnection . createStatement ( ) ; results = queryStatement . executeQuery ( query ) ; if ( results . next ( ) ) { result = new HashMap <> ( ) ; String [ ] columns = getColumnNames ( results . getMetaData ( ) ) ; for ( String column : columns ) { result . put ( column , results . getObject ( column ) ) ; } } } catch ( Exception e ) { } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( queryStatement != null ) { queryStatement . close ( ) ; } } catch ( Exception e ) { } } return result ; }
Gets the first row for a query
202
8
151,551
public Clob toClob ( String stringName , Connection sqlConnection ) { Clob clobName = null ; try { clobName = sqlConnection . createClob ( ) ; clobName . setString ( 1 , stringName ) ; } catch ( SQLException e ) { // TODO Auto-generated catch block logger . info ( "Unable to create clob object" ) ; e . printStackTrace ( ) ; } return clobName ; }
Converts the given string to a clob object
101
10
151,552
private String [ ] getColumnNames ( ResultSetMetaData rsmd ) throws Exception { ArrayList < String > names = new ArrayList < String > ( ) ; // Get result set meta data int numColumns = rsmd . getColumnCount ( ) ; // Get the column names; column indices start from 1 for ( int i = 1 ; i < numColumns + 1 ; i ++ ) { String columnName = rsmd . getColumnName ( i ) ; names . add ( columnName ) ; } return names . toArray ( new String [ 0 ] ) ; }
Gets all of the column names for a result meta data
124
12
151,553
public List < ServerRedirect > tableServers ( int clientId ) { List < ServerRedirect > servers = new ArrayList <> ( ) ; try { Client client = ClientService . getInstance ( ) . getClient ( clientId ) ; servers = tableServers ( client . getProfile ( ) . getId ( ) , client . getActiveServerGroup ( ) ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return servers ; }
Get the server redirects for a given clientId from the database
120
13
151,554
public List < ServerRedirect > tableServers ( int profileId , int serverGroupId ) { ArrayList < ServerRedirect > servers = new ArrayList <> ( ) ; PreparedStatement queryStatement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { queryStatement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_SERVERS + " WHERE " + Constants . GENERIC_PROFILE_ID + " = ?" + " AND " + Constants . SERVER_REDIRECT_GROUP_ID + " = ?" ) ; queryStatement . setInt ( 1 , profileId ) ; queryStatement . setInt ( 2 , serverGroupId ) ; results = queryStatement . executeQuery ( ) ; while ( results . next ( ) ) { ServerRedirect curServer = new ServerRedirect ( results . getInt ( Constants . GENERIC_ID ) , results . getString ( Constants . SERVER_REDIRECT_REGION ) , results . getString ( Constants . SERVER_REDIRECT_SRC_URL ) , results . getString ( Constants . SERVER_REDIRECT_DEST_URL ) , results . getString ( Constants . SERVER_REDIRECT_HOST_HEADER ) ) ; curServer . setProfileId ( profileId ) ; servers . add ( curServer ) ; } } catch ( SQLException e ) { e . printStackTrace ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( queryStatement != null ) { queryStatement . close ( ) ; } } catch ( Exception e ) { } } return servers ; }
Get the server redirects belonging to a server group
404
10
151,555
public List < ServerGroup > tableServerGroups ( int profileId ) { ArrayList < ServerGroup > serverGroups = new ArrayList <> ( ) ; PreparedStatement queryStatement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { queryStatement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_SERVER_GROUPS + " WHERE " + Constants . GENERIC_PROFILE_ID + " = ? " + "ORDER BY " + Constants . GENERIC_NAME ) ; queryStatement . setInt ( 1 , profileId ) ; results = queryStatement . executeQuery ( ) ; while ( results . next ( ) ) { ServerGroup curServerGroup = new ServerGroup ( results . getInt ( Constants . GENERIC_ID ) , results . getString ( Constants . GENERIC_NAME ) , results . getInt ( Constants . GENERIC_PROFILE_ID ) ) ; curServerGroup . setServers ( tableServers ( profileId , curServerGroup . getId ( ) ) ) ; serverGroups . add ( curServerGroup ) ; } } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( queryStatement != null ) { queryStatement . close ( ) ; } } catch ( Exception e ) { } } return serverGroups ; }
Return all server groups for a profile
336
7
151,556
public ServerRedirect getRedirect ( int id ) throws Exception { PreparedStatement queryStatement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { queryStatement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_SERVERS + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; queryStatement . setInt ( 1 , id ) ; results = queryStatement . executeQuery ( ) ; if ( results . next ( ) ) { ServerRedirect curServer = new ServerRedirect ( results . getInt ( Constants . GENERIC_ID ) , results . getString ( Constants . SERVER_REDIRECT_REGION ) , results . getString ( Constants . SERVER_REDIRECT_SRC_URL ) , results . getString ( Constants . SERVER_REDIRECT_DEST_URL ) , results . getString ( Constants . SERVER_REDIRECT_HOST_HEADER ) ) ; curServer . setProfileId ( results . getInt ( Constants . GENERIC_PROFILE_ID ) ) ; return curServer ; } logger . info ( "Did not find the ID: {}" , id ) ; } catch ( SQLException e ) { throw e ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( queryStatement != null ) { queryStatement . close ( ) ; } } catch ( Exception e ) { } } return null ; }
Returns redirect information for the given ID
346
7
151,557
public ServerGroup getServerGroup ( int id , int profileId ) throws Exception { PreparedStatement queryStatement = null ; ResultSet results = null ; if ( id == 0 ) { return new ServerGroup ( 0 , "Default" , profileId ) ; } try ( Connection sqlConnection = sqlService . getConnection ( ) ) { queryStatement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_SERVER_GROUPS + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; queryStatement . setInt ( 1 , id ) ; results = queryStatement . executeQuery ( ) ; if ( results . next ( ) ) { ServerGroup curGroup = new ServerGroup ( results . getInt ( Constants . GENERIC_ID ) , results . getString ( Constants . GENERIC_NAME ) , results . getInt ( Constants . GENERIC_PROFILE_ID ) ) ; return curGroup ; } logger . info ( "Did not find the ID: {}" , id ) ; } catch ( SQLException e ) { throw e ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( queryStatement != null ) { queryStatement . close ( ) ; } } catch ( Exception e ) { } } return null ; }
Returns server group by ID
298
5
151,558
public int addServerRedirectToProfile ( String region , String srcUrl , String destUrl , String hostHeader , int profileId , int clientId ) throws Exception { int serverId = - 1 ; try { Client client = ClientService . getInstance ( ) . getClient ( clientId ) ; serverId = addServerRedirect ( region , srcUrl , destUrl , hostHeader , profileId , client . getActiveServerGroup ( ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return serverId ; }
Add server redirect to a profile using current active ServerGroup
116
11
151,559
public int addServerRedirect ( String region , String srcUrl , String destUrl , String hostHeader , int profileId , int groupId ) throws Exception { int serverId = - 1 ; PreparedStatement statement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "INSERT INTO " + Constants . DB_TABLE_SERVERS + "(" + Constants . SERVER_REDIRECT_REGION + "," + Constants . SERVER_REDIRECT_SRC_URL + "," + Constants . SERVER_REDIRECT_DEST_URL + "," + Constants . SERVER_REDIRECT_HOST_HEADER + "," + Constants . SERVER_REDIRECT_PROFILE_ID + "," + Constants . SERVER_REDIRECT_GROUP_ID + ")" + " VALUES (?, ?, ?, ?, ?, ?);" , PreparedStatement . RETURN_GENERATED_KEYS ) ; statement . setString ( 1 , region ) ; statement . setString ( 2 , srcUrl ) ; statement . setString ( 3 , destUrl ) ; statement . setString ( 4 , hostHeader ) ; statement . setInt ( 5 , profileId ) ; statement . setInt ( 6 , groupId ) ; statement . executeUpdate ( ) ; results = statement . getGeneratedKeys ( ) ; if ( results . next ( ) ) { serverId = results . getInt ( 1 ) ; } else { // something went wrong throw new Exception ( "Could not add path" ) ; } } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } return serverId ; }
Add server redirect to a profile
431
6
151,560
public int addServerGroup ( String groupName , int profileId ) throws Exception { int groupId = - 1 ; PreparedStatement statement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "INSERT INTO " + Constants . DB_TABLE_SERVER_GROUPS + "(" + Constants . GENERIC_NAME + "," + Constants . GENERIC_PROFILE_ID + ")" + " VALUES (?, ?);" , PreparedStatement . RETURN_GENERATED_KEYS ) ; statement . setString ( 1 , groupName ) ; statement . setInt ( 2 , profileId ) ; statement . executeUpdate ( ) ; results = statement . getGeneratedKeys ( ) ; if ( results . next ( ) ) { groupId = results . getInt ( 1 ) ; } else { // something went wrong throw new Exception ( "Could not add group" ) ; } } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } return groupId ; }
Add a new server group
289
5
151,561
public void setGroupName ( String name , int id ) { PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "UPDATE " + Constants . DB_TABLE_SERVER_GROUPS + " SET " + Constants . GENERIC_NAME + " = ?" + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; statement . setString ( 1 , name ) ; statement . setInt ( 2 , id ) ; statement . executeUpdate ( ) ; statement . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Set the group name
176
4
151,562
public void setSourceUrl ( String newUrl , int id ) { PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "UPDATE " + Constants . DB_TABLE_SERVERS + " SET " + Constants . SERVER_REDIRECT_SRC_URL + " = ?" + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; statement . setString ( 1 , newUrl ) ; statement . setInt ( 2 , id ) ; statement . executeUpdate ( ) ; statement . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Set source url for a server
180
6
151,563
public void deleteRedirect ( int id ) { try { sqlService . executeUpdate ( "DELETE FROM " + Constants . DB_TABLE_SERVERS + " WHERE " + Constants . GENERIC_ID + " = " + id + ";" ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
Deletes a redirect by id
76
6
151,564
public void deleteServerGroup ( int id ) { try { sqlService . executeUpdate ( "DELETE FROM " + Constants . DB_TABLE_SERVER_GROUPS + " WHERE " + Constants . GENERIC_ID + " = " + id + ";" ) ; sqlService . executeUpdate ( "DELETE FROM " + Constants . DB_TABLE_SERVERS + " WHERE " + Constants . SERVER_REDIRECT_GROUP_ID + " = " + id ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
Delete a server group by id
128
6
151,565
public Profile [ ] getProfilesForServerName ( String serverName ) throws Exception { int profileId = - 1 ; ArrayList < Profile > returnProfiles = new ArrayList < Profile > ( ) ; PreparedStatement queryStatement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { queryStatement = sqlConnection . prepareStatement ( "SELECT " + Constants . GENERIC_PROFILE_ID + " FROM " + Constants . DB_TABLE_SERVERS + " WHERE " + Constants . SERVER_REDIRECT_SRC_URL + " = ? GROUP BY " + Constants . GENERIC_PROFILE_ID ) ; queryStatement . setString ( 1 , serverName ) ; results = queryStatement . executeQuery ( ) ; while ( results . next ( ) ) { profileId = results . getInt ( Constants . GENERIC_PROFILE_ID ) ; Profile profile = ProfileService . getInstance ( ) . findProfile ( profileId ) ; returnProfiles . add ( profile ) ; } } catch ( SQLException e ) { throw e ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( queryStatement != null ) { queryStatement . close ( ) ; } } catch ( Exception e ) { } } if ( returnProfiles . size ( ) == 0 ) { return null ; } return returnProfiles . toArray ( new Profile [ 0 ] ) ; }
This returns all profiles associated with a server name
330
9
151,566
public static PluginManager getInstance ( ) { if ( _instance == null ) { _instance = new PluginManager ( ) ; _instance . classInformation = new HashMap < String , ClassInformation > ( ) ; _instance . methodInformation = new HashMap < String , com . groupon . odo . proxylib . models . Method > ( ) ; _instance . jarInformation = new ArrayList < String > ( ) ; if ( _instance . proxyLibPath == null ) { //Get the System Classloader ClassLoader sysClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; //Get the URLs URL [ ] urls = ( ( URLClassLoader ) sysClassLoader ) . getURLs ( ) ; for ( int i = 0 ; i < urls . length ; i ++ ) { if ( urls [ i ] . getFile ( ) . contains ( "proxylib" ) ) { // store the path to the proxylib _instance . proxyLibPath = urls [ i ] . getFile ( ) ; break ; } } } _instance . initializePlugins ( ) ; } return _instance ; }
Gets the current instance of plugin manager
244
8
151,567
public void identifyClasses ( final String pluginDirectory ) throws Exception { methodInformation . clear ( ) ; jarInformation . clear ( ) ; try { new FileTraversal ( ) { public void onDirectory ( final File d ) { } public void onFile ( final File f ) { try { // loads class files if ( f . getName ( ) . endsWith ( ".class" ) ) { // get the class name for this path String className = f . getAbsolutePath ( ) ; className = className . replace ( pluginDirectory , "" ) ; className = getClassNameFromPath ( className ) ; logger . info ( "Storing plugin information: {}, {}" , className , f . getName ( ) ) ; ClassInformation classInfo = new ClassInformation ( ) ; classInfo . pluginPath = pluginDirectory ; classInformation . put ( className , classInfo ) ; } else if ( f . getName ( ) . endsWith ( ".jar" ) ) { // loads JAR packages // open up jar and discover files // look for anything with /proxy/ in it // this may discover things we don't need but that is OK try { jarInformation . add ( f . getAbsolutePath ( ) ) ; JarFile jarFile = new JarFile ( f ) ; Enumeration < ? > enumer = jarFile . entries ( ) ; // Use the Plugin-Name manifest entry to match with the provided pluginName String pluginPackageName = jarFile . getManifest ( ) . getMainAttributes ( ) . getValue ( "plugin-package" ) ; if ( pluginPackageName == null ) { return ; } while ( enumer . hasMoreElements ( ) ) { Object element = enumer . nextElement ( ) ; String elementName = element . toString ( ) ; if ( ! elementName . endsWith ( ".class" ) ) { continue ; } String className = getClassNameFromPath ( elementName ) ; if ( className . contains ( pluginPackageName ) ) { logger . info ( "Storing plugin information: {}, {}" , className , f . getAbsolutePath ( ) ) ; ClassInformation classInfo = new ClassInformation ( ) ; classInfo . pluginPath = f . getAbsolutePath ( ) ; classInformation . put ( className , classInfo ) ; } } } catch ( Exception e ) { } } } catch ( Exception e ) { logger . warn ( "Exception caught: {}, {}" , e . getMessage ( ) , e . getCause ( ) ) ; } } } . traverse ( new File ( pluginDirectory ) ) ; } catch ( IOException e ) { throw new Exception ( "Could not identify all plugins: " + e . getMessage ( ) ) ; } }
This loads plugin file information into a hash for lazy loading later on
580
13
151,568
private String getClassNameFromPath ( String path ) { String className = path . replace ( ".class" , "" ) ; // for *nix if ( className . startsWith ( "/" ) ) { className = className . substring ( 1 , className . length ( ) ) ; } className = className . replace ( "/" , "." ) ; // for windows if ( className . startsWith ( "\\" ) ) { className = className . substring ( 1 , className . length ( ) ) ; } className = className . replace ( "\\" , "." ) ; return className ; }
Create a classname from a given path
138
8
151,569
public void loadClass ( String className ) throws Exception { ClassInformation classInfo = classInformation . get ( className ) ; logger . info ( "Loading plugin.: {}, {}" , className , classInfo . pluginPath ) ; // get URL for proxylib // need to load this also otherwise the annotations cannot be found later on File libFile = new File ( proxyLibPath ) ; URL libUrl = libFile . toURI ( ) . toURL ( ) ; // store the last modified time of the plugin File pluginDirectoryFile = new File ( classInfo . pluginPath ) ; classInfo . lastModified = pluginDirectoryFile . lastModified ( ) ; // load the plugin directory URL classURL = new File ( classInfo . pluginPath ) . toURI ( ) . toURL ( ) ; URL [ ] urls = new URL [ ] { classURL } ; URLClassLoader child = new URLClassLoader ( urls , this . getClass ( ) . getClassLoader ( ) ) ; // load the class Class < ? > cls = child . loadClass ( className ) ; // put loaded class into classInfo classInfo . loadedClass = cls ; classInfo . loaded = true ; classInformation . put ( className , classInfo ) ; logger . info ( "Loaded plugin: {}, {} method(s)" , cls . toString ( ) , cls . getDeclaredMethods ( ) . length ) ; }
Loads the specified class name and stores it in the hash
305
12
151,570
public void callFunction ( String className , String methodName , PluginArguments pluginArgs , Object ... args ) throws Exception { Class < ? > cls = getClass ( className ) ; ArrayList < Object > newArgs = new ArrayList <> ( ) ; newArgs . add ( pluginArgs ) ; com . groupon . odo . proxylib . models . Method m = preparePluginMethod ( newArgs , className , methodName , args ) ; m . getMethod ( ) . invoke ( cls , newArgs . toArray ( new Object [ 0 ] ) ) ; }
Calls the specified function with the specified arguments . This is used for v2 response overrides
125
19
151,571
private synchronized Class < ? > getClass ( String className ) throws Exception { // see if we need to invalidate the class ClassInformation classInfo = classInformation . get ( className ) ; File classFile = new File ( classInfo . pluginPath ) ; if ( classFile . lastModified ( ) > classInfo . lastModified ) { logger . info ( "Class {} has been modified, reloading" , className ) ; logger . info ( "Thread ID: {}" , Thread . currentThread ( ) . getId ( ) ) ; classInfo . loaded = false ; classInformation . put ( className , classInfo ) ; // also cleanup anything in methodInformation with this className so it gets reloaded Iterator < Map . Entry < String , com . groupon . odo . proxylib . models . Method > > iter = methodInformation . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry < String , com . groupon . odo . proxylib . models . Method > entry = iter . next ( ) ; if ( entry . getKey ( ) . startsWith ( className ) ) { iter . remove ( ) ; } } } if ( ! classInfo . loaded ) { loadClass ( className ) ; } return classInfo . loadedClass ; }
Obtain the class of a given className
282
9
151,572
public String [ ] getMethods ( String pluginClass ) throws Exception { ArrayList < String > methodNames = new ArrayList < String > ( ) ; Method [ ] methods = getClass ( pluginClass ) . getDeclaredMethods ( ) ; for ( Method method : methods ) { logger . info ( "Checking {}" , method . getName ( ) ) ; com . groupon . odo . proxylib . models . Method methodInfo = this . getMethod ( pluginClass , method . getName ( ) ) ; if ( methodInfo == null ) { continue ; } // check annotations Boolean matchesAnnotation = false ; if ( methodInfo . getMethodType ( ) . endsWith ( Constants . PLUGIN_RESPONSE_OVERRIDE_CLASS ) || methodInfo . getMethodType ( ) . endsWith ( Constants . PLUGIN_RESPONSE_OVERRIDE_V2_CLASS ) ) { matchesAnnotation = true ; } if ( ! methodNames . contains ( method . getName ( ) ) && matchesAnnotation ) { methodNames . add ( method . getName ( ) ) ; } } return methodNames . toArray ( new String [ 0 ] ) ; }
Returns a string array of the methods loaded for a class
257
11
151,573
public List < com . groupon . odo . proxylib . models . Method > getMethodsNotInGroup ( int groupId ) throws Exception { List < com . groupon . odo . proxylib . models . Method > allMethods = getAllMethods ( ) ; List < com . groupon . odo . proxylib . models . Method > methodsNotInGroup = new ArrayList < com . groupon . odo . proxylib . models . Method > ( ) ; List < com . groupon . odo . proxylib . models . Method > methodsInGroup = editService . getMethodsFromGroupId ( groupId , null ) ; for ( int i = 0 ; i < allMethods . size ( ) ; i ++ ) { boolean add = true ; String methodName = allMethods . get ( i ) . getMethodName ( ) ; String className = allMethods . get ( i ) . getClassName ( ) ; for ( int j = 0 ; j < methodsInGroup . size ( ) ; j ++ ) { if ( ( methodName . equals ( methodsInGroup . get ( j ) . getMethodName ( ) ) ) && ( className . equals ( methodsInGroup . get ( j ) . getClassName ( ) ) ) ) { add = false ; } } if ( add ) { methodsNotInGroup . add ( allMethods . get ( i ) ) ; } } return methodsNotInGroup ; }
returns all methods not in the group
309
8
151,574
public Plugin [ ] getPlugins ( Boolean onlyValid ) { Configuration [ ] configurations = ConfigurationService . getInstance ( ) . getConfigurations ( Constants . DB_TABLE_CONFIGURATION_PLUGIN_PATH ) ; ArrayList < Plugin > plugins = new ArrayList < Plugin > ( ) ; if ( configurations == null ) { return new Plugin [ 0 ] ; } for ( Configuration config : configurations ) { Plugin plugin = new Plugin ( ) ; plugin . setId ( config . getId ( ) ) ; plugin . setPath ( config . getValue ( ) ) ; File path = new File ( plugin . getPath ( ) ) ; if ( path . isDirectory ( ) ) { plugin . setStatus ( Constants . PLUGIN_STATUS_VALID ) ; plugin . setStatusMessage ( "Valid" ) ; } else { plugin . setStatus ( Constants . PLUGIN_STATUS_NOT_DIRECTORY ) ; plugin . setStatusMessage ( "Path is not a directory" ) ; } if ( ! onlyValid || plugin . getStatus ( ) == Constants . PLUGIN_STATUS_VALID ) { plugins . add ( plugin ) ; } } return plugins . toArray ( new Plugin [ 0 ] ) ; }
Returns the data about all of the plugins that are set
267
11
151,575
public byte [ ] getResource ( String pluginName , String fileName ) throws Exception { // TODO: This is going to be slow.. future improvement is to cache the data instead of searching all jars for ( String jarFilename : jarInformation ) { JarFile jarFile = new JarFile ( new File ( jarFilename ) ) ; Enumeration < ? > enumer = jarFile . entries ( ) ; // Use the Plugin-Name manifest entry to match with the provided pluginName String jarPluginName = jarFile . getManifest ( ) . getMainAttributes ( ) . getValue ( "Plugin-Name" ) ; if ( ! jarPluginName . equals ( pluginName ) ) { continue ; } while ( enumer . hasMoreElements ( ) ) { Object element = enumer . nextElement ( ) ; String elementName = element . toString ( ) ; // Skip items in the jar that don't start with "resources/" if ( ! elementName . startsWith ( "resources/" ) ) { continue ; } elementName = elementName . replace ( "resources/" , "" ) ; if ( elementName . equals ( fileName ) ) { // get the file from the jar ZipEntry ze = jarFile . getEntry ( element . toString ( ) ) ; InputStream fileStream = jarFile . getInputStream ( ze ) ; byte [ ] data = new byte [ ( int ) ze . getSize ( ) ] ; DataInputStream dataIs = new DataInputStream ( fileStream ) ; dataIs . readFully ( data ) ; dataIs . close ( ) ; return data ; } } } throw new FileNotFoundException ( "Could not find resource" ) ; }
Gets a static resource from a plugin
350
8
151,576
public static boolean changeHost ( String hostName , boolean enable , boolean disable , boolean remove , boolean isEnabled , boolean exists ) throws Exception { // Open the file that is the first // command line parameter File hostsFile = new File ( "/etc/hosts" ) ; FileInputStream fstream = new FileInputStream ( "/etc/hosts" ) ; File outFile = null ; BufferedWriter bw = null ; // only do file output for destructive operations if ( ! exists && ! isEnabled ) { outFile = File . createTempFile ( "HostsEdit" , ".tmp" ) ; bw = new BufferedWriter ( new FileWriter ( outFile ) ) ; System . out . println ( "File name: " + outFile . getPath ( ) ) ; } // Get the object of DataInputStream DataInputStream in = new DataInputStream ( fstream ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( in ) ) ; String strLine ; boolean foundHost = false ; boolean hostEnabled = false ; /* * Group 1 - possible commented out host entry * Group 2 - destination address * Group 3 - host name * Group 4 - everything else */ Pattern pattern = Pattern . compile ( "\\s*(#?)\\s*([^\\s]+)\\s*([^\\s]+)(.*)" ) ; while ( ( strLine = br . readLine ( ) ) != null ) { Matcher matcher = pattern . matcher ( strLine ) ; // if there is a match to the pattern and the host name is the same as the one we want to set if ( matcher . find ( ) && matcher . group ( 3 ) . toLowerCase ( ) . compareTo ( hostName . toLowerCase ( ) ) == 0 ) { foundHost = true ; if ( remove ) { // skip this line altogether continue ; } else if ( enable ) { // we will disregard group 2 and just set it to 127.0.0.1 if ( ! exists && ! isEnabled ) bw . write ( "127.0.0.1 " + matcher . group ( 3 ) + matcher . group ( 4 ) ) ; } else if ( disable ) { if ( ! exists && ! isEnabled ) bw . write ( "# " + matcher . group ( 2 ) + " " + matcher . group ( 3 ) + matcher . group ( 4 ) ) ; } else if ( isEnabled && matcher . group ( 1 ) . compareTo ( "" ) == 0 ) { // host exists and there is no # before it hostEnabled = true ; } } else { // just write the line back out if ( ! exists && ! isEnabled ) bw . write ( strLine ) ; } if ( ! exists && ! isEnabled ) bw . write ( ' ' ) ; } // if we didn't find the host in the file but need to enable it if ( ! foundHost && enable ) { // write a new host entry if ( ! exists && ! isEnabled ) bw . write ( "127.0.0.1 " + hostName + ' ' ) ; } // Close the input stream in . close ( ) ; if ( ! exists && ! isEnabled ) { bw . close ( ) ; outFile . renameTo ( hostsFile ) ; } // return false if the host wasn't found if ( exists && ! foundHost ) return false ; // return false if the host wasn't enabled if ( isEnabled && ! hostEnabled ) return false ; return true ; }
Only one boolean param should be true at a time for this function to return the proper results
741
18
151,577
public static String getByteArrayDataAsString ( String contentEncoding , byte [ ] bytes ) { ByteArrayOutputStream byteout = null ; if ( contentEncoding != null && contentEncoding . equals ( "gzip" ) ) { // GZIP ByteArrayInputStream bytein = null ; GZIPInputStream zis = null ; try { bytein = new ByteArrayInputStream ( bytes ) ; zis = new GZIPInputStream ( bytein ) ; byteout = new ByteArrayOutputStream ( ) ; int res = 0 ; byte buf [ ] = new byte [ 1024 ] ; while ( res >= 0 ) { res = zis . read ( buf , 0 , buf . length ) ; if ( res > 0 ) { byteout . write ( buf , 0 , res ) ; } } zis . close ( ) ; bytein . close ( ) ; byteout . close ( ) ; return byteout . toString ( ) ; } catch ( Exception e ) { // No action to take } } else if ( contentEncoding != null && contentEncoding . equals ( "deflate" ) ) { try { // DEFLATE byte [ ] buffer = new byte [ 1024 ] ; Inflater decompresser = new Inflater ( ) ; byteout = new ByteArrayOutputStream ( ) ; decompresser . setInput ( bytes ) ; while ( ! decompresser . finished ( ) ) { int count = decompresser . inflate ( buffer ) ; byteout . write ( buffer , 0 , count ) ; } byteout . close ( ) ; decompresser . end ( ) ; return byteout . toString ( ) ; } catch ( Exception e ) { // No action to take } } return new String ( bytes ) ; }
Decodes stream data based on content encoding
375
8
151,578
@ SuppressWarnings ( "deprecation" ) @ RequestMapping ( value = "/api/backup" , method = RequestMethod . GET ) public @ ResponseBody String getBackup ( Model model , HttpServletResponse response ) throws Exception { response . addHeader ( "Content-Disposition" , "attachment; filename=backup.json" ) ; response . setContentType ( "application/json" ) ; Backup backup = BackupService . getInstance ( ) . getBackupData ( ) ; ObjectMapper objectMapper = new ObjectMapper ( ) ; ObjectWriter writer = objectMapper . writerWithDefaultPrettyPrinter ( ) ; return writer . withView ( ViewFilters . Default . class ) . writeValueAsString ( backup ) ; }
Get all backup data
167
4
151,579
@ RequestMapping ( value = "/api/backup" , method = RequestMethod . POST ) public @ ResponseBody Backup processBackup ( @ RequestParam ( "fileData" ) MultipartFile fileData ) throws Exception { // Method taken from: http://spring.io/guides/gs/uploading-files/ if ( ! fileData . isEmpty ( ) ) { try { byte [ ] bytes = fileData . getBytes ( ) ; BufferedOutputStream stream = new BufferedOutputStream ( new FileOutputStream ( new File ( "backup-uploaded.json" ) ) ) ; stream . write ( bytes ) ; stream . close ( ) ; } catch ( Exception e ) { } } File f = new File ( "backup-uploaded.json" ) ; BackupService . getInstance ( ) . restoreBackupData ( new FileInputStream ( f ) ) ; return BackupService . getInstance ( ) . getBackupData ( ) ; }
Restore backup data
208
4
151,580
public static void enableHost ( String hostName ) throws Exception { Registry myRegistry = LocateRegistry . getRegistry ( "127.0.0.1" , port ) ; com . groupon . odo . proxylib . hostsedit . rmi . Message impl = ( com . groupon . odo . proxylib . hostsedit . rmi . Message ) myRegistry . lookup ( SERVICE_NAME ) ; impl . enableHost ( hostName ) ; }
Enable a host
103
3
151,581
public static boolean isAvailable ( ) throws Exception { try { Registry myRegistry = LocateRegistry . getRegistry ( "127.0.0.1" , port ) ; com . groupon . odo . proxylib . hostsedit . rmi . Message impl = ( com . groupon . odo . proxylib . hostsedit . rmi . Message ) myRegistry . lookup ( SERVICE_NAME ) ; return true ; } catch ( Exception e ) { return false ; } }
Returns whether or not the host editor service is available
107
10
151,582
protected String getContextPath ( ) { if ( context != null ) return context ; if ( get ( "context_path" ) == null ) { throw new ViewException ( "context_path missing - red alarm!" ) ; } return get ( "context_path" ) . toString ( ) ; }
Returns this applications context path .
64
6
151,583
protected void process ( String text , Map params , Writer writer ) { try { Template t = new Template ( "temp" , new StringReader ( text ) , FreeMarkerTL . getEnvironment ( ) . getConfiguration ( ) ) ; t . process ( params , writer ) ; } catch ( Exception e ) { throw new ViewException ( e ) ; } }
Processes text as a FreeMarker template . Usually used to process an inner body of a tag .
75
21
151,584
protected Map getAllVariables ( ) { try { Iterator names = FreeMarkerTL . getEnvironment ( ) . getKnownVariableNames ( ) . iterator ( ) ; Map vars = new HashMap ( ) ; while ( names . hasNext ( ) ) { Object name = names . next ( ) ; vars . put ( name , get ( name . toString ( ) ) ) ; } return vars ; } catch ( Exception e ) { throw new ViewException ( e ) ; } }
Returns a map of all variables in scope .
105
9
151,585
@ Value ( "${org.apereo.portal.portlets.favorites.MarketplaceFunctionalName:null}" ) public void setMarketplaceFName ( String marketplaceFunctionalName ) { // interpret null, non-text-having, or literal "null" as // signaling lack of Marketplace functional name. if ( ! StringUtils . hasText ( marketplaceFunctionalName ) || "null" . equalsIgnoreCase ( marketplaceFunctionalName ) ) { marketplaceFunctionalName = null ; } this . marketplaceFName = marketplaceFunctionalName ; }
Configures FavoritesController to include a Marketplace portlet functional name in the Model which ultimately signals and enables the View to include convenient link to Marketplace for user to add new favorites .
121
36
151,586
@ EventMapping ( SearchConstants . SEARCH_RESULTS_QNAME_STRING ) public void handleSearchResult ( EventRequest request ) { // UP-3887 Design flaw. Both the searchLauncher portlet instance and the search portlet // instance receive // searchRequest and searchResult events because they are in the same portlet code base (to // share // autosuggest_handler.jsp and because we have to calculate the search portlet url for the // ajax call) // and share the portlet.xml which defines the event handling behavior. // If this instance is the searchLauncher, ignore the searchResult. The search was submitted // to the search // portlet instance. final String searchLaunchFname = request . getPreferences ( ) . getValue ( SEARCH_LAUNCH_FNAME , null ) ; if ( searchLaunchFname != null ) { // Noisy in debug mode so commenting out debug message // logger.debug("SearchLauncher does not process SearchResponse events so discarding // message"); return ; } final Event event = request . getEvent ( ) ; final SearchResults portletSearchResults = ( SearchResults ) event . getValue ( ) ; // get the existing portal search result from the session and append // the results for this event final String queryId = portletSearchResults . getQueryId ( ) ; final PortalSearchResults results = this . getPortalSearchResults ( request , queryId ) ; if ( results == null ) { this . logger . warn ( "No PortalSearchResults found for queryId {}, ignoring search results from {}" , queryId , getSearchResultsSource ( portletSearchResults ) ) ; return ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "For queryId {}, adding {} search results from {}" , queryId , portletSearchResults . getSearchResult ( ) . size ( ) , getSearchResultsSource ( portletSearchResults ) ) ; } final String windowId = portletSearchResults . getWindowId ( ) ; final HttpServletRequest httpServletRequest = this . portalRequestUtils . getPortletHttpRequest ( request ) ; final IPortletWindowId portletWindowId = this . portletWindowRegistry . getPortletWindowId ( httpServletRequest , windowId ) ; // Add the other portlet's results to the main search results object this . addSearchResults ( portletSearchResults , results , httpServletRequest , portletWindowId ) ; }
Handles all the SearchResults events coming back from portlets
529
12
151,587
@ RequestMapping public ModelAndView showSearchForm ( RenderRequest request , RenderResponse response ) { final Map < String , Object > model = new HashMap <> ( ) ; String viewName ; // Determine if the new REST search should be used if ( isRestSearch ( request ) ) { viewName = "/jsp/Search/searchRest" ; } else { // Determine if this portlet displays the search launch view or regular search view. final boolean isMobile = isMobile ( request ) ; viewName = isMobile ? "/jsp/Search/mobileSearch" : "/jsp/Search/search" ; } // If this search portlet is configured to be the searchLauncher, calculate the URLs to the // indicated // search portlet. PortletPreferences prefs = request . getPreferences ( ) ; final String searchLaunchFname = prefs . getValue ( SEARCH_LAUNCH_FNAME , null ) ; if ( searchLaunchFname != null ) { model . put ( "searchLaunchUrl" , calculateSearchLaunchUrl ( request , response ) ) ; model . put ( "autocompleteUrl" , calculateAutocompleteResourceUrl ( request , response ) ) ; viewName = "/jsp/Search/searchLauncher" ; } return new ModelAndView ( viewName , model ) ; }
Display a search form
283
4
151,588
private String calculateSearchLaunchUrl ( RenderRequest request , RenderResponse response ) { final HttpServletRequest httpRequest = this . portalRequestUtils . getPortletHttpRequest ( request ) ; final IPortalUrlBuilder portalUrlBuilder = this . portalUrlProvider . getPortalUrlBuilderByPortletFName ( httpRequest , "search" , UrlType . ACTION ) ; return portalUrlBuilder . getUrlString ( ) ; }
Create an actionUrl for the indicated portlet The resource URL is for the ajax typing search results response .
93
23
151,589
@ ResourceMapping ( value = "retrieveSearchJSONResults" ) public ModelAndView showJSONSearchResults ( PortletRequest request ) { PortletPreferences prefs = request . getPreferences ( ) ; int maxTextLength = Integer . parseInt ( prefs . getValue ( AUTOCOMPLETE_MAX_TEXT_LENGTH_PREF_NAME , "180" ) ) ; final Map < String , Object > model = new HashMap <> ( ) ; List < AutocompleteResultsModel > results = new ArrayList <> ( ) ; final PortletSession session = request . getPortletSession ( ) ; String queryId = ( String ) session . getAttribute ( SEARCH_LAST_QUERY_ID ) ; if ( queryId != null ) { final PortalSearchResults portalSearchResults = this . getPortalSearchResults ( request , queryId ) ; if ( portalSearchResults != null ) { final ConcurrentMap < String , List < Tuple < SearchResult , String > > > resultsMap = portalSearchResults . getResults ( ) ; results = collateResultsForAutoCompleteResponse ( resultsMap , maxTextLength ) ; } } model . put ( "results" , results ) ; model . put ( "count" , results . size ( ) ) ; return new ModelAndView ( "json" , model ) ; }
Display AJAX autocomplete search results for the last query
289
12
151,590
private SortedMap < Integer , List < AutocompleteResultsModel > > getCleanedAndSortedMapResults ( ConcurrentMap < String , List < Tuple < SearchResult , String > > > resultsMap , int maxTextLength ) { SortedMap < Integer , List < AutocompleteResultsModel > > prioritizedResultsMap = createAutocompletePriorityMap ( ) ; // Put the results into the map of <priority,list> for ( Map . Entry < String , List < Tuple < SearchResult , String > > > entry : resultsMap . entrySet ( ) ) { for ( Tuple < SearchResult , String > tupleSearchResult : entry . getValue ( ) ) { SearchResult searchResult = tupleSearchResult . getFirst ( ) ; List < String > resultTypes = searchResult . getType ( ) ; // If the search result doesn't have a type defined, use the undefined result type. if ( resultTypes . size ( ) == 0 ) { resultTypes = UNDEFINED_SEARCH_RESULT_TYPE ; } for ( String category : resultTypes ) { // Exclude the result if it is a result type that's in the ignore list. if ( ! autocompleteIgnoreResultTypes . contains ( category ) ) { int priority = calculatePriorityFromCategory ( category ) ; AutocompleteResultsModel result = new AutocompleteResultsModel ( cleanAndTrimString ( searchResult . getTitle ( ) , maxTextLength ) , cleanAndTrimString ( searchResult . getSummary ( ) , maxTextLength ) , tupleSearchResult . getSecond ( ) , category ) ; prioritizedResultsMap . get ( priority ) . add ( result ) ; } } } } return prioritizedResultsMap ; }
Return the search results in a sorted map based on priority of the search result type
370
16
151,591
protected void modifySearchResultLinkTitle ( SearchResult result , final HttpServletRequest httpServletRequest , final IPortletWindowId portletWindowId ) { // If the title contains a SpEL expression, parse it with the portlet definition in the // evaluation context. if ( result . getType ( ) . size ( ) > 0 && result . getTitle ( ) . contains ( "${" ) ) { final IPortletWindow portletWindow = this . portletWindowRegistry . getPortletWindow ( httpServletRequest , portletWindowId ) ; final IPortletEntity portletEntity = portletWindow . getPortletEntity ( ) ; final IPortletDefinition portletDefinition = portletEntity . getPortletDefinition ( ) ; final SpELEnvironmentRoot spelEnvironment = new SpELEnvironmentRoot ( portletDefinition ) ; try { result . setTitle ( spELService . getValue ( result . getTitle ( ) , spelEnvironment ) ) ; } catch ( SpelParseException | SpelEvaluationException e ) { result . setTitle ( "(Invalid portlet title) - see details in log file" ) ; logger . error ( "Invalid Spring EL expression {} in search result portlet title" , result . getTitle ( ) , e ) ; } } }
Since portlets don t have access to the portlet definition to create a useful search results link using something like the portlet definition s title post - process the link text and for those portlets whose type is present in the substitution set replace the title with the portlet definition s title .
280
58
151,592
protected String getResultUrl ( HttpServletRequest httpServletRequest , SearchResult result , IPortletWindowId portletWindowId ) { final String externalUrl = result . getExternalUrl ( ) ; if ( externalUrl != null ) { return externalUrl ; } UrlType urlType = UrlType . RENDER ; final PortletUrl portletUrl = result . getPortletUrl ( ) ; if ( portletUrl != null ) { final PortletUrlType type = portletUrl . getType ( ) ; if ( type != null ) { switch ( type ) { case ACTION : { urlType = UrlType . ACTION ; break ; } default : case RENDER : { urlType = UrlType . RENDER ; break ; } case RESOURCE : { urlType = UrlType . RESOURCE ; break ; } } } } final IPortalUrlBuilder portalUrlBuilder = this . portalUrlProvider . getPortalUrlBuilderByPortletWindow ( httpServletRequest , portletWindowId , urlType ) ; final IPortletUrlBuilder portletUrlBuilder = portalUrlBuilder . getTargetedPortletUrlBuilder ( ) ; if ( portletUrl != null ) { final String portletMode = portletUrl . getPortletMode ( ) ; if ( portletMode != null ) { portletUrlBuilder . setPortletMode ( PortletUtils . getPortletMode ( portletMode ) ) ; } final String windowState = portletUrl . getWindowState ( ) ; if ( windowState != null ) { portletUrlBuilder . setWindowState ( PortletUtils . getWindowState ( windowState ) ) ; } for ( final PortletUrlParameter param : portletUrl . getParam ( ) ) { final String name = param . getName ( ) ; final List < String > values = param . getValue ( ) ; portletUrlBuilder . addParameter ( name , values . toArray ( new String [ values . size ( ) ] ) ) ; } } return portalUrlBuilder . getUrlString ( ) ; }
Determine the url for the search result
442
9
151,593
public String getParameterValue ( String name ) { NodeList parms = node . getChildNodes ( ) ; for ( int i = 0 ; i < parms . getLength ( ) ; i ++ ) { Element parm = ( Element ) parms . item ( i ) ; if ( parm . getTagName ( ) . equals ( Constants . ELM_PARAMETER ) ) { String parmName = parm . getAttribute ( Constants . ATT_NAME ) ; if ( parmName . equals ( name ) ) { return parm . getAttribute ( Constants . ATT_VALUE ) ; } } } // if we get here then neither the fragment nor the channel definition // provided this parameter return null ; }
Returns the value of an parameter or null if such a parameter is not defined on the underlying channel element .
156
21
151,594
@ RequestMapping ( value = USERINFO_ENDPOINT_URI , produces = USERINFO_CONTENT_TYPE , method = { RequestMethod . GET , RequestMethod . POST } ) public String userInfo ( HttpServletRequest request , @ RequestParam ( value = "claims" , required = false ) String claims , @ RequestParam ( value = "groups" , required = false ) String groups ) { final IPerson person = personManager . getPerson ( request ) ; return createToken ( person , claims , groups ) ; }
Obtain an OIDC Id token for the current user .
117
13
151,595
public void setTargets ( Collection < IPermissionTarget > targets ) { // clear out any existing targets targetMap . clear ( ) ; // add each target to the internal map and index it by the target key for ( IPermissionTarget target : targets ) { targetMap . put ( target . getKey ( ) , target ) ; } }
Set the permission targets for this provider .
73
8
151,596
@ Override public IPersonAttributes getPerson ( String uid ) { final IPersonAttributes rslt = delegatePersonAttributeDao . getPerson ( uid ) ; if ( rslt == null ) { // Nothing we can do with that return null ; } return postProcessPerson ( rslt , uid ) ; }
This method is for filling a specific individual .
67
9
151,597
@ Override public synchronized String register ( ServletConfig config ) throws PortletContainerException { ServletContext servletContext = config . getServletContext ( ) ; String contextPath = servletContext . getContextPath ( ) ; if ( ! portletContexts . containsKey ( contextPath ) ) { PortletApplicationDefinition portletApp = this . getPortletAppDD ( servletContext , contextPath , contextPath ) ; DriverPortletContext portletContext = new DriverPortletContextImpl ( servletContext , portletApp , requestDispatcherService ) ; portletContext . setAttribute ( PlatformApiBroker . PORTLET_CONTEXT_ATTRIBUTE_NAME , platformApiBroker ) ; portletContexts . put ( contextPath , portletContext ) ; fireRegistered ( portletContext ) ; if ( logger . isInfoEnabled ( ) ) { logger . info ( "Registered portlet application for context '" + contextPath + "'" ) ; logger . info ( "Registering " + portletApp . getPortlets ( ) . size ( ) + " portlets for context " + portletContext . getApplicationName ( ) ) ; } // TODO have the portlet servlet provide the portlet's classloader as parameter to this // method // This approach is needed as all pluto callbacks in uPortal have an aspect that // switches the thread classloader back // to uPortal's classloader. ClassLoader classLoader = ThreadContextClassLoaderAspect . getPreviousClassLoader ( ) ; if ( classLoader == null ) { classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; } classLoaders . put ( portletApp . getName ( ) , classLoader ) ; for ( PortletDefinition portlet : portletApp . getPortlets ( ) ) { String appName = portletContext . getApplicationName ( ) ; if ( appName == null ) { throw new PortletContainerException ( "Portlet application name should not be null." ) ; } portletConfigs . put ( portletContext . getApplicationName ( ) + "/" + portlet . getPortletName ( ) , new DriverPortletConfigImpl ( portletContext , portlet ) ) ; } } else { if ( logger . isInfoEnabled ( ) ) { logger . info ( "Portlet application for context '" + contextPath + "' already registered." ) ; } } return contextPath ; }
Retrieves the PortletContext associated with the given ServletContext . If one does not exist it is created .
525
24
151,598
public synchronized PortletApplicationDefinition getPortletAppDD ( ServletContext servletContext , String name , String contextPath ) throws PortletContainerException { PortletApplicationDefinition portletApp = this . portletAppDefinitionCache . get ( servletContext ) ; if ( portletApp == null ) { portletApp = createDefinition ( servletContext , name , contextPath ) ; this . portletAppDefinitionCache . put ( servletContext , portletApp ) ; } return portletApp ; }
Retrieve the Portlet Application Deployment Descriptor for the given servlet context . Create it if it does not allready exist .
107
28
151,599
private PortletApplicationDefinition createDefinition ( ServletContext servletContext , String name , String contextPath ) throws PortletContainerException { PortletApplicationDefinition portletApp = null ; try { InputStream paIn = servletContext . getResourceAsStream ( PORTLET_XML ) ; InputStream webIn = servletContext . getResourceAsStream ( WEB_XML ) ; if ( paIn == null ) { throw new PortletContainerException ( "Cannot find '" + PORTLET_XML + "'. Are you sure it is in the deployed package?" ) ; } if ( webIn == null ) { throw new PortletContainerException ( "Cannot find '" + WEB_XML + "'. Are you sure it is in the deployed package?" ) ; } portletApp = this . portletAppDescriptorService . read ( name , contextPath , paIn ) ; this . portletAppDescriptorService . mergeWebDescriptor ( portletApp , webIn ) ; } catch ( Exception ex ) { throw new PortletContainerException ( "Exception loading portlet descriptor for: " + servletContext . getServletContextName ( ) , ex ) ; } return portletApp ; }
Creates the portlet . xml deployment descriptor representation .
265
11