Ejemplo n.º 1
0
    @Override
    public void run() {
      LOGGER.info("ClusterManager thread starting.");

      long delay = taskManager.getConfiguration().getNodeRegistrationCycleTime() * 1000L;
      while (canRun) {

        OperationResult result = new OperationResult(ClusterManagerThread.class + ".run");

        try {

          checkSystemConfigurationChanged(result);

          // these checks are separate in order to prevent a failure in one method blocking
          // execution of others
          try {
            checkClusterConfiguration(result); // if error, the scheduler will be stopped
            nodeRegistrar.updateNodeObject(
                result); // however, we want to update repo even in that case
          } catch (Throwable t) {
            LoggingUtils.logException(
                LOGGER,
                "Unexpected exception while checking cluster configuration; continuing execution.",
                t);
          }

          try {
            checkWaitingTasks(result);
          } catch (Throwable t) {
            LoggingUtils.logException(
                LOGGER,
                "Unexpected exception while checking waiting tasks; continuing execution.",
                t);
          }

          try {
            checkStalledTasks(result);
          } catch (Throwable t) {
            LoggingUtils.logException(
                LOGGER,
                "Unexpected exception while checking stalled tasks; continuing execution.",
                t);
          }

        } catch (Throwable t) {
          LoggingUtils.logException(
              LOGGER, "Unexpected exception in ClusterManager thread; continuing execution.", t);
        }

        LOGGER.trace("ClusterManager thread sleeping for " + delay + " msec");
        try {
          Thread.sleep(delay);
        } catch (InterruptedException e) {
          LOGGER.trace("ClusterManager thread interrupted.");
        }
      }

      LOGGER.info("ClusterManager thread stopping.");
    }
Ejemplo n.º 2
0
  private ObjectWrapper loadUserWrapper(PrismObject<UserType> userToEdit) {
    OperationResult result = new OperationResult(OPERATION_LOAD_USER);
    PrismObject<UserType> user = null;
    try {

      Collection options =
          SelectorOptions.createCollection(
              UserType.F_CREDENTIALS, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));
      Task task = createSimpleTask(OPERATION_LOAD_USER);
      user =
          getModelService()
              .getObject(
                  UserType.class, SecurityUtils.getPrincipalUser().getOid(), options, task, result);

      result.recordSuccess();
    } catch (Exception ex) {
      result.recordFatalError("Couldn't get user.", ex);
      LoggingUtils.logException(LOGGER, "Couldn't load user PageMyQuestions", ex);
    }

    if (!result.isSuccess()) {
      showResultInSession(result);
    }

    if (user == null) {

      throw new RestartResponseException(PageDashboard.class);
    }

    ContainerStatus status = ContainerStatus.MODIFYING;
    ObjectWrapperFactory owf = new ObjectWrapperFactory(this);
    ObjectWrapper wrapper;
    try {
      wrapper = owf.createObjectWrapper("pageMyPasswordQuestions.userDetails", null, user, status);
    } catch (Exception ex) {
      result.recordFatalError("Couldn't get user.", ex);
      LoggingUtils.logException(LOGGER, "Couldn't load user", ex);
      wrapper =
          owf.createObjectWrapper(
              "pageMyPasswordQuestions.userDetails", null, user, null, null, status, false);
    }
    //        ObjectWrapper wrapper = new ObjectWrapper("pageUser.userDetails", null, user, status);
    if (owf.getResult() != null && !WebMiscUtil.isSuccessOrHandledError(wrapper.getResult())) {
      showResultInSession(wrapper.getResult());
    }

    return wrapper;
  }
Ejemplo n.º 3
0
  private void updateAccountStatusPerformed(
      AjaxRequestTarget target, AccountContentDto dto, boolean enabled) {
    List<AccountContentDto> accounts = isAnythingSelected(target, dto);
    OperationResult result = new OperationResult(OPERATION_ADJUST_ACCOUNT_STATUS);

    if (accounts.isEmpty()) {
      return;
    }

    ActivationStatusType status =
        enabled ? ActivationStatusType.ENABLED : ActivationStatusType.DISABLED;

    for (AccountContentDto acc : accounts) {

      ObjectDelta delta =
          ObjectDelta.createModificationReplaceProperty(
              ShadowType.class,
              acc.getAccountOid(),
              new ItemPath(ShadowType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS),
              getPrismContext(),
              status);

      try {
        Task task = createSimpleTask(OPERATION_ADJUST_ACCOUNT_STATUS);
        getModelService()
            .executeChanges(WebMiscUtil.createDeltaCollection(delta), null, task, result);
      } catch (Exception e) {
        LoggingUtils.logException(LOGGER, "Couldn't enable/disable account(s) on resource", e);
        result.recordPartialError("Couldn't enable/disable account(s) on resource", e);
      }
    }
    result.recomputeStatus();
    showResult(result);
    target.add(getFeedbackPanel());
  }
