Search in sources :

Example 16 with Optional

use of java.util.Optional in project buck by facebook.

the class BuildCommandTest method setUp.

@Before
public void setUp() {
    BuildRuleResolver ruleResolver = new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
    resolver = new SourcePathResolver(new SourcePathRuleFinder(ruleResolver));
    LinkedHashMap<BuildRule, Optional<BuildResult>> ruleToResult = new LinkedHashMap<>();
    FakeBuildRule rule1 = new FakeBuildRule(BuildTargetFactory.newInstance("//fake:rule1"), resolver);
    rule1.setOutputFile("buck-out/gen/fake/rule1.txt");
    ruleResolver.addToIndex(rule1);
    ruleToResult.put(rule1, Optional.of(BuildResult.success(rule1, BUILT_LOCALLY, CacheResult.miss())));
    BuildRule rule2 = new FakeBuildRule(BuildTargetFactory.newInstance("//fake:rule2"), resolver);
    BuildResult rule2Failure = BuildResult.failure(rule2, new RuntimeException("some"));
    ruleToResult.put(rule2, Optional.of(rule2Failure));
    ruleResolver.addToIndex(rule2);
    BuildRule rule3 = new FakeBuildRule(BuildTargetFactory.newInstance("//fake:rule3"), resolver);
    ruleToResult.put(rule3, Optional.of(BuildResult.success(rule3, FETCHED_FROM_CACHE, CacheResult.hit("dir"))));
    ruleResolver.addToIndex(rule3);
    BuildRule rule4 = new FakeBuildRule(BuildTargetFactory.newInstance("//fake:rule4"), resolver);
    ruleToResult.put(rule4, Optional.empty());
    ruleResolver.addToIndex(rule4);
    buildExecutionResult = BuildExecutionResult.builder().setResults(ruleToResult).setFailures(ImmutableSet.of(rule2Failure)).build();
}
Also used : BuildResult(com.facebook.buck.rules.BuildResult) Optional(java.util.Optional) FakeBuildRule(com.facebook.buck.rules.FakeBuildRule) FakeBuildRule(com.facebook.buck.rules.FakeBuildRule) BuildRule(com.facebook.buck.rules.BuildRule) DefaultTargetNodeToBuildRuleTransformer(com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer) SourcePathResolver(com.facebook.buck.rules.SourcePathResolver) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder) BuildRuleResolver(com.facebook.buck.rules.BuildRuleResolver) LinkedHashMap(java.util.LinkedHashMap) Before(org.junit.Before)

Example 17 with Optional

use of java.util.Optional in project che by eclipse.

the class CheEnvironmentEngineTest method machineStopShouldFireEvents.

