com.rits.cloning.Cloner Java Examples

The following examples show how to use com.rits.cloning.Cloner. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConfigSaveDeadlockDetectionIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
private Thread fullConfigSaveThread(final int counter) throws InterruptedException {
    return createThread(new Runnable() {
        @Override
        public void run() {
            try {
                CruiseConfig cruiseConfig = cachedGoConfig.loadForEditing();
                CruiseConfig cruiseConfig1 = new Cloner().deepClone(cruiseConfig);
                cruiseConfig1.addEnvironment(UUID.randomUUID().toString());

                goConfigDao.updateFullConfig(new FullConfigUpdateCommand(cruiseConfig1, cruiseConfig.getMd5()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, "full-config-save-thread" + counter);

}
 
Example #2
Source File: PipelineConfigValidationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldDetectCyclicDependencies() {
    String pipelineName = "p1";
    BasicCruiseConfig cruiseConfig = GoConfigMother.configWithPipelines(pipelineName, "p2", "p3");
    PipelineConfig p2 = cruiseConfig.getPipelineConfigByName(new CaseInsensitiveString("p2"));
    p2.addMaterialConfig(new DependencyMaterialConfig(new CaseInsensitiveString(pipelineName), new CaseInsensitiveString("stage")));
    PipelineConfig p3 = cruiseConfig.getPipelineConfigByName(new CaseInsensitiveString("p3"));
    p3.addMaterialConfig(new DependencyMaterialConfig(new CaseInsensitiveString("p2"), new CaseInsensitiveString("stage")));

    PipelineConfig p1 = cruiseConfig.getPipelineConfigByName(new CaseInsensitiveString(pipelineName));
    p1 = new Cloner().deepClone(p1); // Do not remove cloning else it changes the underlying cache object defeating the purpose of the test.
    p1.addMaterialConfig(new DependencyMaterialConfig(new CaseInsensitiveString("p3"), new CaseInsensitiveString("stage")));
    p1.validateTree(PipelineConfigSaveValidationContext.forChain(true, cruiseConfig.getGroups().first().getGroup(), cruiseConfig, p1));
    assertThat(p1.materialConfigs().errors().isEmpty()).isFalse();
    assertThat(p1.materialConfigs().errors().on("base")).isEqualTo("Circular dependency: p1 <- p2 <- p3 <- p1");
}
 
Example #3
Source File: PipelineConfigTreeValidator.java    From gocd with Apache License 2.0 6 votes vote down vote up
private void validateFetchTasksForOtherPipelines(PipelineConfigSaveValidationContext validationContext, PipelineConfig downstreamPipeline) {
    for (StageConfig stageConfig : downstreamPipeline.getStages()) {
        for (JobConfig jobConfig : stageConfig.getJobs()) {
            for (Task task : jobConfig.getTasks()) {
                if (task instanceof FetchTask) {
                    FetchTask fetchTask = (FetchTask) task;
                    if (fetchTask.getPipelineNamePathFromAncestor() != null && !StringUtils.isBlank(CaseInsensitiveString.str(fetchTask.getPipelineNamePathFromAncestor().getPath())) && fetchTask.getPipelineNamePathFromAncestor().pathIncludingAncestor().contains(pipelineConfig.name())) {
                        fetchTask = new Cloner().deepClone(fetchTask);
                        fetchTask.validateTask(validationContext.withParent(downstreamPipeline).withParent(stageConfig).withParent(jobConfig));
                        List<String> allErrors = fetchTask.errors().getAll();
                        for (String error : allErrors) {
                            pipelineConfig.errors().add("base", error);
                        }
                    }
                }
            }
        }
    }
}
 
Example #4
Source File: PipelineConfigTreeValidator.java    From gocd with Apache License 2.0 6 votes vote down vote up
private void validateDependencyMaterialsForDownstreams(PipelineConfigSaveValidationContext validationContext, CaseInsensitiveString selected, PipelineConfig downstreamPipeline) {
    Node dependenciesOfSelectedPipeline = validationContext.getDependencyMaterialsFor(selected);
    for (Node.DependencyNode dependencyNode : dependenciesOfSelectedPipeline.getDependencies()) {
        if (dependencyNode.getPipelineName().equals(pipelineConfig.name())) {
            for (MaterialConfig materialConfig : downstreamPipeline.materialConfigs()) {
                if (materialConfig instanceof DependencyMaterialConfig) {
                    DependencyMaterialConfig dependencyMaterialConfig = new Cloner().deepClone((DependencyMaterialConfig) materialConfig);
                    dependencyMaterialConfig.validate(validationContext.withParent(downstreamPipeline));
                    List<String> allErrors = dependencyMaterialConfig.errors().getAll();
                    for (String error : allErrors) {
                        pipelineConfig.errors().add("base", error);
                    }
                }
            }
        }
    }
}
 
Example #5
Source File: GoConfigParallelGraphWalkerTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddErrorsToRawCruiseConfigWhenTemplateHasErrors() {
    CruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("pipeline-1");
    cruiseConfig.getTemplates().add(
            new PipelineTemplateConfig(new CaseInsensitiveString("invalid template name"), new StageConfig(new CaseInsensitiveString("stage-1"), new JobConfigs(new JobConfig("job-1"))
            )));
    PipelineConfig pipelineWithTemplate = new PipelineConfig(new CaseInsensitiveString("pipeline-with-template"), MaterialConfigsMother.defaultMaterialConfigs());
    pipelineWithTemplate.setTemplateName(new CaseInsensitiveString("invalid template name"));
    cruiseConfig.getGroups().get(0).add(pipelineWithTemplate);

    CruiseConfig rawCruiseConfig = new Cloner().deepClone(cruiseConfig);
    MagicalGoConfigXmlLoader.validate(cruiseConfig);
    cruiseConfig.copyErrorsTo(rawCruiseConfig);

    ConfigErrors templateErrors = rawCruiseConfig.getTemplateByName(new CaseInsensitiveString("invalid template name")).errors();
    assertThat(templateErrors.getAll().size(), is(1));
    assertThat(templateErrors.getAll().get(0),
            is("Invalid template name 'invalid template name'. This must be alphanumeric and can contain underscores, hyphens and periods (however, it cannot start with a period). The maximum allowed length is 255 characters."));
}
 
Example #6
Source File: GoConfigParallelGraphWalkerTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandlePipelinesWithTemplates() {
    CruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("pipeline-1");
    cruiseConfig.getTemplates().add(
            new PipelineTemplateConfig(new CaseInsensitiveString("template-1"), new StageConfig(new CaseInsensitiveString("invalid stage name"), new JobConfigs(new JobConfig("job-1"))
            )));
    PipelineConfig pipelineWithTemplate = new PipelineConfig(new CaseInsensitiveString("pipeline-with-template"), MaterialConfigsMother.defaultMaterialConfigs());
    pipelineWithTemplate.setTemplateName(new CaseInsensitiveString("template-1"));
    cruiseConfig.getGroups().get(0).add(pipelineWithTemplate);

    CruiseConfig rawCruiseConfig = new Cloner().deepClone(cruiseConfig);
    MagicalGoConfigXmlLoader.validate(cruiseConfig);
    cruiseConfig.copyErrorsTo(rawCruiseConfig);
    assertThat(rawCruiseConfig.pipelineConfigByName(new CaseInsensitiveString("pipeline-with-template")).errors().isEmpty(), is(true));
    assertThat(cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("pipeline-with-template")).getStage(new CaseInsensitiveString("invalid stage name")).errors().isEmpty(), is(false));

    assertThat(rawCruiseConfig.getTemplateByName(new CaseInsensitiveString("template-1")).errors().isEmpty(), is(true));
}
 
Example #7
Source File: CachedGoConfigIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldErrorOutOnUpdateConfigWithValidPartials_WithMainConfigBreakingPartials() throws GitAPIException, IOException {
    setupExternalConfigRepoWithDependencyMaterialOnPipelineInMainXml("upstream", "downstream");
    String gitShaBeforeSave = configRepository.getCurrentRevCommit().getName();
    CruiseConfig originalConfig = cachedGoConfig.loadForEditing();
    CruiseConfig editedConfig = new Cloner().deepClone(originalConfig);

    editedConfig.getGroups().remove(editedConfig.findGroup("default"));

    try {
        cachedGoConfig.writeFullConfigWithLock(new FullConfigUpdateCommand(editedConfig, goConfigService.configFileMd5()));
        fail("Expected the test to fail");
    } catch (Exception e) {
        String gitShaAfterSave = configRepository.getCurrentRevCommit().getName();
        String configXmlFromConfigFolder = FileUtils.readFileToString(new File(goConfigDao.fileLocation()), UTF_8);
        assertThat(cachedGoConfig.loadForEditing()).isEqualTo(originalConfig);
        assertThat(gitShaAfterSave).isEqualTo(gitShaBeforeSave);
        assertThat(cachedGoConfig.loadForEditing().getMd5()).isEqualTo(configRepository.getCurrentRevision().getMd5());
        assertThat(cachedGoConfig.currentConfig().getMd5()).isEqualTo(configRepository.getCurrentRevision().getMd5());
        assertThat(configXmlFromConfigFolder).isEqualTo(configRepository.getCurrentRevision().getContent());
        RepoConfigOrigin origin = (RepoConfigOrigin) cachedGoPartials.lastValidPartials().get(0).getOrigin();
        assertThat(origin.getRevision()).isEqualTo("r1");
    }
}
 
Example #8
Source File: BuildAssignmentServiceIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCancelBuildsForAllJobsWhenPipelineIsDeleted() throws Exception {
    buildAssignmentService.initialize();
    fixture = new PipelineWithTwoStages(materialRepository, transactionTemplate, temporaryFolder).usingTwoJobs();
    fixture.usingConfigHelper(configHelper).usingDbHelper(dbHelper).onSetUp();
    fixture.createPipelineWithFirstStageScheduled();

    buildAssignmentService.onTimer();

    PipelineConfig pipelineConfig = new Cloner().deepClone(configHelper.getCachedGoConfig().currentConfig().getPipelineConfigByName(new CaseInsensitiveString(fixture.pipelineName)));

    pipelineConfigService.deletePipelineConfig(loserUser, pipelineConfig, new HttpLocalizedOperationResult());

    Pipeline pipeline = pipelineDao.mostRecentPipeline(fixture.pipelineName);
    JobInstance job1 = pipeline.getFirstStage().getJobInstances().getByName(fixture.JOB_FOR_DEV_STAGE);
    JobInstance job2 = pipeline.getFirstStage().getJobInstances().getByName(fixture.DEV_STAGE_SECOND_JOB);

    assertThat(job1.getState(), is(JobState.Completed));
    assertThat(job1.getResult(), is(JobResult.Cancelled));
    assertThat(job2.getState(), is(JobState.Completed));
    assertThat(job2.getResult(), is(JobResult.Cancelled));

    buildAssignmentService.onTimer();
    List<JobPlan> latestJobPlans = buildAssignmentService.jobPlans();
    assertThat(latestJobPlans.size(), is(0));
}
 
Example #9
Source File: BuildAssignmentServiceIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCancelBuildsForDeletedStagesWhenPipelineConfigChanges() throws Exception {
    buildAssignmentService.initialize();

    fixture.createPipelineWithFirstStageScheduled();
    buildAssignmentService.onTimer();

    PipelineConfig originalPipelineConfig = configHelper.getCachedGoConfig().currentConfig().getPipelineConfigByName(new CaseInsensitiveString(fixture.pipelineName));
    PipelineConfig pipelineConfig = new Cloner().deepClone(originalPipelineConfig);
    String md5 = entityHashingService.hashForEntity(originalPipelineConfig, fixture.groupName);
    StageConfig devStage = pipelineConfig.findBy(new CaseInsensitiveString(fixture.devStage));
    pipelineConfig.remove(devStage);
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
    pipelineConfigService.updatePipelineConfig(loserUser, pipelineConfig, fixture.groupName, md5, result);

    Pipeline pipeline = pipelineDao.mostRecentPipeline(fixture.pipelineName);
    JobInstance job = pipeline.getFirstStage().getJobInstances().first();
    assertThat(job.getState(), is(JobState.Completed));
    assertThat(job.getResult(), is(JobResult.Cancelled));

    buildAssignmentService.onTimer();
    List<JobPlan> latestJobPlans = buildAssignmentService.jobPlans();
    assertThat(latestJobPlans.size(), is(0));
}
 
Example #10
Source File: GoConfigServiceIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnTheLatestConfigAsResultWhenThereIsAnMd5Conflict() {
    configHelper.addPipeline("pipeline", "stage");
    String md5 = goConfigService.getConfigForEditing().getMd5();
    goConfigService.updateConfigFromUI(new AddStageToPipelineCommand("secondStage"), md5, Username.ANONYMOUS, new HttpLocalizedOperationResult());

    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
    ConfigUpdateResponse response = goConfigService.updateConfigFromUI(new AddStageToPipelineCommand("thirdStage"), md5, Username.ANONYMOUS, result);

    assertFailedResult(result, "Save failed. Configuration file has been modified by someone else.");
    CruiseConfig expectedConfig = goConfigService.getConfigForEditing();
    CruiseConfig modifiedConfig = new Cloner().deepClone(expectedConfig);
    ReflectionUtil.setField(modifiedConfig, "md5", expectedConfig.getMd5());
    PipelineConfig expected = modifiedConfig.pipelineConfigByName(new CaseInsensitiveString("pipeline"));
    expected.addStageWithoutValidityAssertion(StageConfigMother.custom("thirdStage", "job"));

    PipelineConfig actual = (PipelineConfig) response.getNode();

    assertThat(response.configAfterUpdate(), is(expectedConfig));
    assertThat(response.getCruiseConfig(), is(modifiedConfig));
    assertThat(actual, is(expected));
    assertFailedResult(result, "Save failed. Configuration file has been modified by someone else.");
}
 
Example #11
Source File: InvalidateAuthenticationOnSecurityConfigChangeFilterTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldInvalidateAuthenticationTokenIfTheSecurityConfigHasChanged() throws IOException, ServletException {
    request = HttpRequestBuilder.GET("/")
            .withRequestedSessionIdFromSession()
            .build();

    final AuthenticationToken<UsernamePassword> authenticationToken = setupAuthentication();
    SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
    final HttpSession originalSession = request.getSession(false);

    assertThat(SessionUtils.getAuthenticationToken(request).isAuthenticated(clock, systemEnvironment)).isTrue();
    filter.doFilter(request, response, filterChain);

    clock.addSeconds(1);
    GoConfigMother.addUserAsSuperAdmin(cruiseConfig, "bob");
    filter.onConfigChange(new Cloner().deepClone(cruiseConfig));

    response.reset();
    filter.doFilter(request, response, filterChain);

    assertThat(SessionUtils.getAuthenticationToken(request).isAuthenticated(clock, systemEnvironment)).isFalse();
    assertThat(request.getSession(false)).isSameAs(originalSession);
    verify(cacheService, times(1)).invalidateCache();
}
 
Example #12
Source File: InvalidateAuthenticationOnSecurityConfigChangeFilterTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() {
    initMocks(this);
    //request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
    clock = new TestingClock();
    systemEnvironment = new SystemEnvironment();
    filterChain = mock(FilterChain.class);

    cruiseConfig = new BasicCruiseConfig();
    GoConfigMother.enableSecurityWithPasswordFilePlugin(cruiseConfig);

    filter = new InvalidateAuthenticationOnSecurityConfigChangeFilter(goConfigService, clock, cacheService, pluginRoleService);
    filter.initialize();
    filter.onPluginRoleChange();
    filter.onConfigChange(new Cloner().deepClone(cruiseConfig));
    reset(cacheService);
}
 
Example #13
Source File: PipelineConfigServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetAllViewableGroups() throws Exception {
    CruiseConfig cruiseConfig = new Cloner().deepClone(this.cruiseConfig);
    ReflectionUtil.setField(cruiseConfig, "allPipelineConfigs", null);
    cruiseConfig.addPipeline("group1", PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString()));
    cruiseConfig.addPipeline("group2", PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString()));

    when(goConfigService.cruiseConfig()).thenReturn(cruiseConfig);
    when(goConfigService.getAllPipelineConfigs()).thenReturn(cruiseConfig.getAllPipelineConfigs());

    Username username = new Username("user1");

    when(securityService.hasViewPermissionForGroup(CaseInsensitiveString.str(username.getUsername()), "group1")).thenReturn(true);
    when(securityService.hasViewPermissionForGroup(CaseInsensitiveString.str(username.getUsername()), "group2")).thenReturn(false);

    List<PipelineConfigs> pipelineConfigs = pipelineConfigService.viewableGroupsFor(username);

    assertThat(pipelineConfigs.size(), is(1));
    assertThat(pipelineConfigs.get(0).getGroup(), is("group1"));
}
 
Example #14
Source File: PipelineConfigServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetAllViewableMergePipelineConfigs() throws Exception {
    CruiseConfig mergedCruiseConfig = new Cloner().deepClone(cruiseConfig);
    ReflectionUtil.setField(mergedCruiseConfig, "allPipelineConfigs", null);
    mergedCruiseConfig.addPipeline("group1", PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString()));
    mergedCruiseConfig.addPipeline("group2", PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString()));
    mergedCruiseConfig.addPipeline("group3", PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString()));

    when(goConfigService.getMergedConfigForEditing()).thenReturn(mergedCruiseConfig);
    when(goConfigService.getAllPipelineConfigs()).thenReturn(mergedCruiseConfig.getAllPipelineConfigs());

    Username username = new Username("user1");

    when(securityService.hasViewPermissionForGroup(CaseInsensitiveString.str(username.getUsername()), "group1")).thenReturn(true);
    when(securityService.hasViewPermissionForGroup(CaseInsensitiveString.str(username.getUsername()), "group2")).thenReturn(true);
    when(securityService.hasViewPermissionForGroup(CaseInsensitiveString.str(username.getUsername()), "group3")).thenReturn(false);

    List<PipelineConfigs> pipelineConfigs = pipelineConfigService.viewableGroupsForUserIncludingConfigRepos(username);

    assertThat(pipelineConfigs.size(), is(2));
    assertThat(pipelineConfigs.get(0).getGroup(), is("group2"));
    assertThat(pipelineConfigs.get(1).getGroup(), is("group1"));
}
 