Ejemplo n.º 4
0
  private void importReportFromStreamPerformed(AjaxRequestTarget target) {
    String xml = xmlEditorModel.getObject();
    if (StringUtils.isEmpty(xml)) {
      error(getString("PageNewReport.message.emptyXml"));
      target.add(getFeedbackPanel());

      return;
    }

    OperationResult result = new OperationResult(OPERATION_IMPORT_REPORT_XML);
    InputStream stream = null;
    try {

      setResponsePage(new PageReport(new ReportDto(Base64.encodeBase64(xml.getBytes()))));
    } catch (Exception ex) {
      result.recordFatalError("Couldn't import object.", ex);
      LoggingUtils.logException(LOGGER, "Error occured during xml import", ex);
    } finally {
      if (stream != null) {
        IOUtils.closeQuietly(stream);
      }
    }

    if (result.isSuccess()) {
      xmlEditorModel.setObject(null);
    }

    showResult(result);
    target.add(getFeedbackPanel());
  }
Ejemplo n.º 5
0
  private ObjectQuery createQuery() {
    AccountContentSearchDto dto = searchModel.getObject();
    if (StringUtils.isEmpty(dto.getSearchText())) {
      return null;
    }

    try {
      ObjectQuery query = null;

      List<ObjectFilter> conditions = new ArrayList<>();
      ObjectClassComplexTypeDefinition def = getAccountDefinition();
      if (dto.isIdentifiers()) {

        List<ResourceAttributeDefinition> identifiers = new ArrayList<>();
        if (def.getIdentifiers() != null) {
          identifiers.addAll(def.getIdentifiers());
        }

        // TODO set matching rule instead fo null
        for (ResourceAttributeDefinition attrDef : identifiers) {
          conditions.add(
              EqualFilter.createEqual(
                  new ItemPath(ShadowType.F_ATTRIBUTES, attrDef.getName()),
                  attrDef,
                  dto.getSearchText()));
        }
      }

      if (dto.isName()) {
        List<ResourceAttributeDefinition> secondaryIdentifiers = new ArrayList<>();
        if (def.getNamingAttribute() != null) {
          secondaryIdentifiers.add(def.getNamingAttribute());
        } else if (def.getSecondaryIdentifiers() != null) {
          secondaryIdentifiers.addAll(def.getSecondaryIdentifiers());
        }
        for (ResourceAttributeDefinition attrDef : secondaryIdentifiers) {
          conditions.add(
              SubstringFilter.createSubstring(
                  new ItemPath(ShadowType.F_ATTRIBUTES, attrDef.getName()),
                  attrDef,
                  dto.getSearchText()));
        }
      }

      if (!conditions.isEmpty()) {
        if (conditions.size() > 1) {
          query = ObjectQuery.createObjectQuery(OrFilter.createOr(conditions));
        } else {
          query = ObjectQuery.createObjectQuery(conditions.get(0));
        }
      }

      return query;
    } catch (Exception ex) {
      error(getString("pageUsers.message.queryError") + " " + ex.getMessage());
      LoggingUtils.logException(LOGGER, "Couldn't create query filter.", ex);
    }

    return null;
  }
Ejemplo n.º 6
0
  private void importAccount(AjaxRequestTarget target, AccountContentDto row) {
    List<AccountContentDto> accounts = isAnythingSelected(target, row);
    if (accounts.isEmpty()) {
      return;
    }

    OperationResult result = new OperationResult(OPERATION_CREATE_USER_FROM_ACCOUNTS);
    for (AccountContentDto dto : accounts) {
      OperationResult subResult = result.createMinorSubresult(OPERATION_CREATE_USER_FROM_ACCOUNT);
      try {
        getModelService()
            .importFromResource(
                dto.getAccountOid(),
                createSimpleTask(OPERATION_CREATE_USER_FROM_ACCOUNT),
                subResult);
      } catch (Exception ex) {
        subResult.computeStatus(
            getString("pageContentAccounts.message.cantImportAccount", dto.getAccountOid()));
        LoggingUtils.logException(
            LOGGER,
            "Can't import account {},oid={}",
            ex,
            dto.getAccountName(),
            dto.getAccountOid());
      } finally {
        subResult.computeStatusIfUnknown();
      }
    }

    result.computeStatus();
    showResult(result);

    target.add(getFeedbackPanel());
    target.add(getTable());
  }
Ejemplo n.º 7
0
  private InputStream createReport() {
    OperationResult result = new OperationResult(OPERATION_DOWNLOAD_REPORT);
    ReportManager reportManager = getReportManager();

    if (currentReport == null) {
      return null;
    }

    InputStream input = null;
    try {
      input = reportManager.getReportOutputData(currentReport.getOid(), result);
    } catch (Exception e) {
      error(getString("pageCreatedReports.message.downloadError") + " " + e.getMessage());
      LoggingUtils.logException(LOGGER, "Couldn't download report.", e);
      LOGGER.trace(result.debugDump());
    } finally {
      result.computeStatusIfUnknown();
    }

    if (WebMiscUtil.showResultInPage(result)) {
      showResultInSession(result);
    }

    return input;
  }
