org.eclipse.che.commons.annotation.Nullable Java Examples

The following examples show how to use org.eclipse.che.commons.annotation.Nullable. 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: OpenShiftOAuthAuthenticator.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Inject
public OpenShiftOAuthAuthenticator(
    @Nullable @Named("che.oauth.openshift.clientid") String clientId,
    @Nullable @Named("che.oauth.openshift.clientsecret") String clientSecret,
    @Nullable @Named("che.oauth.openshift.oauth_endpoint") String oauthEndpoint,
    @Nullable @Named("che.oauth.openshift.verify_token_url") String verifyTokenUrl,
    @Named("che.api") String apiEndpoint)
    throws IOException {
  this.verifyTokenUrl = verifyTokenUrl;
  String[] redirectUrl = {apiEndpoint + "/oauth/callback"};
  if (!isNullOrEmpty(clientId) && !isNullOrEmpty(clientSecret) && !isNullOrEmpty(oauthEndpoint)) {
    oauthEndpoint = oauthEndpoint.endsWith("/") ? oauthEndpoint : oauthEndpoint + "/";
    configure(
        clientId,
        clientSecret,
        redirectUrl,
        oauthEndpoint + "oauth/authorize",
        oauthEndpoint + "oauth/token",
        new MemoryDataStoreFactory());
  }
}
 
Example #2
Source File: BitbucketOAuthAuthenticator.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@Inject
public BitbucketOAuthAuthenticator(
    @Nullable @Named("oauth.bitbucket.clientid") String clientId,
    @Nullable @Named("oauth.bitbucket.clientsecret") String clientSecret,
    @Nullable @Named("oauth.bitbucket.redirecturis") String[] redirectUris,
    @Nullable @Named("oauth.bitbucket.useruri") String userUri,
    @Nullable @Named("oauth.bitbucket.authuri") String authUri,
    @Nullable @Named("oauth.bitbucket.tokenuri") String tokenUri)
    throws IOException {
  super();
  if (!isNullOrEmpty(clientId)
      && !isNullOrEmpty(clientSecret)
      && !isNullOrEmpty(authUri)
      && !isNullOrEmpty(tokenUri)
      && redirectUris != null
      && redirectUris.length != 0) {

    configure(
        clientId, clientSecret, redirectUris, authUri, tokenUri, new MemoryDataStoreFactory());
  }
  this.userUri = userUri;
}
 
Example #3
Source File: LinkedInOAuthAuthenticator.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@Inject
public LinkedInOAuthAuthenticator(
    @Nullable @Named("oauth.linkedin.clientid") String clientId,
    @Nullable @Named("oauth.linkedin.clientsecret") String clientSecret,
    @Nullable @Named("oauth.linkedin.redirecturis") String[] redirectUris,
    @Nullable @Named("oauth.linkedin.authuri") String authUri,
    @Nullable @Named("oauth.linkedin.tokenuri") String tokenUri,
    @Nullable @Named("oauth.linkedin.useruri") String userUri)
    throws IOException {
  if (!isNullOrEmpty(clientId)
      && !isNullOrEmpty(clientSecret)
      && !isNullOrEmpty(authUri)
      && !isNullOrEmpty(tokenUri)
      && !isNullOrEmpty(userUri)
      && redirectUris != null
      && redirectUris.length != 0) {
    configure(
        clientId, clientSecret, redirectUris, authUri, tokenUri, new MemoryDataStoreFactory());
  }
  this.userUri = userUri;
}
 
Example #4
Source File: SelectorFilter.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns true is specified object is matched by specified selector, false otherwise.
 *
 * <p>An empty selector is considered to match anything.
 *
 * @param metadata object metadata to check matching
 * @param selector the selector to match the metadata with
 */
