Indexes the content of the plugin artifact.  This includes discovering all of the
dependency JARs as well as any configuration resources such as plugin definitions.
@throws IOException if an I/O error has occurred
761203
private void indexPluginArtifact() throws IOException {
        dependencyZips = new ArrayList<>();
        Enumeration<? extends ZipEntry> entries = this.pluginArtifactZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            if (zipEntry.getName().startsWith("WEB-INF/lib/") && zipEntry.getName().toLowerCase().endsWith(".jar")) {
                ZipFile dependencyZipFile = extractDependency(zipEntry);
                if (dependencyZipFile != null) {
                    dependencyZips.add(dependencyZipFile);
                }
            }
        }
    }
388097
protected void loadJars(Path pluginPath, PluginClassLoader pluginClassLoader) {
        for (String libDirectory : pluginClasspath.getLibDirectories()) {
            Path file = pluginPath.resolve(libDirectory);
            List<File> jars = FileUtils.getJars(file);
            for (File jar : jars) {
                pluginClassLoader.addFile(jar);
            }
        }
    }
456443
static PluginMeta loadMeta(final File jar, final ZipInputStream zipinput) throws IOException {
        final String basename = basename(jar);
        PluginMeta metadata = null;
        boolean topfound = false;
        boolean found = false;
        boolean dirfound = false;
        boolean resfound = false;
        ZipEntry nextEntry = zipinput.getNextEntry();
        Set<String> paths = new HashSet<>();
        while (null != nextEntry) {
            paths.add(nextEntry.getName());

            if (!found && !nextEntry.isDirectory() && nextEntry.getName().equals(basename + "/plugin.yaml")) {
//                debug("Found metadata: " + nextEntry.getName());
                try {
                    metadata = loadMetadataYaml(zipinput);
                    found = true;
                } catch (Throwable e) {
                    log.error("Error parsing metadata file plugin.yaml: " + e.getMessage(), e);
                }
            }
            nextEntry = zipinput.getNextEntry();
        }
        if (!found || metadata == null) {
            log.error("Plugin not loaded: Found no " + basename + "/plugin.yaml within: " + jar.getAbsolutePath());
        }
        String resdir = null != metadata ? getResourcesBasePath(metadata) : null;

        for (String path : paths) {
            if (!topfound && path.startsWith(basename + "/")) {
                topfound = true;
            }
            if (!dirfound && (path.startsWith(basename + "/contents/") || path.equals(basename + "/contents"))) {
                dirfound = true;
            }
            if (!resfound
                && resdir != null
                && (path.startsWith(basename + "/" + resdir + "/") || path.equals(basename + "/" + resdir))) {
                resfound = true;
            }
        }
        if (!topfound) {
            log.error("Plugin not loaded: Found no " + basename + "/ dir within file: " + jar.getAbsolutePath());
        }
        if (!dirfound && !resfound) {
            log.error("Plugin not loaded: Found no " +
                      basename +
                      "/contents or " +
                      basename +
                      "/" + resdir + " dir within: " +
                      jar.getAbsolutePath());
        }
        if (found && (dirfound || resfound)) {
            return metadata;
        }
        return null;
    }
1374960
protected void addExtraPluginDependencies(Set<Artifact> artifacts) throws MojoExecutionException {
        if (extraPluginDependencyArtifactId == null && extendedPluginDependencyArtifactId == null) {
            return;
        }

        Set<Artifact> deps = new HashSet<Artifact>(this.pluginDependencies);
        for (Artifact artifact : deps) {
            // must
            if (artifact.getArtifactId().equals(extraPluginDependencyArtifactId)
                    || artifact.getArtifactId().equals(extendedPluginDependencyArtifactId)) {

                getLog().debug("Adding extra plugin dependency artifact: " + artifact.getArtifactId() + " to classpath");
                artifacts.add(artifact);

                // add the transient dependencies of this artifact
                Set<Artifact> resolvedDeps = resolveExecutableDependencies(artifact);
                for (Artifact dep : resolvedDeps) {
                    getLog().debug("Adding extra plugin dependency artifact: " + dep.getArtifactId() + " to classpath");
                    artifacts.add(dep);
                }
            }
        }
    }
944384
private void addRelevantPluginDependenciesToClasspath( List<URL> path )
        throws MojoExecutionException
    {
        if ( hasCommandlineArgs() )
        {
            arguments = parseCommandlineArgs();
        }

        try
        {
            for ( Artifact classPathElement : this.determineRelevantPluginDependencies() )
            {
                getLog().debug( "Adding plugin dependency artifact: " + classPathElement.getArtifactId()
                                    + " to classpath" );
                path.add( classPathElement.getFile().toURI().toURL() );
            }
        }
        catch ( MalformedURLException e )
        {
            throw new MojoExecutionException( "Error during setting up classpath", e );
        }

    }
