org.eclipse.che.commons.lang.Pair Java Examples

The following examples show how to use org.eclipse.che.commons.lang.Pair. 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: PullRequestUpdatedWebhook.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
public PullRequestUpdatedWebhook(
    final String host,
    final String account,
    final String collection,
    final String apiVersion,
    final Pair<String, String> credentials,
    final String... factoriesIds) {
  this.host = host;
  this.account = account;
  this.collection = collection;
  this.apiVersion = apiVersion;
  this.credentials = credentials;

  // No more than one webhook can be configured for a given combination of VSTS
  // account/host/collection
  this.id = account + "-" + host + "-" + collection;

  if (factoriesIds != null && factoriesIds.length > 0) {
    this.factoriesIds = Sets.newHashSet(Arrays.asList(factoriesIds));
  } else {
    this.factoriesIds = Sets.newHashSet();
  }
}
 
Example #2
Source File: LookupSelectorTest.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@BeforeClass
public void setUpServer() throws Exception {
  (server = EmbeddedLdapServer.newDefaultServer()).start();

  connFactory = server.getConnectionFactory();

  // first 100 users have additional attributes
  for (int i = 0; i < 100; i++) {
    server.addDefaultLdapUser(
        i,
        Pair.of("givenName", "test-user-first-name" + i),
        Pair.of("sn", "test-user-last-name"),
        Pair.of("telephoneNumber", "00000000" + i));
  }

  // next 100 users have only required attributes
  for (int i = 100; i < 200; i++) {
    server.addDefaultLdapUser(i);
  }
}
 
Example #3
Source File: CodenvyEditor.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
public Pair<Integer, Integer> getCurrentCursorPosition(int editorIndex) {
  int adoptedIndexOfEditor = editorIndex + 1;
  String editorActiveLineXpath =
      format(DEFINED_EDITOR_ACTIVE_LINE_XPATH_TEMPLATE, adoptedIndexOfEditor);

  List<WebElement> positionWidget =
      seleniumWebDriverHelper.waitPresenceOfAllElements(By.xpath(editorActiveLineXpath));

  String cursorPosition =
      positionWidget
          .stream()
          .filter(element -> !element.getText().isEmpty())
          .findFirst()
          .get()
          .getText();

  List<String> lineAndCharPosition = asList(cursorPosition.split(":"));
  int positionRow = Integer.parseInt(lineAndCharPosition.get(0));
  int positionChar = Integer.parseInt(lineAndCharPosition.get(1));
  return new Pair<>(positionRow, positionChar);
}
 
Example #4
Source File: FileCleaner.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private static void clean() {
  Pair<File, Integer> pair;
  final Set<Pair<File, Integer>> failToDelete = new HashSet<>();
  while ((pair = files.poll()) != null) {
    final File file = pair.first;
    int deleteAttempts = pair.second;
    if (file.exists()) {
      if (!IoUtil.deleteRecursive(file)) {
        failToDelete.add(Pair.of(file, ++deleteAttempts));
        if (deleteAttempts > logAfterAttempts) {
          LOG.error("Unable to delete file '{}' after {} tries", file, deleteAttempts);
        }
      } else if (LOG.isDebugEnabled()) {
        LOG.debug("Deleted file '{}'", file);
      }
    }
  }
  if (!failToDelete.isEmpty()) {
    files.addAll(failToDelete);
  }
}
 
Example #5
Source File: EmbeddedLdapServer.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Adds a new user which matches the default schema pattern, which is:
 *
 * <ul>
 *   <li>objectClass=inetOrgPerson
 *   <li>rdn - uid={id}
 *   <li>cn={name}
 *   <li>mail={mail}
 *   <li>sn={@literal <none>}
 *   <li>other.foreach(pair -> {pair.first}={pair.second})
 * </ul>
 *
 * @return newly created and added entry instance
 * @throws Exception when any error occurs
 */
public ServerEntry addDefaultLdapUser(String id, String name, String mail, Pair... other)
    throws Exception {
  final ServerEntry entry = newEntry("uid", id);
  entry.put("objectClass", "inetOrgPerson");
  entry.put("uid", id);
  entry.put("cn", name);
  entry.put("mail", mail);
  entry.put("sn", "<none>");
  for (Pair pair : other) {
    if (pair.second instanceof byte[]) {
      entry.put(pair.first.toString(), (byte[]) pair.second);
    } else {
      entry.put(pair.first.toString(), pair.second.toString());
    }
  }
  addEntry(entry);
  return entry;
}
 