Ejemplo n.º 8
0
  public void stopClusterManagerThread(long waitTime, OperationResult parentResult) {

    OperationResult result =
        parentResult.createSubresult(ClusterManager.class.getName() + ".stopClusterManagerThread");
    result.addParam("waitTime", waitTime);

    if (clusterManagerThread != null) {
      clusterManagerThread.signalShutdown();
      try {
        clusterManagerThread.join(waitTime);
      } catch (InterruptedException e) {
        LoggingUtils.logException(
            LOGGER, "Waiting for ClusterManagerThread shutdown was interrupted", e);
      }
      if (clusterManagerThread.isAlive()) {
        result.recordWarning(
            "ClusterManagerThread shutdown requested but after "
                + waitTime
                + " ms it is still running.");
      } else {
        result.recordSuccess();
      }
    } else {
      result.recordSuccess();
    }
  }
Ejemplo n.º 9
0
  private void importReportFromFilePerformed(AjaxRequestTarget target) {
    OperationResult result = new OperationResult(OPERATION_IMPORT_REPORT);

    FileUploadField file =
        (FileUploadField)
            get(createComponentPath(ID_MAIN_FORM, ID_INPUT, ID_INPUT_FILE, ID_FILE_INPUT));
    final FileUpload uploadedFile = file.getFileUpload();
    if (uploadedFile == null) {
      error(getString("PageNewReport.message.nullFile"));
      target.add(getFeedbackPanel());

      return;
    }

    InputStream stream = null;
    File newFile = null;
    try {
      // Create new file
      MidPointApplication application = getMidpointApplication();
      WebApplicationConfiguration config = application.getWebApplicationConfiguration();
      File folder = new File(config.getImportFolder());
      if (!folder.exists() || !folder.isDirectory()) {
        folder.mkdir();
      }

      newFile = new File(folder, uploadedFile.getClientFileName());
      // Check new file, delete if it already exists
      if (newFile.exists()) {
        newFile.delete();
      }
      // Save file
      //            Task task = createSimpleTask(OPERATION_IMPORT_FILE);
      newFile.createNewFile();
      uploadedFile.writeTo(newFile);

      InputStreamReader reader = new InputStreamReader(new FileInputStream(newFile), "utf-8");
      //            reader.
      stream = new ReaderInputStream(reader, reader.getEncoding());
      byte[] reportIn = IOUtils.toByteArray(stream);

      setResponsePage(new PageReport(new ReportDto(Base64.encodeBase64(reportIn))));
    } catch (Exception ex) {
      result.recordFatalError("Couldn't import file.", ex);
      LoggingUtils.logException(LOGGER, "Couldn't import file", ex);
    } finally {
      if (stream != null) {
        IOUtils.closeQuietly(stream);
      }
      if (newFile != null) {
        FileUtils.deleteQuietly(newFile);
      }
    }

    showResult(result);
    target.add(getFeedbackPanel());
  }
Ejemplo n.º 10
0
  private void savePerformed(AjaxRequestTarget target) {
    ObjectViewDto dto = model.getObject();
    if (StringUtils.isEmpty(dto.getXml())) {
      error(getString("pageResourceEdit.message.emptyXml"));
      target.add(getFeedbackPanel());
      return;
    }

    Task task = createSimpleTask(OPERATION_SAVE_RESOURCE);
    OperationResult result = task.getResult();
    try {
      Holder<PrismObject<ResourceType>> objectHolder = new Holder<PrismObject<ResourceType>>(null);
      validateObject(dto.getXml(), objectHolder, false, result);

      if (result.isAcceptable()) {
        PrismObject<ResourceType> newResource = objectHolder.getValue();
        updateConnectorRef(newResource, task, result);

        if (!isEditing()) {
          // we're adding new resource
          ObjectDelta delta = ObjectDelta.createAddDelta(newResource);
          getModelService()
              .executeChanges(WebMiscUtil.createDeltaCollection(delta), null, task, result);
        } else {
          // we're editing existing resource
          PrismObject<ResourceType> oldResource = dto.getObject();
          ObjectDelta<ResourceType> delta = oldResource.diff(newResource);

          getModelService()
              .executeChanges(
                  WebMiscUtil.createDeltaCollection(delta),
                  ModelExecuteOptions.createRaw(),
                  task,
                  result);
        }

        result.computeStatus();
      }
    } catch (Exception ex) {
      LoggingUtils.logException(LOGGER, "Couldn't save resource", ex);
      result.recordFatalError("Couldn't save resource.", ex);
    }

    if (WebMiscUtil.isSuccessOrHandledError(result)) {
      showResultInSession(result);
      setResponsePage(PageResources.class);
    } else {
      showResult(result);
      target.add(getFeedbackPanel());
    }
  }