Example #15
Source File: EnvironmentConfigServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReturnAllTheLocalEnvironments() {
    String uat = "uat";

    BasicEnvironmentConfig local = new BasicEnvironmentConfig(new CaseInsensitiveString("uat"));
    local.addEnvironmentVariable("user", "admin");
    BasicEnvironmentConfig remote = new BasicEnvironmentConfig(new CaseInsensitiveString("uat"));
    remote.addEnvironmentVariable("foo", "bar");
    MergeEnvironmentConfig merged = new MergeEnvironmentConfig(local, remote);

    EnvironmentsConfig environments = new EnvironmentsConfig();
    environments.add(merged);

    when(agentService.getAgentInstances()).thenReturn(new AgentInstances(null));

    environmentConfigService.syncEnvironments(environments);

    BasicCruiseConfig cruiseConfig = new BasicCruiseConfig();
    BasicEnvironmentConfig env = (BasicEnvironmentConfig) environmentConfigService.getEnvironmentConfig(uat).getLocal();
    cruiseConfig.addEnvironment(env);
    List<BasicEnvironmentConfig> expectedToEdit = singletonList(new Cloner().deepClone(env));

    when(mockGoConfigService.getConfigForEditing()).thenReturn(cruiseConfig);

    assertThat(environmentConfigService.getAllLocalEnvironments(), is(expectedToEdit));
}
 