public static boolean test(@Nullable ObjectMeta metadata, Map<String, String> selector) {
  if (selector.isEmpty()) {
    // anything matches if we have nothing to select with
    return true;
  }

  if (metadata == null) {
    return false;
  }

  Map<String, String> labels = metadata.getLabels();
  if (labels == null) {
    return false;
  }

  return labels.entrySet().containsAll(selector.entrySet());
}
 
Example #5
Source File: CheTestWorkspace.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
@Nullable
public String getId() throws ExecutionException, InterruptedException {
  if (future == null) {
    try {
      Workspace wsConfig = testWorkspaceServiceClient.getByName(name, owner.getName());
      id.set(wsConfig.getId());
      return id.get();
    } catch (Exception e) {
      String errorMessage =
          format("Failed to obtain id of workspace name='%s' owner='%s'", name, owner.getName());

      LOG.warn(errorMessage, e);

      return null;
    }
  }

  return future.thenApply(aVoid -> id.get()).get();
}
 
Example #6
Source File: ProjectLockerOAuthAuthenticator.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@Inject
public ProjectLockerOAuthAuthenticator(
    @Nullable @Named("oauth.projectlocker.clientid") String clientId,
    @Nullable @Named("oauth.projectlocker.clientsecret") String clientSecret,
    @Nullable @Named("oauth.projectlocker.redirecturis") String[] redirectUris,
    @Nullable @Named("oauth.projectlocker.authuri") String authUri,
    @Nullable @Named("oauth.projectlocker.tokenuri") String tokenUri)
    throws IOException {
  if (!isNullOrEmpty(clientId)
      && !isNullOrEmpty(clientSecret)
      && !isNullOrEmpty(authUri)
      && !isNullOrEmpty(tokenUri)
      && redirectUris != null
      && redirectUris.length != 0) {

    configure(
        clientId, clientSecret, redirectUris, authUri, tokenUri, new MemoryDataStoreFactory());
  }
}
 
Example #7
Source File: KubernetesServerResolver.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private String buildPath(String fragment1, @Nullable String fragment2) {
  StringBuilder sb = new StringBuilder(fragment1);

  if (!isNullOrEmpty(fragment2)) {
    if (!fragment1.endsWith("/")) {
      sb.append('/');
    }

    if (fragment2.startsWith("/")) {
      sb.append(fragment2.substring(1));
    } else {
      sb.append(fragment2);
    }
  }

  // always end server URLs with a slash, so that they can be safely sub-path'd..
  if (sb.charAt(sb.length() - 1) != '/') {
    sb.append('/');
  }

  return sb.toString();
}
 
Example #8
Source File: TestOrganizationServiceClient.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
public OrganizationDto create(String name, @Nullable String parentId) throws Exception {
  OrganizationDto data = newDto(OrganizationDto.class).withName(name).withParent(parentId);

  OrganizationDto organizationDto =
      requestFactory
          .fromUrl(getApiUrl())
          .setBody(data)
          .usePostMethod()
          .request()
          .asDto(OrganizationDto.class);

  LOG.info(
      "Organization with name='{}', id='{}', parent's id='{}' created",
      name,
      organizationDto.getId(),
      parentId);

  return organizationDto;
}
 
Example #9
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Inject
public WorkspaceService(
    @Named("che.api") String apiEndpoint,
    @Named(CHE_WORKSPACE_AUTO_START) boolean cheWorkspaceAutoStart,
    WorkspaceManager workspaceManager,
    MachineTokenProvider machineTokenProvider,
    WorkspaceLinksGenerator linksGenerator,
    @Named(CHE_WORKSPACE_PLUGIN_REGISTRY_URL_PROPERTY) @Nullable String pluginRegistryUrl,
    @Named(CHE_WORKSPACE_DEVFILE_REGISTRY_URL_PROPERTY) @Nullable String devfileRegistryUrl,
    @Named(CHE_WORKSPACE_PERSIST_VOLUMES_PROPERTY) boolean defaultPersistVolumes,
    URLFetcher urlFetcher,
    @Named(DEBUG_WORKSPACE_START_LOG_LIMIT_BYTES) Long logLimitBytes) {
  this.apiEndpoint = apiEndpoint;
  this.cheWorkspaceAutoStart = cheWorkspaceAutoStart;
  this.workspaceManager = workspaceManager;
  this.machineTokenProvider = machineTokenProvider;
  this.linksGenerator = linksGenerator;
  this.pluginRegistryUrl = pluginRegistryUrl;
  this.devfileRegistryUrl = devfileRegistryUrl;
  this.devfileContentProvider = new URLFileContentProvider(null, urlFetcher);
  this.defaultPersistVolumes = defaultPersistVolumes;
  this.logLimitBytes = logLimitBytes;
}
 