Example #6
Source File: MembershipSelectorTest.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@BeforeClass
public void setUpServer() throws Exception {
  (server = EmbeddedLdapServer.newDefaultServer()).start();
  connFactory = server.getConnectionFactory();

  // first 100 users don't belong to any group
  for (int i = 0; i < 100; i++) {
    server.addDefaultLdapUser(i);
  }

  // next 200 users are members of group1/group2
  final List<String> group1Members = new ArrayList<>(100);
  final List<String> group2Members = new ArrayList<>(100);
  for (int i = 100; i < 300; i++) {
    final ServerEntry entry = server.addDefaultLdapUser(i, Pair.of("givenName", "gn-" + i));
    if (i % 2 == 0) {
      group1Members.add(entry.getDn().toString());
    } else {
      group2Members.add(entry.getDn().toString());
    }
    group1Members.add(entry.getDn().toString());
  }
  server.addDefaultLdapGroup("group1", group1Members);
  server.addDefaultLdapGroup("group2", group2Members);
}
 
Example #7
Source File: FactoryServiceTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldReturnFactoryListByCreatorAttribute() throws Exception {
  final FactoryImpl factory1 = createNamedFactory("factory1");
  final FactoryImpl factory2 = createNamedFactory("factory2");
  doReturn(new Page<>(ImmutableList.of(factory1, factory2), 0, 2, 2))
      .when(factoryManager)
      .getByAttribute(2, 0, ImmutableList.of(Pair.of("creator.userId", user.getName())));

  final Response response =
      given()
          .auth()
          .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD)
          .contentType(APPLICATION_JSON)
          .when()
          .expect()
          .statusCode(200)
          .get(SERVICE_PATH + "/find?maxItems=2&skipCount=0&creator.userId=" + user.getName());

  final Set<FactoryDto> res =
      unwrapDtoList(response, FactoryDto.class)
          .stream()
          .map(f -> f.withLinks(emptyList()))
          .collect(toSet());
  assertEquals(res.size(), 2);
  assertTrue(res.containsAll(ImmutableList.of(asDto(factory1, user), asDto(factory2, user))));
}
 
Example #8
Source File: PreferenceDaoTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@BeforeMethod
private void setUp() throws Exception {
  userPreferences = new ArrayList<>(ENTRY_COUNT);
  UserImpl[] users = new UserImpl[ENTRY_COUNT];

  for (int index = 0; index < ENTRY_COUNT; index++) {
    String userId = "userId_" + index;
    users[index] =
        new UserImpl(userId, "email_" + userId, "name_" + userId, "password", emptyList());

    final Map<String, String> prefs = new HashMap<>();
    prefs.put("preference1", "value");
    prefs.put("preference2", "value");
    prefs.put("preference3", "value");
    userPreferences.add(Pair.of(userId, prefs));
  }
  userTckRepository.createAll(Arrays.asList(users));
  preferenceTckRepository.createAll(userPreferences);
}
 
Example #9
Source File: VSTSConnection.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Get URL of repository name
 *
 * @param repositoryIdUrl the repository id URL
 * @param apiVersion the VSTS API version to use
 * @return the repository name URL
 */
public String getRepositoryNameUrl(
    String repositoryIdUrl, String apiVersion, final Pair<String, String> credentials)
    throws ServerException {
  final String userCredentials = credentials.first + ":" + credentials.second;
  final String basicAuth =
      "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));

  HttpJsonRequest httpJsonRequest =
      httpJsonRequestFactory
          .fromUrl(repositoryIdUrl)
          .useGetMethod()
          .setAuthorizationHeader(basicAuth)
          .addQueryParam("api-version", apiVersion);
  try {
    HttpJsonResponse response = httpJsonRequest.request();
    Repository repository = response.asDto(Repository.class);
    LOG.debug("Repository obtained: {}", repository);
    return repository.getRemoteUrl();

  } catch (IOException | ApiException e) {
    LOG.error(e.getLocalizedMessage(), e);
    throw new ServerException(e.getLocalizedMessage());
  }
}
 
Example #10
Source File: SignaturePublicKeyEnvProvider.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Pair<String, String> get(RuntimeIdentity runtimeIdentity) throws InfrastructureException {
  try {
    return Pair.of(
        SIGNATURE_PUBLIC_KEY_ENV,
        new String(
            Base64.getEncoder()
                .encode(
                    keyManager
                        .getOrCreateKeyPair(runtimeIdentity.getWorkspaceId())
                        .getPublic()
                        .getEncoded())));
  } catch (SignatureKeyManagerException e) {
    throw new InfrastructureException(
        "Signature key pair for machine authentication cannot be retrieved. Reason: "
            + e.getMessage());
  }
}
 