Example #16
Source File: StageSqlMapDaoTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() {
    goCache = new StubGoCache(new TestTransactionSynchronizationManager());
    sqlMapClientTemplate = mock(SqlMapClientTemplate.class);
    stageSqlMapDao = new StageSqlMapDao(mock(JobInstanceSqlMapDao.class), new Cache(true, false, false), mock(TransactionTemplate.class), mock(SqlSessionFactory.class), goCache,
            mock(TransactionSynchronizationManager.class), mock(SystemEnvironment.class), null);
    stageSqlMapDao.setSqlMapClientTemplate(sqlMapClientTemplate);
    cloner = mock(Cloner.class);
    ReflectionUtil.setField(stageSqlMapDao, "cloner", cloner);
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) {
            return invocationOnMock.getArguments()[0];
        }
    }).when(cloner).deepClone(anyObject());
}
 
Example #17
Source File: FastFDs.java    From metanome-algorithms with Apache License 2.0 6 votes vote down vote up
public void run() throws OutOfMemoryError {
	int numberOfColumns = this.numberOfColumns;
	
	DifferenceSets[] differenceSetsModulo = this.differenceSets.allModulo(this.numberOfColumns);
	for (int rhsIndex = 0; rhsIndex < numberOfColumns; rhsIndex++) {
		DifferenceSets orig = differenceSetsModulo[rhsIndex];
		Cloner cloner = new Cloner();
		DifferenceSets uncovered = cloner.deepClone(orig);
		if (orig.isEmpty()) {
			ColumnCollection lhs = new ColumnCollection(this.numberOfColumns);
			
			for (int lhsIndex : lhs.setCopy(rhsIndex).complement().getSetBits()) {
				this.minimalDependencies.addRHSColumn(lhs.setCopy(lhsIndex), rhsIndex);
			}
		} 
		else if (!orig.containsEmptySet()) {
			PartialOrder currentOrder = new PartialOrder(orig);
			Path path = new Path(numberOfColumns);
			findCovers(rhsIndex, orig, uncovered, path, currentOrder);
		}
	}
}
 
