Search in sources :

Example 6 with Stream

use of java.util.stream.Stream in project che by eclipse.

the class MachineProviderImplTest method shouldAddEnvVarsFromMachineConfigToContainerOnDevInstanceCreationFromSnapshot.

@Test
public void shouldAddEnvVarsFromMachineConfigToContainerOnDevInstanceCreationFromSnapshot() throws Exception {
    // given
    Map<String, String> envVarsFromConfig = new HashMap<>();
    envVarsFromConfig.put("ENV_VAR1", "123");
    envVarsFromConfig.put("ENV_VAR2", "234");
    final boolean isDev = true;
    CheServiceImpl machine = createService();
    machine.setEnvironment(envVarsFromConfig);
    // when
    createInstanceFromSnapshot(machine, isDev);
    // then
    ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class);
    verify(dockerConnector).createContainer(argumentCaptor.capture());
    assertTrue(asList(argumentCaptor.getValue().getContainerConfig().getEnv()).containsAll(envVarsFromConfig.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.toList())));
}
Also used : RemoveContainerParams(org.eclipse.che.plugin.docker.client.params.RemoveContainerParams) Arrays(java.util.Arrays) Listeners(org.testng.annotations.Listeners) InspectContainerParams(org.eclipse.che.plugin.docker.client.params.InspectContainerParams) DockerConnectorProvider(org.eclipse.che.plugin.docker.client.DockerConnectorProvider) Volume(org.eclipse.che.plugin.docker.client.json.Volume) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) DOCKER_FILE_TYPE(org.eclipse.che.plugin.docker.machine.DockerInstanceProvider.DOCKER_FILE_TYPE) Mockito.doThrow(org.mockito.Mockito.doThrow) Collections.singleton(java.util.Collections.singleton) Collectors.toMap(java.util.stream.Collectors.toMap) Arrays.asList(java.util.Arrays.asList) Matchers.eq(org.mockito.Matchers.eq) Map(java.util.Map) Assert.assertFalse(org.testng.Assert.assertFalse) MockitoTestNGListener(org.mockito.testng.MockitoTestNGListener) MachineConfig(org.eclipse.che.api.core.model.machine.MachineConfig) BeforeMethod(org.testng.annotations.BeforeMethod) RecipeRetriever(org.eclipse.che.api.machine.server.util.RecipeRetriever) Set(java.util.Set) Collectors(java.util.stream.Collectors) WindowsPathEscaper(org.eclipse.che.commons.lang.os.WindowsPathEscaper) MACHINE_SNAPSHOT_PREFIX(org.eclipse.che.plugin.docker.machine.DockerInstanceProvider.MACHINE_SNAPSHOT_PREFIX) Matchers.any(org.mockito.Matchers.any) List(java.util.List) Stream(java.util.stream.Stream) ContainerConfig(org.eclipse.che.plugin.docker.client.json.ContainerConfig) TagParams(org.eclipse.che.plugin.docker.client.params.TagParams) ServerConfImpl(org.eclipse.che.api.machine.server.model.impl.ServerConfImpl) CreateContainerParams(org.eclipse.che.plugin.docker.client.params.CreateContainerParams) SubjectImpl(org.eclipse.che.commons.subject.SubjectImpl) UserSpecificDockerRegistryCredentialsProvider(org.eclipse.che.plugin.docker.client.UserSpecificDockerRegistryCredentialsProvider) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) PullParams(org.eclipse.che.plugin.docker.client.params.PullParams) DockerConnectorConfiguration(org.eclipse.che.plugin.docker.client.DockerConnectorConfiguration) DataProvider(org.testng.annotations.DataProvider) Mock(org.mockito.Mock) LineConsumer(org.eclipse.che.api.core.util.LineConsumer) RecipeImpl(org.eclipse.che.api.machine.server.recipe.RecipeImpl) Assert.assertEquals(org.testng.Assert.assertEquals) HashMap(java.util.HashMap) ContainerCreated(org.eclipse.che.plugin.docker.client.json.ContainerCreated) Mockito.spy(org.mockito.Mockito.spy) Function(java.util.function.Function) StartContainerParams(org.eclipse.che.plugin.docker.client.params.StartContainerParams) Matchers.anyString(org.mockito.Matchers.anyString) ArrayList(java.util.ArrayList) RemoveImageParams(org.eclipse.che.plugin.docker.client.params.RemoveImageParams) HashSet(java.util.HashSet) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) ProgressMonitor(org.eclipse.che.plugin.docker.client.ProgressMonitor) ArgumentCaptor(org.mockito.ArgumentCaptor) ContainerState(org.eclipse.che.plugin.docker.client.json.ContainerState) Collections.singletonMap(java.util.Collections.singletonMap) ContainerInfo(org.eclipse.che.plugin.docker.client.json.ContainerInfo) Collections.emptySet(java.util.Collections.emptySet) DockerNode(org.eclipse.che.plugin.docker.machine.node.DockerNode) ServerConf(org.eclipse.che.api.core.model.machine.ServerConf) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) Machine(org.eclipse.che.api.core.model.machine.Machine) Mockito.never(org.mockito.Mockito.never) ServerException(org.eclipse.che.api.core.ServerException) DockerConnector(org.eclipse.che.plugin.docker.client.DockerConnector) Assert.assertTrue(org.testng.Assert.assertTrue) Collections(java.util.Collections) Assert.assertEqualsNoOrder(org.testng.Assert.assertEqualsNoOrder) HashMap(java.util.HashMap) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) CreateContainerParams(org.eclipse.che.plugin.docker.client.params.CreateContainerParams) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.testng.annotations.Test)