482662
private void readRequiredJarFiles(final DataInput in) throws IOException {

		// Do jar files follow;
		final int numJars = in.readInt();

		if (numJars > 0) {

			for (int i = 0; i < numJars; i++) {

				final Path p = new Path();
				p.read(in);
				this.userJars.add(p);

				// Read the size of the jar file
				final long sizeOfJar = in.readLong();

				// Add the jar to the library manager
				LibraryCacheManager.addLibrary(this.jobID, p, sizeOfJar, in);
			}

		}

		// Register this job with the library cache manager
		LibraryCacheManager.register(this.jobID, this.userJars.toArray(new Path[0]));
	}
307054
protected void copyJarsToStageDirectory() throws IOException {
        final String stagingDirectory = getDeploymentStagingDirectoryPath();
        info("");
        info(COPY_JARS + stagingDirectory);
        Utils.copyResources(
                getProject(),
                getSession(),
                getMavenResourcesFiltering(),
                getResources(),
                stagingDirectory);
        info(COPY_SUCCESS);
    }
716357
public PluginDescriptor loadPlugin(Plugin plugin)
			throws MojoExecutionException {
		try {
			final Object repositorySessionObject = this.getRepositorySessionMethod.invoke(this.session);
			return (PluginDescriptor) this.loadPluginMethod.invoke(
					this.buildPluginManager,
					plugin,
					getSession().getCurrentProject().getRemotePluginRepositories(),
					repositorySessionObject);
		} catch (IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			throw new MojoExecutionException(e.getLocalizedMessage(), e);
		}
	}
1157572
public int execute() throws IOException {
        outputDir.mkdirs();

        if (packageName == null || packageName.length() == 0) {
            packageName = groupId + "." + artifactId;
        }

        String packageDir = packageName.replace('.', '/');

        debug("Creating archetype using Maven groupId: " + groupId + ", artifactId: " + artifactId + ", version: " + version + " in directory: " + outputDir);

        Map<String, String> replaceProperties = parseProperties();
        replaceProperties.putAll(overrideProperties);

        debug("Using replace properties: " + replaceProperties);

        ZipFile zip = null;
        try {
            zip = new ZipFile(archetypeFile);
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                final ZipEntry entry = entries.nextElement();
                if (!entry.isDirectory()) {
                    String fullName = entry.getName();
                    if (fullName != null && fullName.startsWith(zipEntryPrefix)) {
                        String name = replaceFileProperties(fullName.substring(zipEntryPrefix.length()), replaceProperties);
                        debug("Processing resource: " + name);

                        int idx = name.lastIndexOf('/');
                        Matcher matcher = sourcePathRegexPattern.matcher(name);
                        String dirName;
                        if (packageName.length() > 0 && idx > 0 && matcher.matches()) {
                            String prefix = matcher.group(1);
                            dirName = prefix + packageDir + "/" + name.substring(prefix.length());
                        } else if (packageName.length() > 0 && name.startsWith(webInfResources)) {
                            dirName = "src/main/webapp/WEB-INF/" + packageDir + "/resources" + name.substring(webInfResources.length());
                        } else {
                            dirName = name;
                        }

                        // lets replace properties...
                        File file = new File(outputDir, dirName);
                        file.getParentFile().mkdirs();
                        FileOutputStream out = null;
                        try {
                            out = new FileOutputStream(file);
                            boolean isBinary = false;
                            for (String suffix : binarySuffixes) {
                                if (name.endsWith(suffix)) {
                                    isBinary = true;
                                    break;
                                }
                            }
                            if (isBinary) {
                                // binary file?  don't transform.
                                IOHelpers.copy(zip.getInputStream(entry), out);
                            } else {
                                // text file...
                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                IOHelpers.copy(zip.getInputStream(entry), bos);
                                String text = new String(bos.toByteArray(), "UTF-8");
                                out.write(transformContents(text, replaceProperties).getBytes());
                            }
                        } finally {
                            if (out != null) {
                                IOHelpers.close(out);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        } finally {
            if (zip != null) {
                IOHelpers.close(zip);
            }
        }

        // now lets replace all the properties in the pom.xml
        if (!replaceProperties.isEmpty()) {
            File pom = new File(outputDir, "pom.xml");
            if (!pom.isFile()) {
                // must be non maven archetype?
                return 0;
            }
            String text = IOHelpers.readFully(new FileReader(pom));
            for (Map.Entry<String, String> e : replaceProperties.entrySet()) {
                text = replaceVariable(text, e.getKey(), e.getValue());
            }
            // replace name if we have a custom name
            if (Strings.isNotBlank(name)) {
                text = text.replaceFirst("<name>(.*)</name>", "<name>" + name + "</name>");
            }
            // replace description if we have a custom description
            if (Strings.isNotBlank(description)) {
                text = text.replaceFirst("<description>(.*)</description>", "<description>" + description + "</description>");
            }
            IOHelpers.writeTo(pom, text);
        }

        // now lets create the default directories
        if (createDefaultDirectories) {
            File srcDir = new File(outputDir, "src");
            File mainDir = new File(srcDir, "main");
            File testDir = new File(srcDir, "test");

            String srcDirName = "java";

            for (File dir : new File[]{mainDir, testDir}) {
                for (String name : new String[]{srcDirName + "/" + packageDir, "resources"}) {
                    new File(dir, name).mkdirs();
                }
            }
        }

        return 0;
    }
783819
protected void copyBundledPlugin(URL src, String fileName) throws IOException {
        LOGGER.log(FINE, "Copying {0}", src);
        fileName = fileName.replace(".hpi",".jpi"); // normalize fileNames to have the correct suffix
        String legacyName = fileName.replace(".jpi",".hpi");
        long lastModified = getModificationDate(src);
        File file = new File(rootDir, fileName);

        // normalization first, if the old file exists.
        rename(new File(rootDir,legacyName),file);

        // update file if:
        //  - no file exists today
        //  - bundled version and current version differs (by timestamp).
        if (!file.exists() || file.lastModified() != lastModified) {
            FileUtils.copyURLToFile(src, file);
            file.setLastModified(getModificationDate(src));
            // lastModified is set for two reasons:
            // - to avoid unpacking as much as possible, but still do it on both upgrade and downgrade
            // - to make sure the value is not changed after each restart, so we can avoid
            // unpacking the plugin itself in ClassicPluginStrategy.explode
        }

        // Plugin pinning has been deprecated.
        // See https://groups.google.com/d/msg/jenkinsci-dev/kRobm-cxFw8/6V66uhibAwAJ
    }
1118076
public void load() throws IOException {
        logRecorders.clear();
        File dir = configDir();
        File[] files = dir.listFiles((FileFilter)new WildcardFileFilter("*.xml"));
        if(files==null)     return;
        for (File child : files) {
            String name = child.getName();
            name = name.substring(0,name.length()-4);   // cut off ".xml"
            LogRecorder lr = new LogRecorder(name);
            lr.load();
            logRecorders.put(name,lr);
        }
    }
880334
private static void indexDirectory(IndexWriter writer, File dir)
        throws IOException {
        
        File[] files = dir.listFiles();

        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            if (f.isDirectory()) {
                indexDirectory(writer, f);
            } else if (f.getName().endsWith(".txt")) {
                indexFile(writer, f);
            }
        }
    }
385840
private void indexEntity(String type, String id, XContentBuilder sourceEntity) throws StorageException {
        indexEntity(type, id, sourceEntity, false);
    }
951402
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());
        }
    }