Ejemplo n.º 11
0
  private void deleteConfirmedPerformed(AjaxRequestTarget target) {
    List<AccountContentDto> selected = new ArrayList<AccountContentDto>();

    if (singleDelete != null) {
      selected.add(singleDelete);
    } else {
      selected = isAnythingSelected(target, null);
    }

    OperationResult result = new OperationResult(OPERATION_DELETE_ACCOUNT_FROM_RESOURCE);

    for (AccountContentDto acc : selected) {
      String accOid = acc.getAccountOid();

      try {
        Task task = createSimpleTask(OPERATION_DELETE_ACCOUNT_FROM_RESOURCE);

        ObjectDelta delta =
            ObjectDelta.createDeleteDelta(ShadowType.class, accOid, getPrismContext());
        getModelService()
            .executeChanges(WebMiscUtil.createDeltaCollection(delta), null, task, result);

      } catch (Exception e) {
        result.recordPartialError("Couldn't delete account from resource.", e);
        LoggingUtils.logException(LOGGER, "Couldn't delete account from resource", e);
      }
    }

    if (result.isUnknown()) {
      result.recomputeStatus("Error occurred during resource account deletion.");
    }

    if (result.isSuccess()) {
      result.recordStatus(
          OperationResultStatus.SUCCESS, "Selected accounts have been successfully deleted.");
    }

    AccountContentDataProvider provider =
        (AccountContentDataProvider) getTable().getDataTable().getDataProvider();
    provider.clearCache();

    TablePanel table = getTable();
    target.add(table);
    showResult(result);
    target.add(getFeedbackPanel());
  }
Ejemplo n.º 12
0
  private ObjectViewDto loadResource() {
    if (!isEditing()) {
      return new ObjectViewDto();
    }

    ObjectViewDto dto;
    try {
      PrismObject<ResourceType> resource = loadResource(null);
      String xml = getPrismContext().serializeObjectToString(resource, PrismContext.LANG_XML);

      dto = new ObjectViewDto(resource.getOid(), WebMiscUtil.getName(resource), resource, xml);
    } catch (Exception ex) {
      LoggingUtils.logException(LOGGER, "Couldn't load resource", ex);
      throw new RestartResponseException(PageResources.class);
    }

    return dto;
  }
  @Override
  public Object getObject() {
    PrismProperty property;
    try {
      property = getPrismObject().findOrCreateProperty(path);
    } catch (SchemaException ex) {
      LoggingUtils.logException(LOGGER, "Couldn't create property in path {}", ex, path);
      // todo show message in page error [lazyman]
      throw new RestartResponseException(PageError.class);
    }

    Object val = getRealValue(property != null ? property.getRealValue() : null);
    if (val == null) {
      return defaultValue;
    } else {
      return val;
    }
  }
Ejemplo n.º 14
0
  private ObjectQuery createQuery() {
    ReportOutputSearchDto dto = searchModel.getObject();

    try {
      List<ObjectFilter> ands = new ArrayList<>();

      if (StringUtils.isNotEmpty(dto.getText())) {
        PolyStringNormalizer normalizer = getPrismContext().getDefaultPolyStringNormalizer();
        String normalizedString = normalizer.normalize(dto.getText());

        SubstringFilter substring =
            SubstringFilter.createSubstring(
                ReportOutputType.F_NAME,
                ReportOutputType.class,
                getPrismContext(),
                PolyStringNormMatchingRule.NAME,
                normalizedString);
        ands.add(substring);
      }

      String oid = dto.getReportTypeMap().get(dto.getReportType());
      if (StringUtils.isNotEmpty(oid)) {
        RefFilter ref =
            RefFilter.createReferenceEqual(
                ReportOutputType.F_REPORT_REF, ReportOutputType.class, getPrismContext(), oid);
        ands.add(ref);
      }

      switch (ands.size()) {
        case 0:
          return null;
        case 1:
          return ObjectQuery.createObjectQuery(ands.get(0));
        default:
          AndFilter and = AndFilter.createAnd(ands);
          return ObjectQuery.createObjectQuery(and);
      }
    } catch (Exception e) {
      error(getString("pageCreatedReports.message.queryError") + " " + e.getMessage());
      LoggingUtils.logException(LOGGER, "Couldn't create query filter.", e);
      return null;
    }
  }