Example #11
Source File: FactoryServiceTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldReturnFactoryListByNameAttribute() throws Exception {
  final FactoryImpl factory = createFactory();
  doReturn(new Page<>(ImmutableList.of(factory), 0, 1, 1))
      .when(factoryManager)
      .getByAttribute(1, 0, ImmutableList.of(Pair.of("name", factory.getName())));
  final Response response =
      given()
          .auth()
          .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD)
          .contentType(APPLICATION_JSON)
          .when()
          .expect()
          .statusCode(200)
          .get(SERVICE_PATH + "/find?maxItems=1&skipCount=0&name=" + factory.getName());

  final List<FactoryDto> res = unwrapDtoList(response, FactoryDto.class);
  assertEquals(res.size(), 1);
  assertEquals(res.get(0).withLinks(emptyList()), asDto(factory, user));
}
 
Example #12
Source File: JpaFactoryDao.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private Long countFactoriesByAttributes(List<Pair<String, String>> attributes) {
  final Map<String, String> params = new HashMap<>();
  StringBuilder query = new StringBuilder("SELECT COUNT(factory) FROM Factory factory");
  if (!attributes.isEmpty()) {
    final StringJoiner matcher = new StringJoiner(" AND ", " WHERE ", " ");
    int i = 0;
    for (Pair<String, String> attribute : attributes) {
      final String parameterName = "parameterName" + i++;
      params.put(parameterName, attribute.second);
      matcher.add("factory." + attribute.first + " = :" + parameterName);
    }
    query.append(matcher);
  }
  TypedQuery<Long> typedQuery = managerProvider.get().createQuery(query.toString(), Long.class);
  for (Map.Entry<String, String> entry : params.entrySet()) {
    typedQuery.setParameter(entry.getKey(), entry.getValue());
  }
  return typedQuery.getSingleResult();
}
 
Example #13
Source File: JpaFactoryDao.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private List<FactoryImpl> getFactoriesByAttributes(
    int maxItems, long skipCount, List<Pair<String, String>> attributes) {
  final Map<String, String> params = new HashMap<>();
  StringBuilder query = new StringBuilder("SELECT factory FROM Factory factory");
  if (!attributes.isEmpty()) {
    final StringJoiner matcher = new StringJoiner(" AND ", " WHERE ", " ");
    int i = 0;
    for (Pair<String, String> attribute : attributes) {
      final String parameterName = "parameterName" + i++;
      params.put(parameterName, attribute.second);
      matcher.add("factory." + attribute.first + " = :" + parameterName);
    }
    query.append(matcher);
  }
  TypedQuery<FactoryImpl> typedQuery =
      managerProvider
          .get()
          .createQuery(query.toString(), FactoryImpl.class)
          .setFirstResult((int) skipCount)
          .setMaxResults(maxItems);
  for (Map.Entry<String, String> entry : params.entrySet()) {
    typedQuery.setParameter(entry.getKey(), entry.getValue());
  }
  return typedQuery.getResultList().stream().map(FactoryImpl::new).collect(toList());
}
 
Example #14
Source File: JpaFactoryDao.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackOn = {ServerException.class})
public Page<FactoryImpl> getByUser(String userId, int maxItems, long skipCount)
    throws ServerException {
  requireNonNull(userId);
  final Pair<String, String> factoryCreator = Pair.of("creator.userId", userId);
  try {
    long totalCount = countFactoriesByAttributes(singletonList(factoryCreator));
    return new Page<>(
        getFactoriesByAttributes(maxItems, skipCount, singletonList(factoryCreator)),
        skipCount,
        maxItems,
        totalCount);
  } catch (RuntimeException ex) {
    throw new ServerException(ex.getMessage(), ex);
  }
}
 