529284
private static IndexEnvironment setupIndexer(File outputDirectory, int memory,
      boolean storeDocs) throws Exception {
    final IndexEnvironment env = new IndexEnvironment();
    env.setMemory(memory * ONE_MEGABYTE);
    final Specification spec = env.getFileClassSpec("trectext");
    env.addFileClass(spec);
    env.setStoreDocs(storeDocs);
    // if we don't build indices on DOCNO then getting the docIds at query time is
    // extremely slow
    env.setMetadataIndexedFields(new String[]{"docno"}, new String[]{"docno"});
    env.create(outputDirectory.getAbsolutePath(), statusMonitor);
    return env;
  }
48940
public static PluginSpec readPluginSpecFile(URL pluginSpec) throws IOException {
        return (PluginSpec) mapper.reader(PluginSpec.class).readValue(pluginSpec);
    }
183310
@Requires({
    "sourceDependencyLoader != null",
    "type != null"
  })
  @Ensures({
    "importNames != null",
    "rootLineNumberIterator != null"
  })
  @SuppressWarnings("unchecked")
  protected void fetchSourceDependency() throws IOException {
    String fileName = type.getName().getBinaryName()
        + JavaUtils.SOURCE_DEPENDENCY_EXTENSION;
    InputStream in =
        sourceDependencyLoader.getResourceAsStream(fileName);
    if (in == null) {
      throw new FileNotFoundException();
    }
    ObjectInputStream oin = new ObjectInputStream(in);
    try {
      importNames = (Set<String>) oin.readObject();
      rootLineNumberIterator = ((List<Long>) oin.readObject()).iterator();
    } catch (ClassNotFoundException e) {
      throw new IOException(e);
    }
    oin.close();
  }