Example #18
Source File: EnvironmentConfigServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldGetEditablePartOfEnvironmentConfig() {
    String uat = "uat";

    BasicEnvironmentConfig local = new BasicEnvironmentConfig(new CaseInsensitiveString("uat"));
    local.addEnvironmentVariable("user", "admin");
    BasicEnvironmentConfig remote = new BasicEnvironmentConfig(new CaseInsensitiveString("uat"));
    remote.addEnvironmentVariable("foo", "bar");
    MergeEnvironmentConfig merged = new MergeEnvironmentConfig(local, remote);

    EnvironmentsConfig environments = new EnvironmentsConfig();
    environments.add(merged);

    environmentConfigService.syncEnvironments(environments);

    BasicCruiseConfig cruiseConfig = new BasicCruiseConfig();
    BasicEnvironmentConfig env = (BasicEnvironmentConfig) environmentConfigService.getEnvironmentConfig(uat).getLocal();
    cruiseConfig.addEnvironment(env);
    BasicEnvironmentConfig expectedToEdit = new Cloner().deepClone(env);

    when(mockGoConfigService.getConfigForEditing()).thenReturn(cruiseConfig);

    assertThat(environmentConfigService.getEnvironmentForEdit(uat), is(expectedToEdit));
}
 
Example #19
Source File: CachedGoConfigIntegrationTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUpdateConfigWithNoValidPartialsAndInvalidKnownPartials() throws GitAPIException, IOException {
    String gitShaBeforeSave = configRepository.getCurrentRevCommit().getName();
    PartialConfig invalidPartial = PartialConfigMother.invalidPartial("invalid", new RepoConfigOrigin(configRepo, "revision1"));
    goPartialConfig.onSuccessPartialConfig(configRepo, invalidPartial);

    assertThat(cachedGoPartials.lastValidPartials().isEmpty()).isTrue();
    assertThat(cachedGoPartials.lastKnownPartials().contains(invalidPartial)).isTrue();

    CruiseConfig config = new Cloner().deepClone(cachedGoConfig.loadForEditing());

    config.addEnvironment(UUID.randomUUID().toString());

    ConfigSaveState state = cachedGoConfig.writeFullConfigWithLock(new FullConfigUpdateCommand(config, goConfigService.configFileMd5()));

    String gitShaAfterSave = configRepository.getCurrentRevCommit().getName();
    String configXmlFromConfigFolder = FileUtils.readFileToString(new File(goConfigDao.fileLocation()), UTF_8);

    assertThat(state).isEqualTo(ConfigSaveState.UPDATED);
    assertThat(cachedGoConfig.loadForEditing()).isEqualTo(config);
    assertThat(gitShaAfterSave).isNotEqualTo(gitShaBeforeSave);
    assertThat(cachedGoConfig.loadForEditing().getMd5()).isEqualTo(configRepository.getCurrentRevision().getMd5());
    assertThat(cachedGoConfig.currentConfig().getMd5()).isEqualTo(configRepository.getCurrentRevision().getMd5());
    assertThat(configXmlFromConfigFolder).isEqualTo(configRepository.getCurrentRevision().getContent());
    assertThat(cachedGoPartials.lastValidPartials().isEmpty()).isTrue();
    assertThat(cachedGoPartials.lastKnownPartials().contains(invalidPartial)).isTrue();
}
 