Example #10
Source File: GitHubOAuthAuthenticator.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Inject
public GitHubOAuthAuthenticator(
    @Nullable @Named("che.oauth.github.clientid") String clientId,
    @Nullable @Named("che.oauth.github.clientsecret") String clientSecret,
    @Nullable @Named("che.oauth.github.redirecturis") String[] redirectUris,
    @Nullable @Named("che.oauth.github.authuri") String authUri,
    @Nullable @Named("che.oauth.github.tokenuri") String tokenUri)
    throws IOException {
  if (!isNullOrEmpty(clientId)
      && !isNullOrEmpty(clientSecret)
      && !isNullOrEmpty(authUri)
      && !isNullOrEmpty(tokenUri)
      && redirectUris != null
      && redirectUris.length != 0) {

    configure(
        clientId, clientSecret, redirectUris, authUri, tokenUri, new MemoryDataStoreFactory());
  }
}
 
Example #11
Source File: ExternalServerExposer.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Exposes service port on given service externally (outside kubernetes cluster). The exposed
 * service port is associated with a specific Server configuration. Server configuration should be
 * encoded in the exposing object's annotations, to be used by {@link KubernetesServerResolver}.
 *
 * @param k8sEnv Kubernetes environment
 * @param machineName machine containing servers
 * @param serviceName service associated with machine, mapping all machine server ports
 * @param serverId non-null for a unique server, null for a compound set of servers that should be
 *     exposed together.
 * @param servicePort specific service port to be exposed externally
 * @param externalServers server configs of servers to be exposed externally
 */
public void expose(
    T k8sEnv,
    @Nullable String machineName,
    String serviceName,
    String serverId,
    ServicePort servicePort,
    Map<String, ServerConfig> externalServers) {

  if (serverId == null) {
    // this is the ID for non-unique servers
    serverId = servicePort.getName();
  }

  Ingress ingress =
      generateIngress(machineName, serviceName, serverId, servicePort, externalServers);

  k8sEnv.getIngresses().put(ingress.getMetadata().getName(), ingress);
}
 
Example #12
Source File: KubernetesClientFactory.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Inject
public KubernetesClientFactory(
    @Nullable @Named("che.infra.kubernetes.master_url") String masterUrl,
    @Nullable @Named("che.infra.kubernetes.trust_certs") Boolean doTrustCerts,
    @Named("che.infra.kubernetes.client.http.async_requests.max") int maxConcurrentRequests,
    @Named("che.infra.kubernetes.client.http.async_requests.max_per_host")
        int maxConcurrentRequestsPerHost,
    @Named("che.infra.kubernetes.client.http.connection_pool.max_idle") int maxIdleConnections,
    @Named("che.infra.kubernetes.client.http.connection_pool.keep_alive_min")
        int connectionPoolKeepAlive,
    EventListener eventListener) {
  this.defaultConfig = buildDefaultConfig(masterUrl, doTrustCerts);
  OkHttpClient temporary = HttpClientUtils.createHttpClient(defaultConfig);
  OkHttpClient.Builder builder = temporary.newBuilder();
  ConnectionPool oldPool = temporary.connectionPool();
  builder.connectionPool(
      new ConnectionPool(maxIdleConnections, connectionPoolKeepAlive, TimeUnit.MINUTES));
  oldPool.evictAll();
  this.httpClient = builder.eventListener(eventListener).build();
  httpClient.dispatcher().setMaxRequests(maxConcurrentRequests);
  httpClient.dispatcher().setMaxRequestsPerHost(maxConcurrentRequestsPerHost);
}
 