Example 7 with Stream

use of java.util.stream.Stream in project che by eclipse.

the class MachineProviderImplTest method shouldAddEnvVarsFromMachineConfigToContainerOnNonDevInstanceCreationFromRecipe.

@Test
public void shouldAddEnvVarsFromMachineConfigToContainerOnNonDevInstanceCreationFromRecipe() throws Exception {
    // given
    Map<String, String> envVarsFromConfig = new HashMap<>();
    envVarsFromConfig.put("ENV_VAR1", "123");
    envVarsFromConfig.put("ENV_VAR2", "234");
    final boolean isDev = false;
    CheServiceImpl service = createService();
    service.setEnvironment(envVarsFromConfig);
    // when
    createInstanceFromRecipe(service, isDev);
    // then
    ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class);
    verify(dockerConnector).createContainer(argumentCaptor.capture());
    assertTrue(asList(argumentCaptor.getValue().getContainerConfig().getEnv()).containsAll(envVarsFromConfig.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.toList())));
}
Also used : RemoveContainerParams(org.eclipse.che.plugin.docker.client.params.RemoveContainerParams) Arrays(java.util.Arrays) Listeners(org.testng.annotations.Listeners) InspectContainerParams(org.eclipse.che.plugin.docker.client.params.InspectContainerParams) DockerConnectorProvider(org.eclipse.che.plugin.docker.client.DockerConnectorProvider) Volume(org.eclipse.che.plugin.docker.client.json.Volume) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) DOCKER_FILE_TYPE(org.eclipse.che.plugin.docker.machine.DockerInstanceProvider.DOCKER_FILE_TYPE) Mockito.doThrow(org.mockito.Mockito.doThrow) Collections.singleton(java.util.Collections.singleton) Collectors.toMap(java.util.stream.Collectors.toMap) Arrays.asList(java.util.Arrays.asList) Matchers.eq(org.mockito.Matchers.eq) Map(java.util.Map) Assert.assertFalse(org.testng.Assert.assertFalse) MockitoTestNGListener(org.mockito.testng.MockitoTestNGListener) MachineConfig(org.eclipse.che.api.core.model.machine.MachineConfig) BeforeMethod(org.testng.annotations.BeforeMethod) RecipeRetriever(org.eclipse.che.api.machine.server.util.RecipeRetriever) Set(java.util.Set) Collectors(java.util.stream.Collectors) WindowsPathEscaper(org.eclipse.che.commons.lang.os.WindowsPathEscaper) MACHINE_SNAPSHOT_PREFIX(org.eclipse.che.plugin.docker.machine.DockerInstanceProvider.MACHINE_SNAPSHOT_PREFIX) Matchers.any(org.mockito.Matchers.any) List(java.util.List) Stream(java.util.stream.Stream) ContainerConfig(org.eclipse.che.plugin.docker.client.json.ContainerConfig) TagParams(org.eclipse.che.plugin.docker.client.params.TagParams) ServerConfImpl(org.eclipse.che.api.machine.server.model.impl.ServerConfImpl) CreateContainerParams(org.eclipse.che.plugin.docker.client.params.CreateContainerParams) SubjectImpl(org.eclipse.che.commons.subject.SubjectImpl) UserSpecificDockerRegistryCredentialsProvider(org.eclipse.che.plugin.docker.client.UserSpecificDockerRegistryCredentialsProvider) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) PullParams(org.eclipse.che.plugin.docker.client.params.PullParams) DockerConnectorConfiguration(org.eclipse.che.plugin.docker.client.DockerConnectorConfiguration) DataProvider(org.testng.annotations.DataProvider) Mock(org.mockito.Mock) LineConsumer(org.eclipse.che.api.core.util.LineConsumer) RecipeImpl(org.eclipse.che.api.machine.server.recipe.RecipeImpl) Assert.assertEquals(org.testng.Assert.assertEquals) HashMap(java.util.HashMap) ContainerCreated(org.eclipse.che.plugin.docker.client.json.ContainerCreated) Mockito.spy(org.mockito.Mockito.spy) Function(java.util.function.Function) StartContainerParams(org.eclipse.che.plugin.docker.client.params.StartContainerParams) Matchers.anyString(org.mockito.Matchers.anyString) ArrayList(java.util.ArrayList) RemoveImageParams(org.eclipse.che.plugin.docker.client.params.RemoveImageParams) HashSet(java.util.HashSet) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) ProgressMonitor(org.eclipse.che.plugin.docker.client.ProgressMonitor) ArgumentCaptor(org.mockito.ArgumentCaptor) ContainerState(org.eclipse.che.plugin.docker.client.json.ContainerState) Collections.singletonMap(java.util.Collections.singletonMap) ContainerInfo(org.eclipse.che.plugin.docker.client.json.ContainerInfo) Collections.emptySet(java.util.Collections.emptySet) DockerNode(org.eclipse.che.plugin.docker.machine.node.DockerNode) ServerConf(org.eclipse.che.api.core.model.machine.ServerConf) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) Machine(org.eclipse.che.api.core.model.machine.Machine) Mockito.never(org.mockito.Mockito.never) ServerException(org.eclipse.che.api.core.ServerException) DockerConnector(org.eclipse.che.plugin.docker.client.DockerConnector) Assert.assertTrue(org.testng.Assert.assertTrue) Collections(java.util.Collections) Assert.assertEqualsNoOrder(org.testng.Assert.assertEqualsNoOrder) HashMap(java.util.HashMap) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) CreateContainerParams(org.eclipse.che.plugin.docker.client.params.CreateContainerParams) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.testng.annotations.Test)