Example #20
Source File: Maps.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <K, V> HashMap<K, V> deepCopy(Map<K, V> map) {

    if (map == null) {
        return (HashMap) Collections.emptyMap();
    }

    Cloner cloner = new Cloner();
    HashMap<K, V> copy = (HashMap<K, V>) cloner.deepClone(map);

    return copy;
}
 
Example #21
Source File: PipelineConfigMother.java    From gocd with Apache License 2.0 5 votes vote down vote up
public static PipelineConfig renamePipeline(PipelineConfig oldConfig, String newPipelineName) {
    PipelineConfig newConfig = new Cloner().deepClone(oldConfig);
    HashMap attributes = new HashMap();
    attributes.put(PipelineConfig.NAME, newPipelineName);
    newConfig.setConfigAttributes(attributes);
    return newConfig;
}
 
Example #22
Source File: GrobidPDFProcessor.java    From science-result-extractor with Apache License 2.0 5 votes vote down vote up
private GrobidPDFProcessor() throws IOException, Exception {
        prop = new Properties();
        prop.load(new FileReader("config.properties"));
        grobidHome = prop.getProperty("pGrobidHome");
        grobidProperties = prop.getProperty("pGrobidProperties");
        GrobidHomeFinder grobidHomeFinder = new GrobidHomeFinder(Arrays.asList(grobidHome));
        GrobidProperties.getInstance(grobidHomeFinder);
//        System.out.println(">>>>>>>> GROBID_HOME="+GrobidProperties.get_GROBID_HOME_PATH());
        engine = GrobidFactory.getInstance().createEngine();
        parsers = new EngineParsers();
        gson = new Gson();
        cloner = new Cloner();
    }
 