Example #13
Source File: WorkspaceRuntimes.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@VisibleForTesting
InternalEnvironment createInternalEnvironment(
    @Nullable Environment environment,
    Map<String, String> workspaceConfigAttributes,
    List<? extends Command> commands,
    DevfileImpl devfile)
    throws InfrastructureException, ValidationException, NotFoundException {
  String recipeType;
  if (environment == null) {
    recipeType = Constants.NO_ENVIRONMENT_RECIPE_TYPE;
  } else {
    recipeType = environment.getRecipe().getType();
  }
  InternalEnvironmentFactory factory = environmentFactories.get(recipeType);
  if (factory == null) {
    throw new NotFoundException(
        format("InternalEnvironmentFactory is not configured for recipe type: '%s'", recipeType));
  }
  InternalEnvironment internalEnvironment = factory.create(environment);
  internalEnvironment.setAttributes(new HashMap<>(workspaceConfigAttributes));
  internalEnvironment.setCommands(commands.stream().map(CommandImpl::new).collect(toList()));
  internalEnvironment.setDevfile(devfile);

  return internalEnvironment;
}
 
Example #14
Source File: KubernetesNamespaceFactory.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Inject
public KubernetesNamespaceFactory(
    @Nullable @Named("che.infra.kubernetes.namespace") String legacyNamespaceName,
    @Nullable @Named("che.infra.kubernetes.service_account_name") String serviceAccountName,
    @Nullable @Named("che.infra.kubernetes.cluster_role_name") String clusterRoleName,
    @Nullable @Named("che.infra.kubernetes.namespace.default") String defaultNamespaceName,
    @Named("che.infra.kubernetes.namespace.allow_user_defined")
        boolean allowUserDefinedNamespaces,
    KubernetesClientFactory clientFactory,
    UserManager userManager,
    KubernetesSharedPool sharedPool)
    throws ConfigurationException {
  this.userManager = userManager;
  this.legacyNamespaceName = legacyNamespaceName;
  this.serviceAccountName = serviceAccountName;
  this.clusterRoleName = clusterRoleName;
  this.clientFactory = clientFactory;
  this.defaultNamespaceName = defaultNamespaceName;
  this.allowUserDefinedNamespaces = allowUserDefinedNamespaces;
  this.sharedPool = sharedPool;

  if (isNullOrEmpty(defaultNamespaceName)) {
    throw new ConfigurationException("che.infra.kubernetes.namespace.default must be configured");
  }
}
 
Example #15
Source File: End2EndFlowService.java    From rh-che with Eclipse Public License 2.0 6 votes vote down vote up
@Inject
public End2EndFlowService(
    @Nullable @Named("che.fabric8.end2end.protect.site_key") String siteKey,
    @Nullable @Named("che.fabric8.end2end.protect.secret_key") String secretKey,
    @Named("che.fabric8.end2end.protect.verify_with_ip") boolean verifyWithIp) {
  this.verifyWithIp = verifyWithIp;
  this.reCaptchaSiteKey = siteKey;
  this.reCaptchaSecretKey = secretKey;
  this.staticFilesFilters = new HashMap<>();
  String siteKeyDecl;
  if (siteKey != null && !siteKey.isEmpty()) {
    siteKeyDecl = "var siteKey='" + siteKey + "';";
  } else {
    siteKeyDecl = "var siteKey='';";
    LOG.warn("No ReCaptcha site key was provided. ReCaptcha user verification is disabled !");
  }
  staticFilesFilters.put(
      "files/provision.html", line -> line.replace("const siteKey;", siteKeyDecl));
}
 
