/** * Utility to aid in performing a round trip migration test on a <code>CpwrScmConfiguration</code> configuration. * <p> * An existing project is loaded, migrated, saved, and reloaded where the original configuration is compared against * the reloaded configuration. The test project is loaded from a .zip file that mimics a Jenkins project's * layout within. * * See test resource for the migration test: src/test/resources/com.compuware.jenkins.scm/<test>/<test method>.zip * * @param jenkinsRule * the Jenkins rule */ public static void migrateDataTest(JenkinsRule jenkinsRule) { try { // Load and migrate the specified project from the test resource .zip file TopLevelItem item = jenkinsRule.jenkins.getItem("TestProject"); assertDataMigrated(item); } catch (Exception e) { // Add the print of the stack trace because the exception message is not enough to troubleshoot the root issue. For // example, if the exception is constructed without a message, you get no information from executing fail(). e.printStackTrace(); fail(e.getMessage()); } }
/** * Perform a round trip migration test on the configuration. * <p> * An existing project is loaded, migrated, saved, and reloaded where the original configuration is compared against * the reloaded configuration. The test project is loaded from a .zip file that mimics a Jenkins project's * layout within. * * See test resource for the migration test: src/test/resources/com.compuware.jenkins.scm/<test>/<test method>.zip */ @Test @LocalData public void migrateDataTest() { try { // Load and migrate the specified project from the test resource .zip file TopLevelItem item = m_jenkinsRule.jenkins.getItem("TestProject"); assertDataMigrated(item); } catch (Exception e) { // Add the print of the stack trace because the exception message is not enough to troubleshoot the root issue. For // example, if the exception is constructed without a message, you get no information from executing fail(). e.printStackTrace(); fail(e.getMessage()); } }
private void registerJobs(UsageComputation uc) throws IOException, InterruptedException { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { throw new IllegalStateException("Jenkins has not been started, or was already shut down"); } // Remove useless entries for jobs for (JobDiskItem item : jobsUsages) { if (!item.getPath().exists() || jenkins.getItemByFullName(item.getFullName(), Job.class) == null) { jobsUsages.remove(item); } } // Add or update entries for jobs for (Job job : jenkins.getAllItems(Job.class)) { if (job instanceof TopLevelItem) { uc.addListener(job.getRootDir().toPath(), new JobUsageListener(job)); } } }
@Override public List<TopLevelItem> filter(List<TopLevelItem> added, List<TopLevelItem> all, View filteringView) { List<Pattern> patterns = getCompiled(); List<TopLevelItem> workList = added.isEmpty() ? all : added; List<TopLevelItem> filtered = new LinkedList<TopLevelItem>(); for (TopLevelItem item : workList) { if (item instanceof ParameterizedJobMixIn.ParameterizedJob) { DockerHubTrigger trigger = DockerHubTrigger.getTrigger((ParameterizedJobMixIn.ParameterizedJob)item); if (trigger != null) { if (patterns.isEmpty()) { filtered.add(item); } else { for (String name : trigger.getAllRepoNames()) { if(matches(name)) { filtered.add(item); } } } } } } return filtered; }
@Before public void setUp() throws Exception { items = new LinkedList<TopLevelItem>(); groups = new LinkedList<GitLabGroupInfo>(); // mock itemGroup#getGetItems() returning the items list itemGroup = createMock(ModifiableTopLevelItemGroup.class); expect(itemGroup.getItems()).andReturn(items).anyTimes(); // mock creating new GitLabFolderAuthorization folder properties expectNewFolderAuthorization(); mockStatic(GitLab.class); folderManager = new GroupFolderManager(this, itemGroup, folderDescriptor); }
@Test public void testGetItems() throws Exception { List<TopLevelItem> list = ImmutableList.of(mockItem, mockItem); when(mockItemGroup.getItems()).thenReturn(list); JobHistoryView underTest = new JobHistoryView() { @Override public ItemGroup getOwnerItemGroup() { return mockItemGroup; } }; assertEquals(list, underTest.getItems()); verify(mockItemGroup, times(1)).getItems(); verifyNoMoreInteractions(mockItemGroup); verifyNoMoreInteractions(mockItem); }
@Test public void testGetItems() throws Exception { List<TopLevelItem> list = ImmutableList.of(mockItem, mockItem); when(mockItemGroup.getItems()).thenReturn(list); LastProjectView underTest = new LastProjectView() { @Override public ItemGroup getOwnerItemGroup() { return mockItemGroup; } }; assertEquals(0, underTest.getItems().size()); verifyNoMoreInteractions(mockItemGroup); verifyNoMoreInteractions(mockItem); }
public void submit(PrintStream log) throws IOException { FreeStyleProject project = null; TopLevelItem item = Jenkins.getActiveInstance().getItem(JobDslPluginJobSubmitter.UPDATE_JOB); if (item != null && item instanceof FreeStyleProject) { project = ((FreeStyleProject) item); project.getBuildersList().clear(); project.save(); } for (Job job : jobs) { job.submit(log); } if (project != null) { project.scheduleBuild(new MonitorTemplateJobs.TemplateTriggerCause()); log.println("Triggered " + project.getName()); } }
private void initPython() { if (pexec == null) { pexec = new PythonExecutor(this); String[] jMethods = new String[1]; jMethods[0] = "locate"; String[] pFuncs = new String[1]; pFuncs[0] = "locate"; Class[][] argTypes = new Class[1][]; argTypes[0] = new Class[2]; argTypes[0][0] = TopLevelItem.class; argTypes[0][1] = Node.class; pexec.checkAbstrMethods(jMethods, pFuncs, argTypes); String[] functions = new String[0]; int[] argsCount = new int[0]; pexec.registerFunctions(functions, argsCount); } }
@Override public Item doCreateItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { //First, we just create this item Item item = null; ItemGroup<? extends TopLevelItem> ig = getOwnerItemGroup(); if (ig instanceof ModifiableItemGroup) item = ((ModifiableItemGroup<? extends TopLevelItem>)ig).doCreateItem(req, rsp); //Checking if we deal with an inheritable job if (item == null || !(item instanceof InheritanceProject)) { return item; } //If we deal with an inheritable project, we assign it to the currently //viewed creation class, if any InheritanceProject ip = (InheritanceProject) item; //Checking if we define a CC if (!this.creationClassFilter.isEmpty()) { ip.setCreationClass(this.creationClassFilter); } return item; }
@Override public void triggerManual(AbstractProject<?, ?> project, AbstractProject<?, ?> upstream, String buildId, ItemGroup<? extends TopLevelItem> itemGroup) throws TriggerException { StandardBuildCard buildCard = new StandardBuildCard(); if (upstream != null && upstream.getBuild(buildId) != null) { try { buildCard.triggerManualBuild(itemGroup, Integer.parseInt(buildId), project.getRelativeNameFrom(itemGroup), upstream.getRelativeNameFrom(itemGroup)); } catch (Exception e) { throw new TriggerException("Could not trigger", e); } } else { throw new TriggerException("Could not find build: " + buildId + " for project: " + upstream); } }
@Test public void testGetItemsAndContains() throws Exception { final FreeStyleProject build = jenkins.createFreeStyleProject("build"); final FreeStyleProject sonar = jenkins.createFreeStyleProject("sonar"); final FreeStyleProject packaging = jenkins.createFreeStyleProject("packaging"); build.getPublishersList().add(new BuildTrigger("sonar", false)); build.getPublishersList().add(new BuildTrigger("packaging", false)); jenkins.getInstance().rebuildDependencyGraph(); List<DeliveryPipelineView.ComponentSpec> specs = new ArrayList<>(); specs.add(new DeliveryPipelineView.ComponentSpec("Comp", "build", NONE, DO_NOT_SHOW_UPSTREAM)); DeliveryPipelineView view = new DeliveryPipelineView("name"); view.setComponentSpecs(specs); jenkins.getInstance().addView(view); assertTrue(view.contains(build)); assertTrue(view.contains(sonar)); assertTrue(view.contains(packaging)); Collection<TopLevelItem> items = view.getItems(); assertEquals(3, items.size()); }
@Test public void testGetItemsGetPipelinesWhenNoProjectFound() throws Exception { List<DeliveryPipelineView.ComponentSpec> specs = new ArrayList<>(); specs.add(new DeliveryPipelineView.ComponentSpec("Comp", "build", NONE, DO_NOT_SHOW_UPSTREAM)); DeliveryPipelineView view = new DeliveryPipelineView("name"); view.setComponentSpecs(specs); jenkins.getInstance().addView(view); Collection<TopLevelItem> items = view.getItems(); assertNotNull(items); assertEquals(0, items.size()); List<Component> components = view.getPipelines(); assertNotNull(components); assertTrue(components.isEmpty()); assertNotNull(view.getError()); }
@Test public void testGetItemsAndContainsWithFolders() throws Exception { MockFolder folder = jenkins.createFolder("folder"); final FreeStyleProject build = folder.createProject(FreeStyleProject.class, "build"); final FreeStyleProject sonar = folder.createProject(FreeStyleProject.class, "sonar"); final FreeStyleProject packaging = folder.createProject(FreeStyleProject.class, "packaging"); build.getPublishersList().add(new BuildTrigger("sonar", false)); build.getPublishersList().add(new BuildTrigger("packaging", false)); jenkins.getInstance().rebuildDependencyGraph(); List<DeliveryPipelineView.ComponentSpec> specs = new ArrayList<>(); specs.add(new DeliveryPipelineView.ComponentSpec("Comp", "build", NONE, DO_NOT_SHOW_UPSTREAM)); DeliveryPipelineView view = new DeliveryPipelineView("name"); view.setComponentSpecs(specs); folder.addView(view); assertTrue(view.contains(build)); assertTrue(view.contains(sonar)); assertTrue(view.contains(packaging)); Collection<TopLevelItem> items = view.getItems(); assertEquals(3, items.size()); }
@Test public void testGetItems() throws IOException { final FreeStyleProject firstJob = jenkins.createFreeStyleProject("Project1"); final FreeStyleProject secondJob = jenkins.createFreeStyleProject("Project2"); final FreeStyleProject thirdJob = jenkins.createFreeStyleProject("Project3"); firstJob.getPublishersList().add((new BuildTrigger(secondJob.getName(), true))); jenkins.getInstance().rebuildDependencyGraph(); DeliveryPipelineView pipeline = new DeliveryPipelineView("Pipeline"); List<DeliveryPipelineView.ComponentSpec> componentSpecs = new ArrayList<>(); componentSpecs.add(new DeliveryPipelineView.ComponentSpec("Spec", firstJob.getName(), NONE, DO_NOT_SHOW_UPSTREAM)); pipeline.setComponentSpecs(componentSpecs); jenkins.getInstance().addView(pipeline); Collection<TopLevelItem> jobs = pipeline.getItems(); assertTrue(jobs.contains(firstJob)); assertTrue(jobs.contains(secondJob)); assertFalse(jobs.contains(thirdJob)); }
public List<CaseResult> getQuarantinedTests() { ArrayList<CaseResult> list = new ArrayList<CaseResult>(); for (TopLevelItem item : getOwner().getItems()) { if (item instanceof Job) { Job job = (Job) item; Run lb = job.getLastBuild(); while (lb != null && (lb.hasntStartedYet() || lb.isBuilding())) lb = lb.getPreviousBuild(); if (lb != null && lb.getAction(TestResultAction.class) != null) { for (SuiteResult suite : lb.getAction(TestResultAction.class).getResult().getSuites()) { for (CaseResult test : suite.getCases()) { QuarantineTestAction action = test.getTestAction(QuarantineTestAction.class); if (action != null && action.isQuarantined()) { list.add(test); } } } } } } return list; }
@Override public List<TopLevelItem> filter(List<TopLevelItem> added, List<TopLevelItem> all, View filteringView) { for (TopLevelItem item : all) { if (added.contains(item)) { continue; } if (SCMHead.HeadByItem.findHead(item) instanceof GitLabSCMTagHead) { added.add(item); } } return added; }
@Override public List<TopLevelItem> filter(List<TopLevelItem> added, List<TopLevelItem> all, View filteringView) { for (TopLevelItem item : all) { if (added.contains(item)) { continue; } SCMHead head = SCMHead.HeadByItem.findHead(item); if (head instanceof GitLabSCMMergeRequestHead && (!originOnly || ((GitLabSCMMergeRequestHead) head).fromOrigin())) { added.add(item); } } return added; }
@Override public List<TopLevelItem> filter(List<TopLevelItem> added, List<TopLevelItem> all, View filteringView) { for (TopLevelItem item : all) { if (added.contains(item)) { continue; } SCMHead head = SCMHead.HeadByItem.findHead(item); if (head instanceof GitLabSCMBranchHead && filter(item) && filter((GitLabSCMBranchHead) head)) { added.add(item); } } return added; }
public static Job getJob(String job) { TopLevelItem item = Jenkins.getActiveInstance().getItem(job); if (item instanceof Job) { return (Job) item; } return null; }
private Collection<View> getViewsAffectedBy(Run<?, ?> run) { Collection<View> views = Jenkins.getInstance().getViews(); List<View> affected = new ArrayList<>(views.size()); TopLevelItem parent = getTopLevelParent(run); if (parent != null) { for (View view : views) { if (view.contains(parent)) { affected.add(view); } } } else { LOG.log(Level.WARNING, run.getParent().getClass() + " not instanceof TopLevelItem"); } return affected; }
private TopLevelItem getTopLevelParent(Object o) { if(o == null) return null; if(o instanceof TopLevelItem) return (TopLevelItem) o; Object parent = null; try { Method getParent = o.getClass().getMethod("getParent", null); parent = getParent.invoke(o, null); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { LOG.log(Level.WARNING,e.getMessage()); } return getTopLevelParent(parent); }
private Result getResult(View view) { Result ret = Result.SUCCESS; for (TopLevelItem item : view.getAllItems()) { for (Job<?,?> job : item.getAllJobs()) { Run<?, ?> build = job.getLastCompletedBuild(); if(build != null) { Result result = build.getResult(); if(result.isBetterOrEqualTo(Result.FAILURE)) ret = ret.combine(result); } } } return ret; }
public Collection<String> getImageNames(TopLevelItem item) { if (item instanceof ParameterizedJobMixIn.ParameterizedJob) { DockerHubTrigger trigger = DockerHubTrigger.getTrigger((ParameterizedJobMixIn.ParameterizedJob)item); if (trigger != null) { Set<String> names = trigger.getAllRepoNames(); if (showMax <= 0 || names.size() <= showMax) { return names; } else { String[] array = names.toArray(new String[names.size()]); return Arrays.asList(Arrays.copyOf(array, showMax)); } } } return Collections.emptySet(); }
/** * Snapshot of files before Branch trigger refactoring. */ @LocalData @Test public void ensureOldValid() { final TopLevelItem item = j.getInstance().getItem("test-job"); assertThat(item, notNullValue()); final FreeStyleProject project = (FreeStyleProject) item; final GitHubPRRepository prRepository = project.getAction(GitHubPRRepository.class); assertThat(project, notNullValue()); assertThat(prRepository.getFullName(), is("KostyaSha-auto/test")); final Map<Integer, GitHubPRPullRequest> pulls = prRepository.getPulls(); assertThat(pulls.size(), is(1)); final GitHubPRPullRequest pullRequest = pulls.get(1); assertThat(pullRequest, notNullValue()); assertThat(pullRequest.getTitle(), is("Update README.md")); assertThat(pullRequest.getHeadRef(), is("KostyaSha-auto-patch-1")); assertThat(pullRequest.isMergeable(), is(true)); assertThat(pullRequest.getBaseRef(), is("master")); assertThat(pullRequest.getUserLogin(), is("KostyaSha-auto")); assertThat(pullRequest.getSourceRepoOwner(), is("KostyaSha-auto")); assertThat(pullRequest.getLabels(), Matchers.<String>empty()); final GitHubPRTrigger trigger = project.getTrigger(GitHubPRTrigger.class); assertThat(trigger, notNullValue()); assertThat(trigger.getTriggerMode(), is(CRON)); assertThat(trigger.getEvents(), hasSize(2)); assertThat(trigger.isPreStatus(), is(false)); assertThat(trigger.isCancelQueued(), is(false)); assertThat(trigger.isSkipFirstRun(), is(false)); }
/** * Create an group folder info object from an item. * * @param item the top level item * @return a group folder info object or null if the item isn't a group folder */ public static GroupFolderInfo createFromItem(TopLevelItem item) { if (item instanceof Folder) { GitLabFolderAuthorization property = ((Folder)item).getProperties().get(GitLabFolderAuthorization.class); if (property != null) { return new GroupFolderInfo(property); } } // not a group folder return null; }
/** * Gets a list of {@link GroupFolderInfo} for GitLab groups that does have an * associated folder created. * * @param auth the authentication object * @return a list of {@link GroupFolderInfo} * @throws GitLabApiException if the connection against GitLab failed */ public static List<GroupFolderInfo> getExistingFolders(Authentication auth) throws GitLabApiException { List<GroupFolderInfo> groups = new ArrayList<GroupFolderInfo>(); for (TopLevelItem item : Jenkins.getInstance().getItems()) { if (item instanceof Folder) { GitLabFolderAuthorization property = GitLabFolderAuthorization.getFolderProperty((Folder) item); if (property != null && property.getACL().hasPermission(auth, Item.READ)) { groups.add(new GroupFolderInfo(property)); } } } return groups; }
/** * Checks if a folder can be created for the given group. * * @param group the group * @return true if a folder can be created */ private static boolean folderExists(GitLabGroupInfo group) { for (TopLevelItem item : Jenkins.getInstance().getItems()) { GroupFolderInfo folderInfo = GroupFolderInfo.createFromItem(item); // if not null, folderInfo is a folder if (folderInfo != null) { if (folderInfo.getGroupId() == group.getId()) { return true; } } } return false; }
/** * Gets all group folders without applying the filter. * * @return all group folders */ private Map<Integer, GroupFolderInfo> getUnfilteredFolders() { Map<Integer, GroupFolderInfo> folders = new TreeMap<Integer, GroupFolderInfo>(); for (TopLevelItem item : itemGroup.getItems()) { // check if the item is a group folder GroupFolderInfo groupFolderInfo = GroupFolderInfo.createFromItem(item); if (groupFolderInfo != null) { folders.put(groupFolderInfo.getGroupId(), groupFolderInfo); } } return folders; }
/** * Creates a builder for a specific class. * * @param itemType the class for the item type * @param <ITEMTYPE> type parameter of the item class * @return a builder */ public static <ITEMTYPE extends TopLevelItem> MockTopLevelItemBuilder mockItem(Class<ITEMTYPE> itemType) { if (itemType == Folder.class) { return new MockFolderBuilder(); } else { return new MockTopLevelItemBuilder<ITEMTYPE, MockTopLevelItemBuilder>(itemType); } }
@Before public void setUp() throws Exception { // clear lists groups = new LinkedList<GitLabGroupInfo>(); items = new LinkedList<TopLevelItem>(); // mock itemGroup#getGetItems() returning the items list itemGroup = createMock(ModifiableTopLevelItemGroup.class); expect(itemGroup.getItems()).andReturn(items).anyTimes(); // mock creating new GitLabFolderAuthorization folder properties expectNewFolderAuthorization(); synchronizer = new FolderSynchronizerImplementation(itemGroup, folderDescriptor); }
/** * Calculates the color of the status ball for the owner based on selected descendants. * <br> * Logic kanged from Branch API (original author Stephen Connolly). * * @return the color of the status ball for the owner. */ @Nonnull private BallColor calculateBallColor() { if (owner instanceof TemplateDrivenMultiBranchProject && ((TemplateDrivenMultiBranchProject) owner).isDisabled()) { return BallColor.DISABLED; } BallColor c = BallColor.DISABLED; boolean animated = false; StringTokenizer tokens = new StringTokenizer(Util.fixNull(jobs), ","); while (tokens.hasMoreTokens()) { String jobName = tokens.nextToken().trim(); TopLevelItem item = owner.getItem(jobName); if (item != null && item instanceof Job) { BallColor d = ((Job) item).getIconColor(); animated |= d.isAnimated(); d = d.noAnime(); if (d.compareTo(c) < 0) { c = d; } } } if (animated) { c = c.anime(); } return c; }
@SuppressWarnings("rawtypes") public static AbstractProject getMatchingJob(String issueId) { List<TopLevelItem> projects = Jenkins.getInstance().getItems(); for (TopLevelItem project : projects) { if (project instanceof Job && issueId != null) { if (project.getName().contains(issueId)) { return (AbstractProject) project; } } } return null; }
@Override public TopLevelItem doCreateItem(final StaplerRequest req, final StaplerResponse rsp) throws IOException, ServletException { final ItemGroup<? extends TopLevelItem> ig = getOwnerItemGroup(); if (ig instanceof ModifiableItemGroup) { return ((ModifiableItemGroup<? extends TopLevelItem>) ig).doCreateItem(req, rsp); } return null; }
@Override public Collection<TopLevelItem> getItems() { final List<TopLevelItem> items = new LinkedList<>(); for (final TopLevelItem item : getOwnerItemGroup().getItems()) { if (item.hasPermission(Job.CONFIGURE)) { items.add(item); } } return Collections.unmodifiableList(items); }
@Override public boolean contains(TopLevelItem item) { //TODO: "lastItems" should probably not be buffered for hours if (this.lastItems == null) { return this.getItems().contains(item); } return this.lastItems.contains(item); }