Example #23
Source File: Tane.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
private CollectionSet<ColumnCollection> generateNextLevel(CollectionSet<ColumnCollection> currentLevel) {
	CollectionSet<ColumnCollection> nextLevel = new CollectionSet<>();
	
	Cloner cloner = new Cloner();
	AprioriGeneration<ColumnCollection> prefixBlockGenerator = new AprioriGeneration<>(cloner.deepClone(currentLevel));
	for (CollectionSet<ColumnCollection> k : prefixBlockGenerator.prefixBlocks()) {
		for (ColumnCollection y : k) {
			for (ColumnCollection z : k.tailSet(y)) {
				ColumnCollection x = y.orCopy(z);
				boolean xInNextLevel = true;
				for (int a : x.getSetBits()) {
					x.clear(a);
					if (!currentLevel.contains(x)) {
						xInNextLevel = false;
						break;
					}
					x.set(a);
				}
				if (xInNextLevel) {
					nextLevel.add(x);
					strippedPartitions.put(x, strippedProduct(strippedPartitions.get(y), strippedPartitions.get(z)));
				}
			}
		}
	}

	return nextLevel;
}
 
Example #24
Source File: BasicCruiseConfig.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public CruiseConfig cloneForValidation() {
    Cloner cloner = new Cloner();
    BasicCruiseConfig configForValidation = cloner.deepClone(BasicCruiseConfig.this);
    // This needs to be done clear the cached fields else the cloned object will all get them.
    configForValidation.resetAllPipelineConfigsCache();
    return configForValidation;
}
 