Example #16
Source File: OAuthAuthenticator.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
protected OAuthAuthenticator(
    String clientId,
    String requestTokenUri,
    String accessTokenUri,
    String authorizeTokenUri,
    String redirectUri,
    @Nullable String clientSecret,
    @Nullable String privateKey) {
  this.clientId = clientId;
  this.clientSecret = clientSecret;
  this.privateKey = privateKey;
  this.requestTokenUri = requestTokenUri;
  this.accessTokenUri = accessTokenUri;
  this.authorizeTokenUri = authorizeTokenUri;
  this.redirectUri = redirectUri;
  this.httpTransport = new NetHttpTransport();
  this.credentialsStore = new HashMap<>();
  this.credentialsStoreLock = new ReentrantLock();
  this.sharedTokenSecrets = new HashMap<>();
}
 
Example #17
Source File: ApiInfoService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@GET
@Produces({MediaType.APPLICATION_JSON})
public RootResourcesList listJSON(@Context ServletContext context) {
  ResourceBinder binder = (ResourceBinder) context.getAttribute(ResourceBinder.class.getName());
  return new RootResourcesList(
      binder
          .getResources()
          .stream()
          .map(
              new Function<ObjectFactory<ResourceDescriptor>, RootResource>() {
                @Nullable
                @Override
                public RootResource apply(ObjectFactory<ResourceDescriptor> input) {
                  ResourceDescriptor descriptor = input.getObjectModel();
                  return new RootResource(
                      descriptor.getObjectClass().getName(), //
                      descriptor.getPathValue().getPath(), //
                      descriptor.getUriPattern().getRegex());
                }
              })
          .collect(toList()));
}
 
Example #18
Source File: OpenShiftClientFactory.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Inject
public OpenShiftClientFactory(
    OpenShiftClientConfigFactory configBuilder,
    @Nullable @Named("che.infra.kubernetes.master_url") String masterUrl,
    @Nullable @Named("che.infra.kubernetes.trust_certs") Boolean doTrustCerts,
    @Named("che.infra.kubernetes.client.http.async_requests.max") int maxConcurrentRequests,
    @Named("che.infra.kubernetes.client.http.async_requests.max_per_host")
        int maxConcurrentRequestsPerHost,
    @Named("che.infra.kubernetes.client.http.connection_pool.max_idle") int maxIdleConnections,
    @Named("che.infra.kubernetes.client.http.connection_pool.keep_alive_min")
        int connectionPoolKeepAlive,
    EventListener eventListener) {
  super(
      masterUrl,
      doTrustCerts,
      maxConcurrentRequests,
      maxConcurrentRequestsPerHost,
      maxIdleConnections,
      connectionPoolKeepAlive,
      eventListener);
  this.configBuilder = configBuilder;
}
 
Example #19
Source File: SeleniumWebDriver.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Read supported version info from official site.
 *
 * @param webDriverOfficialNotes address of official page with Google driver info
 * @return string with supported version range (for example, "36-40"), or null if version info
 *     doesn't found inside the official notes.
 * @throws IOException
 */
@Nullable
private String readSupportedVersionInfoForGoogleDriver(URL webDriverOfficialNotes)
    throws IOException {
  try (Scanner scanner = new Scanner(webDriverOfficialNotes.openStream(), "UTF-8")) {
    while (scanner.hasNextLine()) {
      String versionLine = scanner.findInLine("Supports Chrome v([\\d-]+)");
      if (versionLine != null) {
        return scanner.match().group(1);
      }

      scanner.nextLine();
    }
  }

  return null;
}
 