Example 8 with Stream

use of java.util.stream.Stream in project che by eclipse.

the class JGitConnection method branchList.

@Override
public List<Branch> branchList(BranchListMode listMode) throws GitException {
    ListBranchCommand listBranchCommand = getGit().branchList();
    if (LIST_ALL == listMode || listMode == null) {
        listBranchCommand.setListMode(ListMode.ALL);
    } else if (LIST_REMOTE == listMode) {
        listBranchCommand.setListMode(ListMode.REMOTE);
    }
    List<Ref> refs;
    String currentRef;
    try {
        refs = listBranchCommand.call();
        String headBranch = getRepository().getBranch();
        Optional<Ref> currentTag = getGit().tagList().call().stream().filter(tag -> tag.getObjectId().getName().equals(headBranch)).findFirst();
        if (currentTag.isPresent()) {
            currentRef = currentTag.get().getName();
        } else {
            currentRef = "refs/heads/" + headBranch;
        }
    } catch (GitAPIException | IOException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
    List<Branch> branches = new ArrayList<>();
    for (Ref ref : refs) {
        String refName = ref.getName();
        boolean isCommitOrTag = Constants.HEAD.equals(refName);
        String branchName = isCommitOrTag ? currentRef : refName;
        String branchDisplayName;
        if (isCommitOrTag) {
            branchDisplayName = "(detached from " + Repository.shortenRefName(currentRef) + ")";
        } else {
            branchDisplayName = Repository.shortenRefName(refName);
        }
        Branch branch = newDto(Branch.class).withName(branchName).withActive(isCommitOrTag || refName.equals(currentRef)).withDisplayName(branchDisplayName).withRemote(refName.startsWith("refs/remotes"));
        branches.add(branch);
    }
    return branches;
}
Also used : InvalidRefNameException(org.eclipse.jgit.api.errors.InvalidRefNameException) Arrays(java.util.Arrays) LsFilesParams(org.eclipse.che.api.git.params.LsFilesParams) RevObject(org.eclipse.jgit.revwalk.RevObject) RebaseResponse(org.eclipse.che.api.git.shared.RebaseResponse) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig) RepositoryState(org.eclipse.jgit.lib.RepositoryState) PullParams(org.eclipse.che.api.git.params.PullParams) SshTransport(org.eclipse.jgit.transport.SshTransport) RevWalk(org.eclipse.jgit.revwalk.RevWalk) CloneParams(org.eclipse.che.api.git.params.CloneParams) RevTag(org.eclipse.jgit.revwalk.RevTag) ResetCommand(org.eclipse.jgit.api.ResetCommand) PathFilter(org.eclipse.jgit.treewalk.filter.PathFilter) Map(java.util.Map) URIish(org.eclipse.jgit.transport.URIish) PullResponse(org.eclipse.che.api.git.shared.PullResponse) TrueFileFilter(org.apache.commons.io.filefilter.TrueFileFilter) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) RebaseStatus(org.eclipse.che.api.git.shared.RebaseResponse.RebaseStatus) GitConflictException(org.eclipse.che.api.git.exception.GitConflictException) EnumSet(java.util.EnumSet) TagCommand(org.eclipse.jgit.api.TagCommand) RepositoryCache(org.eclipse.jgit.lib.RepositoryCache) Result(org.eclipse.jgit.lib.RefUpdate.Result) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) TreeFilter(org.eclipse.jgit.treewalk.filter.TreeFilter) GitConnection(org.eclipse.che.api.git.GitConnection) RefSpec(org.eclipse.jgit.transport.RefSpec) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) RebaseResult(org.eclipse.jgit.api.RebaseResult) CommitCommand(org.eclipse.jgit.api.CommitCommand) Config(org.eclipse.che.api.git.Config) RefUpdate(org.eclipse.jgit.lib.RefUpdate) OpenSshConfig(org.eclipse.jgit.transport.OpenSshConfig) Set(java.util.Set) Status(org.eclipse.che.api.git.shared.Status) Constants(org.eclipse.jgit.lib.Constants) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) TransportCommand(org.eclipse.jgit.api.TransportCommand) Nullable(org.eclipse.che.commons.annotation.Nullable) RevTree(org.eclipse.jgit.revwalk.RevTree) DirectoryFileFilter(org.apache.commons.io.filefilter.DirectoryFileFilter) RemoteUpdateParams(org.eclipse.che.api.git.params.RemoteUpdateParams) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GitInvalidRefNameException(org.eclipse.che.api.git.exception.GitInvalidRefNameException) StatusFormat(org.eclipse.che.api.git.shared.StatusFormat) FileUtils(org.eclipse.jgit.util.FileUtils) Stream(java.util.stream.Stream) CredentialsLoader(org.eclipse.che.api.git.CredentialsLoader) Session(com.jcraft.jsch.Session) PushResult(org.eclipse.jgit.transport.PushResult) DirCache(org.eclipse.jgit.dircache.DirCache) GitRefNotFoundException(org.eclipse.che.api.git.exception.GitRefNotFoundException) FS(org.eclipse.jgit.util.FS) JSchException(com.jcraft.jsch.JSchException) Revision(org.eclipse.che.api.git.shared.Revision) FilenameFilter(java.io.FilenameFilter) RevCommit(org.eclipse.jgit.revwalk.RevCommit) LogCommand(org.eclipse.jgit.api.LogCommand) LogPage(org.eclipse.che.api.git.LogPage) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) PROVIDER_NAME(org.eclipse.che.api.git.shared.ProviderInfo.PROVIDER_NAME) ArrayList(java.util.ArrayList) LogParams(org.eclipse.che.api.git.params.LogParams) SetupUpstreamMode(org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode) ListMode(org.eclipse.jgit.api.ListBranchCommand.ListMode) ResetParams(org.eclipse.che.api.git.params.ResetParams) PushResponse(org.eclipse.che.api.git.shared.PushResponse) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) PushCommand(org.eclipse.jgit.api.PushCommand) RefAlreadyExistsException(org.eclipse.jgit.api.errors.RefAlreadyExistsException) PathFilterGroup(org.eclipse.jgit.treewalk.filter.PathFilterGroup) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) DiffPage(org.eclipse.che.api.git.DiffPage) ErrorCodes(org.eclipse.che.api.core.ErrorCodes) BranchListMode(org.eclipse.che.api.git.shared.BranchListMode) Tag(org.eclipse.che.api.git.shared.Tag) AddRequest(org.eclipse.che.api.git.shared.AddRequest) FileOutputStream(java.io.FileOutputStream) MergeResult(org.eclipse.che.api.git.shared.MergeResult) ProviderInfo(org.eclipse.che.api.git.shared.ProviderInfo) IOException(java.io.IOException) File(java.io.File) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) DiffParams(org.eclipse.che.api.git.params.DiffParams) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) ServerException(org.eclipse.che.api.core.ServerException) StoredConfig(org.eclipse.jgit.lib.StoredConfig) Repository(org.eclipse.jgit.lib.Repository) IOFileFilter(org.apache.commons.io.filefilter.IOFileFilter) PushParams(org.eclipse.che.api.git.params.PushParams) LineConsumerFactory(org.eclipse.che.api.core.util.LineConsumerFactory) FetchParams(org.eclipse.che.api.git.params.FetchParams) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) GitRefAlreadyExistsException(org.eclipse.che.api.git.exception.GitRefAlreadyExistsException) AddCommand(org.eclipse.jgit.api.AddCommand) UserCredential(org.eclipse.che.api.git.UserCredential) CheckoutConflictException(org.eclipse.jgit.api.errors.CheckoutConflictException) NullOutputStream(org.eclipse.jgit.util.io.NullOutputStream) FetchResult(org.eclipse.jgit.transport.FetchResult) CommitParams(org.eclipse.che.api.git.params.CommitParams) ProxyAuthenticator(org.eclipse.che.commons.proxy.ProxyAuthenticator) ResetType(org.eclipse.jgit.api.ResetCommand.ResetType) RemoteAddParams(org.eclipse.che.api.git.params.RemoteAddParams) AUTHENTICATE_URL(org.eclipse.che.api.git.shared.ProviderInfo.AUTHENTICATE_URL) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) GitException(org.eclipse.che.api.git.exception.GitException) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) DtoFactory.newDto(org.eclipse.che.dto.server.DtoFactory.newDto) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) List(java.util.List) Branch(org.eclipse.che.api.git.shared.Branch) RemoteReference(org.eclipse.che.api.git.shared.RemoteReference) Ref(org.eclipse.jgit.lib.Ref) TagCreateParams(org.eclipse.che.api.git.params.TagCreateParams) Optional(java.util.Optional) ListBranchCommand(org.eclipse.jgit.api.ListBranchCommand) Pattern(java.util.regex.Pattern) RmCommand(org.eclipse.jgit.api.RmCommand) GitUrlUtils(org.eclipse.che.api.git.GitUrlUtils) Remote(org.eclipse.che.api.git.shared.Remote) System.lineSeparator(java.lang.System.lineSeparator) JSch(com.jcraft.jsch.JSch) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) LineConsumer(org.eclipse.che.api.core.util.LineConsumer) CloneCommand(org.eclipse.jgit.api.CloneCommand) HashMap(java.util.HashMap) RebaseCommand(org.eclipse.jgit.api.RebaseCommand) LIST_ALL(org.eclipse.che.api.git.shared.BranchListMode.LIST_ALL) LIST_LOCAL(org.eclipse.che.api.git.shared.BranchListMode.LIST_LOCAL) FetchCommand(org.eclipse.jgit.api.FetchCommand) Inject(javax.inject.Inject) HashSet(java.util.HashSet) RmParams(org.eclipse.che.api.git.params.RmParams) LIST_REMOTE(org.eclipse.che.api.git.shared.BranchListMode.LIST_REMOTE) Files(com.google.common.io.Files) SshKeyProvider(org.eclipse.che.plugin.ssh.key.script.SshKeyProvider) SshSessionFactory(org.eclipse.jgit.transport.SshSessionFactory) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) BatchingProgressMonitor(org.eclipse.jgit.lib.BatchingProgressMonitor) AndTreeFilter(org.eclipse.jgit.treewalk.filter.AndTreeFilter) EmptyTreeIterator(org.eclipse.jgit.treewalk.EmptyTreeIterator) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) AddParams(org.eclipse.che.api.git.params.AddParams) GitUserResolver(org.eclipse.che.api.git.GitUserResolver) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) CreateBranchCommand(org.eclipse.jgit.api.CreateBranchCommand) ConfigConstants(org.eclipse.jgit.lib.ConfigConstants) ShowFileContentResponse(org.eclipse.che.api.git.shared.ShowFileContentResponse) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) ObjectId(org.eclipse.jgit.lib.ObjectId) TransportException(org.eclipse.jgit.api.errors.TransportException) OWNER_READ(java.nio.file.attribute.PosixFilePermission.OWNER_READ) RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) LsRemoteCommand(org.eclipse.jgit.api.LsRemoteCommand) CheckoutParams(org.eclipse.che.api.git.params.CheckoutParams) TrackingRefUpdate(org.eclipse.jgit.transport.TrackingRefUpdate) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Git(org.eclipse.jgit.api.Git) DetachedHeadException(org.eclipse.jgit.api.errors.DetachedHeadException) DiffEntry(org.eclipse.jgit.diff.DiffEntry) OWNER_WRITE(java.nio.file.attribute.PosixFilePermission.OWNER_WRITE) GitUser(org.eclipse.che.api.git.shared.GitUser) Collections(java.util.Collections) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) SECONDS(java.util.concurrent.TimeUnit.SECONDS) GitException(org.eclipse.che.api.git.exception.GitException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ListBranchCommand(org.eclipse.jgit.api.ListBranchCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Ref(org.eclipse.jgit.lib.Ref) Branch(org.eclipse.che.api.git.shared.Branch)

Example 9 with Stream

use of java.util.stream.Stream in project che by eclipse.

the class WorkspaceDaoTest method shouldUpdateWorkspace.

@Test(dependsOnMethods = "shouldGetWorkspaceById")
public void shouldUpdateWorkspace() throws Exception {
    final WorkspaceImpl workspace = new WorkspaceImpl(workspaces[0], workspaces[0].getAccount());
    // Remove an existing project configuration from workspace
    workspace.getConfig().getProjects().remove(1);
    // Add new project to the workspace configuration
    final SourceStorageImpl source3 = new SourceStorageImpl();
    source3.setType("type3");
    source3.setLocation("location3");
    source3.setParameters(new HashMap<>(ImmutableMap.of("param1", "value1", "param2", "value2", "param3", "value3")));
    final ProjectConfigImpl newProjectCfg = new ProjectConfigImpl();
    newProjectCfg.setPath("/path3");
    newProjectCfg.setType("type3");
    newProjectCfg.setName("project3");
    newProjectCfg.setDescription("description3");
    newProjectCfg.getMixins().addAll(asList("mixin3", "mixin4"));
    newProjectCfg.setSource(source3);
    newProjectCfg.getAttributes().put("new-key", asList("1", "2"));
    workspace.getConfig().getProjects().add(newProjectCfg);
    // Update an existing project configuration
    final ProjectConfigImpl projectCfg = workspace.getConfig().getProjects().get(0);
    projectCfg.getAttributes().clear();
    projectCfg.getSource().setLocation("new-location");
    projectCfg.getSource().setType("new-type");
    projectCfg.getSource().getParameters().put("new-param", "new-param-value");
    projectCfg.getMixins().add("new-mixin");
    projectCfg.setPath("/new-path");
    projectCfg.setDescription("new project description");
    // Remove an existing command
    workspace.getConfig().getCommands().remove(1);
    // Add a new command
    final CommandImpl newCmd = new CommandImpl();
    newCmd.setName("name3");
    newCmd.setType("type3");
    newCmd.setCommandLine("cmd3");
    newCmd.getAttributes().putAll(ImmutableMap.of("attr1", "value1", "attr2", "value2", "attr3", "value3"));
    workspace.getConfig().getCommands().add(newCmd);
    // Update an existing command
    final CommandImpl command = workspace.getConfig().getCommands().get(0);
    command.setName("new-name");
    command.setType("new-type");
    command.setCommandLine("new-command-line");
    command.getAttributes().clear();
    // Add a new environment
    final EnvironmentRecipeImpl newRecipe = new EnvironmentRecipeImpl();
    newRecipe.setLocation("new-location");
    newRecipe.setType("new-type");
    newRecipe.setContentType("new-content-type");
    newRecipe.setContent("new-content");
    final ExtendedMachineImpl newMachine = new ExtendedMachineImpl();
    final ServerConf2Impl serverConf1 = new ServerConf2Impl("2265", "http", singletonMap("prop1", "val"));
    final ServerConf2Impl serverConf2 = new ServerConf2Impl("2266", "ftp", singletonMap("prop1", "val"));
    newMachine.setServers(ImmutableMap.of("ref1", serverConf1, "ref2", serverConf2));
    newMachine.setAgents(ImmutableList.of("agent5", "agent4"));
    newMachine.setAttributes(singletonMap("att1", "val"));
    final EnvironmentImpl newEnv = new EnvironmentImpl();
    newEnv.setMachines(ImmutableMap.of("new-machine", newMachine));
    newEnv.setRecipe(newRecipe);
    workspace.getConfig().getEnvironments().put("new-env", newEnv);
    // Update an existing environment
    final EnvironmentImpl defaultEnv = workspace.getConfig().getEnvironments().get(workspace.getConfig().getDefaultEnv());
    // Remove an existing machine config
    final List<String> machineNames = new ArrayList<>(defaultEnv.getMachines().keySet());
    // Update an existing machine
    final ExtendedMachineImpl existingMachine = defaultEnv.getMachines().get(machineNames.get(1));
    existingMachine.setAgents(asList("new-agent1", "new-agent2"));
    existingMachine.setAttributes(ImmutableMap.of("attr1", "value1", "attr2", "value2", "attr3", "value3"));
    existingMachine.getServers().clear();
    existingMachine.getServers().put("new-ref", new ServerConf2Impl("new-port", "new-protocol", ImmutableMap.of("prop1", "value")));
    defaultEnv.getMachines().remove(machineNames.get(0));
    defaultEnv.getRecipe().setContent("updated-content");
    defaultEnv.getRecipe().setContentType("updated-content-type");
    defaultEnv.getRecipe().setLocation("updated-location");
    defaultEnv.getRecipe().setType("updated-type");
    // Remove an existing environment
    final Optional<String> nonDefaultEnv = workspace.getConfig().getEnvironments().keySet().stream().filter(key -> !key.equals(workspace.getConfig().getDefaultEnv())).findAny();
    assertTrue(nonDefaultEnv.isPresent());
    workspace.getConfig().getEnvironments().remove(nonDefaultEnv.get());
    // Update workspace configuration
    final WorkspaceConfigImpl wCfg = workspace.getConfig();
    wCfg.setDefaultEnv("new-env");
    wCfg.setName("new-name");
    wCfg.setDescription("This is a new description");
    // Update workspace object
    workspace.setAccount(new AccountImpl("accId", "new-namespace", "test"));
    workspace.getAttributes().clear();
    workspaceDao.update(workspace);
    assertEquals(workspaceDao.get(workspace.getId()), new WorkspaceImpl(workspace, workspace.getAccount()));
}
Also used : CommandImpl(org.eclipse.che.api.machine.server.model.impl.CommandImpl) BeforeWorkspaceRemovedEvent(org.eclipse.che.api.workspace.server.event.BeforeWorkspaceRemovedEvent) Mockito.doCallRealMethod(org.mockito.Mockito.doCallRealMethod) SourceStorageImpl(org.eclipse.che.api.workspace.server.model.impl.SourceStorageImpl) Arrays(java.util.Arrays) Listeners(org.testng.annotations.Listeners) EnvironmentImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl) TckRepository(org.eclipse.che.commons.test.tck.repository.TckRepository) WorkspaceConfigImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) HashMap(java.util.HashMap) AccountImpl(org.eclipse.che.account.spi.AccountImpl) ExtendedMachineImpl(org.eclipse.che.api.workspace.server.model.impl.ExtendedMachineImpl) TckRepositoryException(org.eclipse.che.commons.test.tck.repository.TckRepositoryException) AfterMethod(org.testng.annotations.AfterMethod) ServerConf2Impl(org.eclipse.che.api.workspace.server.model.impl.ServerConf2Impl) CascadeEvent(org.eclipse.che.core.db.cascade.event.CascadeEvent) ArrayList(java.util.ArrayList) Collections.singletonList(java.util.Collections.singletonList) Inject(javax.inject.Inject) HashSet(java.util.HashSet) Mockito.doThrow(org.mockito.Mockito.doThrow) ImmutableList(com.google.common.collect.ImmutableList) CascadeEventSubscriber(org.eclipse.che.core.db.cascade.CascadeEventSubscriber) WorkspaceRemovedEvent(org.eclipse.che.api.workspace.server.event.WorkspaceRemovedEvent) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) ConflictException(org.eclipse.che.api.core.ConflictException) Collections.singletonMap(java.util.Collections.singletonMap) WorkspaceDao(org.eclipse.che.api.workspace.server.spi.WorkspaceDao) EventService(org.eclipse.che.api.core.notification.EventService) EnvironmentRecipeImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentRecipeImpl) ImmutableMap(com.google.common.collect.ImmutableMap) Assert.fail(org.testng.Assert.fail) BeforeMethod(org.testng.annotations.BeforeMethod) NotFoundException(org.eclipse.che.api.core.NotFoundException) Matchers.any(org.mockito.Matchers.any) TckListener(org.eclipse.che.commons.test.tck.TckListener) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Stream(java.util.stream.Stream) ServerException(org.eclipse.che.api.core.ServerException) CommandImpl(org.eclipse.che.api.machine.server.model.impl.CommandImpl) ProjectConfigImpl(org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl) Optional(java.util.Optional) Assert.assertTrue(org.testng.Assert.assertTrue) WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) Mockito.mock(org.mockito.Mockito.mock) WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) ArrayList(java.util.ArrayList) AccountImpl(org.eclipse.che.account.spi.AccountImpl) EnvironmentImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl) SourceStorageImpl(org.eclipse.che.api.workspace.server.model.impl.SourceStorageImpl) ServerConf2Impl(org.eclipse.che.api.workspace.server.model.impl.ServerConf2Impl) ExtendedMachineImpl(org.eclipse.che.api.workspace.server.model.impl.ExtendedMachineImpl) WorkspaceConfigImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl) ProjectConfigImpl(org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl) EnvironmentRecipeImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentRecipeImpl) Test(org.testng.annotations.Test)