Ejemplo n.º 15
0
  private UiWidget initWidget(String type, List<PropertyType> properties) {
    try {
      Class<? extends UiWidget> clazz = UiRegistry.getWidget(type);
      Constructor<? extends UiWidget> constructor =
          clazz.getConstructor(String.class, IModel.class);

      UiWidget widget = constructor.newInstance("widget", createValueModel());
      widget.setProperties(properties);

      return widget;
    } catch (Exception ex) {
      StringBuilder builder = new StringBuilder();
      StructuredFormUtils.createMessage(ex, builder);
      error(builder.toString());

      LoggingUtils.logException(LOGGER, "Couldn't create widget", ex);
    }

    return new TextWidget("widget", createValueModel());
  }
  @Override
  public void setObject(Object object) {
    try {
      PrismProperty property = getPrismObject().findOrCreateProperty(path);

      if (object != null) {
        PrismPropertyDefinition def = property.getDefinition();
        if (PolyString.class.equals(def.getTypeClass())) {
          object = new PolyString((String) object);
        }

        property.setValue(new PrismPropertyValue(object, OriginType.USER_ACTION, null));
      } else {
        PrismContainerValue parent = (PrismContainerValue) property.getParent();
        parent.remove(property);
      }
    } catch (Exception ex) {
      LoggingUtils.logException(LOGGER, "Couldn't update prism property model", ex);
    }
  }
  private HookOperationMode applyScenario(
      GeneralChangeProcessorScenarioType scenarioType,
      GcpScenarioBean scenarioBean,
      ModelContext context,
      Task taskFromModel,
      OperationResult result) {

    try {
      // ========== preparing root task ===========

      JobCreationInstruction rootInstruction =
          baseModelInvocationProcessingHelper.createInstructionForRoot(
              this, context, taskFromModel);
      Job rootJob =
          baseModelInvocationProcessingHelper.createRootJob(rootInstruction, taskFromModel, result);

      // ========== preparing child task, starting WF process ===========

      JobCreationInstruction instruction =
          scenarioBean.prepareJobCreationInstruction(
              scenarioType, (LensContext<?>) context, rootJob, taskFromModel, result);
      jobController.createJob(instruction, rootJob, result);

      // ========== complete the action ===========

      baseModelInvocationProcessingHelper.logJobsBeforeStart(rootJob, result);
      rootJob.startWaitingForSubtasks(result);

      return HookOperationMode.BACKGROUND;

    } catch (SchemaException
        | ObjectNotFoundException
        | CommunicationException
        | ConfigurationException
        | RuntimeException e) {
      LoggingUtils.logException(LOGGER, "Workflow process(es) could not be started", e);
      result.recordFatalError("Workflow process(es) could not be started: " + e, e);
      return HookOperationMode.ERROR;
      // todo rollback - at least close open tasks, maybe stop workflow process instances
    }
  }
Ejemplo n.º 18
0
  private void ownerChangePerformed(AjaxRequestTarget target, UserType user) {
    AccountOwnerChangeDto dto = ownerChangeModel.getObject();
    OperationResult result = new OperationResult(OPERATION_CHANGE_OWNER);
    try {
      Task task = createSimpleTask(OPERATION_CHANGE_OWNER);
      if (StringUtils.isNotEmpty(dto.getOldOwnerOid())) {
        ObjectDelta delta = new ObjectDelta(UserType.class, ChangeType.MODIFY, getPrismContext());
        delta.setOid(dto.getOldOwnerOid());
        PrismReferenceValue refValue = new PrismReferenceValue(dto.getAccountOid());
        refValue.setTargetType(dto.getAccountType());
        delta.addModification(
            ReferenceDelta.createModificationDelete(
                UserType.class, UserType.F_LINK_REF, getPrismContext(), refValue));
        getModelService()
            .executeChanges(WebMiscUtil.createDeltaCollection(delta), null, task, result);
      }

      if (user != null) {
        ObjectDelta delta = new ObjectDelta(UserType.class, ChangeType.MODIFY, getPrismContext());
        delta.setOid(user.getOid());
        PrismReferenceValue refValue = new PrismReferenceValue(dto.getAccountOid());
        refValue.setTargetType(dto.getAccountType());
        delta.addModification(
            ReferenceDelta.createModificationAdd(
                UserType.class, UserType.F_LINK_REF, getPrismContext(), refValue));

        getModelService()
            .executeChanges(WebMiscUtil.createDeltaCollection(delta), null, task, result);
      }
      result.recomputeStatus();
    } catch (Exception ex) {
      result.recordFatalError("Couldn't submit user.", ex);
      LoggingUtils.logException(LOGGER, "Couldn't submit user", ex);
    }

    showResult(result);
    target.add(getFeedbackPanel());
  }