Example #20
Source File: IdentityProviderConfigFactory.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Inject
public IdentityProviderConfigFactory(
    KeycloakServiceClient keycloakServiceClient,
    KeycloakSettings keycloakSettings,
    Provider<WorkspaceRuntimes> workspaceRuntimeProvider,
    @Nullable @Named("che.infra.openshift.oauth_identity_provider") String oauthIdentityProvider,
    @Named("che.api") String apiEndpoint) {
  this.keycloakServiceClient = keycloakServiceClient;
  this.workspaceRuntimeProvider = workspaceRuntimeProvider;
  this.oauthIdentityProvider = oauthIdentityProvider;

  messageToLinkAccount =
      "You should link your account with the <strong>"
          + oauthIdentityProvider
          + "</strong> \n"
          + "identity provider by visiting the "
          + "<a href='"
          + keycloakSettings.get().get(AUTH_SERVER_URL_SETTING)
          + "/realms/"
          + keycloakSettings.get().get(REALM_SETTING)
          + "/account/identity?referrer="
          + keycloakSettings.get().get(CLIENT_ID_SETTING)
          + "&referrer_uri="
          + buildReferrerURI(apiEndpoint)
          + "' target='_blank' rel='noopener noreferrer'><strong>Federated Identities</strong></a> page of your Che account";
}
 
Example #21
Source File: OpenshiftUserTokenProvider.java    From rh-che with Eclipse Public License 2.0 5 votes vote down vote up
@Inject
public OpenshiftUserTokenProvider(
    @Nullable @Named(OIDC_PROVIDER_SETTING) String oidcProvider,
    @Nullable @Named(AUTH_SERVER_URL_SETTING) String keycloakServerURL,
    @Nullable @Named(REALM_SETTING) String keycloakRealm,
    OkHttpClient httpClient,
    @Named("che.fabric8.standalone") boolean standalone) {

  if (standalone) {
    // When RhChe is used in standalone mode, it uses the dedicated Keycloak as
    // the Che authentication provider

    if (keycloakServerURL == null) {
      throw new RuntimeException("The 'AUTH_SERVER_URL_SETTING' property should be set");
    }
    tokenEndpoint = keycloakServerURL + "/realms/" + keycloakRealm + "/broker/openshift-v3/token";
  } else {
    // When RhChe is used in OSIO mode (along with the oter fabric8 services, it uses the
    // alternate
    // fabric8_auth OIDC provider as the Che authentication provider.

    if (oidcProvider == null) {
      throw new RuntimeException("The 'OIDC_PROVIDER_SETTING' property should be set");
    }
    tokenEndpoint = oidcProvider + "/token?for=openshift";
  }
  this.httpClient = httpClient;
  this.tokenCache =
      CacheBuilder.newBuilder()
          .maximumSize(CONCURRENT_USERS)
          .expireAfterWrite(CACHE_TIMEOUT_MINUTES, TimeUnit.MINUTES)
          .build(CacheLoader.from(this::getOsToken));
}
 
Example #22
Source File: LdapUserIdNormalizer.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Normalizes user identifier by modifying a {@link LdapEntry}, does nothing if the entry doesn't
 * contain id attribute.
 *
 * @param entry the entry to normalize
 */
public void normalize(@Nullable LdapEntry entry) {
  if (entry != null) {
    final LdapAttribute idAttr = entry.getAttribute(idAttributeName);
    if (idAttr != null) {
      final String normalizedId = normalize(idAttr.getStringValue());
      idAttr.clear();
      idAttr.addStringValue(normalizedId);
    }
  }
}
 