Example #25
Source File: MergeCruiseConfigTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCollectPipelineNameConflictErrorsInTheChildren_InMergedConfig_WhenCloned() {
    //we need this case because cloning has proven to be problematic with complex object graph in merged config
    BasicCruiseConfig mainCruiseConfig = GoConfigMother.configWithPipelines("pipeline-1");
    PartialConfig partialConfig = PartialConfigMother.withPipelineInGroup("pipeline-1", "g2");
    partialConfig.setOrigin(new RepoConfigOrigin());
    CruiseConfig config = new BasicCruiseConfig(mainCruiseConfig, partialConfig);
    Cloner CLONER = new Cloner();
    CruiseConfig cloned = CLONER.deepClone(config);

    List<ConfigErrors> allErrors = cloned.validateAfterPreprocess();
    assertThat(allErrors.size(), is(2));
    assertThat(allErrors.get(0).on("name"), is("You have defined multiple pipelines named 'pipeline-1'. Pipeline names must be unique. Source(s): [http://some.git at 1234fed, cruise-config.xml]"));
    assertThat(allErrors.get(1).on("name"), is("You have defined multiple pipelines named 'pipeline-1'. Pipeline names must be unique. Source(s): [http://some.git at 1234fed, cruise-config.xml]"));
}
 
Example #26
Source File: GoConfigParallelGraphWalkerTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCopyErrorsForFieldsOnPipelineConfig(){
    PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("pipeline", MaterialConfigsMother.defaultMaterialConfigs(), new JobConfigs(JobConfigMother.createJobConfigWithJobNameAndEmptyResources()));
    pipelineConfig.setVariables(new EnvironmentVariablesConfig(asList(new EnvironmentVariableConfig("name", "value"))));

    PipelineConfig pipelineWithErrors = new Cloner().deepClone(pipelineConfig);
    pipelineWithErrors.getVariables().get(0).addError("name", "error on environment variable");
    pipelineWithErrors.first().addError("name", "error on stage");
    pipelineWithErrors.first().getJobs().first().addError("name", "error on job");
    BasicCruiseConfig.copyErrors(pipelineWithErrors, pipelineConfig);
    assertThat(pipelineConfig.getVariables().get(0).errors().on("name"), is("error on environment variable"));
    assertThat(pipelineConfig.first().errors().on("name"), is("error on stage"));
    assertThat(pipelineConfig.first().getJobs().first().errors().on("name"), is("error on job"));
}
 