Ejemplo n.º 19
0
  public List<SecurityQuestionAnswerDTO> createUsersSecurityQuestionsList(
      PrismObject<UserType> user) {
    LOGGER.debug("Security Questions Loading for user: "******"User SecurityQuestion ANswer List is Not null");
        List<SecurityQuestionAnswerDTO> secQuestAnswListDTO =
            new ArrayList<SecurityQuestionAnswerDTO>();
        for (Iterator iterator = secQuestAnsList.iterator(); iterator.hasNext(); ) {
          SecurityQuestionAnswerType securityQuestionAnswerType =
              (SecurityQuestionAnswerType) iterator.next();

          Protector protector = getPrismContext().getDefaultProtector();
          String decoded = "";
          if (securityQuestionAnswerType.getQuestionAnswer().getEncryptedDataType() != null) {
            try {
              decoded = protector.decryptString(securityQuestionAnswerType.getQuestionAnswer());

            } catch (EncryptionException e) {
              LoggingUtils.logException(LOGGER, "Couldn't decrypt user answer", e);
            }
          }
          // LOGGER.debug("SecAnswerIdentifier:"+securityQuestionAnswerType.getQuestionIdentifier());
          secQuestAnswListDTO.add(
              new SecurityQuestionAnswerDTO(
                  securityQuestionAnswerType.getQuestionIdentifier(), decoded));
        }

        return secQuestAnswListDTO;
      }
    }
    return null;
  }
  private List<ObjectReferenceType> createResourceList() {
    resourceMap.clear();
    OperationResult result = new OperationResult(OPERATION_LOAD_RESOURCES);
    Task task = getPageBase().createSimpleTask(OPERATION_LOAD_RESOURCES);
    List<PrismObject<ResourceType>> resources = null;
    List<ObjectReferenceType> references = new ArrayList<>();

    try {
      resources =
          getPageBase()
              .getModelService()
              .searchObjects(ResourceType.class, new ObjectQuery(), null, task, result);
      result.recomputeStatus();
    } catch (Exception e) {
      result.recordFatalError("Couldn't get resource list.", e);
      LoggingUtils.logException(LOGGER, "Couldn't get resource list.", e);
    }

    // TODO - show error somehow
    // if(!result.isSuccess()){
    //    getPageBase().showResult(result);
    // }

    if (resources != null) {
      ObjectReferenceType ref;
      for (PrismObject<ResourceType> r : resources) {
        resourceMap.put(r.getOid(), WebMiscUtil.getName(r));
        ref = new ObjectReferenceType();
        ref.setType(ResourceType.COMPLEX_TYPE);
        ref.setOid(r.getOid());
        references.add(ref);
      }
    }

    return references;
  }
  @Override
  public TaskRunResult run(Task task) {

    OperationResult result = task.getResult().createSubresult(DOT_CLASS + "run");
    TaskRunResult runResult = new TaskRunResult();

    LensContextType contextType = task.getModelOperationContext();
    if (contextType == null) {
      LOGGER.trace("No model context found, skipping the model operation execution.");
      if (result.isUnknown()) {
        result.computeStatus();
      }
      runResult.setRunResultStatus(TaskRunResult.TaskRunResultStatus.FINISHED);
    } else {
      LensContext context = null;
      try {
        context =
            LensContext.fromLensContextType(contextType, prismContext, provisioningService, result);
      } catch (SchemaException e) {
        throw new SystemException(
            "Cannot recover model context from task " + task + " due to schema exception", e);
      } catch (ObjectNotFoundException e) {
        throw new SystemException("Cannot recover model context from task " + task, e);
      } catch (CommunicationException e) {
        throw new SystemException(
            "Cannot recover model context from task " + task, e); // todo wait and retry
      } catch (ConfigurationException e) {
        throw new SystemException("Cannot recover model context from task " + task, e);
      }

      if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Context to be executed = {}", context.debugDump());
      }

      try {
        // here we brutally remove all the projection contexts -- because if we are continuing after
        // rejection of a role/resource assignment
        // that resulted in such projection contexts, we DO NOT want them to appear in the context
        // any more
        context.rot();
        Iterator<LensProjectionContext> projectionIterator =
            context.getProjectionContextsIterator();
        while (projectionIterator.hasNext()) {
          LensProjectionContext projectionContext = projectionIterator.next();
          if (projectionContext.getPrimaryDelta() != null
              && !projectionContext.getPrimaryDelta().isEmpty()) {
            continue; // don't remove client requested actions!
          }
          if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(
                "Removing projection context {}", projectionContext.getHumanReadableName());
          }
          projectionIterator.remove();
        }
        if (task.getChannel() == null) {
          task.setChannel(context.getChannel());
        }
        clockwork.run(context, task, result);

        task.setModelOperationContext(context.toLensContextType());
        task.savePendingModifications(result);

        if (result.isUnknown()) {
          result.computeStatus();
        }
        runResult.setRunResultStatus(TaskRunResult.TaskRunResultStatus.FINISHED);
      } catch (Exception e) { // too many various exceptions; will be fixed with java7 :)
        String message = "An exception occurred within model operation, in task " + task;
        LoggingUtils.logException(LOGGER, message, e);
        result.recordPartialError(message, e);
        // TODO: here we do not know whether the error is temporary or permanent (in the future we
        // could discriminate on the basis of particular exception caught)
        runResult.setRunResultStatus(TaskRunResult.TaskRunResultStatus.TEMPORARY_ERROR);
      }
    }

    task.getResult().recomputeStatus();
    runResult.setOperationResult(task.getResult());
    return runResult;
  }
