private void handleError(PromiseError error) {
   view.showLoader(false);
   final ServiceError serviceError =
       dtoFactory.createDtoFromJson(error.getMessage(), ServiceError.class);
   notificationManager.notify(serviceError.getMessage(), FAIL, true);
   view.showError(serviceError.getMessage());
 }
  private void loadOpenShiftData() {
    final ProjectConfigDto projectConfig = appContext.getCurrentProject().getRootProject();
    view.setApplicationName(projectConfig.getName());
    view.show();

    osService
        .getProjects()
        .then(
            new Operation<List<Project>>() {
              @Override
              public void apply(List<Project> projects) throws OperationException {
                if (projects == null || projects.isEmpty()) {
                  return;
                }
                osProjects.clear();
                osProjects.addAll(unmodifiableList(projects));
                view.setProjects(osProjects);
              }
            })
        .then(
            osService
                .getImageStreams("openshift", null)
                .then(
                    new Operation<List<ImageStream>>() {
                      @Override
                      public void apply(List<ImageStream> streams) throws OperationException {
                        if (streams == null || streams.isEmpty()) {
                          return;
                        }

                        osImageStreams = unmodifiableList(streams);

                        final List<String> imageNames =
                            Lists.transform(
                                osImageStreams,
                                new com.google.common.base.Function<ImageStream, String>() {
                                  @Override
                                  public String apply(ImageStream input) {
                                    return input.getMetadata().getName();
                                  }
                                });

                        view.setImages(imageNames);
                        view.setLabels(Collections.<KeyValue>emptyList());
                      }
                    }));
    applicationManager
        .getApplicationNamesByNamespaces()
        .then(
            new Operation<List<Pair<String, String>>>() {
              @Override
              public void apply(List<Pair<String, String>> arg) throws OperationException {
                osApplications.clear();
                osApplications.addAll(arg);
              }
            });
  }
 @Override
 public void updateControls() {
   view.setDeployButtonEnabled(
       isApplicationNameValid()
           & isProjectNameValid()
           & isVariablesListValid()
           & isLabelListValid()
           & osImageStreams != null
           & view.getActiveImage() != null);
 }
 private boolean isApplicationNameValid() {
   if (!OpenshiftValidator.isApplicationNameValid(osAppName)) {
     view.showApplicationNameError(
         locale.invalidApplicationNameError(), locale.invalidApplicationNameDetailError());
     return false;
   }
   if (view.getMode() == CREATE_NEW_PROJECT) {
     for (Pair<String, String> pair : osApplications) {
       if (pair.getFirst().equals(view.getOpenShiftProjectName())
           && pair.getSecond().equals(osAppName)) {
         view.showApplicationNameError(locale.existingApplicationNameError(), null);
         return false;
       }
     }
   } else if (view.getMode() == SELECT_EXISTING_PROJECT
       && view.getOpenShiftSelectedProject() != null) {
     for (Pair<String, String> pair : osApplications) {
       if (pair.getFirst().equals(view.getOpenShiftSelectedProject().getMetadata().getName())
           && pair.getSecond().equals(osAppName)) {
         view.showApplicationNameError(locale.existingApplicationNameError(), null);
         return false;
       }
     }
   }
   view.hideApplicationNameError();
   return true;
 }
 private boolean isVariablesListValid() {
   List<KeyValue> variables = view.getEnvironmentVariables();
   if (variables.isEmpty()) {
     view.hideVariablesError();
     return true;
   }
   for (KeyValue keyValue : variables) {
     if (!OpenshiftValidator.isEnvironmentVariableNameValid(keyValue.getKey())) {
       view.showVariablesError(locale.invalidVariablesError());
       return false;
     }
   }
   view.hideVariablesError();
   return true;
 }
 private boolean isLabelListValid() {
   List<KeyValue> labels = view.getLabels();
   if (labels.isEmpty()) {
     view.hideLabelsError();
     return true;
   }
   for (KeyValue keyValue : labels) {
     if (!OpenshiftValidator.isLabelNameValid(keyValue.getKey())
         || !OpenshiftValidator.isLabelValueValid(keyValue.getValue())) {
       view.showLabelsError(locale.invalidLabelsError(), locale.invalidLabelsDetailError());
       return false;
     }
   }
   view.hideLabelsError();
   return true;
 }
 @Inject
 public NewApplicationPresenter(
     NewApplicationView view,
     AppContext appContext,
     DialogFactory dialogFactory,
     OpenshiftLocalizationConstant locale,
     GitServiceClient gitService,
     OpenshiftServiceClient osService,
     DtoFactory dtoFactory,
     ProjectServiceClient projectService,
     EventBus eventBus,
     NotificationManager notificationManager,
     ApplicationManager applicationManager,
     OpenshiftAuthenticator openshiftAuthenticator,
     OpenshiftAuthorizationHandler openshiftAuthorizationHandler) {
   super(openshiftAuthenticator, openshiftAuthorizationHandler, locale, notificationManager);
   this.view = view;
   this.appContext = appContext;
   this.dialogFactory = dialogFactory;
   this.locale = locale;
   this.gitService = gitService;
   this.osService = osService;
   this.dtoFactory = dtoFactory;
   this.projectService = projectService;
   this.eventBus = eventBus;
   this.notificationManager = notificationManager;
   this.applicationManager = applicationManager;
   view.setDelegate(this);
   osProjects = new ArrayList<>();
   osApplications = new ArrayList<>();
 }
 private boolean isProjectNameValid() {
   String osProjectName = view.getOpenShiftProjectName();
   if (view.getMode() == CREATE_NEW_PROJECT) {
     if (!OpenshiftValidator.isProjectNameValid(osProjectName)) {
       view.showProjectNameError(
           locale.invalidProjectNameError(), locale.invalidProjectNameDetailError());
       return false;
     }
     for (Project project : osProjects) {
       if (project.getMetadata().getName().equals(osProjectName)) {
         view.showProjectNameError(locale.existingProjectNameError(), null);
         return false;
       }
     }
   } else if (view.getMode() == SELECT_EXISTING_PROJECT) {
     if (view.getOpenShiftSelectedProject() == null) {
       return false;
     }
   }
   view.hideProjectNameError();
   return true;
 }
  private DeploymentConfig generateDeploymentConfig(String namespace, Map<String, String> labels) {
    Object exposedPorts =
        osActiveStreamTag
            .getImage()
            .getDockerImageMetadata()
            .getContainerConfig()
            .getExposedPorts();
    List<ContainerPort> ports = parsePorts(exposedPorts);

    Map<String, String> templateLabels = new HashMap<>(labels);
    templateLabels.put("deploymentconfig", osAppName);

    List<EnvVar> env = newArrayList();

    for (KeyValue variable : view.getEnvironmentVariables()) {
      env.add(newDto(EnvVar.class).withName(variable.getKey()).withValue(variable.getValue()));
    }

    final String steamTagName = osAppName + ":latest";
    PodSpec podSpec =
        newDto(PodSpec.class)
            .withContainers(
                newArrayList(
                    newDto(Container.class)
                        .withImage(steamTagName)
                        .withName(osAppName)
                        .withPorts(ports)
                        .withEnv(env)));

    PodTemplateSpec template =
        newDto(PodTemplateSpec.class)
            .withMetadata(newDto(ObjectMeta.class).withLabels(templateLabels))
            .withSpec(podSpec);

    DeploymentTriggerPolicy imageChange =
        newDto(DeploymentTriggerPolicy.class)
            .withType("ImageChange")
            .withImageChangeParams(
                newDto(DeploymentTriggerImageChangeParams.class)
                    .withAutomatic(true)
                    .withContainerNames(newArrayList(osAppName))
                    .withFrom(
                        newDto(ObjectReference.class)
                            .withKind("ImageStreamTag")
                            .withName(steamTagName)));

    DeploymentTriggerPolicy configChange =
        newDto(DeploymentTriggerPolicy.class).withType("ConfigChange");

    return newDto(DeploymentConfig.class)
        .withApiVersion(API_VERSION)
        .withKind("DeploymentConfig")
        .withMetadata(
            newDto(ObjectMeta.class)
                .withName(osAppName)
                .withLabels(labels)
                .withNamespace(namespace))
        .withSpec(
            newDto(DeploymentConfigSpec.class)
                .withReplicas(1)
                .withSelector(Collections.singletonMap("deploymentconfig", osAppName))
                .withTemplate(template)
                .withTriggers(newArrayList(imageChange, configChange)));
  }
  @Override
  public void onDeployClicked() {
    Promise<Project> projectPromise;
    view.showLoader(true);
    switch (view.getMode()) {
      case CREATE_NEW_PROJECT:
        String osProjectName = view.getOpenShiftProjectName();
        String osProjectDisplayName = view.getOpenShiftProjectDisplayName();
        String osProjectDescription = view.getOpenShiftProjectDescription();
        // create new project
        ProjectRequest request =
            newDto(ProjectRequest.class)
                .withApiVersion(API_VERSION)
                .withDisplayName(osProjectDisplayName)
                .withDescription(osProjectDescription)
                .withMetadata(newDto(ObjectMeta.class).withName(osProjectName));
        projectPromise = osService.createProject(request);
        break;
      case SELECT_EXISTING_PROJECT:
      default:
        Project osSelectedProject = view.getOpenShiftSelectedProject();
        projectPromise = Promises.resolve(osSelectedProject);
    }

    projectPromise
        .then(
            new Operation<Project>() {
              @Override
              public void apply(final Project project) throws OperationException {
                final Map<String, String> labels = new HashMap<>();
                labels.put("generatedby", "Che");
                labels.put("application", osAppName);

                for (KeyValue label : view.getLabels()) {
                  labels.put(label.getKey(), label.getValue());
                }

                final DockerImageMetadata imageMetadata =
                    osActiveStreamTag.getImage().getDockerImageMetadata();
                Object exposedPorts =
                    (imageMetadata.getConfig() != null)
                        ? imageMetadata.getConfig().getExposedPorts()
                        : imageMetadata.getContainerConfig().getExposedPorts();
                List<ContainerPort> ports = parsePorts(exposedPorts);

                String namespace = project.getMetadata().getName();
                List<Promise<?>> promises = new ArrayList<>();
                promises.add(osService.createImageStream(generateImageStream(namespace, labels)));
                promises.add(osService.createBuildConfig(generateBuildConfig(namespace, labels)));
                promises.add(
                    osService.createDeploymentConfig(generateDeploymentConfig(namespace, labels)));
                promises.add(osService.createRoute(generateRoute(namespace, labels)));

                if (!ports.isEmpty()) {
                  promises.add(
                      osService.createService(
                          generateService(namespace, getFirstPort(ports), labels)));
                }

                Promises.all(promises.toArray(new Promise[promises.size()]))
                    .then(
                        new Operation<JsArrayMixed>() {
                          @Override
                          public void apply(JsArrayMixed arg) throws OperationException {
                            view.showLoader(false);
                            view.hide();
                            notificationManager.notify(
                                locale.deployProjectSuccess(
                                    appContext.getCurrentProject().getRootProject().getName()),
                                SUCCESS,
                                true);
                            setupMixin(project);
                          }
                        })
                    .catchError(
                        new Operation<PromiseError>() {
                          @Override
                          public void apply(PromiseError arg) throws OperationException {
                            handleError(arg);
                          }
                        });
              }
            })
        .catchError(
            new Operation<PromiseError>() {
              @Override
              public void apply(PromiseError arg) throws OperationException {
                handleError(arg);
              }
            });
  }
 @Override
 public void onCancelClicked() {
   view.hide();
 }
  private void reset() {
    osProjects.clear();
    osApplications.clear();
    osImageStreams = null;
    osAppName = null;
    osActiveStreamTag = null;
    projectRemotes = null;

    view.setDeployButtonEnabled(false);
    view.setLabels(Collections.<KeyValue>emptyList());
    view.setEnvironmentVariables(Collections.<KeyValue>emptyList());
    view.setApplicationName(null);
    view.hideApplicationNameError();
    view.hideProjectNameError();
    view.hideLabelsError();
    view.hideVariablesError();
    view.setOpenShiftProjectName(null);
    view.setOpenShiftProjectDisplayName(null);
    view.setOpenShiftProjectDescription(null);
    view.setMode(CREATE_NEW_PROJECT);
    view.setImages(Collections.<String>emptyList());
    view.setProjects(Collections.<Project>emptyList());
  }