@Test
public void machineStopShouldFireEvents() throws Exception {
    // given
    List<Instance> instances = startEnv();
    Optional<Instance> instanceOpt = instances.stream().filter(machine -> !machine.getConfig().isDev()).findAny();
    assertTrue(instanceOpt.isPresent(), "Required for test non-dev machine is not found");
    Instance instance = instanceOpt.get();
    // when
    engine.stopMachine(instance.getWorkspaceId(), instance.getId());
    // then
    verify(eventService).publish(newDto(MachineStatusEvent.class).withEventType(MachineStatusEvent.EventType.CREATING).withDev(instance.getConfig().isDev()).withMachineName(instance.getConfig().getName()).withMachineId(instance.getId()).withWorkspaceId(instance.getWorkspaceId()));
    verify(eventService).publish(newDto(MachineStatusEvent.class).withEventType(MachineStatusEvent.EventType.RUNNING).withDev(instance.getConfig().isDev()).withMachineName(instance.getConfig().getName()).withMachineId(instance.getId()).withWorkspaceId(instance.getWorkspaceId()));
}
Also used : Agent(org.eclipse.che.api.agent.shared.model.Agent) MachineStatusEvent(org.eclipse.che.api.machine.shared.dto.event.MachineStatusEvent) Listeners(org.testng.annotations.Listeners) MachineStatus(org.eclipse.che.api.core.model.machine.MachineStatus) EnvironmentImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl) MachineLimitsImpl(org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl) Test(org.testng.annotations.Test) WorkspaceSharedPool(org.eclipse.che.api.workspace.server.WorkspaceSharedPool) AfterMethod(org.testng.annotations.AfterMethod) ServerConf2Impl(org.eclipse.che.api.workspace.server.model.impl.ServerConf2Impl) Collections.singletonList(java.util.Collections.singletonList) Mockito.doThrow(org.mockito.Mockito.doThrow) Matchers.anyBoolean(org.mockito.Matchers.anyBoolean) EnvironmentStartInterruptedException(org.eclipse.che.api.environment.server.exception.EnvironmentStartInterruptedException) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Arrays.asList(java.util.Arrays.asList) Matchers.eq(org.mockito.Matchers.eq) Map(java.util.Map) EnvironmentNotRunningException(org.eclipse.che.api.environment.server.exception.EnvironmentNotRunningException) MessageConsumer(org.eclipse.che.api.core.util.MessageConsumer) CheServiceBuildContextImpl(org.eclipse.che.api.environment.server.model.CheServiceBuildContextImpl) Mockito.doReturn(org.mockito.Mockito.doReturn) EventService(org.eclipse.che.api.core.notification.EventService) Assert.assertNotEquals(org.testng.Assert.assertNotEquals) MockitoTestNGListener(org.mockito.testng.MockitoTestNGListener) EventSubscriber(org.eclipse.che.api.core.notification.EventSubscriber) Collections.emptyList(java.util.Collections.emptyList) BeforeMethod(org.testng.annotations.BeforeMethod) DtoFactory.newDto(org.eclipse.che.dto.server.DtoFactory.newDto) UUID(java.util.UUID) String.format(java.lang.String.format) Matchers.any(org.mockito.Matchers.any) List(java.util.List) Mockito.inOrder(org.mockito.Mockito.inOrder) Optional(java.util.Optional) AgentKey(org.eclipse.che.api.agent.shared.model.AgentKey) ServerConfImpl(org.eclipse.che.api.machine.server.model.impl.ServerConfImpl) SubjectImpl(org.eclipse.che.commons.subject.SubjectImpl) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) AgentRegistry(org.eclipse.che.api.agent.server.AgentRegistry) Mockito.mock(org.mockito.Mockito.mock) MachineInstanceProviders(org.eclipse.che.api.machine.server.MachineInstanceProviders) Assert.assertNull(org.testng.Assert.assertNull) Size(org.eclipse.che.commons.lang.Size) Mock(org.mockito.Mock) LineConsumer(org.eclipse.che.api.core.util.LineConsumer) Assert.assertEquals(org.testng.Assert.assertEquals) HashMap(java.util.HashMap) ExtendedMachineImpl(org.eclipse.che.api.workspace.server.model.impl.ExtendedMachineImpl) Mockito.spy(org.mockito.Mockito.spy) Captor(org.mockito.Captor) CheServicesEnvironmentImpl(org.eclipse.che.api.environment.server.model.CheServicesEnvironmentImpl) SnapshotImpl(org.eclipse.che.api.machine.server.model.impl.SnapshotImpl) Matchers.anyString(org.mockito.Matchers.anyString) ArrayList(java.util.ArrayList) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) InstanceProvider(org.eclipse.che.api.machine.server.spi.InstanceProvider) ArgumentCaptor(org.mockito.ArgumentCaptor) ServerConf2(org.eclipse.che.api.core.model.workspace.ServerConf2) ConflictException(org.eclipse.che.api.core.ConflictException) Collections.singletonMap(java.util.Collections.singletonMap) InstanceStateEvent(org.eclipse.che.api.machine.server.event.InstanceStateEvent) Instance(org.eclipse.che.api.machine.server.spi.Instance) MachineRuntimeInfoImpl(org.eclipse.che.api.machine.server.model.impl.MachineRuntimeInfoImpl) SnapshotDao(org.eclipse.che.api.machine.server.spi.SnapshotDao) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) Collections.emptyMap(java.util.Collections.emptyMap) EnvironmentRecipeImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentRecipeImpl) InOrder(org.mockito.InOrder) ExtendedMachine(org.eclipse.che.api.core.model.workspace.ExtendedMachine) Assert.fail(org.testng.Assert.fail) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) MachineLogMessage(org.eclipse.che.api.core.model.machine.MachineLogMessage) NotFoundException(org.eclipse.che.api.core.NotFoundException) Mockito.verify(org.mockito.Mockito.verify) Machine(org.eclipse.che.api.core.model.machine.Machine) MachineSourceImpl(org.eclipse.che.api.machine.server.model.impl.MachineSourceImpl) Mockito.never(org.mockito.Mockito.never) MachineImpl(org.eclipse.che.api.machine.server.model.impl.MachineImpl) RecipeDownloader(org.eclipse.che.api.machine.server.util.RecipeDownloader) ServerException(org.eclipse.che.api.core.ServerException) MachineConfigImpl(org.eclipse.che.api.machine.server.model.impl.MachineConfigImpl) Assert.assertTrue(org.testng.Assert.assertTrue) Collections(java.util.Collections) Instance(org.eclipse.che.api.machine.server.spi.Instance) Test(org.testng.annotations.Test)