Example #23
Source File: Fabric8OpenShiftClientFactory.java    From rh-che with Eclipse Public License 2.0 5 votes vote down vote up
@Inject
public Fabric8OpenShiftClientFactory(
    Fabric8WorkspaceEnvironmentProvider envProvider,
    Provider<WorkspaceRuntimes> workspaceRuntimeProvider,
    WorkspaceSubjectsRegistry subjectsRegistry,
    KubernetesRuntimeStateCache runtimeStateCache,
    CheServiceAccountTokenToggle cheServiceAccountTokenToggle,
    @Nullable @Named("che.infra.kubernetes.trust_certs") Boolean doTrustCerts,
    @Named("che.infra.kubernetes.client.http.async_requests.max") int maxConcurrentRequests,
    @Named("che.infra.kubernetes.client.http.async_requests.max_per_host")
        int maxConcurrentRequestsPerHost,
    @Named("che.infra.kubernetes.client.http.connection_pool.max_idle") int maxIdleConnections,
    @Named("che.infra.kubernetes.client.http.connection_pool.keep_alive_min")
        int connectionPoolKeepAlive,
    EventListener eventListener) {
  super(
      null,
      null,
      doTrustCerts != null ? doTrustCerts.booleanValue() : false,
      maxConcurrentRequests,
      maxConcurrentRequestsPerHost,
      maxIdleConnections,
      connectionPoolKeepAlive,
      eventListener);
  this.envProvider = envProvider;
  this.workspaceRuntimeProvider = workspaceRuntimeProvider;
  this.subjectsRegistry = subjectsRegistry;
  this.runtimeStateCache = runtimeStateCache;
  this.cheServiceAccountTokenToggle = cheServiceAccountTokenToggle;
}
 
Example #24
Source File: BrokerService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Nullable
private List<ChePlugin> parseTooling(String toolingString) {
  if (!isNullOrEmpty(toolingString)) {
    try {
      List<ChePlugin> plugins =
          objectMapper.readValue(toolingString, new TypeReference<List<ChePlugin>>() {});
      // when id of plugin is not set, we can compose it from publisher, name and version
      return plugins.stream().map(this::composePluginIdWhenNull).collect(Collectors.toList());
    } catch (IOException e) {
      LOG.error("Parsing Che plugin broker event failed. Error: " + e.getMessage(), e);
    }
  }
  return null;
}
 
Example #25
Source File: AwsEcrAuthResolver.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Retrieves actual auth data for Amazon ECR. If no credential found for specified registry, null
 * will be returned.
 *
 * <p>Note, that credentials is changed every 12 hours.
 *
 * @return actual auth credentials for given AWS ECR or null if no credentials found
 */
@Override
@Nullable
public AuthConfig getXRegistryAuth(@Nullable String registry) {
  if (registry != null) {
    AwsAccountCredentials awsAccountCredentials =
        awsEcrInitialAuthConfig.getAuthConfigs().get(registry);
    if (awsAccountCredentials != null) { // given registry is configured
      try {
        String authorizationToken =
            getAwsAuthorizationToken(
                awsAccountCredentials.getAccessKeyId(),
                awsAccountCredentials.getSecretAccessKey());
        if (authorizationToken != null) {
          String decodedAuthorizationToken =
              new String(Base64.getDecoder().decode(authorizationToken));
          int colonIndex = decodedAuthorizationToken.indexOf(':');
          if (colonIndex != -1) {
            return newDto(AuthConfig.class)
                .withUsername(decodedAuthorizationToken.substring(0, colonIndex))
                .withPassword(decodedAuthorizationToken.substring(colonIndex + 1));
          } else {
            LOG.error("Cannot retrieve ECR credentials from token for {} registry", registry);
          }
        }
      } catch (IllegalArgumentException e) {
        LOG.error(
            "Retrieved AWS ECR authorization token for {} registry has invalid format", registry);
      }
    }
  }
  return null;
}
 