Example 10 with Stream

use of java.util.stream.Stream in project vert.x by eclipse.

the class SSLHelper method getTrustMgrFactory.

private TrustManagerFactory getTrustMgrFactory(VertxInternal vertx) throws Exception {
    TrustManagerFactory fact;
    if (trustAll) {
        TrustManager[] mgrs = new TrustManager[] { createTrustAllTrustManager() };
        fact = new VertxTrustManagerFactory(mgrs);
    } else if (trustOptions != null) {
        fact = trustOptions.getTrustManagerFactory(vertx);
    } else {
        return null;
    }
    if (crlPaths != null && crlValues != null && (crlPaths.size() > 0 || crlValues.size() > 0)) {
        Stream<Buffer> tmp = crlPaths.stream().map(path -> vertx.resolveFile(path).getAbsolutePath()).map(vertx.fileSystem()::readFileBlocking);
        tmp = Stream.concat(tmp, crlValues.stream());
        CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
        ArrayList<CRL> crls = new ArrayList<>();
        for (Buffer crlValue : tmp.collect(Collectors.toList())) {
            crls.addAll(certificatefactory.generateCRLs(new ByteArrayInputStream(crlValue.getBytes())));
        }
        TrustManager[] mgrs = createUntrustRevokedCertTrustManager(fact.getTrustManagers(), crls);
        fact = new VertxTrustManagerFactory(mgrs);
    }
    return fact;
}
Also used : VertxException(io.vertx.core.VertxException) X509Certificate(java.security.cert.X509Certificate) java.util(java.util) CertificateFactory(java.security.cert.CertificateFactory) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) SimpleTrustManagerFactory(io.netty.handler.ssl.util.SimpleTrustManagerFactory) LoggerFactory(io.vertx.core.logging.LoggerFactory) OpenSSLEngineOptions(io.vertx.core.net.OpenSSLEngineOptions) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpVersion(io.vertx.core.http.HttpVersion) KeyCertOptions(io.vertx.core.net.KeyCertOptions) HttpClientOptions(io.vertx.core.http.HttpClientOptions) Logger(io.vertx.core.logging.Logger) CRL(java.security.cert.CRL) JdkSSLEngineOptions(io.vertx.core.net.JdkSSLEngineOptions) TCPSSLOptions(io.vertx.core.net.TCPSSLOptions) SSLEngineOptions(io.vertx.core.net.SSLEngineOptions) VertxInternal(io.vertx.core.impl.VertxInternal) KeyStore(java.security.KeyStore) CertificateException(java.security.cert.CertificateException) io.netty.handler.ssl(io.netty.handler.ssl) Collectors(java.util.stream.Collectors) NetClientOptions(io.vertx.core.net.NetClientOptions) TrustOptions(io.vertx.core.net.TrustOptions) NetServerOptions(io.vertx.core.net.NetServerOptions) Stream(java.util.stream.Stream) Buffer(io.vertx.core.buffer.Buffer) ClientAuth(io.vertx.core.http.ClientAuth) HttpServerOptions(io.vertx.core.http.HttpServerOptions) javax.net.ssl(javax.net.ssl) Buffer(io.vertx.core.buffer.Buffer) ByteArrayInputStream(java.io.ByteArrayInputStream) SimpleTrustManagerFactory(io.netty.handler.ssl.util.SimpleTrustManagerFactory) CRL(java.security.cert.CRL) CertificateFactory(java.security.cert.CertificateFactory)

Aggregations

Stream (java.util.stream.Stream)161 Collectors (java.util.stream.Collectors)98 List (java.util.List)89 ArrayList (java.util.ArrayList)66 Map (java.util.Map)66 Set (java.util.Set)59 IOException (java.io.IOException)58 Optional (java.util.Optional)45 Collections (java.util.Collections)43 HashMap (java.util.HashMap)43 Arrays (java.util.Arrays)33 HashSet (java.util.HashSet)33 File (java.io.File)32 Path (java.nio.file.Path)32 Function (java.util.function.Function)28 Logger (org.slf4j.Logger)26 LoggerFactory (org.slf4j.LoggerFactory)26 java.util (java.util)25 Predicate (java.util.function.Predicate)23 Objects (java.util.Objects)22