Example #15
Source File: JpaFactoryDao.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackOn = {ServerException.class})
public Page<FactoryImpl> getByAttributes(
    int maxItems, int skipCount, List<Pair<String, String>> attributes) throws ServerException {
  checkArgument(maxItems >= 0, "The number of items to return can't be negative.");
  checkArgument(
      skipCount >= 0 && skipCount <= Integer.MAX_VALUE,
      "The number of items to skip can't be negative or greater than " + Integer.MAX_VALUE);
  try {
    LOG.debug(
        "FactoryDao#getByAttributes #maxItems: {} #skipCount: {}, #attributes: {}",
        maxItems,
        skipCount,
        attributes);
    final long count = countFactoriesByAttributes(attributes);
    if (count == 0) {
      return new Page<>(emptyList(), skipCount, maxItems, count);
    }
    List<FactoryImpl> result = getFactoriesByAttributes(maxItems, skipCount, attributes);
    return new Page<>(result, skipCount, maxItems, count);
  } catch (RuntimeException ex) {
    throw new ServerException(ex.getLocalizedMessage(), ex);
  }
}
 
Example #16
Source File: MachineResolverTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() {
  endpoints = new ArrayList<>();
  cheContainer = new CheContainer();
  container = new Container();
  component = new ComponentImpl("chePlugin", PLUGIN_ID);
  resolver =
      new MachineResolver(
          new Pair<>(PROJECTS_ENV_VAR, PROJECTS_MOUNT_PATH),
          container,
          cheContainer,
          DEFAULT_MEM_LIMIT,
          DEFAULT_MEM_REQUEST,
          DEFAULT_CPU_LIMIT,
          DEFAULT_CPU_REQUEST,
          endpoints,
          component);
}
 
Example #17
Source File: KubernetesServerResolverTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void
    testResolvingServersWhenThereIsNoTheCorrespondingServiceAndIngressForTheSpecifiedMachine() {
  // given
  Service nonMatchedByPodService =
      createService("nonMatched", "foreignMachine", CONTAINER_PORT, null);
  Ingress ingress =
      createIngress(
          "nonMatched",
          "foreignMachine",
          Pair.of("http-server", new ServerConfigImpl("3054", "http", "/api", ATTRIBUTES_MAP)));

  KubernetesServerResolver serverResolver =
      new KubernetesServerResolver(
          new NoopPathTransformInverter(),
          singletonList(nonMatchedByPodService),
          singletonList(ingress));

  // when
  Map<String, ServerImpl> resolved = serverResolver.resolve("machine");

  // then
  assertTrue(resolved.isEmpty());
}
 
Example #18
Source File: KubernetesServerResolverTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testResolvingServersWhenThereIsMatchedIngressForMachineAndServerPathIsRelative() {
  Ingress ingress =
      createIngress(
          "matched",
          "machine",
          Pair.of("http-server", new ServerConfigImpl("3054", "http", "api", ATTRIBUTES_MAP)));

  KubernetesServerResolver serverResolver =
      new KubernetesServerResolver(
          new NoopPathTransformInverter(), emptyList(), singletonList(ingress));

  Map<String, ServerImpl> resolved = serverResolver.resolve("machine");

  assertEquals(resolved.size(), 1);
  assertEquals(
      resolved.get("http-server"),
      new ServerImpl()
          .withUrl("http://" + INGRESS_IP + INGRESS_RULE_PATH_PREFIX + "/api/")
          .withStatus(ServerStatus.UNKNOWN)
          .withAttributes(defaultAttributeAnd(Constants.SERVER_PORT_ATTRIBUTE, "3054")));
}
 
Example #19
Source File: UserLinksInjectorTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldInjectLinks() throws Exception {
  final UserDto userDto =
      DtoFactory.newDto(UserDto.class)
          .withId("user123")
          .withEmail("[email protected]")
          .withName("user");

  linksInjector.injectLinks(userDto, serviceContext);

  // [rel, method] pairs links
  final Set<Pair<String, String>> links =
      userDto
          .getLinks()
          .stream()
          .map(link -> Pair.of(link.getMethod(), link.getRel()))
          .collect(Collectors.toSet());
  final Set<Pair<String, String>> expectedLinks =
      new HashSet<>(
          asList(
              Pair.of("GET", Constants.LINK_REL_SELF),
              Pair.of("GET", Constants.LINK_REL_CURRENT_USER),
              Pair.of("GET", Constants.LINK_REL_PROFILE),
              Pair.of("GET", Constants.LINK_REL_CURRENT_USER_SETTINGS),
              Pair.of("GET", Constants.LINK_REL_PREFERENCES),
              Pair.of("POST", Constants.LINK_REL_CURRENT_USER_PASSWORD)));

  assertEquals(
      links,
      expectedLinks,
      "Difference " + Sets.symmetricDifference(links, expectedLinks) + "\n");
}
 