Ejemplo n.º 22
0
  private List<ItemWrapper> createProperties(PageBase pageBase) {
    result = new OperationResult(CREATE_PROPERTIES);

    List<ItemWrapper> properties = new ArrayList<ItemWrapper>();

    PrismContainerDefinition definition = null;
    PrismObject parent = getObject().getObject();
    Class clazz = parent.getCompileTimeClass();
    if (ShadowType.class.isAssignableFrom(clazz)) {
      QName name = containerDefinition.getName();

      if (ShadowType.F_ATTRIBUTES.equals(name)) {
        try {
          definition = objectWrapper.getRefinedAttributeDefinition();

          if (definition == null) {
            PrismReference resourceRef = parent.findReference(ShadowType.F_RESOURCE_REF);
            PrismObject<ResourceType> resource = resourceRef.getValue().getObject();

            definition =
                pageBase
                    .getModelInteractionService()
                    .getEditObjectClassDefinition(
                        (PrismObject<ShadowType>) objectWrapper.getObject(),
                        resource,
                        AuthorizationPhaseType.REQUEST)
                    .toResourceAttributeContainerDefinition();

            if (LOGGER.isTraceEnabled()) {
              LOGGER.trace("Refined account def:\n{}", definition.debugDump());
            }
          }
        } catch (Exception ex) {
          LoggingUtils.logException(
              LOGGER, "Couldn't load definitions from refined schema for shadow", ex);
          result.recordFatalError(
              "Couldn't load definitions from refined schema for shadow, reason: "
                  + ex.getMessage(),
              ex);

          return properties;
        }
      } else {
        definition = containerDefinition;
      }
    } else if (ResourceType.class.isAssignableFrom(clazz)) {
      if (containerDefinition != null) {
        definition = containerDefinition;
      } else {
        definition = container.getDefinition();
      }
    } else {
      definition = containerDefinition;
    }

    if (definition == null) {
      LOGGER.error(
          "Couldn't get property list from null definition {}",
          new Object[] {container.getElementName()});
      return properties;
    }

    // assignments are treated in a special way -- we display names of
    // org.units and roles
    // (but only if ObjectWrapper.isShowAssignments() is true; otherwise
    // they are filtered out by ObjectWrapper)
    if (container.getCompileTimeClass() != null
        && AssignmentType.class.isAssignableFrom(container.getCompileTimeClass())) {

      for (Object o : container.getValues()) {
        PrismContainerValue<AssignmentType> pcv = (PrismContainerValue<AssignmentType>) o;

        AssignmentType assignmentType = pcv.asContainerable();

        if (assignmentType.getTargetRef() == null) {
          continue;
        }

        // hack... we want to create a definition for Name
        // PrismPropertyDefinition def = ((PrismContainerValue)
        // pcv.getContainer().getParent()).getContainer().findProperty(ObjectType.F_NAME).getDefinition();
        PrismPropertyDefinition def =
            new PrismPropertyDefinition(
                ObjectType.F_NAME, DOMUtil.XSD_STRING, pcv.getPrismContext());

        if (OrgType.COMPLEX_TYPE.equals(assignmentType.getTargetRef().getType())) {
          def.setDisplayName("Org.Unit");
          def.setDisplayOrder(100);
        } else if (RoleType.COMPLEX_TYPE.equals(assignmentType.getTargetRef().getType())) {
          def.setDisplayName("Role");
          def.setDisplayOrder(200);
        } else {
          continue;
        }

        PrismProperty<Object> temp = def.instantiate();

        String value = formatAssignmentBrief(assignmentType);

        temp.setValue(new PrismPropertyValue<Object>(value));
        // TODO: do this.isReadOnly() - is that OK? (originally it was the default behavior for all
        // cases)
        properties.add(new PropertyWrapper(this, temp, this.isReadonly(), ValueStatus.NOT_CHANGED));
      }

    } else if (isShadowAssociation()) {
      PrismContext prismContext = objectWrapper.getObject().getPrismContext();
      Map<QName, PrismContainer<ShadowAssociationType>> assocMap = new HashMap<>();
      if (objectWrapper.getAssociations() != null) {
        for (PrismContainerValue<ShadowAssociationType> cval : objectWrapper.getAssociations()) {
          ShadowAssociationType associationType = cval.asContainerable();
          QName assocName = associationType.getName();
          PrismContainer<ShadowAssociationType> fractionalContainer = assocMap.get(assocName);
          if (fractionalContainer == null) {
            fractionalContainer =
                new PrismContainer<>(
                    ShadowType.F_ASSOCIATION, ShadowAssociationType.class, cval.getPrismContext());
            fractionalContainer.setDefinition(cval.getParent().getDefinition());
            // HACK: set the name of the association as the element name so wrapper.getName() will
            // return correct data.
            fractionalContainer.setElementName(assocName);
            assocMap.put(assocName, fractionalContainer);
          }
          try {
            fractionalContainer.add(cval.clone());
          } catch (SchemaException e) {
            // Should not happen
            throw new SystemException("Unexpected error: " + e.getMessage(), e);
          }
        }
      }

      PrismReference resourceRef = parent.findReference(ShadowType.F_RESOURCE_REF);
      PrismObject<ResourceType> resource = resourceRef.getValue().getObject();

      // HACK. The revive should not be here. Revive is no good. The next use of the resource will
      // cause parsing of resource schema. We need some centralized place to maintain live cached
      // copies
      // of resources.
      try {
        resource.revive(prismContext);
      } catch (SchemaException e) {
        throw new SystemException(e.getMessage(), e);
      }
      RefinedResourceSchema refinedSchema;
      CompositeRefinedObjectClassDefinition rOcDef;
      try {
        refinedSchema = RefinedResourceSchema.getRefinedSchema(resource);
        rOcDef = refinedSchema.determineCompositeObjectClassDefinition(parent);
      } catch (SchemaException e) {
        throw new SystemException(e.getMessage(), e);
      }
      // Make sure even empty associations have their wrappers so they can be displayed and edited
      for (RefinedAssociationDefinition assocDef : rOcDef.getAssociations()) {
        QName name = assocDef.getName();
        if (!assocMap.containsKey(name)) {
          PrismContainer<ShadowAssociationType> fractionalContainer =
              new PrismContainer<>(
                  ShadowType.F_ASSOCIATION, ShadowAssociationType.class, prismContext);
          fractionalContainer.setDefinition(getItemDefinition());
          // HACK: set the name of the association as the element name so wrapper.getName() will
          // return correct data.
          fractionalContainer.setElementName(name);
          assocMap.put(name, fractionalContainer);
        }
      }

      for (Entry<QName, PrismContainer<ShadowAssociationType>> assocEntry : assocMap.entrySet()) {
        // HACK HACK HACK, the container wrapper should not parse itself. This code should not be
        // here.
        AssociationWrapper assocWrapper =
            new AssociationWrapper(
                this, assocEntry.getValue(), this.isReadonly(), ValueStatus.NOT_CHANGED);
        properties.add(assocWrapper);
      }

    } else { // if not an assignment

      if ((container.getValues().size() == 1 || container.getValues().isEmpty())
          && (containerDefinition == null || containerDefinition.isSingleValue())) {

        // there's no point in showing properties for non-single-valued
        // parent containers,
        // so we continue only if the parent is single-valued

        Collection<ItemDefinition> propertyDefinitions = definition.getDefinitions();
        for (ItemDefinition itemDef : propertyDefinitions) {
          if (itemDef instanceof PrismPropertyDefinition) {

            PrismPropertyDefinition def = (PrismPropertyDefinition) itemDef;
            if (def.isIgnored() || skipProperty(def)) {
              continue;
            }
            if (!showInheritedObjectAttributes
                && INHERITED_OBJECT_ATTRIBUTES.contains(def.getName())) {
              continue;
            }

            // capability handling for activation properties
            if (isShadowActivation() && !hasCapability(def)) {
              continue;
            }

            if (isShadowAssociation()) {
              continue;
            }

            PrismProperty property = container.findProperty(def.getName());
            boolean propertyIsReadOnly;
            // decision is based on parent object status, not this
            // container's one (because container can be added also
            // to an existing object)
            if (objectWrapper.getStatus() == ContainerStatus.MODIFYING) {

              propertyIsReadOnly = !def.canModify();
            } else {
              propertyIsReadOnly = !def.canAdd();
            }
            if (property == null) {
              properties.add(
                  new PropertyWrapper(
                      this, def.instantiate(), propertyIsReadOnly, ValueStatus.ADDED));
            } else {
              properties.add(
                  new PropertyWrapper(this, property, propertyIsReadOnly, ValueStatus.NOT_CHANGED));
            }
          } else if (itemDef instanceof PrismReferenceDefinition) {
            PrismReferenceDefinition def = (PrismReferenceDefinition) itemDef;

            if (INHERITED_OBJECT_ATTRIBUTES.contains(def.getName())) {
              continue;
            }

            PrismReference reference = container.findReference(def.getName());
            boolean propertyIsReadOnly;
            // decision is based on parent object status, not this
            // container's one (because container can be added also
            // to an existing object)
            if (objectWrapper.getStatus() == ContainerStatus.MODIFYING) {

              propertyIsReadOnly = !def.canModify();
            } else {
              propertyIsReadOnly = !def.canAdd();
            }
            if (reference == null) {
              properties.add(
                  new ReferenceWrapper(
                      this, def.instantiate(), propertyIsReadOnly, ValueStatus.ADDED));
            } else {
              properties.add(
                  new ReferenceWrapper(
                      this, reference, propertyIsReadOnly, ValueStatus.NOT_CHANGED));
            }
          }
        }
      }
    }

    Collections.sort(properties, new ItemWrapperComparator());

    result.recomputeStatus();

    return properties;
  }