idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
151,300
private ServerDetails createInitialDeployDetailsFromOldDeployDetails ( ServerDetails oldDeployerDetails ) { RepositoryConf oldDeployRepositoryConfig = oldDeployerDetails . getDeployReleaseRepository ( ) ; RepositoryConf oldSnapshotDeployRepositoryConfig = oldDeployerDetails . getDeploySnapshotRepository ( ) ; RepositoryConf deployReleaseRepos = oldDeployRepositoryConfig == null ? RepositoryConf . emptyRepositoryConfig : oldDeployRepositoryConfig ; RepositoryConf deploySnapshotRepos = oldSnapshotDeployRepositoryConfig == null ? RepositoryConf . emptyRepositoryConfig : oldSnapshotDeployRepositoryConfig ; return new ServerDetails ( oldDeployerDetails . getArtifactoryName ( ) , oldDeployerDetails . getArtifactoryUrl ( ) , deployReleaseRepos , deploySnapshotRepos , null , null , null , null ) ; }
Creates a new ServerDetails object for deployer this will take URL and name from the oldDeployer ServerDetails
186
23
151,301
private static Properties loadGradleProperties ( FilePath gradlePropertiesFilePath ) throws IOException , InterruptedException { return gradlePropertiesFilePath . act ( new MasterToSlaveFileCallable < Properties > ( ) { public Properties invoke ( File gradlePropertiesFile , VirtualChannel channel ) throws IOException , InterruptedException { Properties gradleProps = new Properties ( ) ; if ( gradlePropertiesFile . exists ( ) ) { debuggingLogger . fine ( "Gradle properties file exists at: " + gradlePropertiesFile . getAbsolutePath ( ) ) ; FileInputStream stream = null ; try { stream = new FileInputStream ( gradlePropertiesFile ) ; gradleProps . load ( stream ) ; } catch ( IOException e ) { debuggingLogger . fine ( "IO exception occurred while trying to read properties file from: " + gradlePropertiesFile . getAbsolutePath ( ) ) ; throw new RuntimeException ( e ) ; } finally { IOUtils . closeQuietly ( stream ) ; } } return gradleProps ; } } ) ; }
Load a properties file from a file path
239
8
151,302
public Module generateBuildInfoModule ( Run build , TaskListener listener , ArtifactoryConfigurator config , String buildName , String buildNumber , String timestamp ) throws IOException { if ( artifactsProps == null ) { artifactsProps = ArrayListMultimap . create ( ) ; } artifactsProps . put ( "build.name" , buildName ) ; artifactsProps . put ( "build.number" , buildNumber ) ; artifactsProps . put ( "build.timestamp" , timestamp ) ; String artifactsPropsStr = ExtractorUtils . buildPropertiesString ( artifactsProps ) ; Properties buildInfoItemsProps = new Properties ( ) ; buildInfoItemsProps . setProperty ( "build.name" , buildName ) ; buildInfoItemsProps . setProperty ( "build.number" , buildNumber ) ; buildInfoItemsProps . setProperty ( "build.timestamp" , timestamp ) ; ArtifactoryServer server = config . getArtifactoryServer ( ) ; CredentialsConfig preferredResolver = server . getDeployerCredentialsConfig ( ) ; ArtifactoryDependenciesClient dependenciesClient = null ; ArtifactoryBuildInfoClient propertyChangeClient = null ; try { dependenciesClient = server . createArtifactoryDependenciesClient ( preferredResolver . provideUsername ( build . getParent ( ) ) , preferredResolver . providePassword ( build . getParent ( ) ) , server . createProxyConfiguration ( Jenkins . getInstance ( ) . proxy ) , listener ) ; CredentialsConfig preferredDeployer = CredentialManager . getPreferredDeployer ( config , server ) ; propertyChangeClient = server . createArtifactoryClient ( preferredDeployer . provideUsername ( build . getParent ( ) ) , preferredDeployer . providePassword ( build . getParent ( ) ) , server . createProxyConfiguration ( Jenkins . getInstance ( ) . proxy ) ) ; Module buildInfoModule = new Module ( ) ; buildInfoModule . setId ( imageTag . substring ( imageTag . indexOf ( "/" ) + 1 ) ) ; // If manifest and imagePath not found, return. if ( ( StringUtils . isEmpty ( manifest ) || StringUtils . isEmpty ( imagePath ) ) && ! findAndSetManifestFromArtifactory ( server , dependenciesClient , listener ) ) { return buildInfoModule ; } listener . getLogger ( ) . println ( "Fetching details of published docker layers from Artifactory..." ) ; boolean includeVirtualReposSupported = propertyChangeClient . getArtifactoryVersion ( ) . isAtLeast ( VIRTUAL_REPOS_SUPPORTED_VERSION ) ; DockerLayers layers = createLayers ( dependenciesClient , includeVirtualReposSupported ) ; listener . getLogger ( ) . println ( "Tagging published docker layers with build properties in Artifactory..." ) ; setDependenciesAndArtifacts ( buildInfoModule , layers , artifactsPropsStr , buildInfoItemsProps , dependenciesClient , propertyChangeClient , server ) ; setBuildInfoModuleProps ( buildInfoModule ) ; return buildInfoModule ; } finally { if ( dependenciesClient != null ) { dependenciesClient . close ( ) ; } if ( propertyChangeClient != null ) { propertyChangeClient . close ( ) ; } } }
Generates the build - info module for this docker image . Additionally . this method tags the deployed docker layers with properties such as build . name build . number and custom properties defined in the Jenkins build .
708
40
151,303
private boolean findAndSetManifestFromArtifactory ( ArtifactoryServer server , ArtifactoryDependenciesClient dependenciesClient , TaskListener listener ) throws IOException { String candidateImagePath = DockerUtils . getImagePath ( imageTag ) ; String manifestPath ; // Try to get manifest, assuming reverse proxy manifestPath = StringUtils . join ( new String [ ] { server . getUrl ( ) , targetRepo , candidateImagePath , "manifest.json" } , "/" ) ; if ( checkAndSetManifestAndImagePathCandidates ( manifestPath , candidateImagePath , dependenciesClient , listener ) ) { return true ; } // Try to get manifest, assuming proxy-less candidateImagePath = candidateImagePath . substring ( candidateImagePath . indexOf ( "/" ) + 1 ) ; manifestPath = StringUtils . join ( new String [ ] { server . getUrl ( ) , targetRepo , candidateImagePath , "manifest.json" } , "/" ) ; if ( checkAndSetManifestAndImagePathCandidates ( manifestPath , candidateImagePath , dependenciesClient , listener ) ) { return true ; } // Couldn't find correct manifest listener . getLogger ( ) . println ( "Could not find corresponding manifest.json file in Artifactory." ) ; return false ; }
Find and validate manifest . json file in Artifactory for the current image . Since provided imageTag differs between reverse - proxy and proxy - less configuration try to build the correct manifest path .
282
38
151,304
private boolean checkAndSetManifestAndImagePathCandidates ( String manifestPath , String candidateImagePath , ArtifactoryDependenciesClient dependenciesClient , TaskListener listener ) throws IOException { String candidateManifest = getManifestFromArtifactory ( dependenciesClient , manifestPath ) ; if ( candidateManifest == null ) { return false ; } String imageDigest = DockerUtils . getConfigDigest ( candidateManifest ) ; if ( imageDigest . equals ( imageId ) ) { manifest = candidateManifest ; imagePath = candidateImagePath ; return true ; } listener . getLogger ( ) . println ( String . format ( "Found incorrect manifest.json file in Artifactory in the following path: %s\nExpecting: %s got: %s" , manifestPath , imageId , imageDigest ) ) ; return false ; }
Check if the provided manifestPath is correct . Set the manifest and imagePath in case of the correct manifest .
183
22
151,305
private List < org . jfrog . hudson . pipeline . types . File > getBuildFilesList ( Stream < ? extends BaseBuildFileBean > buildFilesStream ) { return buildFilesStream . filter ( buildFile -> StringUtils . isNotBlank ( buildFile . getLocalPath ( ) ) ) . filter ( buildFile -> StringUtils . isNotBlank ( buildFile . getRemotePath ( ) ) ) . map ( org . jfrog . hudson . pipeline . types . File :: new ) . distinct ( ) . collect ( Collectors . toList ( ) ) ; }
Return a list of Files of downloaded or uploaded files . Filters build files without local and remote paths .
129
21
151,306
public List < Integer > getConnectionRetries ( ) { List < Integer > items = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < 10 ; i ++ ) { items . add ( i ) ; } return items ; }
To populate the dropdown list from the jelly
54
9
151,307
public CredentialsConfig getResolvingCredentialsConfig ( ) { if ( resolverCredentialsConfig != null && resolverCredentialsConfig . isCredentialsProvided ( ) ) { return getResolverCredentialsConfig ( ) ; } if ( deployerCredentialsConfig != null ) { return getDeployerCredentialsConfig ( ) ; } return CredentialsConfig . EMPTY_CREDENTIALS_CONFIG ; }
Decides what are the preferred credentials to use for resolving the repo keys of the server
98
17
151,308
public Boolean invoke ( File pomFile , VirtualChannel channel ) throws IOException , InterruptedException { org . jfrog . build . extractor . maven . reader . ModuleName current = new org . jfrog . build . extractor . maven . reader . ModuleName ( currentModule . groupId , currentModule . artifactId ) ; Map < org . jfrog . build . extractor . maven . reader . ModuleName , String > modules = Maps . newLinkedHashMap ( ) ; for ( Map . Entry < ModuleName , String > entry : versionsByModule . entrySet ( ) ) { modules . put ( new org . jfrog . build . extractor . maven . reader . ModuleName ( entry . getKey ( ) . groupId , entry . getKey ( ) . artifactId ) , entry . getValue ( ) ) ; } org . jfrog . build . extractor . maven . transformer . PomTransformer transformer = new org . jfrog . build . extractor . maven . transformer . PomTransformer ( current , modules , scmUrl , failOnSnapshot ) ; return transformer . transform ( pomFile ) ; }
Performs the transformation .
247
5
151,309
public void edit ( int currentChangeListId , FilePath filePath ) throws Exception { establishConnection ( ) . editFile ( currentChangeListId , new File ( filePath . getRemote ( ) ) ) ; }
Opens file for editing .
45
6
151,310
private void convertJdkPath ( Launcher launcher , EnvVars extendedEnv ) { String separator = launcher . isUnix ( ) ? "/" : "\\" ; String java_home = extendedEnv . get ( "JAVA_HOME" ) ; if ( StringUtils . isNotEmpty ( java_home ) ) { if ( ! StringUtils . endsWith ( java_home , separator ) ) { java_home += separator ; } extendedEnv . put ( "PATH+JDK" , java_home + "bin" ) ; } }
The Maven3Builder class is looking for the PATH + JDK environment variable due to legacy code . In The pipeline flow we need to convert the JAVA_HOME to PATH + JDK in order to reuse the code .
124
47
151,311
public static AbstractBuild < ? , ? > getRootBuild ( AbstractBuild < ? , ? > currentBuild ) { AbstractBuild < ? , ? > rootBuild = null ; AbstractBuild < ? , ? > parentBuild = getUpstreamBuild ( currentBuild ) ; while ( parentBuild != null ) { if ( isPassIdentifiedDownstream ( parentBuild ) ) { rootBuild = parentBuild ; } parentBuild = getUpstreamBuild ( parentBuild ) ; } if ( rootBuild == null && isPassIdentifiedDownstream ( currentBuild ) ) { return currentBuild ; } return rootBuild ; }
Get the root build which triggered the current build . The build root is considered to be the one furthest one away from the current build which has the isPassIdentifiedDownstream active if no parent build exists check that the current build needs an upstream identifier if it does return it .
126
57
151,312
private static AbstractProject < ? , ? > getProject ( String fullName ) { Item item = Hudson . getInstance ( ) . getItemByFullName ( fullName ) ; if ( item != null && item instanceof AbstractProject ) { return ( AbstractProject < ? , ? > ) item ; } return null ; }
Get a project according to its full name .
67
9
151,313
public void pushDryRun ( ) throws Exception { if ( releaseAction . isCreateVcsTag ( ) ) { if ( scmManager . isTagExists ( scmManager . getRemoteConfig ( releaseAction . getTargetRemoteName ( ) ) , releaseAction . getTagUrl ( ) ) ) { throw new Exception ( String . format ( "Tag with name '%s' already exists" , releaseAction . getTagUrl ( ) ) ) ; } } String testTagName = releaseAction . getTagUrl ( ) + "_test" ; try { scmManager . testPush ( scmManager . getRemoteConfig ( releaseAction . getTargetRemoteName ( ) ) , testTagName ) ; } catch ( Exception e ) { throw new Exception ( String . format ( "Failed while attempting push dry-run: %s" , e . getMessage ( ) ) , e ) ; } finally { if ( scmManager . isTagExists ( scmManager . getRemoteConfig ( releaseAction . getTargetRemoteName ( ) ) , testTagName ) ) { scmManager . deleteLocalTag ( testTagName ) ; } } }
This method uses the configured git credentials and repo to test its validity . In addition in case the user requested creation of a new tag it checks that another tag with the same name doesn t exist
245
38
151,314
public synchronized static void registerImagOnAgents ( Launcher launcher , final String imageTag , final String host , final String targetRepo , final ArrayListMultimap < String , String > artifactsProps , final int buildInfoId ) throws IOException , InterruptedException { // Master final String imageId = getImageIdFromAgent ( launcher , imageTag , host ) ; registerImage ( imageId , imageTag , targetRepo , artifactsProps , buildInfoId ) ; // Agents List < Node > nodes = Jenkins . getInstance ( ) . getNodes ( ) ; for ( Node node : nodes ) { if ( node == null || node . getChannel ( ) == null ) { continue ; } try { node . getChannel ( ) . call ( new MasterToSlaveCallable < Boolean , IOException > ( ) { public Boolean call ( ) throws IOException { registerImage ( imageId , imageTag , targetRepo , artifactsProps , buildInfoId ) ; return true ; } } ) ; } catch ( Exception e ) { launcher . getListener ( ) . getLogger ( ) . println ( "Could not register docker image " + imageTag + " on Jenkins node '" + node . getDisplayName ( ) + "' due to: " + e . getMessage ( ) + " This could be because this node is now offline." ) ; } } }
Registers an image to be captured by the build - info proxy .
291
14
151,315
private static void registerImage ( String imageId , String imageTag , String targetRepo , ArrayListMultimap < String , String > artifactsProps , int buildInfoId ) throws IOException { DockerImage image = new DockerImage ( imageId , imageTag , targetRepo , buildInfoId , artifactsProps ) ; images . add ( image ) ; }
Registers an image to the images cache so that it can be captured by the build - info proxy .
77
21
151,316
public static List < DockerImage > getImagesByBuildId ( int buildInfoId ) { List < DockerImage > list = new ArrayList < DockerImage > ( ) ; Iterator < DockerImage > it = images . iterator ( ) ; while ( it . hasNext ( ) ) { DockerImage image = it . next ( ) ; if ( image . getBuildInfoId ( ) == buildInfoId && image . hasManifest ( ) ) { list . add ( image ) ; } } return list ; }
Gets a list of registered docker images from the images cache if it has been registered to the cache for a specific build - info ID and if a docker manifest has been captured for it by the build - info proxy .
107
44
151,317
public static List < DockerImage > getAndDiscardImagesByBuildId ( int buildInfoId ) { List < DockerImage > list = new ArrayList < DockerImage > ( ) ; synchronized ( images ) { Iterator < DockerImage > it = images . iterator ( ) ; while ( it . hasNext ( ) ) { DockerImage image = it . next ( ) ; if ( image . getBuildInfoId ( ) == buildInfoId ) { if ( image . hasManifest ( ) ) { list . add ( image ) ; } it . remove ( ) ; } else // Remove old images from the cache, for which build-info hasn't been published to Artifactory: if ( image . isExpired ( ) ) { it . remove ( ) ; } } } return list ; }
Gets a list of registered docker images from the images cache if it has been registered to the cache for a specific build - info ID and if a docker manifest has been captured for it by the build - info proxy . Additionally the methods also removes the returned images from the cache .
167
56
151,318
public static List < DockerImage > getDockerImagesFromAgents ( final int buildInfoId , TaskListener listener ) throws IOException , InterruptedException { List < DockerImage > dockerImages = new ArrayList < DockerImage > ( ) ; // Collect images from the master: dockerImages . addAll ( getAndDiscardImagesByBuildId ( buildInfoId ) ) ; // Collect images from all the agents: List < Node > nodes = Jenkins . getInstance ( ) . getNodes ( ) ; for ( Node node : nodes ) { if ( node == null || node . getChannel ( ) == null ) { continue ; } try { List < DockerImage > partialDockerImages = node . getChannel ( ) . call ( new MasterToSlaveCallable < List < DockerImage > , IOException > ( ) { public List < DockerImage > call ( ) throws IOException { List < DockerImage > dockerImages = new ArrayList < DockerImage > ( ) ; dockerImages . addAll ( getAndDiscardImagesByBuildId ( buildInfoId ) ) ; return dockerImages ; } } ) ; dockerImages . addAll ( partialDockerImages ) ; } catch ( Exception e ) { listener . getLogger ( ) . println ( "Could not collect docker images from Jenkins node '" + node . getDisplayName ( ) + "' due to: " + e . getMessage ( ) ) ; } } return dockerImages ; }
Retrieves from all the Jenkins agents all the docker images which have been registered for a specific build - info ID Only images for which manifests have been captured are returned .
304
34
151,319
public static boolean pushImage ( Launcher launcher , final JenkinsBuildInfoLog log , final String imageTag , final String username , final String password , final String host ) throws IOException , InterruptedException { return launcher . getChannel ( ) . call ( new MasterToSlaveCallable < Boolean , IOException > ( ) { public Boolean call ( ) throws IOException { String message = "Pushing image: " + imageTag ; if ( StringUtils . isNotEmpty ( host ) ) { message += " using docker daemon host: " + host ; } log . info ( message ) ; DockerUtils . pushImage ( imageTag , username , password , host ) ; return true ; } } ) ; }
Execute push docker image on agent
148
7
151,320
public static boolean pullImage ( Launcher launcher , final String imageTag , final String username , final String password , final String host ) throws IOException , InterruptedException { return launcher . getChannel ( ) . call ( new MasterToSlaveCallable < Boolean , IOException > ( ) { public Boolean call ( ) throws IOException { DockerUtils . pullImage ( imageTag , username , password , host ) ; return true ; } } ) ; }
Execute pull docker image on agent
94
7
151,321
public static boolean updateImageParentOnAgents ( final JenkinsBuildInfoLog log , final String imageTag , final String host , final int buildInfoId ) throws IOException , InterruptedException { boolean parentUpdated = updateImageParent ( log , imageTag , host , buildInfoId ) ; List < Node > nodes = Jenkins . getInstance ( ) . getNodes ( ) ; for ( Node node : nodes ) { if ( node == null || node . getChannel ( ) == null ) { continue ; } boolean parentNodeUpdated = node . getChannel ( ) . call ( new MasterToSlaveCallable < Boolean , IOException > ( ) { public Boolean call ( ) throws IOException { return updateImageParent ( log , imageTag , host , buildInfoId ) ; } } ) ; parentUpdated = parentUpdated ? parentUpdated : parentNodeUpdated ; } return parentUpdated ; }
Updates property of parent id for the image provided . Returns false if image was not captured true otherwise .
185
21
151,322
public static String getImageIdFromAgent ( Launcher launcher , final String imageTag , final String host ) throws IOException , InterruptedException { return launcher . getChannel ( ) . call ( new MasterToSlaveCallable < String , IOException > ( ) { public String call ( ) throws IOException { return DockerUtils . getImageIdFromTag ( imageTag , host ) ; } } ) ; }
Get image ID from imageTag on the current agent .
86
11
151,323
public static String getParentIdFromAgent ( Launcher launcher , final String imageID , final String host ) throws IOException , InterruptedException { return launcher . getChannel ( ) . call ( new MasterToSlaveCallable < String , IOException > ( ) { public String call ( ) throws IOException { return DockerUtils . getParentId ( imageID , host ) ; } } ) ; }
Get image parent ID from imageID on the current agent .
84
12
151,324
@ Override protected void initBuilderSpecific ( ) throws Exception { reset ( ) ; FilePath workspace = getModuleRoot ( EnvVars . masterEnvVars ) ; FilePath gradlePropertiesPath = new FilePath ( workspace , "gradle.properties" ) ; if ( releaseProps == null ) { releaseProps = PropertyUtils . getModulesPropertiesFromPropFile ( gradlePropertiesPath , getReleaseProperties ( ) ) ; } if ( nextIntegProps == null ) { nextIntegProps = PropertyUtils . getModulesPropertiesFromPropFile ( gradlePropertiesPath , getNextIntegProperties ( ) ) ; } }
Initialize the version properties map from the gradle . properties file and the additional properties from the gradle . properties file .
145
25
151,325
public FilePath getModuleRoot ( Map < String , String > globalEnv ) throws IOException , InterruptedException { FilePath someWorkspace = project . getSomeWorkspace ( ) ; if ( someWorkspace == null ) { throw new IllegalStateException ( "Couldn't find workspace" ) ; } Map < String , String > workspaceEnv = Maps . newHashMap ( ) ; workspaceEnv . put ( "WORKSPACE" , someWorkspace . getRemote ( ) ) ; for ( Builder builder : getBuilders ( ) ) { if ( builder instanceof Gradle ) { Gradle gradleBuilder = ( Gradle ) builder ; String rootBuildScriptDir = gradleBuilder . getRootBuildScriptDir ( ) ; if ( rootBuildScriptDir != null && rootBuildScriptDir . trim ( ) . length ( ) != 0 ) { String rootBuildScriptNormalized = Util . replaceMacro ( rootBuildScriptDir . trim ( ) , workspaceEnv ) ; rootBuildScriptNormalized = Util . replaceMacro ( rootBuildScriptNormalized , globalEnv ) ; return new FilePath ( someWorkspace , rootBuildScriptNormalized ) ; } else { return someWorkspace ; } } } throw new IllegalArgumentException ( "Couldn't find Gradle builder in the current builders list" ) ; }
Get the root path where the build is located the project may be checked out to a sub - directory from the root workspace location .
284
26
151,326
private String extractNumericVersion ( Collection < String > versionStrings ) { if ( versionStrings == null ) { return "" ; } for ( String value : versionStrings ) { String releaseValue = calculateReleaseVersion ( value ) ; if ( ! releaseValue . equals ( value ) ) { return releaseValue ; } } return "" ; }
Try to extract a numeric version from a collection of strings .
72
12
151,327
@ SuppressWarnings ( "UnusedDeclaration" ) public void init ( ) throws Exception { initBuilderSpecific ( ) ; resetFields ( ) ; if ( ! UserPluginInfo . NO_PLUGIN_KEY . equals ( getSelectedStagingPluginName ( ) ) ) { PluginSettings selectedStagingPluginSettings = getSelectedStagingPlugin ( ) ; try { stagingStrategy = getArtifactoryServer ( ) . getStagingStrategy ( selectedStagingPluginSettings , Util . rawEncode ( project . getName ( ) ) , project ) ; } catch ( Exception e ) { log . log ( Level . WARNING , "Failed to obtain staging strategy: " + e . getMessage ( ) , e ) ; strategyRequestFailed = true ; strategyRequestErrorMessage = "Failed to obtain staging strategy '" + selectedStagingPluginSettings . getPluginName ( ) + "': " + e . getMessage ( ) + ".\nPlease review the log for further information." ; stagingStrategy = null ; } strategyPluginExists = ( stagingStrategy != null ) && ! stagingStrategy . isEmpty ( ) ; } prepareDefaultVersioning ( ) ; prepareDefaultGlobalModule ( ) ; prepareDefaultModules ( ) ; prepareDefaultVcsSettings ( ) ; prepareDefaultPromotionConfig ( ) ; }
invoked from the jelly file
285
6
151,328
@ SuppressWarnings ( { "UnusedDeclaration" } ) protected void doApi ( StaplerRequest req , StaplerResponse resp ) throws IOException , ServletException { try { log . log ( Level . INFO , "Initiating Artifactory Release Staging using API" ) ; // Enforce release permissions project . checkPermission ( ArtifactoryPlugin . RELEASE ) ; // In case a staging user plugin is configured, the init() method invoke it: init ( ) ; // Read the values provided by the staging user plugin and assign them to data members in this class. // Those values can be overriden by URL arguments sent with the API: readStagingPluginValues ( ) ; // Read values from the request and override the staging plugin values: overrideStagingPluginParams ( req ) ; // Schedule the release build: Queue . WaitingItem item = Jenkins . getInstance ( ) . getQueue ( ) . schedule ( project , 0 , new Action [ ] { this , new CauseAction ( new Cause . UserIdCause ( ) ) } ) ; if ( item == null ) { log . log ( Level . SEVERE , "Failed to schedule a release build following a Release API invocation" ) ; resp . setStatus ( StaplerResponse . SC_INTERNAL_SERVER_ERROR ) ; } else { String url = req . getContextPath ( ) + ' ' + item . getUrl ( ) ; JSONObject json = new JSONObject ( ) ; json . element ( "queueItem" , item . getId ( ) ) ; json . element ( "releaseVersion" , getReleaseVersion ( ) ) ; json . element ( "nextVersion" , getNextVersion ( ) ) ; json . element ( "releaseBranch" , getReleaseBranch ( ) ) ; // Must use getOutputStream as sendRedirect uses getOutputStream (and closes it) resp . getOutputStream ( ) . print ( json . toString ( ) ) ; resp . sendRedirect ( 201 , url ) ; } } catch ( Exception e ) { log . log ( Level . SEVERE , "Artifactory Release Staging API invocation failed: " + e . getMessage ( ) , e ) ; resp . setStatus ( StaplerResponse . SC_INTERNAL_SERVER_ERROR ) ; ErrorResponse errorResponse = new ErrorResponse ( StaplerResponse . SC_INTERNAL_SERVER_ERROR , e . getMessage ( ) ) ; ObjectMapper mapper = new ObjectMapper ( ) ; mapper . enable ( SerializationFeature . INDENT_OUTPUT ) ; resp . getWriter ( ) . write ( mapper . writeValueAsString ( errorResponse ) ) ; } }
This method is used to initiate a release staging process using the Artifactory Release Staging API .
577
20
151,329
protected String calculateNextVersion ( String fromVersion ) { // first turn it to release version fromVersion = calculateReleaseVersion ( fromVersion ) ; String nextVersion ; int lastDotIndex = fromVersion . lastIndexOf ( ' ' ) ; try { if ( lastDotIndex != - 1 ) { // probably a major minor version e.g., 2.1.1 String minorVersionToken = fromVersion . substring ( lastDotIndex + 1 ) ; String nextMinorVersion ; int lastDashIndex = minorVersionToken . lastIndexOf ( ' ' ) ; if ( lastDashIndex != - 1 ) { // probably a minor-buildNum e.g., 2.1.1-4 (should change to 2.1.1-5) String buildNumber = minorVersionToken . substring ( lastDashIndex + 1 ) ; int nextBuildNumber = Integer . parseInt ( buildNumber ) + 1 ; nextMinorVersion = minorVersionToken . substring ( 0 , lastDashIndex + 1 ) + nextBuildNumber ; } else { nextMinorVersion = Integer . parseInt ( minorVersionToken ) + 1 + "" ; } nextVersion = fromVersion . substring ( 0 , lastDotIndex + 1 ) + nextMinorVersion ; } else { // maybe it's just a major version; try to parse as an int int nextMajorVersion = Integer . parseInt ( fromVersion ) + 1 ; nextVersion = nextMajorVersion + "" ; } } catch ( NumberFormatException e ) { return fromVersion ; } return nextVersion + "-SNAPSHOT" ; }
Calculates the next snapshot version based on the current release version
332
13
151,330
public void addVars ( Map < String , String > env ) { if ( tagUrl != null ) { env . put ( "RELEASE_SCM_TAG" , tagUrl ) ; env . put ( RT_RELEASE_STAGING + "SCM_TAG" , tagUrl ) ; } if ( releaseBranch != null ) { env . put ( "RELEASE_SCM_BRANCH" , releaseBranch ) ; env . put ( RT_RELEASE_STAGING + "SCM_BRANCH" , releaseBranch ) ; } if ( releaseVersion != null ) { env . put ( RT_RELEASE_STAGING + "VERSION" , releaseVersion ) ; } if ( nextVersion != null ) { env . put ( RT_RELEASE_STAGING + "NEXT_VERSION" , nextVersion ) ; } }
Add some of the release build properties to a map .
188
11
151,331
public String generateInitScript ( EnvVars env ) throws IOException , InterruptedException { StringBuilder initScript = new StringBuilder ( ) ; InputStream templateStream = getClass ( ) . getResourceAsStream ( "/initscripttemplate.gradle" ) ; String templateAsString = IOUtils . toString ( templateStream , Charsets . UTF_8 . name ( ) ) ; File extractorJar = PluginDependencyHelper . getExtractorJar ( env ) ; FilePath dependencyDir = PluginDependencyHelper . getActualDependencyDirectory ( extractorJar , rootPath ) ; String absoluteDependencyDirPath = dependencyDir . getRemote ( ) ; absoluteDependencyDirPath = absoluteDependencyDirPath . replace ( "\\" , "/" ) ; String str = templateAsString . replace ( "${pluginLibDir}" , absoluteDependencyDirPath ) ; initScript . append ( str ) ; return initScript . toString ( ) ; }
Generate the init script from the Artifactory URL .
214
12
151,332
public static int convertBytesToInt ( byte [ ] bytes , int offset ) { return ( BITWISE_BYTE_TO_INT & bytes [ offset + 3 ] ) | ( ( BITWISE_BYTE_TO_INT & bytes [ offset + 2 ] ) << 8 ) | ( ( BITWISE_BYTE_TO_INT & bytes [ offset + 1 ] ) << 16 ) | ( ( BITWISE_BYTE_TO_INT & bytes [ offset ] ) << 24 ) ; }
Take four bytes from the specified position in the specified block and convert them into a 32 - bit int using the big - endian convention .
109
28
151,333
public static int [ ] convertBytesToInts ( byte [ ] bytes ) { if ( bytes . length % 4 != 0 ) { throw new IllegalArgumentException ( "Number of input bytes must be a multiple of 4." ) ; } int [ ] ints = new int [ bytes . length / 4 ] ; for ( int i = 0 ; i < ints . length ; i ++ ) { ints [ i ] = convertBytesToInt ( bytes , i * 4 ) ; } return ints ; }
Convert an array of bytes into an array of ints . 4 bytes from the input data map to a single int in the output data .
108
29
151,334
public static long convertBytesToLong ( byte [ ] bytes , int offset ) { long value = 0 ; for ( int i = offset ; i < offset + 8 ; i ++ ) { byte b = bytes [ i ] ; value <<= 8 ; value |= b ; } return value ; }
Utility method to convert an array of bytes into a long . Byte ordered is assumed to be big - endian .
62
24
151,335
private double getExpectedProbability ( double x ) { double y = 1 / ( standardDeviation * Math . sqrt ( Math . PI * 2 ) ) ; double z = - ( Math . pow ( x - mean , 2 ) / ( 2 * Math . pow ( standardDeviation , 2 ) ) ) ; return y * Math . exp ( z ) ; }
This is the probability density function for the Gaussian distribution .
79
12
151,336
public final void reset ( ) { for ( int i = 0 ; i < permutationIndices . length ; i ++ ) { permutationIndices [ i ] = i ; } remainingPermutations = totalPermutations ; }
Resets the generator state .
49
6
151,337
@ SuppressWarnings ( "unchecked" ) public T [ ] nextPermutationAsArray ( ) { T [ ] permutation = ( T [ ] ) Array . newInstance ( elements . getClass ( ) . getComponentType ( ) , permutationIndices . length ) ; return nextPermutationAsArray ( permutation ) ; }
Generate the next permutation and return an array containing the elements in the appropriate order .
75
18
151,338
public List < T > nextPermutationAsList ( ) { List < T > permutation = new ArrayList < T > ( elements . length ) ; return nextPermutationAsList ( permutation ) ; }
Generate the next permutation and return a list containing the elements in the appropriate order .
46
18
151,339
private static long createLongSeed ( byte [ ] seed ) { if ( seed == null || seed . length != SEED_SIZE_BYTES ) { throw new IllegalArgumentException ( "Java RNG requires a 64-bit (8-byte) seed." ) ; } return BinaryUtils . convertBytesToLong ( seed , 0 ) ; }
Helper method to convert seed bytes into the long value required by the super class .
76
16
151,340
public void execute ( ) { Runnable task = new Runnable ( ) { public void run ( ) { final V result = performTask ( ) ; SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { postProcessing ( result ) ; latch . countDown ( ) ; } } ) ; } } ; new Thread ( task , "SwingBackgroundTask-" + id ) . start ( ) ; }
Asynchronous call that begins execution of the task and returns immediately .
94
13
151,341
public void addValue ( double value ) { if ( dataSetSize == dataSet . length ) { // Increase the capacity of the array. int newLength = ( int ) ( GROWTH_RATE * dataSetSize ) ; double [ ] newDataSet = new double [ newLength ] ; System . arraycopy ( dataSet , 0 , newDataSet , 0 , dataSetSize ) ; dataSet = newDataSet ; } dataSet [ dataSetSize ] = value ; updateStatsWithNewValue ( value ) ; ++ dataSetSize ; }
Adds a single value to the data set and updates any statistics that are calculated cumulatively .
117
19
151,342
public final double getMedian ( ) { assertNotEmpty ( ) ; // Sort the data (take a copy to do this). double [ ] dataCopy = new double [ getSize ( ) ] ; System . arraycopy ( dataSet , 0 , dataCopy , 0 , dataCopy . length ) ; Arrays . sort ( dataCopy ) ; int midPoint = dataCopy . length / 2 ; if ( dataCopy . length % 2 != 0 ) { return dataCopy [ midPoint ] ; } else { return dataCopy [ midPoint - 1 ] + ( dataCopy [ midPoint ] - dataCopy [ midPoint - 1 ] ) / 2 ; } }
Determines the median value of the data set .
138
11
151,343
private double sumSquaredDiffs ( ) { double mean = getArithmeticMean ( ) ; double squaredDiffs = 0 ; for ( int i = 0 ; i < getSize ( ) ; i ++ ) { double diff = mean - dataSet [ i ] ; squaredDiffs += ( diff * diff ) ; } return squaredDiffs ; }
Helper method for variance calculations .
74
6
151,344
public boolean getBit ( int index ) { assertValidIndex ( index ) ; int word = index / WORD_LENGTH ; int offset = index % WORD_LENGTH ; return ( data [ word ] & ( 1 << offset ) ) != 0 ; }
Returns the bit at the specified index .
55
8
151,345
public void setBit ( int index , boolean set ) { assertValidIndex ( index ) ; int word = index / WORD_LENGTH ; int offset = index % WORD_LENGTH ; if ( set ) { data [ word ] |= ( 1 << offset ) ; } else // Unset the bit. { data [ word ] &= ~ ( 1 << offset ) ; } }
Sets the bit at the specified index .
82
9
151,346
public void flipBit ( int index ) { assertValidIndex ( index ) ; int word = index / WORD_LENGTH ; int offset = index % WORD_LENGTH ; data [ word ] ^= ( 1 << offset ) ; }
Inverts the value of the bit at the specified index .
51
12
151,347
public void swapSubstring ( BitString other , int start , int length ) { assertValidIndex ( start ) ; other . assertValidIndex ( start ) ; int word = start / WORD_LENGTH ; int partialWordSize = ( WORD_LENGTH - start ) % WORD_LENGTH ; if ( partialWordSize > 0 ) { swapBits ( other , word , 0xFFFFFFFF << ( WORD_LENGTH - partialWordSize ) ) ; ++ word ; } int remainingBits = length - partialWordSize ; int stop = remainingBits / WORD_LENGTH ; for ( int i = word ; i < stop ; i ++ ) { int temp = data [ i ] ; data [ i ] = other . data [ i ] ; other . data [ i ] = temp ; } remainingBits %= WORD_LENGTH ; if ( remainingBits > 0 ) { swapBits ( other , word , 0xFFFFFFFF >>> ( WORD_LENGTH - remainingBits ) ) ; } }
An efficient method for exchanging data between two bit strings . Both bit strings must be long enough that they contain the full length of the specified substring .
221
30
151,348
public int compareTo ( Rational other ) { if ( denominator == other . getDenominator ( ) ) { return ( ( Long ) numerator ) . compareTo ( other . getNumerator ( ) ) ; } else { Long adjustedNumerator = numerator * other . getDenominator ( ) ; Long otherAdjustedNumerator = other . getNumerator ( ) * denominator ; return adjustedNumerator . compareTo ( otherAdjustedNumerator ) ; } }
Compares this value with the specified object for order . Returns a negative integer zero or a positive integer as this value is less than equal to or greater than the specified value .
106
35
151,349
public static void generateOutputFile ( Random rng , File outputFile ) throws IOException { DataOutputStream dataOutput = null ; try { dataOutput = new DataOutputStream ( new BufferedOutputStream ( new FileOutputStream ( outputFile ) ) ) ; for ( int i = 0 ; i < INT_COUNT ; i ++ ) { dataOutput . writeInt ( rng . nextInt ( ) ) ; } dataOutput . flush ( ) ; } finally { if ( dataOutput != null ) { dataOutput . close ( ) ; } } }
Generates a file of random data in a format suitable for the DIEHARD test . DIEHARD requires 3 million 32 - bit integers .
116
31
151,350
public static long raiseToPower ( int value , int power ) { if ( power < 0 ) { throw new IllegalArgumentException ( "This method does not support negative powers." ) ; } long result = 1 ; for ( int i = 0 ; i < power ; i ++ ) { result *= value ; } return result ; }
Calculate the first argument raised to the power of the second . This method only supports non - negative powers .
70
23
151,351
public static int restrictRange ( int value , int min , int max ) { return Math . min ( ( Math . max ( value , min ) ) , max ) ; }
If the specified value is not greater than or equal to the specified minimum and less than or equal to the specified maximum adjust it so that it is .
36
30
151,352
protected static Map < Double , Double > doQuantization ( double max , double min , double [ ] values ) { double range = max - min ; int noIntervals = 20 ; double intervalSize = range / noIntervals ; int [ ] intervals = new int [ noIntervals ] ; for ( double value : values ) { int interval = Math . min ( noIntervals - 1 , ( int ) Math . floor ( ( value - min ) / intervalSize ) ) ; assert interval >= 0 && interval < noIntervals : "Invalid interval: " + interval ; ++ intervals [ interval ] ; } Map < Double , Double > discretisedValues = new HashMap < Double , Double > ( ) ; for ( int i = 0 ; i < intervals . length ; i ++ ) { // Correct the value to take into account the size of the interval. double value = ( 1 / intervalSize ) * ( double ) intervals [ i ] ; discretisedValues . put ( min + ( ( i + 0.5 ) * intervalSize ) , value ) ; } return discretisedValues ; }
Convert the continuous values into discrete values by chopping up the distribution into several equally - sized intervals .
230
20
151,353
public final void reset ( ) { for ( int i = 0 ; i < combinationIndices . length ; i ++ ) { combinationIndices [ i ] = i ; } remainingCombinations = totalCombinations ; }
Reset the combination generator .
45
6
151,354
@ SuppressWarnings ( "unchecked" ) public T [ ] nextCombinationAsArray ( ) { T [ ] combination = ( T [ ] ) Array . newInstance ( elements . getClass ( ) . getComponentType ( ) , combinationIndices . length ) ; return nextCombinationAsArray ( combination ) ; }
Generate the next combination and return an array containing the appropriate elements .
70
14
151,355
public void setValue ( T value ) { try { lock . writeLock ( ) . lock ( ) ; this . value = value ; } finally { lock . writeLock ( ) . unlock ( ) ; } }
Change the value that is returned by this generator .
44
10
151,356
public static String urlEncode ( String path ) throws URISyntaxException { if ( isNullOrEmpty ( path ) ) return path ; return UrlEscapers . urlFragmentEscaper ( ) . escape ( path ) ; }
used for encoding url path segment
50
6
151,357
public static String encode ( String value ) throws UnsupportedEncodingException { if ( isNullOrEmpty ( value ) ) return value ; return URLEncoder . encode ( value , URL_ENCODING ) ; }
used for encoding queries or form data
46
7
151,358
public static HttpResponse getResponse ( String urls , HttpRequest request , HttpMethod method , int connectTimeoutMillis , int readTimeoutMillis ) throws IOException { OutputStream out = null ; InputStream content = null ; HttpResponse response = null ; HttpURLConnection httpConn = request . getHttpConnection ( urls , method . name ( ) ) ; httpConn . setConnectTimeout ( connectTimeoutMillis ) ; httpConn . setReadTimeout ( readTimeoutMillis ) ; try { httpConn . connect ( ) ; if ( null != request . getPayload ( ) && request . getPayload ( ) . length > 0 ) { out = httpConn . getOutputStream ( ) ; out . write ( request . getPayload ( ) ) ; } content = httpConn . getInputStream ( ) ; response = new HttpResponse ( ) ; parseHttpConn ( response , httpConn , content ) ; return response ; } catch ( SocketTimeoutException e ) { throw e ; } catch ( IOException e ) { content = httpConn . getErrorStream ( ) ; response = new HttpResponse ( ) ; parseHttpConn ( response , httpConn , content ) ; return response ; } finally { if ( content != null ) { content . close ( ) ; } httpConn . disconnect ( ) ; } }
Get http response
281
3
151,359
public void refreshCredentials ( ) { if ( this . credsProvider == null ) return ; try { AlibabaCloudCredentials creds = this . credsProvider . getCredentials ( ) ; this . accessKeyID = creds . getAccessKeyId ( ) ; this . accessKeySecret = creds . getAccessKeySecret ( ) ; if ( creds instanceof BasicSessionCredentials ) { this . securityToken = ( ( BasicSessionCredentials ) creds ) . getSessionToken ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } }
refresh credentials if CredentialProvider set
131
9
151,360
public void addExtraInfo ( String key , Object value ) { // Turn extraInfo into map Map < String , Object > infoMap = ( HashMap < String , Object > ) getMapFromJSON ( extraInfo ) ; // Add value infoMap . put ( key , value ) ; // Turn back into string extraInfo = getJSONFromMap ( infoMap ) ; }
Add key value pair to extra info
77
7
151,361
private Map < String , Object > getMapFromJSON ( String json ) { Map < String , Object > propMap = new HashMap < String , Object > ( ) ; ObjectMapper mapper = new ObjectMapper ( ) ; // Initialize string if empty if ( json == null || json . length ( ) == 0 ) { json = "{}" ; } try { // Convert string propMap = mapper . readValue ( json , new TypeReference < HashMap < String , Object > > ( ) { } ) ; } catch ( Exception e ) { ; } return propMap ; }
Turn json string into map
124
5
151,362
private String getJSONFromMap ( Map < String , Object > propMap ) { try { return new JSONObject ( propMap ) . toString ( ) ; } catch ( Exception e ) { return "{}" ; } }
Turn map into string
46
4
151,363
public boolean preHandle ( HttpServletRequest request , HttpServletResponse response , Object handler ) throws Exception { String queryString = request . getQueryString ( ) == null ? "" : request . getQueryString ( ) ; if ( ConfigurationService . getInstance ( ) . isValid ( ) || request . getServletPath ( ) . startsWith ( "/configuration" ) || request . getServletPath ( ) . startsWith ( "/resources" ) || queryString . contains ( "requestFromConfiguration=true" ) ) { return true ; } else { response . sendRedirect ( "configuration" ) ; return false ; } }
This will check to see if certain configuration values exist from the ConfigurationService If not then it redirects to the configuration screen
137
24
151,364
@ RequestMapping ( value = "api/edit/server" , method = RequestMethod . POST ) public @ ResponseBody ServerRedirect addRedirectToProfile ( Model model , @ RequestParam ( value = "profileId" , required = false ) Integer profileId , @ RequestParam ( value = "profileIdentifier" , required = false ) String profileIdentifier , @ RequestParam ( value = "srcUrl" , required = true ) String srcUrl , @ RequestParam ( value = "destUrl" , required = true ) String destUrl , @ RequestParam ( value = "clientUUID" , required = true ) String clientUUID , @ RequestParam ( value = "hostHeader" , required = false ) String hostHeader ) throws Exception { if ( profileId == null && profileIdentifier == null ) { throw new Exception ( "profileId required" ) ; } if ( profileId == null ) { profileId = ProfileService . getInstance ( ) . getIdFromName ( profileIdentifier ) ; } int clientId = ClientService . getInstance ( ) . findClient ( clientUUID , profileId ) . getId ( ) ; int redirectId = ServerRedirectService . getInstance ( ) . addServerRedirectToProfile ( "" , srcUrl , destUrl , hostHeader , profileId , clientId ) ; return ServerRedirectService . getInstance ( ) . getRedirect ( redirectId ) ; }
Adds a redirect URL to the specified profile ID
302
9
151,365
@ RequestMapping ( value = "api/edit/server" , method = RequestMethod . GET ) public @ ResponseBody HashMap < String , Object > getjqRedirects ( Model model , @ RequestParam ( value = "profileId" , required = false ) Integer profileId , @ RequestParam ( value = "clientUUID" , required = true ) String clientUUID , @ RequestParam ( value = "profileIdentifier" , required = false ) String profileIdentifier ) throws Exception { if ( profileId == null && profileIdentifier == null ) { throw new Exception ( "profileId required" ) ; } if ( profileId == null ) { profileId = ProfileService . getInstance ( ) . getIdFromName ( profileIdentifier ) ; } int clientId = ClientService . getInstance ( ) . findClient ( clientUUID , profileId ) . getId ( ) ; HashMap < String , Object > returnJson = Utils . getJQGridJSON ( ServerRedirectService . getInstance ( ) . tableServers ( clientId ) , "servers" ) ; returnJson . put ( "hostEditor" , Client . isAvailable ( ) ) ; return returnJson ; }
Redirect URL to the specified profile ID
260
8
151,366
@ RequestMapping ( value = "api/servergroup" , method = RequestMethod . GET ) public @ ResponseBody HashMap < String , Object > getServerGroups ( Model model , @ RequestParam ( value = "profileId" , required = false ) Integer profileId , @ RequestParam ( value = "search" , required = false ) String search , @ RequestParam ( value = "profileIdentifier" , required = false ) String profileIdentifier ) throws Exception { if ( profileId == null && profileIdentifier == null ) { throw new Exception ( "profileId required" ) ; } if ( profileId == null ) { profileId = ProfileService . getInstance ( ) . getIdFromName ( profileIdentifier ) ; } List < ServerGroup > serverGroups = ServerRedirectService . getInstance ( ) . tableServerGroups ( profileId ) ; if ( search != null ) { Iterator < ServerGroup > iterator = serverGroups . iterator ( ) ; while ( iterator . hasNext ( ) ) { ServerGroup serverGroup = iterator . next ( ) ; if ( ! serverGroup . getName ( ) . toLowerCase ( ) . contains ( search . toLowerCase ( ) ) ) { iterator . remove ( ) ; } } } HashMap < String , Object > returnJson = Utils . getJQGridJSON ( serverGroups , "servergroups" ) ; return returnJson ; }
Obtains the collection of server groups defined for a profile
302
11
151,367
@ RequestMapping ( value = "api/servergroup" , method = RequestMethod . POST ) public @ ResponseBody ServerGroup createServerGroup ( Model model , @ RequestParam ( value = "name" ) String name , @ RequestParam ( value = "profileId" , required = false ) Integer profileId , @ RequestParam ( value = "profileIdentifier" , required = false ) String profileIdentifier ) throws Exception { if ( profileId == null && profileIdentifier == null ) { throw new Exception ( "profileId required" ) ; } if ( profileId == null ) { profileId = ProfileService . getInstance ( ) . getIdFromName ( profileIdentifier ) ; } int groupId = ServerRedirectService . getInstance ( ) . addServerGroup ( name , profileId ) ; return ServerRedirectService . getInstance ( ) . getServerGroup ( groupId , profileId ) ; }
Create a new server group for a profile
193
8
151,368
@ RequestMapping ( value = "/cert" , method = { RequestMethod . GET , RequestMethod . HEAD } ) public String certPage ( ) throws Exception { return "cert" ; }
Returns a simple web page where certs can be downloaded . This is meant for mobile device setup .
40
19
151,369
public static Map < String , String [ ] > mapUrlEncodedParameters ( byte [ ] dataArray ) throws Exception { Map < String , String [ ] > mapPostParameters = new HashMap < String , String [ ] > ( ) ; try { ByteArrayOutputStream byteout = new ByteArrayOutputStream ( ) ; for ( int x = 0 ; x < dataArray . length ; x ++ ) { // split the data up by & to get the parts if ( dataArray [ x ] == ' ' || x == ( dataArray . length - 1 ) ) { if ( x == ( dataArray . length - 1 ) ) { byteout . write ( dataArray [ x ] ) ; } // find '=' and split the data up into key value pairs int equalsPos = - 1 ; ByteArrayOutputStream key = new ByteArrayOutputStream ( ) ; ByteArrayOutputStream value = new ByteArrayOutputStream ( ) ; byte [ ] byteArray = byteout . toByteArray ( ) ; for ( int xx = 0 ; xx < byteArray . length ; xx ++ ) { if ( byteArray [ xx ] == ' ' ) { equalsPos = xx ; } else { if ( equalsPos == - 1 ) { key . write ( byteArray [ xx ] ) ; } else { value . write ( byteArray [ xx ] ) ; } } } ArrayList < String > values = new ArrayList < String > ( ) ; if ( mapPostParameters . containsKey ( key . toString ( ) ) ) { values = new ArrayList < String > ( Arrays . asList ( mapPostParameters . get ( key . toString ( ) ) ) ) ; mapPostParameters . remove ( key . toString ( ) ) ; } values . add ( value . toString ( ) ) ; /** * If equalsPos is not -1, then there was a '=' for the key * If value.size is 0, then there is no value so want to add in the '=' * Since it will not be added later like params with keys and valued */ if ( equalsPos != - 1 && value . size ( ) == 0 ) { key . write ( ( byte ) ' ' ) ; } mapPostParameters . put ( key . toString ( ) , values . toArray ( new String [ values . size ( ) ] ) ) ; byteout = new ByteArrayOutputStream ( ) ; } else { byteout . write ( dataArray [ x ] ) ; } } } catch ( Exception e ) { throw new Exception ( "Could not parse request data: " + e . getMessage ( ) ) ; } return mapPostParameters ; }
Obtain collection of Parameters from request
553
7
151,370
public static String getURL ( String sourceURI ) { String retval = sourceURI ; int qPos = sourceURI . indexOf ( "?" ) ; if ( qPos != - 1 ) { retval = retval . substring ( 0 , qPos ) ; } return retval ; }
Retrieve URL without parameters
62
5
151,371
public static String getHeaders ( HttpMethod method ) { String headerString = "" ; Header [ ] headers = method . getRequestHeaders ( ) ; for ( Header header : headers ) { String name = header . getName ( ) ; if ( name . equals ( Constants . ODO_PROXY_HEADER ) ) { // skip.. don't want to log this continue ; } if ( headerString . length ( ) != 0 ) { headerString += "\n" ; } headerString += header . getName ( ) + ": " + header . getValue ( ) ; } return headerString ; }
Obtain newline - delimited headers from method
130
10
151,372
public static String getHeaders ( HttpServletRequest request ) { String headerString = "" ; Enumeration < String > headerNames = request . getHeaderNames ( ) ; while ( headerNames . hasMoreElements ( ) ) { String name = headerNames . nextElement ( ) ; if ( name . equals ( Constants . ODO_PROXY_HEADER ) ) { // skip.. don't want to log this continue ; } if ( headerString . length ( ) != 0 ) { headerString += "\n" ; } headerString += name + ": " + request . getHeader ( name ) ; } return headerString ; }
Obtain newline - delimited headers from request
137
10
151,373
public static String getHeaders ( HttpServletResponse response ) { String headerString = "" ; Collection < String > headerNames = response . getHeaderNames ( ) ; for ( String headerName : headerNames ) { // there may be multiple headers per header name for ( String headerValue : response . getHeaders ( headerName ) ) { if ( headerString . length ( ) != 0 ) { headerString += "\n" ; } headerString += headerName + ": " + headerValue ; } } return headerString ; }
Obtain newline - delimited headers from response
112
10
151,374
public static HashMap < String , String > getParameters ( String query ) { HashMap < String , String > params = new HashMap < String , String > ( ) ; if ( query == null || query . length ( ) == 0 ) { return params ; } String [ ] splitQuery = query . split ( "&" ) ; for ( String splitItem : splitQuery ) { String [ ] items = splitItem . split ( "=" ) ; if ( items . length == 1 ) { params . put ( items [ 0 ] , "" ) ; } else { params . put ( items [ 0 ] , items [ 1 ] ) ; } } return params ; }
Obtain parameters from query
139
5
151,375
public List < Method > getMethodsFromGroupIds ( int [ ] groupIds , String [ ] filters ) throws Exception { ArrayList < Method > methods = new ArrayList < Method > ( ) ; for ( int groupId : groupIds ) { methods . addAll ( getMethodsFromGroupId ( groupId , filters ) ) ; } return methods ; }
Return all methods for a list of groupIds
77
10
151,376
public void updateRepeatNumber ( int newNum , int path_id , String client_uuid ) throws Exception { updateRequestResponseTables ( "repeat_number" , newNum , getProfileIdFromPathID ( path_id ) , client_uuid , path_id ) ; }
Update the repeat number for a client path
62
8
151,377
public void disableAll ( int profileId , String client_uuid ) { PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "DELETE FROM " + Constants . DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants . CLIENT_PROFILE_ID + " = ?" + " AND " + Constants . CLIENT_CLIENT_UUID + " =? " ) ; statement . setInt ( 1 , profileId ) ; statement . setString ( 2 , client_uuid ) ; statement . executeUpdate ( ) ; statement . close ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Delete all enabled overrides for a client
193
8
151,378
public void removePathnameFromProfile ( int path_id , int profileId ) { PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "DELETE FROM " + Constants . DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants . ENABLED_OVERRIDES_PATH_ID + " = ?" ) ; statement . setInt ( 1 , path_id ) ; statement . executeUpdate ( ) ; statement . close ( ) ; statement = sqlConnection . prepareStatement ( "DELETE FROM " + Constants . DB_TABLE_PATH + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; statement . setInt ( 1 , path_id ) ; statement . executeUpdate ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Remove a path from a profile
228
6
151,379
public List < Method > getMethodsFromGroupId ( int groupId , String [ ] filters ) throws Exception { ArrayList < Method > methods = new ArrayList < Method > ( ) ; PreparedStatement statement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_OVERRIDE + " WHERE " + Constants . OVERRIDE_GROUP_ID + " = ?" ) ; statement . setInt ( 1 , groupId ) ; results = statement . executeQuery ( ) ; while ( results . next ( ) ) { Method method = PathOverrideService . getInstance ( ) . getMethodForOverrideId ( results . getInt ( "id" ) ) ; if ( method == null ) { continue ; } // decide whether or not to add this method based on the filters boolean add = true ; if ( filters != null ) { add = false ; for ( String filter : filters ) { if ( method . getMethodType ( ) . endsWith ( filter ) ) { add = true ; break ; } } } if ( add && ! methods . contains ( method ) ) { methods . add ( method ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } return methods ; }
Returns all methods for a specific group
338
7
151,380
public void enableCustomResponse ( String custom , int path_id , String client_uuid ) throws Exception { updateRequestResponseTables ( "custom_response" , custom , getProfileIdFromPathID ( path_id ) , client_uuid , path_id ) ; }
Enable a custom response
60
4
151,381
public static void updatePathTable ( String columnName , Object newData , int path_id ) { PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "UPDATE " + Constants . DB_TABLE_PATH + " SET " + columnName + " = ?" + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; statement . setObject ( 1 , newData ) ; statement . setInt ( 2 , path_id ) ; statement . executeUpdate ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Updates a path table value for column columnName
170
10
151,382
public void removeCustomOverride ( int path_id , String client_uuid ) throws Exception { updateRequestResponseTables ( "custom_response" , "" , getProfileIdFromPathID ( path_id ) , client_uuid , path_id ) ; }
Remove custom overrides
57
4
151,383
public static int getProfileIdFromPathID ( int path_id ) throws Exception { return ( Integer ) SQLService . getInstance ( ) . getFromTable ( Constants . GENERIC_PROFILE_ID , Constants . GENERIC_ID , path_id , Constants . DB_TABLE_PATH ) ; }
Return the profileId for a path
72
7
151,384
public List < Group > findAllGroups ( ) { ArrayList < Group > allGroups = new ArrayList < Group > ( ) ; PreparedStatement queryStatement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { queryStatement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_GROUPS + " ORDER BY " + Constants . GROUPS_GROUP_NAME ) ; results = queryStatement . executeQuery ( ) ; while ( results . next ( ) ) { Group group = new Group ( ) ; group . setId ( results . getInt ( Constants . GENERIC_ID ) ) ; group . setName ( results . getString ( Constants . GROUPS_GROUP_NAME ) ) ; allGroups . add ( group ) ; } } 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 allGroups ; }
Obtain all groups
262
4
151,385
public int addPathnameToProfile ( int id , String pathname , String actualPath ) throws Exception { int pathOrder = getPathOrder ( id ) . size ( ) + 1 ; int pathId = - 1 ; PreparedStatement statement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "INSERT INTO " + Constants . DB_TABLE_PATH + "(" + Constants . PATH_PROFILE_PATHNAME + "," + Constants . PATH_PROFILE_ACTUAL_PATH + "," + Constants . PATH_PROFILE_GROUP_IDS + "," + Constants . PATH_PROFILE_PROFILE_ID + "," + Constants . PATH_PROFILE_PATH_ORDER + "," + Constants . PATH_PROFILE_CONTENT_TYPE + "," + Constants . PATH_PROFILE_REQUEST_TYPE + "," + Constants . PATH_PROFILE_GLOBAL + ")" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?);" , PreparedStatement . RETURN_GENERATED_KEYS ) ; statement . setString ( 1 , pathname ) ; statement . setString ( 2 , actualPath ) ; statement . setString ( 3 , "" ) ; statement . setInt ( 4 , id ) ; statement . setInt ( 5 , pathOrder ) ; statement . setString ( 6 , Constants . PATH_PROFILE_DEFAULT_CONTENT_TYPE ) ; // should be set by UI/API statement . setInt ( 7 , Constants . REQUEST_TYPE_GET ) ; // should be set by UI/API statement . setBoolean ( 8 , false ) ; statement . executeUpdate ( ) ; // execute statement and get resultSet which will have the generated path ID as the first field results = statement . getGeneratedKeys ( ) ; if ( results . next ( ) ) { pathId = results . getInt ( 1 ) ; } else { // something went wrong throw new Exception ( "Could not add path" ) ; } } catch ( SQLException e ) { throw e ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } // need to add to request response table for all clients for ( Client client : ClientService . getInstance ( ) . findAllClients ( id ) ) { this . addPathToRequestResponseTable ( id , client . getUUID ( ) , pathId ) ; } return pathId ; }
Add a path to a profile returns the id
584
9
151,386
public void addPathToRequestResponseTable ( int profileId , String clientUUID , int pathId ) throws Exception { PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "INSERT INTO " + Constants . DB_TABLE_REQUEST_RESPONSE + "(" + Constants . REQUEST_RESPONSE_PATH_ID + "," + Constants . GENERIC_PROFILE_ID + "," + Constants . GENERIC_CLIENT_UUID + "," + Constants . REQUEST_RESPONSE_REPEAT_NUMBER + "," + Constants . REQUEST_RESPONSE_RESPONSE_ENABLED + "," + Constants . REQUEST_RESPONSE_REQUEST_ENABLED + "," + Constants . REQUEST_RESPONSE_CUSTOM_RESPONSE + "," + Constants . REQUEST_RESPONSE_CUSTOM_REQUEST + ")" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?);" ) ; statement . setInt ( 1 , pathId ) ; statement . setInt ( 2 , profileId ) ; statement . setString ( 3 , clientUUID ) ; statement . setInt ( 4 , - 1 ) ; statement . setInt ( 5 , 0 ) ; statement . setInt ( 6 , 0 ) ; statement . setString ( 7 , "" ) ; statement . setString ( 8 , "" ) ; statement . executeUpdate ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Adds a path to the request response table with the specified values
398
12
151,387
public List < Integer > getPathOrder ( int profileId ) { ArrayList < Integer > pathOrder = new ArrayList < Integer > ( ) ; PreparedStatement queryStatement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { queryStatement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_PATH + " WHERE " + Constants . GENERIC_PROFILE_ID + " = ? " + " ORDER BY " + Constants . PATH_PROFILE_PATH_ORDER + " ASC" ) ; queryStatement . setInt ( 1 , profileId ) ; results = queryStatement . executeQuery ( ) ; while ( results . next ( ) ) { pathOrder . add ( results . getInt ( Constants . GENERIC_ID ) ) ; } } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( queryStatement != null ) { queryStatement . close ( ) ; } } catch ( Exception e ) { } } logger . info ( "pathOrder = {}" , pathOrder ) ; return pathOrder ; }
Return collection of path Ids in priority order
274
9
151,388
public void setGroupsForPath ( Integer [ ] groups , int pathId ) { String newGroups = Arrays . toString ( groups ) ; newGroups = newGroups . substring ( 1 , newGroups . length ( ) - 1 ) . replaceAll ( "\\s" , "" ) ; logger . info ( "adding groups={}, to pathId={}" , newGroups , pathId ) ; EditService . updatePathTable ( Constants . PATH_PROFILE_GROUP_IDS , newGroups , pathId ) ; }
Set the groups assigned to a path
118
7
151,389
public static boolean intArrayContains ( int [ ] array , int numToCheck ) { for ( int i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] == numToCheck ) { return true ; } } return false ; }
a simple contains helper method checks if array contains a numToCheck
57
13
151,390
public Integer getGroupIdFromName ( String groupName ) { return ( Integer ) sqlService . getFromTable ( Constants . GENERIC_ID , Constants . GROUPS_GROUP_NAME , groupName , Constants . DB_TABLE_GROUPS ) ; }
given the groupName it returns the groupId
60
9
151,391
public void createOverride ( int groupId , String methodName , String className ) throws Exception { // first make sure this doesn't already exist for ( Method method : EditService . getInstance ( ) . getMethodsFromGroupId ( groupId , null ) ) { if ( method . getMethodName ( ) . equals ( methodName ) && method . getClassName ( ) . equals ( className ) ) { // don't add if it already exists in the group return ; } } try ( Connection sqlConnection = sqlService . getConnection ( ) ) { PreparedStatement statement = sqlConnection . prepareStatement ( "INSERT INTO " + Constants . DB_TABLE_OVERRIDE + "(" + Constants . OVERRIDE_METHOD_NAME + "," + Constants . OVERRIDE_CLASS_NAME + "," + Constants . OVERRIDE_GROUP_ID + ")" + " VALUES (?, ?, ?)" ) ; statement . setString ( 1 , methodName ) ; statement . setString ( 2 , className ) ; statement . setInt ( 3 , groupId ) ; statement . executeUpdate ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } }
given the groupId and 2 string arrays adds the name - responses pair to the table_override
260
20
151,392
public String getGroupNameFromId ( int groupId ) { return ( String ) sqlService . getFromTable ( Constants . GROUPS_GROUP_NAME , Constants . GENERIC_ID , groupId , Constants . DB_TABLE_GROUPS ) ; }
given the groupId returns the groupName
60
8
151,393
public void updateGroupName ( String newGroupName , int id ) { PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "UPDATE " + Constants . DB_TABLE_GROUPS + " SET " + Constants . GROUPS_GROUP_NAME + " = ? " + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; statement . setString ( 1 , newGroupName ) ; statement . setInt ( 2 , id ) ; statement . executeUpdate ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
updates the groupname in the table given the id
176
11
151,394
public void removeGroup ( int groupId ) { PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { statement = sqlConnection . prepareStatement ( "DELETE FROM " + Constants . DB_TABLE_GROUPS + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; statement . setInt ( 1 , groupId ) ; statement . executeUpdate ( ) ; statement . close ( ) ; statement = sqlConnection . prepareStatement ( "DELETE FROM " + Constants . DB_TABLE_OVERRIDE + " WHERE " + Constants . OVERRIDE_GROUP_ID + " = ?" ) ; statement . setInt ( 1 , groupId ) ; statement . executeUpdate ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } removeGroupIdFromTablePaths ( groupId ) ; }
Remove the group and all references to it
226
8
151,395
private void removeGroupIdFromTablePaths ( int groupIdToRemove ) { PreparedStatement queryStatement = null ; PreparedStatement statement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { queryStatement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_PATH ) ; results = queryStatement . executeQuery ( ) ; // this is a hashamp from a pathId to the string of groups HashMap < Integer , String > idToGroups = new HashMap < Integer , String > ( ) ; while ( results . next ( ) ) { int pathId = results . getInt ( Constants . GENERIC_ID ) ; String stringGroupIds = results . getString ( Constants . PATH_PROFILE_GROUP_IDS ) ; int [ ] groupIds = Utils . arrayFromStringOfIntegers ( stringGroupIds ) ; String newGroupIds = "" ; for ( int i = 0 ; i < groupIds . length ; i ++ ) { if ( groupIds [ i ] != groupIdToRemove ) { newGroupIds += ( groupIds [ i ] + "," ) ; } } idToGroups . put ( pathId , newGroupIds ) ; } // now i want to go though the hashmap and for each pathId, add // update the newGroupIds for ( Map . Entry < Integer , String > entry : idToGroups . entrySet ( ) ) { Integer pathId = entry . getKey ( ) ; String newGroupIds = entry . getValue ( ) ; statement = sqlConnection . prepareStatement ( "UPDATE " + Constants . DB_TABLE_PATH + " SET " + Constants . PATH_PROFILE_GROUP_IDS + " = ? " + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; statement . setString ( 1 , newGroupIds ) ; statement . setInt ( 2 , pathId ) ; statement . executeUpdate ( ) ; } } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( queryStatement != null ) { queryStatement . close ( ) ; } } catch ( Exception e ) { } try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Remove all references to a groupId
541
7
151,396
public void removePath ( int pathId ) { PreparedStatement statement = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { // remove any enabled overrides with this path statement = sqlConnection . prepareStatement ( "DELETE FROM " + Constants . DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants . ENABLED_OVERRIDES_PATH_ID + " = ?" ) ; statement . setInt ( 1 , pathId ) ; statement . executeUpdate ( ) ; statement . close ( ) ; // remove path statement = sqlConnection . prepareStatement ( "DELETE FROM " + Constants . DB_TABLE_PATH + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; statement . setInt ( 1 , pathId ) ; statement . executeUpdate ( ) ; statement . close ( ) ; //remove path from responseRequest statement = sqlConnection . prepareStatement ( "DELETE FROM " + Constants . DB_TABLE_REQUEST_RESPONSE + " WHERE " + Constants . REQUEST_RESPONSE_PATH_ID + " = ?" ) ; statement . setInt ( 1 , pathId ) ; statement . executeUpdate ( ) ; statement . close ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { try { if ( statement != null ) { statement . close ( ) ; } } catch ( Exception e ) { } } }
Remove a path
324
3
151,397
public com . groupon . odo . proxylib . models . Method getMethodForOverrideId ( int overrideId ) { com . groupon . odo . proxylib . models . Method method = null ; // special case for IDs < 0 if ( overrideId < 0 ) { method = new com . groupon . odo . proxylib . models . Method ( ) ; method . setId ( overrideId ) ; if ( method . getId ( ) == Constants . PLUGIN_RESPONSE_OVERRIDE_CUSTOM || method . getId ( ) == Constants . PLUGIN_RESPONSE_HEADER_OVERRIDE_ADD || method . getId ( ) == Constants . PLUGIN_RESPONSE_HEADER_OVERRIDE_REMOVE ) { method . setMethodType ( Constants . PLUGIN_TYPE_RESPONSE_OVERRIDE ) ; } else { method . setMethodType ( Constants . PLUGIN_TYPE_REQUEST_OVERRIDE ) ; } } else { // get method information from the database PreparedStatement queryStatement = null ; ResultSet results = null ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { queryStatement = sqlConnection . prepareStatement ( "SELECT * FROM " + Constants . DB_TABLE_OVERRIDE + " WHERE " + Constants . GENERIC_ID + " = ?" ) ; queryStatement . setInt ( 1 , overrideId ) ; results = queryStatement . executeQuery ( ) ; if ( results . next ( ) ) { method = new com . groupon . odo . proxylib . models . Method ( ) ; method . setClassName ( results . getString ( Constants . OVERRIDE_CLASS_NAME ) ) ; method . setMethodName ( results . getString ( Constants . OVERRIDE_METHOD_NAME ) ) ; } } catch ( SQLException e ) { e . printStackTrace ( ) ; return null ; } finally { try { if ( results != null ) { results . close ( ) ; } } catch ( Exception e ) { } try { if ( queryStatement != null ) { queryStatement . close ( ) ; } } catch ( Exception e ) { } } // if method is still null then just return if ( method == null ) { return method ; } // now get the rest of the data from the plugin manager // this gets all of the actual method data try { method = PluginManager . getInstance ( ) . getMethod ( method . getClassName ( ) , method . getMethodName ( ) ) ; method . setId ( overrideId ) ; } catch ( Exception e ) { // there was some problem.. return null return null ; } } return method ; }
Gets a method based on data in the override_db table
598
13
151,398
public void updatePathOrder ( int profileId , int [ ] pathOrder ) { for ( int i = 0 ; i < pathOrder . length ; i ++ ) { EditService . updatePathTable ( Constants . PATH_PROFILE_PATH_ORDER , ( i + 1 ) , pathOrder [ i ] ) ; } }
Updates the path_order column in the table loops though the pathOrder array and changes the value to the loop index + 1 for the specified pathId
70
31
151,399
public int getPathId ( String pathName , int profileId ) { PreparedStatement queryStatement = null ; ResultSet results = null ; // first get the pathId for the pathName/profileId int pathId = - 1 ; try ( Connection sqlConnection = sqlService . getConnection ( ) ) { queryStatement = sqlConnection . prepareStatement ( "SELECT " + Constants . GENERIC_ID + " FROM " + Constants . DB_TABLE_PATH + " WHERE " + Constants . PATH_PROFILE_PATHNAME + "= ? " + " AND " + Constants . GENERIC_PROFILE_ID + "= ?" ) ; queryStatement . setString ( 1 , pathName ) ; queryStatement . setInt ( 2 , profileId ) ; results = queryStatement . executeQuery ( ) ; if ( results . next ( ) ) { pathId = results . getInt ( Constants . GENERIC_ID ) ; } } 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 pathId ; }
Get path ID for a given profileId and pathName
278
11