Example #20
Source File: JpaTckModule.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void configure() {
  H2DBTestServer server = H2DBTestServer.startDefault();
  install(
      new PersistTestModuleBuilder()
          .setDriver(Driver.class)
          .runningOn(server)
          .addEntityClasses(
              UserImpl.class, ProfileImpl.class, PreferenceEntity.class, AccountImpl.class)
          .setExceptionHandler(H2ExceptionHandler.class)
          .build());
  bind(DBInitializer.class).asEagerSingleton();
  bind(SchemaInitializer.class)
      .toInstance(new FlywaySchemaInitializer(server.getDataSource(), "che-schema"));
  bind(TckResourcesCleaner.class).toInstance(new H2JpaCleaner(server.getDataSource()));

  bind(new TypeLiteral<TckRepository<UserImpl>>() {}).to(UserJpaTckRepository.class);
  bind(new TypeLiteral<TckRepository<ProfileImpl>>() {})
      .toInstance(new JpaTckRepository<>(ProfileImpl.class));
  bind(new TypeLiteral<TckRepository<Pair<String, Map<String, String>>>>() {})
      .to(PreferenceJpaTckRepository.class);

  bind(UserDao.class).to(JpaUserDao.class);
  bind(ProfileDao.class).to(JpaProfileDao.class);
  bind(PreferenceDao.class).to(JpaPreferenceDao.class);
  // SHA-512 encryptor is faster than PBKDF2 so it is better for testing
  bind(PasswordEncryptor.class).to(SHA512PasswordEncryptor.class).in(Singleton.class);
}
 
Example #21
Source File: EnvVarEnvironmentProvisioner.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void provision(RuntimeIdentity id, InternalEnvironment internalEnvironment)
    throws InfrastructureException {
  LOG.debug("Provisioning environment variables for workspace '{}'", id.getWorkspaceId());
  for (EnvVarProvider envVarProvider : envVarProviders) {
    Pair<String, String> envVar = envVarProvider.get(id);
    if (envVar != null) {
      internalEnvironment
          .getMachines()
          .values()
          .forEach(m -> m.getEnv().putIfAbsent(envVar.first, envVar.second));
    }
  }
  LOG.debug("Environment variables provisioning done for workspace '{}'", id.getWorkspaceId());
}
 
Example #22
Source File: CodenvyEditor.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public void waitCursorPosition(
    final int editorIndex, final int linePosition, final int charPosition) {
  webDriverWaitFactory
      .get()
      .until(
          (ExpectedCondition<Boolean>)
              webDriver -> {
                Pair<Integer, Integer> position = getCurrentCursorPosition(editorIndex);

                return (linePosition == position.first) && (charPosition == position.second);
              });
}
 
Example #23
Source File: DefaultHttpJsonRequest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public HttpJsonRequest addHeader(@NotNull String name, @NotNull String value) {
  requireNonNull(name, "Required non-null header name");
  requireNonNull(value, "Required non-null header value");
  if (headers == null) {
    headers = new ArrayList<>();
  }
  headers.add(Pair.of(name, value));
  return this;
}
 
Example #24
Source File: BrokerEnvironmentFactoryTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
  factory =
      spy(
          new BrokerEnvironmentFactory<KubernetesEnvironment>(
              PUSH_ENDPOINT,
              IMAGE_PULL_POLICY,
              authEnableEnvVarProvider,
              machineTokenEnvVarProvider,
              ARTIFACTS_BROKER_IMAGE,
              METADATA_BROKER_IMAGE,
              DEFAULT_REGISTRY,
              certProvisioner) {
            @Override
            protected KubernetesEnvironment doCreate(BrokersConfigs brokersConfigs) {
              return null;
            }
          });

  when(authEnableEnvVarProvider.get(any(RuntimeIdentity.class)))
      .thenReturn(new Pair<>("test1", "value1"));
  when(machineTokenEnvVarProvider.get(any(RuntimeIdentity.class)))
      .thenReturn(new Pair<>("test2", "value2"));
  when(runtimeId.getEnvName()).thenReturn("env");
  when(runtimeId.getOwnerId()).thenReturn("owner");
  when(runtimeId.getWorkspaceId()).thenReturn("wsid");
  when(certProvisioner.isConfigured()).thenReturn(false);
}
 
