@Override public void createOrUpdateView(String path, String config, boolean ignoreExisting) { validateUpdateArgs(path, config); String viewBaseName = FilenameUtils.getName(path); Jenkins.checkGoodName(viewBaseName); try { InputStream inputStream = new ByteArrayInputStream(config.getBytes("UTF-8")); ItemGroup parent = lookupStrategy.getParent(build.getProject(), path); if (parent instanceof ViewGroup) { View view = ((ViewGroup) parent).getView(viewBaseName); if (view == null) { if (parent instanceof Jenkins) { ((Jenkins) parent).addView(createViewFromXML(viewBaseName, inputStream)); } else if (parent instanceof Folder) { ((Folder) parent).addView(createViewFromXML(viewBaseName, inputStream)); } else { LOGGER.log(Level.WARNING, format("Could not create view within %s", parent.getClass())); } } else if (!ignoreExisting) { view.updateByXml(new StreamSource(inputStream)); } } else if (parent == null) { throw new DslException(format(Messages.CreateView_UnknownParent(), path)); } else { LOGGER.log(Level.WARNING, format("Could not create view within %s", parent.getClass())); } } catch (UnsupportedEncodingException e) { LOGGER.log(Level.WARNING, "Unsupported encoding used in config. Should be UTF-8."); } catch (IOException e) { e.printStackTrace(); LOGGER.log(Level.WARNING, format("Error writing config for new view %s.", path), e); } }
/** * Construct an object from parameters input by a user. * * <p>Not using {@link DataBoundConstructor}, but using {@link * Descriptor#newInstance(StaplerRequest, JSONObject)}. * * @param req * @param formData * @param fieldName used for exception information. * @return * @throws hudson.model.Descriptor.FormException */ private BuildStep bindJSONWithDescriptor( StaplerRequest req, JSONObject formData, String fieldName) throws hudson.model.Descriptor.FormException { if (formData == null || formData.isNullObject()) { return null; } String clazzName = formData.optString("$class", null); if (clazzName == null) { // Fall back on the legacy stapler-class attribute. clazzName = formData.optString("stapler-class", null); } if (clazzName == null) { throw new FormException("No $class or stapler-class is specified", fieldName); } try { @SuppressWarnings("unchecked") Class<? extends Describable<?>> clazz = (Class<? extends Describable<?>>) Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass(clazzName); Descriptor<?> d = Jenkins.getInstance().getDescriptorOrDie(clazz); return (BuildStep) d.newInstance(req, formData); } catch (ClassNotFoundException e) { throw new FormException( String.format("Failed to instantiate: class not found %s", clazzName), e, fieldName); } }
public void testDoDelete() throws Exception { UpdateSite target = new UpdateSite("test1", "http://example.com/test/update-center.json"); Jenkins.getInstance().getUpdateCenter().getSites().clear(); Jenkins.getInstance().getUpdateCenter().getSites().add(target); int initialSize = Jenkins.getInstance().getUpdateCenter().getSites().size(); WebClient wc = new WebClient(); HtmlPage deleteSitePage = wc.goTo(String.format("%s/%s/delete", UpdateSitesManager.URL, target.getId())); assertEquals( "UpdateSite must not be deleted yet.", initialSize, Jenkins.getInstance().getUpdateCenter().getSites().size()); HtmlForm deleteSiteForm = deleteSitePage.getFormByName("deleteSiteForm"); assertNotNull("There must be deleteSiteForm", deleteSiteForm); submit(deleteSiteForm); assertEquals( "UpdateSite must be deleted.", initialSize - 1, Jenkins.getInstance().getUpdateCenter().getSites().size()); }
public void testDoConfigure() throws Exception { UpdateSite target = new UpdateSite("test1", "http://example.com/test/update-center.json"); // Multiple update site. Jenkins.getInstance().getUpdateCenter().getSites().clear(); Jenkins.getInstance().getUpdateCenter().getSites().add(target); String originalId = target.getId(); WebClient wc = new WebClient(); HtmlPage editSitePage = wc.goTo(String.format("%s/%s", UpdateSitesManager.URL, target.getId())); HtmlForm editSiteForm = editSitePage.getFormByName("editSiteForm"); assertNotNull("There must be editSiteForm", editSiteForm); String newId = "newId"; String newUrl = "http://localhost/update-center.json"; editSiteForm.getInputByName("_.id").setValueAttribute(newId); editSiteForm.getInputByName("_.url").setValueAttribute(newUrl); submit(editSiteForm); UpdateSite site = null; for (UpdateSite s : Jenkins.getInstance().getUpdateCenter().getSites()) { if (newId.equals(s.getId())) { site = s; } assertFalse("id must be updated(old one must not remain)", originalId.equals(s.getId())); } assertNotNull("id must be updated", site); assertEquals("url must be updated", newUrl, site.getUrl()); }
@Override public String createOrUpdateConfigFile(ConfigFile configFile, boolean ignoreExisting) { validateNameArg(configFile.getName()); Jenkins jenkins = Jenkins.getInstance(); if (jenkins.getPlugin("config-file-provider") == null) { throw new DslException(Messages.CreateOrUpdateConfigFile_PluginNotInstalled()); } ConfigProvider configProvider = findConfigProvider(configFile.getType()); if (configProvider == null) { throw new DslException( format( Messages.CreateOrUpdateConfigFile_ConfigProviderNotFound(), configFile.getClass())); } Config config = findConfig(configProvider, configFile.getName()); if (config == null) { config = configProvider.newConfig(); } else if (ignoreExisting) { return config.id; } config = createNewConfig(config, configFile); if (config == null) { throw new DslException( format(Messages.CreateOrUpdateConfigFile_UnknownConfigFileType(), configFile.getClass())); } configProvider.save(config); return config.id; }
/** * Constructor. * * @param type the type. */ DescriptorOrder(Class<T> type) { Jenkins j = Jenkins.getInstance(); if (j == null) { throw new IllegalStateException(); // TODO 1.590+ getActiveInstance } descriptors = j.getDescriptorList(type); }
/** Accepts submission from the configuration page. */ @RequirePOST public synchronized void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { checkPermission(CONFIGURE); description = req.getParameter("description"); keepDependencies = req.getParameter("keepDependencies") != null; try { JSONObject json = req.getSubmittedForm(); setDisplayName(json.optString("displayNameOrNull")); if (req.getParameter("logrotate") != null) logRotator = LogRotator.DESCRIPTOR.newInstance(req, json.getJSONObject("logrotate")); else logRotator = null; DescribableList<JobProperty<?>, JobPropertyDescriptor> t = new DescribableList<JobProperty<?>, JobPropertyDescriptor>(NOOP, getAllProperties()); t.rebuild( req, json.optJSONObject("properties"), JobPropertyDescriptor.getPropertyDescriptors(Job.this.getClass())); properties.clear(); for (JobProperty p : t) { p.setOwner(this); properties.add(p); } submit(req, rsp); save(); ItemListener.fireOnUpdated(this); String newName = req.getParameter("name"); final ProjectNamingStrategy namingStrategy = Jenkins.getInstance().getProjectNamingStrategy(); if (newName != null && !newName.equals(name)) { // check this error early to avoid HTTP response splitting. Jenkins.checkGoodName(newName); namingStrategy.checkName(newName); rsp.sendRedirect("rename?newName=" + URLEncoder.encode(newName, "UTF-8")); } else { if (namingStrategy.isForceExistingJobs()) { namingStrategy.checkName(name); } FormApply.success(".").generateResponse(req, rsp, null); } } catch (JSONException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println("Failed to parse form data. Please report this problem as a bug"); pw.println("JSON=" + req.getSubmittedForm()); pw.println(); e.printStackTrace(pw); rsp.setStatus(SC_BAD_REQUEST); sendError(sw.toString(), req, rsp, true); } }
@Restricted(DoNotUse.class) // accessed via REST API public HttpResponse doGenerateSnippet(StaplerRequest req, @QueryParameter String json) throws Exception { // TODO JENKINS-31458 is there not an easier way to do this? JSONObject jsonO = JSONObject.fromObject(json); Jenkins j = Jenkins.getActiveInstance(); Class<?> c = j.getPluginManager().uberClassLoader.loadClass(jsonO.getString("stapler-class")); StepDescriptor descriptor = (StepDescriptor) j.getDescriptor(c.asSubclass(Step.class)); Object o; try { o = descriptor.newInstance(req, jsonO); } catch (RuntimeException x) { // e.g. IllegalArgumentException return HttpResponses.plainText(Functions.printThrowable(x)); } try { String groovy = object2Groovy(o); if (descriptor.isAdvanced()) { String warning = Messages.Snippetizer_this_step_should_not_normally_be_used_in(); groovy = "// " + warning + "\n" + groovy; } return HttpResponses.plainText(groovy); } catch (UnsupportedOperationException x) { Logger.getLogger(CpsFlowExecution.class.getName()) .log(Level.WARNING, "failed to render " + json, x); return HttpResponses.plainText(x.getMessage()); } }
public synchronized TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException { acl.checkPermission(Job.CREATE); Jenkins.getInstance().getProjectNamingStrategy().checkName(name); // place it as config.xml File configXml = Items.getConfigFile(getRootDirFor(name)).getFile(); configXml.getParentFile().mkdirs(); try { IOUtils.copy(xml, configXml); // load it TopLevelItem result; Items.updatingByXml.set(true); try { result = (TopLevelItem) Items.load(parent, configXml.getParentFile()); } finally { Items.updatingByXml.set(false); } add(result); ItemListener.fireOnCreated(result); Jenkins.getInstance().rebuildDependencyGraph(); return result; } catch (IOException e) { // if anything fails, delete the config file to avoid further confusion Util.deleteRecursive(configXml.getParentFile()); throw e; } }
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify) throws IOException { acl.checkPermission(Job.CREATE); Jenkins.getInstance().getProjectNamingStrategy().checkName(name); if (parent.getItem(name) != null) throw new IllegalArgumentException("Project of the name " + name + " already exists"); TopLevelItem item; try { item = type.newInstance(parent, name); } catch (Exception e) { throw new IllegalArgumentException(e); } try { callOnCreatedFromScratch(item); } catch (AbstractMethodError e) { // ignore this error. Must be older plugin that doesn't have this method } item.save(); add(item); Jenkins.getInstance().rebuildDependencyGraph(); if (notify) ItemListener.fireOnCreated(item); return item; }
// TODO Tag projects as created by us, so that we can intelligently delete them and prevent // multiple jobs editing Projects private boolean createNewJob(String jobName, String config) { LOGGER.log(Level.FINE, String.format("Creating project as %s", config)); boolean created; try { InputStream is = new ByteArrayInputStream(config.getBytes("UTF-8")); // TODO confirm that we're using UTF-8 int i = jobName.lastIndexOf('/'); Jenkins jenkins = Jenkins.getInstance(); ModifiableTopLevelItemGroup ctx = jenkins; if (i > 0) { String contextName = jobName.substring(0, i); jobName = jobName.substring(i + 1); Item contextItem = jenkins.getItemByFullName(contextName); if (contextItem instanceof ModifiableItemGroup) { ctx = (ModifiableTopLevelItemGroup) contextItem; } } TopLevelItem item = ctx.createProjectFromXML(jobName, is); created = true; } catch (UnsupportedEncodingException ueex) { LOGGER.log(Level.WARNING, "Unsupported encoding used in config. Should be UTF-8."); created = false; } catch (IOException ioex) { LOGGER.log( Level.WARNING, String.format("Error writing config for new job %s.", jobName), ioex); created = false; } return created; }
@Override public List<? extends ItemGroup<?>> validDestinations(Item item) { List<DirectlyModifiableTopLevelItemGroup> result = new ArrayList<DirectlyModifiableTopLevelItemGroup>(); Jenkins instance = Jenkins.getActiveInstance(); if (permitted(item, instance)) { result.add(instance); } ITEM: for (Item g : instance.getAllItems()) { if (g instanceof DirectlyModifiableTopLevelItemGroup) { DirectlyModifiableTopLevelItemGroup itemGroup = (DirectlyModifiableTopLevelItemGroup) g; if (!permitted(item, itemGroup)) { continue; } ItemGroup<?> p = itemGroup; while (p instanceof Item) { Item i = (Item) p; if (i == item) { // Cannot move a folder into itself or a descendant. continue ITEM; } p = i.getParent(); } result.add(itemGroup); } } return result; }
/** * Extracts user groups from {@link SecurityRealm}. * * @param userId * @return List of effective groups. Null if there's no info */ private static @CheckForNull List<String> getAuthoritiesFromRealm(@Nonnull String userId) { final Jenkins instance = Jenkins.getInstance(); if (instance == null) { return null; // Jenkins has not been started yet } @CheckForNull UserDetails userDetails = null; try { final SecurityRealm sr = instance.getSecurityRealm(); userDetails = sr.loadUserByUsername(userId); } catch (DataAccessException ex) { // fallback to null handler } catch (UsernameNotFoundException ex) { // fallback to null handler } if (userDetails == null) { return null; } GrantedAuthority[] authorities = userDetails.getAuthorities(); List<String> authorityList = new ArrayList<String>(authorities.length); for (GrantedAuthority auth : authorities) { authorityList.add(auth.getAuthority()); } return authorityList; }
/** * @see * org.jenkins.plugins.audit2db.reports.JobsByParamReport#getProjectExecutions(java.lang.String, * java.lang.String, java.lang.String, java.lang.String) */ @Override public Map<String, List<BuildDetails>> getProjectExecutions( final String paramName, final String paramValue, final String startDateString, final String endDateString) { final Jenkins jenkins = Jenkins.getInstance(); if (jenkins != null) { // unit tests won't have a Jenkins instance jenkins.checkPermission(DbAuditPlugin.RUN); } final Map<String, List<BuildDetails>> retval = new HashMap<String, List<BuildDetails>>(); final Date startDate = DbAuditReportUtils.stringToDate(startDateString); final Date endDate = DbAuditReportUtils.stringToDate(endDateString); final String jenkinsHost = getJenkinsHostname(); final List<BuildDetails> buildDetails = getRepository() .getBuildDetailsByParams(jenkinsHost, paramName, paramValue, startDate, endDate); for (final BuildDetails details : buildDetails) { final String projectName = details.getName(); if (!retval.containsKey(projectName)) { retval.put(projectName, new ArrayList<BuildDetails>()); } retval.get(projectName).add(details); } return retval; }
public static String getRootUrl() { if (Jenkins.getInstance() == null || Jenkins.getInstance().getRootUrl() == null) { return "http://localhost:8080/"; } else { return Jenkins.getInstance().getRootUrl(); } }
@Override public Iterable<Edge> getEdgesIncidentWith(AbstractProject<?, ?> project) { Set<Edge> artifactEdges = Sets.newHashSet(); if (copyartifactIsInstalled) { if (project instanceof FreeStyleProject) { FreeStyleProject proj = (FreeStyleProject) project; List<Builder> builders = proj.getBuilders(); for (Builder builder : builders) { if (builder instanceof CopyArtifact) { CopyArtifact caBuilder = (CopyArtifact) builder; String projectName = caBuilder.getProjectName(); Jenkins jenkins = Jenkins.getInstance(); AbstractProject<?, ?> projectFromName = jenkins.getItem(projectName, project.getParent(), AbstractProject.class); if (projectFromName != null) { artifactEdges.add(new CopyArtifactEdge(node(projectFromName), node(project))); } } } } } return artifactEdges; }
/** * Since this shares much of the configuration with {@link EC2Computer}, check its help page, * too. */ @Override public String getHelpFile(String fieldName) { String p = super.getHelpFile(fieldName); if (p == null) p = Jenkins.getInstance().getDescriptor(EC2OndemandSlave.class).getHelpFile(fieldName); if (p == null) p = Jenkins.getInstance().getDescriptor(EC2SpotSlave.class).getHelpFile(fieldName); return p; }
/** * Creates a {@link TopLevelItem} from the submission of the '/lib/hudson/newFromList/formList' or * throws an exception if it fails. */ public synchronized TopLevelItem createTopLevelItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { acl.checkPermission(Job.CREATE); TopLevelItem result; String requestContentType = req.getContentType(); if (requestContentType == null) throw new Failure("No Content-Type header set"); boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml"); String name = req.getParameter("name"); if (name == null) throw new Failure("Query parameter 'name' is required"); { // check if the name looks good Jenkins.checkGoodName(name); name = name.trim(); if (parent.getItem(name) != null) throw new Failure(Messages.Hudson_JobAlreadyExists(name)); } String mode = req.getParameter("mode"); if (mode != null && mode.equals("copy")) { String from = req.getParameter("from"); // resolve a name to Item Item src = null; if (!from.startsWith("/")) src = parent.getItem(from); if (src == null) src = Jenkins.getInstance().getItemByFullName(from); if (src == null) { if (Util.fixEmpty(from) == null) throw new Failure("Specify which job to copy"); else throw new Failure("No such job: " + from); } if (!(src instanceof TopLevelItem)) throw new Failure(from + " cannot be copied"); result = copy((TopLevelItem) src, name); } else { if (isXmlSubmission) { result = createProjectFromXML(name, req.getInputStream()); rsp.setStatus(HttpServletResponse.SC_OK); return result; } else { if (mode == null) throw new Failure("No mode given"); // create empty job and redirect to the project config screen result = createProject(Items.all().findByName(mode), name, true); } } rsp.sendRedirect2(redirectAfterCreateItem(req, result)); return result; }
/** Really deletes the slave. */ @CLIMethod(name = "delete-node") public HttpResponse doDoDelete() throws IOException { checkPermission(DELETE); Node node = getNode(); if (node != null) { Jenkins.getInstance().removeNode(node); } else { AbstractCIBase app = Jenkins.getInstance(); app.removeComputer(this); } return new HttpRedirect(".."); }
/** Bare-minimum configuration mechanism to change the update center. */ public HttpResponse doSiteConfigure(@QueryParameter String site) throws IOException { Jenkins hudson = Jenkins.getInstance(); hudson.checkPermission(CONFIGURE_UPDATECENTER); UpdateCenter uc = hudson.getUpdateCenter(); PersistedList<UpdateSite> sites = uc.getSites(); for (UpdateSite s : sites) { if (s.getId().equals(UpdateCenter.ID_DEFAULT)) sites.remove(s); } sites.add(new UpdateSite(UpdateCenter.ID_DEFAULT, site)); return HttpResponses.redirectToContextRoot(); }
private void redirectToBuildPage(StaplerResponse res, Run build) { if (build != null) { try { res.sendRedirect2(Jenkins.getInstance().getRootUrl() + build.getUrl()); } catch (IOException e) { try { res.sendRedirect2(Jenkins.getInstance().getRootUrl() + build.getBuildStatusUrl()); } catch (IOException e1) { e1.printStackTrace(); } } } }
@Override public Integer getVSphereCloudHash(String name) { Jenkins jenkins = Jenkins.getInstance(); if (jenkins.getPlugin("vsphere-cloud") != null) { for (Cloud cloud : jenkins.clouds) { if (cloud instanceof vSphereCloud && ((vSphereCloud) cloud).getVsDescription().equals(name)) { return ((vSphereCloud) cloud).getHash(); } } } return null; }
/** * Returns the description of the build used for the Stash notification. Uses the build * description provided by the Jenkins job, if available. * * @param build the build to be described * @param state the state of the build * @return the description of the build */ private String getBuildDescription(final AbstractBuild<?, ?> build, final StashBuildState state) { if (build.getDescription() != null && build.getDescription().trim().length() > 0) { return build.getDescription(); } else { switch (state) { case INPROGRESS: return "building on Jenkins @ " + Jenkins.getInstance().getRootUrl(); default: return "built by Jenkins @ " + Jenkins.getInstance().getRootUrl(); } } }
protected void doRun() { Jenkins j = Jenkins.getInstance(); List<Queue.BuildableItem> bis = j.getQueue().getBuildableItems(); // update statistics on agents for (Label l : j.getLabels()) { l.loadStatistics.updateCounts(l.loadStatistics.computeSnapshot(bis)); } // update statistics of the entire system j.unlabeledLoad.updateCounts(j.unlabeledLoad.computeSnapshot(bis)); j.overallLoad.updateCounts(j.overallLoad.computeSnapshot(bis)); }
/** Try to make this user a super-user */ private void tryToMakeAdmin(User u) throws IOException { WwpassIdentity p = u.getProperty(WwpassIdentity.class); p.activate(); u.save(); AuthorizationStrategy as = Jenkins.getInstance().getAuthorizationStrategy(); for (PermissionAdder adder : Jenkins.getInstance().getExtensionList(PermissionAdder.class)) { if (adder.add(as, u, Jenkins.ADMINISTER)) { return; } } LOGGER.severe( "Admin permission wasn't added for user: "******", ID: " + u.getId()); }
public HttpResponse doProxyConfigure(StaplerRequest req) throws IOException, ServletException { Jenkins jenkins = Jenkins.getInstance(); jenkins.checkPermission(CONFIGURE_UPDATECENTER); ProxyConfiguration pc = req.bindJSON(ProxyConfiguration.class, req.getSubmittedForm()); if (pc.name == null) { jenkins.proxy = null; ProxyConfiguration.getXmlFile().delete(); } else { jenkins.proxy = pc; jenkins.proxy.save(); } return new HttpRedirect("advanced"); }
@Override public String getConfigFileId(ConfigFileType type, String name) { Jenkins jenkins = Jenkins.getInstance(); if (jenkins.getPlugin("config-file-provider") != null) { ConfigProvider configProvider = findConfigProvider(type); if (configProvider != null) { Config config = findConfig(configProvider, name); if (config != null) { return config.id; } } } return null; }
public List<Queue.Item> getQueueItems() { if (!isFilterQueue()) { return Arrays.asList(Jenkins.getInstance().getQueue().getItems()); } Collection<TopLevelItem> items = getItems(); List<Queue.Item> result = new ArrayList<Queue.Item>(); for (Queue.Item qi : Jenkins.getInstance().getQueue().getItems()) { if (items.contains(qi.task)) { result.add(qi); } } return result; }
public static void injectMembers(Object target) { Jenkins instance = Jenkins.getInstance(); if (instance == null) { log.log(Level.SEVERE, "Jenkins Instance cannot be loaded"); } else { try { instance.getInjector().injectMembers(target); } catch (Throwable ex) { log.log( Level.WARNING, "JIRA Plugin, which should provide connection to JIRA, is not installed, so JIRA metadata cannot be obtained."); } } }
public HttpResponse doUpdateSources(StaplerRequest req) throws IOException { Jenkins.getInstance().checkPermission(CONFIGURE_UPDATECENTER); if (req.hasParameter("remove")) { UpdateCenter uc = Jenkins.getInstance().getUpdateCenter(); BulkChange bc = new BulkChange(uc); try { for (String id : req.getParameterValues("sources")) uc.getSites().remove(uc.getById(id)); } finally { bc.commit(); } } else if (req.hasParameter("add")) return new HttpRedirect("addSite"); return new HttpRedirect("./sites"); }