private SearchParameters getSearchParameters(SearchType searchType, String constraint) {
    SearchParameters searchParams = new SearchParameters(constraint, searchType);
    HashMap<String, String> matrixConstraints =
        QueryHelper.getMatrixConstraints(
            getUriInfo(), CASE_SENSITIVE_CONSTRAINT_PARAMETER, FROM_CONSTRAINT_PARAMETER);

    // preserved in sake if backward compatibility until 4.0
    HashMap<String, String> queryConstraints =
        QueryHelper.getQueryConstraints(getUriInfo(), FROM_CONSTRAINT_PARAMETER);

    if (matrixConstraints.containsKey(FROM_CONSTRAINT_PARAMETER)) {
      try {
        searchParams.setSearchFrom(
            Long.parseLong(matrixConstraints.get(FROM_CONSTRAINT_PARAMETER)));
      } catch (Exception ex) {
        LOG.error(
            "Unwrapping of '" + FROM_CONSTRAINT_PARAMETER + "' matrix search parameter failed.",
            ex);
      }
    } else if (queryConstraints.containsKey(FROM_CONSTRAINT_PARAMETER)) {
      // preserved in sake if backward compatibility until 4.0
      try {
        searchParams.setSearchFrom(Long.parseLong(queryConstraints.get(FROM_CONSTRAINT_PARAMETER)));
      } catch (Exception ex) {
        LOG.error(
            "Unwrapping of '" + FROM_CONSTRAINT_PARAMETER + "' query search parameter failed.", ex);
      }
    }
    if (matrixConstraints.containsKey(CASE_SENSITIVE_CONSTRAINT_PARAMETER)) {
      try {
        searchParams.setCaseSensitive(
            Boolean.parseBoolean(matrixConstraints.get(CASE_SENSITIVE_CONSTRAINT_PARAMETER)));
      } catch (Exception ex) {
        LOG.error(
            "Unwrapping of '" + CASE_SENSITIVE_CONSTRAINT_PARAMETER + "' search parameter failed.",
            ex);
      }
    }

    try {
      if (QueryHelper.hasMatrixParam(getUriInfo(), MAX) && getMaxResults() != NO_LIMIT) {
        searchParams.setMaxCount(getMaxResults());
      }
    } catch (MalformedNumberException ex) {
      handleError(ex, false);
    }
    return searchParams;
  }
  /**
   * Creates {@code ExecutionContext} which defines the context for executing the finalizing step of
   * the job. If the step exists, it must be part of a job, therefore the {@code Job} entity is
   * being set as part of the context.
   *
   * @param stepId The unique identifier of the step. Must not be {@code null}.
   * @return The context for monitoring the finalizing step of the job, or {@code null} if no such
   *     step.
   */
  public static ExecutionContext createFinalizingContext(Guid stepId) {
    ExecutionContext context = null;
    try {
      Step step = JobRepositoryFactory.getJobRepository().getStep(stepId);
      if (step != null && step.getParentStepId() != null) {
        context = new ExecutionContext();
        Step executionStep =
            JobRepositoryFactory.getJobRepository().getStep(step.getParentStepId());

        // indicates if a step is monitored at Job level or as an inner step
        Guid parentStepId = executionStep.getParentStepId();
        if (parentStepId == null) {
          context.setExecutionMethod(ExecutionMethod.AsJob);
          context.setJob(JobRepositoryFactory.getJobRepository().getJobWithSteps(step.getJobId()));
        } else {
          context.setExecutionMethod(ExecutionMethod.AsStep);
          Step parentStep = JobRepositoryFactory.getJobRepository().getStep(parentStepId);
          parentStep.setSteps(
              DbFacade.getInstance().getStepDao().getStepsByParentStepId(parentStep.getId()));
          context.setStep(parentStep);
        }
        context.setMonitored(true);
      }
    } catch (Exception e) {
      log.error(e);
    }
    return context;
  }
  /**
   * Finalizes a {@code Job} execution by a given context in which the job was performed and by the
   * exit status of the step. If the {@code Job} execution continues beyond the scope of the
   * command, the {@code Job.isAsyncJob()} should be set to {@code true}. If {@code
   * ExecutionMethod.AsStep} is defined, the current active step can end the running {@code Job} by
   * setting the {@ExecutionContext.shouldEndJob()} to {@code true}.
   *
   * @param executionContext The context of the execution which defines how the job should be ended
   * @param exitStatus Indicates if the execution described by the job ended successfully or not.
   */
  public static void endJob(ExecutionContext context, boolean exitStatus) {
    if (context == null) {
      return;
    }

    Job job = context.getJob();

    try {
      if (context.isMonitored()) {
        if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null) {
          if (context.shouldEndJob() || !(job.isAsyncJob() && exitStatus)) {
            context.setCompleted(true);
            endJob(exitStatus, job);
          }
        } else {
          Step step = context.getStep();
          if (context.getExecutionMethod() == ExecutionMethod.AsStep && step != null) {
            if (context.shouldEndJob()) {
              if (job == null) {
                job = JobRepositoryFactory.getJobRepository().getJob(step.getJobId());
              }

              if (job != null) {
                context.setCompleted(true);
                endJob(exitStatus, job);
              }
            }
          }
        }
      }
    } catch (Exception e) {
      log.error(e);
    }
  }
  /**
   * Finalizes a {@code Step} execution by a given context in which the step was performed and by
   * the exit status of the step.
   *
   * @param context The context in which the {@code Step} was executed.
   * @param step The step to finalize.
   * @param exitStatus Indicates if the execution described by the step ended successfully or not.
   */
  public static void endStep(ExecutionContext context, Step step, boolean exitStatus) {
    if (context == null) {
      return;
    }
    if (context.isMonitored()) {
      Job job = context.getJob();
      try {
        if (step != null) {
          step.markStepEnded(exitStatus);
          JobRepositoryFactory.getJobRepository().updateStep(step);
        }

        if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null && !exitStatus) {
          // step failure will cause the job to be marked as failed
          context.setCompleted(true);
          job.markJobEnded(false);
          JobRepositoryFactory.getJobRepository().updateCompletedJobAndSteps(job);
        } else {
          Step parentStep = context.getStep();
          if (context.getExecutionMethod() == ExecutionMethod.AsStep && parentStep != null) {
            context.setCompleted(true);
            if (!exitStatus) {
              job.markJobEnded(false);
              JobRepositoryFactory.getJobRepository().updateCompletedJobAndSteps(job);
            }
          }
        }
      } catch (Exception e) {
        log.error(e);
      }
    }
  }
 /**
  * Process the return value and reply back. When exceptions raises they will be logged and set a
  * return value accordingly.
  *
  * @param timeout
  * @param unit
  * @return VDSReturnValue
  * @throws TimeoutException
  */
 @Override
 public VDSReturnValue get(long timeout, TimeUnit unit) throws TimeoutException {
   try {
     status = new StatusOnlyReturnForXmlRpc(httpTask.get(timeout, unit));
     ProceedProxyReturnValue();
   } catch (TimeoutException e) {
     httpTask.cancel(true);
     setVdsNetworkError(new VDSNetworkException(new RuntimeException(e.getCause())));
     log.error("Timeout waiting for VDSM response. " + e);
     throw e;
   } catch (Exception e) {
     log.error(e);
     setVdsRuntimeError(
         e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e));
   }
   return getVDSReturnValue();
 }
 /**
  * Updates Job for the same entity for a specific action as completed with a given exit status.
  *
  * @param entityId The entity to search for its jobs
  * @param actionType The action type to search for
  * @param status The exist status to be set for the job
  */
 public static void updateSpecificActionJobCompleted(
     Guid entityId, VdcActionType actionType, boolean status) {
   try {
     List<Job> jobs =
         JobRepositoryFactory.getJobRepository().getJobsByEntityAndAction(entityId, actionType);
     for (Job job : jobs) {
       if (job.getStatus() == JobExecutionStatus.STARTED) job.markJobEnded(status);
       JobRepositoryFactory.getJobRepository().updateCompletedJobAndSteps(job);
     }
   } catch (RuntimeException e) {
     log.error(e);
   }
 }
 public static void loadDbFacadeConfig() throws Exception {
   boolean configSucceeded = false;
   final String ENGINE_CONF_FILE = "/etc/ovirt-engine/engine.conf";
   final String ON_START_CONNECTION_TIMEOUT = "OnStartConnectionTimeout";
   final String CONNECTION_CHECK_INTERVAL = "ConnectionCheckInterval";
   final String DEFAULT_TIMEOUT_VALUE = "300000";
   final String DEFAULT_INTERVAL_VALUE = "1000";
   InputStream inputStream = null;
   try {
     String onStartConnectionTimeout = null;
     String connectionCheckInterval = null;
     Properties props = new Properties();
     if (FileUtil.fileExists(ENGINE_CONF_FILE)) {
       // File exists, load /etc/ovirt-engine/engine.conf and set values in DbFacade
       inputStream = new FileInputStream(ENGINE_CONF_FILE);
       props.load(inputStream);
       onStartConnectionTimeout = props.getProperty(ON_START_CONNECTION_TIMEOUT);
       connectionCheckInterval = props.getProperty(CONNECTION_CHECK_INTERVAL);
       if (!validNumber(onStartConnectionTimeout)) {
         onStartConnectionTimeout = DEFAULT_TIMEOUT_VALUE;
       }
       if (!validNumber(connectionCheckInterval)) {
         connectionCheckInterval = DEFAULT_INTERVAL_VALUE;
       }
     } else {
       // File does not exist - use defaults
       log.warn(
           String.format(
               "%1$s file is not found. Please check your engine installation. "
                   + "Default values will be used",
               ENGINE_CONF_FILE));
       onStartConnectionTimeout = DEFAULT_TIMEOUT_VALUE;
       connectionCheckInterval = DEFAULT_INTERVAL_VALUE;
     }
     dbFacade.setOnStartConnectionTimeout(Integer.parseInt(onStartConnectionTimeout));
     dbFacade.setConnectionCheckInterval(Integer.parseInt(connectionCheckInterval));
     configSucceeded = true;
   } catch (Exception ex) {
     log.error("Error in configuration of db facade " + ExceptionUtils.getMessage(ex));
   } finally {
     if (!configSucceeded) {
       dbFacade.setOnStartConnectionTimeout(300000);
       dbFacade.setConnectionCheckInterval(1000);
     }
     if (inputStream != null) {
       inputStream.close();
     }
   }
 }
 protected void getEntity(String id) {
   try {
     Method method = getMethod(this.getClass(), SingleEntityResource.class);
     if (method == null) {
       LOG.error("Could not find sub-resource in the collection resource");
     } else {
       Object entityResource = method.invoke(this, id);
       method = entityResource.getClass().getMethod("get");
       method.invoke(entityResource);
     }
   } catch (IllegalAccessException e) {
     LOG.error("Reflection Error", e);
   } catch (InvocationTargetException e) {
     if (e.getTargetException() instanceof WebApplicationException) {
       throw ((WebApplicationException) e.getTargetException());
     } else {
       LOG.error("Reflection Error", e);
     }
   } catch (SecurityException e) {
     LOG.error("Reflection Error", e);
   } catch (NoSuchMethodException e) {
     LOG.error("Reflection Error", e);
   }
 }
  /**
   * Method should be called when finalizing the command. The execution step is being ended with
   * success and the finalization step is started.
   *
   * @param executionContext The context of the job
   * @return A created instance of the Finalizing step
   */
  public static Step startFinalizingStep(ExecutionContext executionContext) {
    if (executionContext == null) {
      return null;
    }
    Step step = null;

    try {
      if (executionContext.getExecutionMethod() == ExecutionMethod.AsJob) {
        Job job = executionContext.getJob();
        if (job != null) {
          Step executingStep = job.getStep(StepEnum.EXECUTING);
          Step finalizingStep =
              job.addStep(
                  StepEnum.FINALIZING,
                  ExecutionMessageDirector.getInstance().getStepMessage(StepEnum.FINALIZING));

          if (executingStep != null) {
            executingStep.markStepEnded(true);
            JobRepositoryFactory.getJobRepository()
                .updateExistingStepAndSaveNewStep(executingStep, finalizingStep);
          } else {
            JobRepositoryFactory.getJobRepository().saveStep(finalizingStep);
          }
        }
      } else if (executionContext.getExecutionMethod() == ExecutionMethod.AsStep) {
        Step parentStep = executionContext.getStep();
        if (parentStep != null) {
          Step executingStep = parentStep.getStep(StepEnum.EXECUTING);
          Step finalizingStep =
              parentStep.addStep(
                  StepEnum.FINALIZING,
                  ExecutionMessageDirector.getInstance().getStepMessage(StepEnum.FINALIZING));
          if (executingStep != null) {
            executingStep.markStepEnded(true);
            JobRepositoryFactory.getJobRepository()
                .updateExistingStepAndSaveNewStep(executingStep, finalizingStep);
          } else {
            JobRepositoryFactory.getJobRepository().saveStep(finalizingStep);
          }
        }
      }
    } catch (Exception e) {
      log.error(e);
    }
    return step;
  }
  /**
   * Adds a {@link Step} entity by the provided context. A {@link Step} will not be created if
   * {@code ExecutionContext.isMonitored()} returns false.
   *
   * @param context The context of the execution which defines visibility and execution method.
   * @param stepName The name of the step.
   * @param description A presentation name for the step. If not provided, the presentation name is
   *     resolved by the {@code stepName}.
   * @param isExternal Indicates if the step is invoked by a plug-in
   * @return
   */
  public static Step addStep(
      ExecutionContext context, StepEnum stepName, String description, boolean isExternal) {
    if (context == null) {
      return null;
    }
    Step step = null;

    if (context.isMonitored()) {
      if (description == null) {
        description = ExecutionMessageDirector.getInstance().getStepMessage(stepName);
      }

      try {
        Job job = context.getJob();
        if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null) {
          step = job.addStep(stepName, description);
          try {
            step.setExternal(isExternal);
            JobRepositoryFactory.getJobRepository().saveStep(step);
          } catch (Exception e) {
            log.errorFormat(
                "Failed to save new step {0} for job {1}, {2}.",
                stepName.name(), job.getId(), job.getActionType().name(), e);
            job.getSteps().remove(step);
            step = null;
          }
        } else {
          Step contextStep = context.getStep();
          if (context.getExecutionMethod() == ExecutionMethod.AsStep && contextStep != null) {
            step = addSubStep(contextStep, stepName, description);
            step.setExternal(isExternal);
          }
        }
      } catch (Exception e) {
        log.error(e);
      }
    }
    return step;
  }
  /**
   * Finalizes Job with VDSM tasks, as this case requires verification that no other steps are
   * running in order to close the entire Job
   *
   * @param executionContext The context of the execution which defines how the job should be ended
   * @param exitStatus Indicates if the execution described by the job ended successfully or not.
   */
  public static void endTaskJob(ExecutionContext context, boolean exitStatus) {
    if (context == null) {
      return;
    }

    try {
      if (context.getExecutionMethod() == ExecutionMethod.AsJob && context.getJob() != null) {
        endJob(context, exitStatus);
      } else {
        Step parentStep = context.getStep();
        if (context.getExecutionMethod() == ExecutionMethod.AsStep && parentStep != null) {
          Step finalizingStep = parentStep.getStep(StepEnum.FINALIZING);
          if (finalizingStep != null) {
            finalizingStep.markStepEnded(exitStatus);
            JobRepositoryFactory.getJobRepository().updateStep(finalizingStep);
          }
          parentStep.markStepEnded(exitStatus);
          JobRepositoryFactory.getJobRepository().updateStep(parentStep);

          List<Step> steps =
              DbFacade.getInstance().getStepDao().getStepsByJobId(parentStep.getJobId());
          boolean hasChildStepsRunning = false;
          for (Step step : steps) {
            if (step.getStatus() == JobExecutionStatus.STARTED && step.getParentStepId() != null) {
              hasChildStepsRunning = true;
              break;
            }
          }
          if (!hasChildStepsRunning) {
            endJob(
                exitStatus, JobRepositoryFactory.getJobRepository().getJob(parentStep.getJobId()));
          }
        }
      }
    } catch (RuntimeException e) {
      log.error(e);
    }
  }
  /**
   * Checks if a Job has any Step associated with VDSM task
   *
   * @param context The context of the execution stores the Job
   * @return true if Job has any Step for VDSM Task, else false.
   */
  public static boolean checkIfJobHasTasks(ExecutionContext context) {
    if (context == null || !context.isMonitored()) {
      return false;
    }

    try {
      Guid jobId = null;
      if (context.getExecutionMethod() == ExecutionMethod.AsJob && context.getJob() != null) {
        jobId = context.getJob().getId();
      } else if (context.getExecutionMethod() == ExecutionMethod.AsStep
          && context.getStep() != null) {
        jobId = context.getStep().getId();
      }

      if (jobId != null) {
        return DbFacade.getInstance().getJobDao().checkIfJobHasTasks(jobId);
      }
    } catch (RuntimeException e) {
      log.error(e);
    }

    return false;
  }
  /**
   * Adds a {@link Step} entity by the provided context as a child step of a given parent step. A
   * {@link Step} will not be created if {@code ExecutionContext.isMonitored()} returns false.
   *
   * @param context The context of the execution which defines visibility and execution method.
   * @param parentStep The parent step which the new step will be added as its child.
   * @param newStepName The name of the step.
   * @param description A presentation name for the step. If not provided, the presentation name is
   *     resolved by the {@code stepName}.
   * @param isExternal Indicates if the step is invoked by a plug-in
   * @return
   */
  public static Step addSubStep(
      ExecutionContext context,
      Step parentStep,
      StepEnum newStepName,
      String description,
      boolean isExternal) {
    Step step = null;

    if (context == null || parentStep == null) {
      return null;
    }

    try {
      if (context.isMonitored()) {
        if (description == null) {
          description = ExecutionMessageDirector.getInstance().getStepMessage(newStepName);
        }

        if (context.getExecutionMethod() == ExecutionMethod.AsJob) {
          if (DbFacade.getInstance().getStepDao().exists(parentStep.getId())) {
            if (parentStep.getJobId().equals(context.getJob().getId())) {
              step = parentStep.addStep(newStepName, description);
            }
          }
        } else if (context.getExecutionMethod() == ExecutionMethod.AsStep) {
          step = parentStep.addStep(newStepName, description);
        }
      }
      if (step != null) {
        step.setExternal(isExternal);
        JobRepositoryFactory.getJobRepository().saveStep(step);
      }
    } catch (Exception e) {
      log.error(e);
    }
    return step;
  }
 protected void logUnsupportedInterfaceType() {
   log.error("Unsupported interface type, ISCSI interface type is not supported.");
 }