Example #25
Source File: WorkspaceNameEnvVarProviderTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldReturnNameVar()
    throws NotFoundException, ServerException, InfrastructureException {
  // given
  when(runtimeIdentity.getWorkspaceId()).thenReturn("ws-id111");
  doReturn(workspace).when(workspaceDao).get(Mockito.eq("ws-id111"));
  when(workspace.getName()).thenReturn("ws-name");

  // when
  Pair<String, String> actual = provider.get(runtimeIdentity);

  // then
  assertEquals(actual.first, WorkspaceNameEnvVarProvider.CHE_WORKSPACE_NAME);
  assertEquals(actual.second, "ws-name");
}
 
Example #26
Source File: EnvVarEnvironmentProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldProvideRuntimeIdentityToEnvProviders() throws Exception {
  // given
  EnvVarEnvironmentProvisioner provisioner =
      new EnvVarEnvironmentProvisioner(singleton(provider1));
  when(provider1.get(any())).thenReturn(Pair.of("test", "test"));

  // when
  provisioner.provision(RUNTIME_IDENTITY, internalEnvironment);

  // then
  verify(provider1).get(eq(RUNTIME_IDENTITY));
}
 
Example #27
Source File: KubernetesPluginsToolingApplierTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() {
  internalEnvironment = spy(KubernetesEnvironment.builder().build());
  internalEnvironment.setDevfile(new DevfileImpl());
  applier =
      new KubernetesPluginsToolingApplier(
          TEST_IMAGE_POLICY,
          MEMORY_LIMIT_MB,
          MEMORY_REQUEST_MB,
          CPU_LIMIT,
          CPU_REQUEST,
          false,
          projectsRootEnvVariableProvider,
          chePluginsVolumeApplier,
          envVars);

  Map<String, InternalMachineConfig> machines = new HashMap<>();
  List<Container> containers = new ArrayList<>();
  containers.add(userContainer);
  machines.put(USER_MACHINE_NAME, userMachineConfig);

  when(pod.getSpec()).thenReturn(podSpec);
  lenient().when(podSpec.getContainers()).thenReturn(containers);
  lenient().when(pod.getMetadata()).thenReturn(meta);
  lenient().when(meta.getName()).thenReturn(POD_NAME);
  internalEnvironment.addPod(pod);
  internalEnvironment.getMachines().putAll(machines);

  lenient()
      .when(projectsRootEnvVariableProvider.get(any()))
      .thenReturn(new Pair<>("projects_root", "/somewhere/over/the/rainbow"));
}
 
Example #28
Source File: KubernetesServerResolverTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Ingress createIngress(
    String name, String machineName, Pair<String, ServerConfig> server) {
  Serializer serializer = Annotations.newSerializer();
  serializer.machineName(machineName);
  serializer.server(server.first, server.second);

  return new IngressBuilder()
      .withNewMetadata()
      .withName(name)
      .withAnnotations(serializer.annotations())
      .endMetadata()
      .withNewSpec()
      .withRules(
          new IngressRule(
              null,
              new HTTPIngressRuleValue(
                  singletonList(
                      new HTTPIngressPath(
                          new IngressBackend(name, new IntOrString("8080")),
                          INGRESS_PATH_PREFIX)))))
      .endSpec()
      .withNewStatus()
      .withNewLoadBalancer()
      .addNewIngress()
      .withIp("127.0.0.1")
      .endIngress()
      .endLoadBalancer()
      .endStatus()
      .build();
}
 
Example #29
Source File: EnvVarEnvironmentProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldCallAllProviders() throws Exception {
  // given
  EnvVarEnvironmentProvisioner provisioner =
      new EnvVarEnvironmentProvisioner(ImmutableSet.of(provider1, provider2));
  when(provider1.get(any())).thenReturn(Pair.of("test", "test"));
  when(provider2.get(any())).thenReturn(Pair.of("test", "test"));

  // when
  provisioner.provision(RUNTIME_IDENTITY, internalEnvironment);

  // then
  verify(provider1).get(eq(RUNTIME_IDENTITY));
  verify(provider2).get(eq(RUNTIME_IDENTITY));
}
 
Example #30
Source File: FactoryDaoTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldGetFactoryByIdAttribute() throws Exception {
  final FactoryImpl factory = factories[0];
  final List<Pair<String, String>> attributes = ImmutableList.of(Pair.of("id", factory.getId()));
  final Page<FactoryImpl> result = factoryDao.getByAttributes(1, 0, attributes);

  assertEquals(new HashSet<>(result.getItems()), ImmutableSet.of(factory));
}