Example 18 with Optional

use of java.util.Optional in project jetty.project by eclipse.

the class Modules method enable.

private void enable(Set<String> newlyEnabled, Module module, String enabledFrom, boolean transitive) {
    StartLog.debug("enable %s from %s transitive=%b", module, enabledFrom, transitive);
    if (newlyEnabled.contains(module.getName())) {
        StartLog.debug("Cycle at %s", module);
        return;
    }
    // Check that this is not already provided by another module!
    for (String name : module.getProvides()) {
        Set<Module> providers = _provided.get(name);
        if (providers != null) {
            for (Module p : providers) {
                if (p != module && p.isEnabled()) {
                    // If the already enabled module is transitive and this enable is not
                    if (p.isTransitive() && !transitive)
                        p.clearTransitiveEnable();
                    else
                        throw new UsageException("Module %s provides %s, which is already provided by %s enabled in %s", module.getName(), name, p.getName(), p.getEnableSources());
                }
            }
            ;
        }
    }
    // Enable the  module
    if (module.enable(enabledFrom, transitive)) {
        StartLog.debug("enabled %s", module.getName());
        newlyEnabled.add(module.getName());
        // Expand module properties
        module.expandDependencies(_args.getProperties());
        // Apply default configuration
        if (module.hasDefaultConfig()) {
            for (String line : module.getDefaultConfig()) _args.parse(line, module.getName() + "[ini]");
            for (Module m : _modules) m.expandDependencies(_args.getProperties());
        }
    }
    // Process module dependencies (always processed as may be dynamic)
    for (String dependsOn : module.getDepends()) {
        // Look for modules that provide that dependency
        Set<Module> providers = getAvailableProviders(dependsOn);
        StartLog.debug("Module %s depends on %s provided by ", module, dependsOn, providers);
        // If there are no known providers of the module
        if (providers.isEmpty()) {
            // look for a dynamic module
            if (dependsOn.contains("/")) {
                Path file = _baseHome.getPath("modules/" + dependsOn + ".mod");
                registerModule(file).expandDependencies(_args.getProperties());
                providers = _provided.get(dependsOn);
                if (providers == null || providers.isEmpty())
                    throw new UsageException("Module %s does not provide %s", _baseHome.toShortForm(file), dependsOn);
                enable(newlyEnabled, providers.stream().findFirst().get(), "dynamic dependency of " + module.getName(), true);
                continue;
            }
            throw new UsageException("No module found to provide %s for %s", dependsOn, module);
        }
        // If a provider is already enabled, then add a transitive enable
        if (providers.stream().filter(Module::isEnabled).count() != 0)
            providers.stream().filter(m -> m.isEnabled() && m != module).forEach(m -> enable(newlyEnabled, m, "transitive provider of " + dependsOn + " for " + module.getName(), true));
        else {
            // Is there an obvious default?
            Optional<Module> dftProvider = (providers.size() == 1) ? providers.stream().findFirst() : providers.stream().filter(m -> m.getName().equals(dependsOn)).findFirst();
            if (dftProvider.isPresent())
                enable(newlyEnabled, dftProvider.get(), "transitive provider of " + dependsOn + " for " + module.getName(), true);
            else if (StartLog.isDebugEnabled())
                StartLog.debug("Module %s requires a %s implementation from one of %s", module, dependsOn, providers);
        }
    }
}
Also used : Path(java.nio.file.Path) Properties(java.util.Properties) Iterator(java.util.Iterator) Set(java.util.Set) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IOException(java.io.IOException) HashMap(java.util.HashMap) FileInputStream(java.io.FileInputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Consumer(java.util.function.Consumer) List(java.util.List) Stream(java.util.stream.Stream) Map(java.util.Map) Optional(java.util.Optional) Path(java.nio.file.Path) Collections(java.util.Collections)

Example 19 with Optional

use of java.util.Optional 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 20 with Optional

use of java.util.Optional in project che by eclipse.

the class JGitConnection method checkout.

@Override
public void checkout(CheckoutParams params) throws GitException {
    CheckoutCommand checkoutCommand = getGit().checkout();
    String startPoint = params.getStartPoint();
    String name = params.getName();
    String trackBranch = params.getTrackBranch();
    // checkout files?
    List<String> files = params.getFiles();
    boolean shouldCheckoutToFile = name != null && new File(getWorkingDir(), name).exists();
    if (shouldCheckoutToFile || !files.isEmpty()) {
        if (shouldCheckoutToFile) {
            checkoutCommand.addPath(params.getName());
        } else {
            files.forEach(checkoutCommand::addPath);
        }
    } else {
        // checkout branch
        if (startPoint != null && trackBranch != null) {
            throw new GitException("Start point and track branch can not be used together.");
        }
        if (params.isCreateNew() && name == null) {
            throw new GitException("Branch name must be set when createNew equals to true.");
        }
        if (startPoint != null) {
            checkoutCommand.setStartPoint(startPoint);
        }
        if (params.isCreateNew()) {
            checkoutCommand.setCreateBranch(true);
            checkoutCommand.setName(name);
        } else if (name != null) {
            checkoutCommand.setName(name);
            List<String> localBranches = branchList(LIST_LOCAL).stream().map(Branch::getDisplayName).collect(Collectors.toList());
            if (!localBranches.contains(name)) {
                Optional<Branch> remoteBranch = branchList(LIST_REMOTE).stream().filter(branch -> branch.getName().contains(name)).findFirst();
                if (remoteBranch.isPresent()) {
                    checkoutCommand.setCreateBranch(true);
                    checkoutCommand.setStartPoint(remoteBranch.get().getName());
                }
            }
        }
        if (trackBranch != null) {
            if (name == null) {
                checkoutCommand.setName(cleanRemoteName(trackBranch));
            }
            checkoutCommand.setCreateBranch(true);
            checkoutCommand.setStartPoint(trackBranch);
        }
        checkoutCommand.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
    }
    try {
        checkoutCommand.call();
    } catch (CheckoutConflictException exception) {
        throw new GitConflictException(exception.getMessage(), exception.getConflictingPaths());
    } catch (RefAlreadyExistsException exception) {
        throw new GitRefAlreadyExistsException(exception.getMessage());
    } catch (RefNotFoundException exception) {
        throw new GitRefNotFoundException(exception.getMessage());
    } catch (InvalidRefNameException exception) {
        throw new GitInvalidRefNameException(exception.getMessage());
    } catch (GitAPIException exception) {
        if (exception.getMessage().endsWith("already exists")) {
            throw new GitException(format(ERROR_CHECKOUT_BRANCH_NAME_EXISTS, name != null ? name : cleanRemoteName(trackBranch)));
        }
        throw new GitException(exception.getMessage(), exception);
    }
}
Also used : CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) Optional(java.util.Optional) GitException(org.eclipse.che.api.git.exception.GitException) CheckoutConflictException(org.eclipse.jgit.api.errors.CheckoutConflictException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) GitRefNotFoundException(org.eclipse.che.api.git.exception.GitRefNotFoundException) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) Branch(org.eclipse.che.api.git.shared.Branch) RefAlreadyExistsException(org.eclipse.jgit.api.errors.RefAlreadyExistsException) GitRefAlreadyExistsException(org.eclipse.che.api.git.exception.GitRefAlreadyExistsException) GitRefAlreadyExistsException(org.eclipse.che.api.git.exception.GitRefAlreadyExistsException) InvalidRefNameException(org.eclipse.jgit.api.errors.InvalidRefNameException) GitInvalidRefNameException(org.eclipse.che.api.git.exception.GitInvalidRefNameException) ArrayList(java.util.ArrayList) List(java.util.List) GitConflictException(org.eclipse.che.api.git.exception.GitConflictException) GitRefNotFoundException(org.eclipse.che.api.git.exception.GitRefNotFoundException) GitInvalidRefNameException(org.eclipse.che.api.git.exception.GitInvalidRefNameException) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) File(java.io.File)

Aggregations

Optional (java.util.Optional)3042 List (java.util.List)1831 Map (java.util.Map)1086 ArrayList (java.util.ArrayList)1032 Collectors (java.util.stream.Collectors)971 Set (java.util.Set)768 IOException (java.io.IOException)742 HashMap (java.util.HashMap)644 Test (org.junit.Test)526 Collections (java.util.Collections)506 Arrays (java.util.Arrays)454 Collection (java.util.Collection)442 Logger (org.slf4j.Logger)432 LoggerFactory (org.slf4j.LoggerFactory)425 HashSet (java.util.HashSet)386 Objects (java.util.Objects)324 ImmutableList (com.google.common.collect.ImmutableList)290 Stream (java.util.stream.Stream)282 ImmutableMap (com.google.common.collect.ImmutableMap)243 Function (java.util.function.Function)226