Example #26
Source File: BrokerEnvironmentFactory.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Container newContainer(
    RuntimeIdentity runtimeId,
    List<EnvVar> envVars,
    String image,
    @Nullable String brokerVolumeName) {
  String containerName = generateContainerNameFromImageRef(image);
  final ContainerBuilder cb =
      new ContainerBuilder()
          .withName(containerName)
          .withImage(image)
          .withArgs(
              "-push-endpoint",
              cheWebsocketEndpoint,
              "-runtime-id",
              String.format(
                  "%s:%s:%s",
                  runtimeId.getWorkspaceId(),
                  MoreObjects.firstNonNull(runtimeId.getEnvName(), ""),
                  runtimeId.getOwnerId()),
              "-cacert",
              certProvisioner.isConfigured() ? certProvisioner.getCertPath() : "",
              "--registry-address",
              Strings.nullToEmpty(pluginRegistryUrl))
          .withImagePullPolicy(brokerPullPolicy)
          .withEnv(envVars);
  if (brokerVolumeName != null) {
    cb.withVolumeMounts(
        new VolumeMount(CONF_FOLDER + "/", null, brokerVolumeName, true, null, null));
    cb.addToArgs("-metas", CONF_FOLDER + "/" + CONFIG_FILE);
  }
  Container container = cb.build();
  Containers.addRamLimit(container, "250Mi");
  Containers.addRamRequest(container, "250Mi");
  return container;
}
 
Example #27
Source File: JpaWorkerDao.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Transactional
protected List<WorkerImpl> doGetByUser(@Nullable String userId) throws ServerException {
  try {
    return managerProvider
        .get()
        .createNamedQuery("Worker.getByUserId", WorkerImpl.class)
        .setParameter("userId", userId)
        .getResultList();
  } catch (RuntimeException e) {
    throw new ServerException(e.getLocalizedMessage(), e);
  }
}
 
Example #28
Source File: ContainerSearch.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Constructs a new {@code ContainerSearch} instance in somewhat unsurprising manner.
 *
 * @param parentName the name of the parent object that should (indirectly) contain the containers
 * @param parentSelector the labels to match on the parent object, if any
 * @param containerName only search for containers with given name
 */
public ContainerSearch(
    @Nullable String parentName,
    @Nullable Map<String, String> parentSelector,
    @Nullable String containerName) {
  this.parentName = parentName;
  this.parentSelector = parentSelector;
  this.containerName = containerName;
}
 
Example #29
Source File: LimitsCheckingWorkspaceManager.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@VisibleForTesting
void checkRamResourcesAvailability(
    String accountId, String namespace, WorkspaceConfig config, @Nullable String envName)
    throws NotFoundException, ServerException, ConflictException {
  if (config.getEnvironments().isEmpty()) {
    return;
  }
  final Environment environment =
      config.getEnvironments().get(firstNonNull(envName, config.getDefaultEnv()));
  final ResourceImpl ramToUse =
      new ResourceImpl(
          RamResourceType.ID,
          environmentRamCalculator.calculate(environment),
          RamResourceType.UNIT);
  try {
    resourceManager.checkResourcesAvailability(accountId, singletonList(ramToUse));
  } catch (NoEnoughResourcesException e) {
    final Resource requiredRam =
        e.getRequiredResources().get(0); // starting of workspace requires only RAM resource
    final Resource availableRam =
        getResourceOrDefault(
            e.getAvailableResources(), RamResourceType.ID, 0, RamResourceType.UNIT);
    final Resource usedRam =
        getResourceOrDefault(
            resourceManager.getUsedResources(accountId),
            RamResourceType.ID,
            0,
            RamResourceType.UNIT);

    throw new LimitExceededException(
        format(
            "Workspace %s/%s needs %s to start. Your account has %s available and %s in use. "
                + "The workspace can't be start. Stop other workspaces or grant more resources.",
            namespace,
            config.getName(),
            printResourceInfo(requiredRam),
            printResourceInfo(availableRam),
            printResourceInfo(usedRam)));
  }
}
 
Example #30
Source File: KeycloakTokenProvider.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Inject
public KeycloakTokenProvider(
    @Nullable @Named("che.keycloak.github.endpoint") String gitHubEndpoint,
    @Nullable @Named("che.keycloak.oso.endpoint") String openShiftEndpoint,
    HttpJsonRequestFactory httpJsonRequestFactory) {
  this.gitHubEndpoint = gitHubEndpoint;
  this.openShiftEndpoint = openShiftEndpoint;
  this.httpJsonRequestFactory = httpJsonRequestFactory;
}