Example #27
Source File: ResourceTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldBeAbleToCreateACopyOfItself() {
    Resource existingResource = new Resource("some-name");
    existingResource.setId(2);
    existingResource.setBuildId(10);

    assertThat(existingResource).isEqualTo(new Resource(existingResource));
    assertThat(existingResource).isEqualTo(new Cloner().deepClone(existingResource));
}
 
Example #28
Source File: GoConfigParallelGraphWalkerTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldWalkCruiseConfigObjectsParallelly() {
    CruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("bad pipeline name");
    CruiseConfig rawCruiseConfig = new Cloner().deepClone(cruiseConfig);
    MagicalGoConfigXmlLoader.validate(cruiseConfig);
    cruiseConfig.copyErrorsTo(rawCruiseConfig);
    assertThat(rawCruiseConfig.pipelineConfigByName(new CaseInsensitiveString("bad pipeline name")).errors(),
            is(cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("bad pipeline name")).errors()));
}
 
Example #29
Source File: GoFileConfigDataSourceIntegrationTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void updateConfigOnFileSystem(UpdateConfig updateConfig) throws Exception {
    String cruiseConfigFile = systemEnvironment.getCruiseConfigFile();
    CruiseConfig updatedConfig = new Cloner().deepClone(goConfigService.getConfigForEditing());
    updateConfig.update(updatedConfig);
    File configFile = new File(cruiseConfigFile);
    FileOutputStream outputStream = new FileOutputStream(configFile);
    new MagicalGoConfigXmlWriter(configCache, configElementImplementationRegistry).write(updatedConfig, outputStream, true);
}
 
Example #30
Source File: CachedGoConfigIntegrationTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldMarkAPreviousInvalidPartialAsValid_IfMainXMLSatisfiesTheDependency() throws GitAPIException, IOException {
    String gitShaBeforeSave = configRepository.getCurrentRevCommit().getName();
    PipelineConfig upstream = PipelineConfigMother.createPipelineConfig("upstream", "S", "J");
    PartialConfig partialConfig = PartialConfigMother.pipelineWithDependencyMaterial("downstream", upstream, new RepoConfigOrigin(configRepo, "r2"));
    goPartialConfig.onSuccessPartialConfig(configRepo, partialConfig);

    assertThat(cachedGoPartials.lastKnownPartials().contains(partialConfig)).isTrue();
    assertThat(cachedGoPartials.lastValidPartials().isEmpty()).isTrue();

    CruiseConfig originalConfig = cachedGoConfig.loadForEditing();
    CruiseConfig editedConfig = new Cloner().deepClone(originalConfig);

    editedConfig.addPipeline("default", upstream);
    ConfigSaveState state = cachedGoConfig.writeFullConfigWithLock(new FullConfigUpdateCommand(editedConfig, goConfigService.configFileMd5()));

    String gitShaAfterSave = configRepository.getCurrentRevCommit().getName();
    String configXmlFromConfigFolder = FileUtils.readFileToString(new File(goConfigDao.fileLocation()), UTF_8);

    assertThat(state).isEqualTo(ConfigSaveState.UPDATED);
    assertThat(cachedGoConfig.loadForEditing()).isEqualTo(editedConfig);
    assertThat(gitShaAfterSave).isNotEqualTo(gitShaBeforeSave);
    assertThat(cachedGoConfig.loadForEditing().getMd5()).isEqualTo(configRepository.getCurrentRevision().getMd5());
    assertThat(cachedGoConfig.currentConfig().getMd5()).isEqualTo(configRepository.getCurrentRevision().getMd5());
    assertThat(configXmlFromConfigFolder).isEqualTo(configRepository.getCurrentRevision().getContent());
    RepoConfigOrigin origin = (RepoConfigOrigin) cachedGoPartials.lastValidPartials().get(0).getOrigin();
    assertThat(origin.getRevision()).isEqualTo("r2");
    assertThat(cachedGoPartials.lastKnownPartials().contains(partialConfig)).isTrue();
    assertThat(cachedGoPartials.lastValidPartials().contains(partialConfig)).isTrue();
}