@Override
 public String getIdentifier() {
   String id = getGroupId() + ":" + getArtifactId() + ":" + getVersion();
   if (!StringUtils.isEmpty(kbaseName)) {
     id = id.concat(":" + kbaseName);
   }
   if (!StringUtils.isEmpty(ksessionName)) {
     id = id.concat(":" + ksessionName);
   }
   return id;
 }
Beispiel #2
0
  protected void populateRHS(
      Rule rule,
      PMML pmmlDocument,
      Scorecard scorecard,
      Characteristic c,
      Attribute scoreAttribute,
      int position) {
    Consequence consequence = new Consequence();
    StringBuilder stringBuilder = new StringBuilder();
    String objectClass = scorecard.getModelName().replaceAll(" ", "");

    String setter = "insertLogical(new PartialScore(\"";
    String field = ScorecardPMMLUtils.extractFieldNameFromCharacteristic(c);

    stringBuilder
        .append(setter)
        .append(objectClass)
        .append("\",\"")
        .append(field)
        .append("\",")
        .append(scoreAttribute.getPartialScore());
    if (scorecard.isUseReasonCodes()) {
      String reasonCode = scoreAttribute.getReasonCode();
      if (reasonCode == null || StringUtils.isEmpty(reasonCode)) {
        reasonCode = c.getReasonCode();
      }
      stringBuilder.append(",\"").append(reasonCode).append("\", ").append(position);
    }
    stringBuilder.append("));");
    consequence.setSnippet(stringBuilder.toString());
    rule.addConsequence(consequence);
  }
Beispiel #3
0
 public File getFile(String name) {
   if (!StringUtils.isEmpty(path)) {
     return mfs.getFile(path + "/" + name);
   } else {
     return mfs.getFile(name);
   }
 }
Beispiel #4
0
  public Folder getParent() {
    if (pFolder == null) {
      String p = trimLeadingAndTrailing(path);

      if (p.indexOf('/') == -1) {
        pFolder = new MemoryFolder(mfs, "");
      } else {
        String[] elements = p.split("/");

        String newPath = "";
        boolean first = true;
        for (int i = 0; i < elements.length - 1; i++) {
          if (!StringUtils.isEmpty(elements[i])) {
            if (!first) {
              newPath = newPath + "/";
            }
            newPath = newPath + elements[i];
            first = false;
          }
        }
        pFolder = new MemoryFolder(mfs, newPath);
      }
    }

    return pFolder;
  }
Beispiel #5
0
 public Folder getFolder(String name) {
   if (!StringUtils.isEmpty(path)) {
     return mfs.getFolder(path + "/" + name);
   } else {
     return mfs.getFolder(name);
   }
 }
 private static String getPomPropertiesFromFileSystem(String rootPath) {
   Reader reader = null;
   try {
     File file = KieBuilderImpl.findPomProperties(new File(rootPath));
     if (file == null) {
       log.warn("Unable to find pom.properties in " + rootPath);
       return null;
     }
     reader = new InputStreamReader(new FileInputStream(file), IoUtils.UTF8_CHARSET);
     log.debug("Found and used pom.properties " + file);
     return StringUtils.toString(reader);
   } catch (Exception e) {
     log.warn(
         "Unable to load pom.properties tried recursing down from "
             + rootPath
             + "\n"
             + e.getMessage());
   } finally {
     if (reader != null) {
       try {
         reader.close();
       } catch (IOException e) {
         log.error("Error when closing InputStream to " + rootPath + "\n" + e.getMessage());
       }
     }
   }
   return null;
 }
Beispiel #7
0
  public RuleAgendaItem createRuleAgendaItem(
      final int salience, final PathMemory rs, final TerminalNode rtn) {
    String agendaGroupName = rtn.getRule().getAgendaGroup();
    String ruleFlowGroupName = rtn.getRule().getRuleFlowGroup();

    RuleAgendaItem lazyAgendaItem;
    if (!StringUtils.isEmpty(ruleFlowGroupName)) {
      lazyAgendaItem =
          new RuleAgendaItem(
              activationCounter++,
              null,
              salience,
              null,
              rs,
              rtn,
              isDeclarativeAgenda(),
              (InternalAgendaGroup) getAgendaGroup(ruleFlowGroupName));
    } else {
      lazyAgendaItem =
          new RuleAgendaItem(
              activationCounter++,
              null,
              salience,
              null,
              rs,
              rtn,
              isDeclarativeAgenda(),
              (InternalAgendaGroup) getRuleFlowGroup(agendaGroupName));
    }

    return lazyAgendaItem;
  }
Beispiel #8
0
  public String getProperty(String name) {
    name = name.trim();
    if (StringUtils.isEmpty(name)) {
      return null;
    }

    if (name.equals(SequentialAgendaOption.PROPERTY_NAME)) {
      return getSequentialAgenda().toExternalForm();
    } else if (name.equals(SequentialOption.PROPERTY_NAME)) {
      return Boolean.toString(isSequential());
    } else if (name.equals(RemoveIdentitiesOption.PROPERTY_NAME)) {
      return Boolean.toString(isRemoveIdentities());
    } else if (name.equals(ShareAlphaNodesOption.PROPERTY_NAME)) {
      return Boolean.toString(isShareAlphaNodes());
    } else if (name.equals(ShareBetaNodesOption.PROPERTY_NAME)) {
      return Boolean.toString(isShareBetaNodes());
    } else if (name.equals(PermGenThresholdOption.PROPERTY_NAME)) {
      return Integer.toString(getPermGenThreshold());
    } else if (name.equals(AlphaThresholdOption.PROPERTY_NAME)) {
      return Integer.toString(getAlphaNodeHashingThreshold());
    } else if (name.equals(CompositeKeyDepthOption.PROPERTY_NAME)) {
      return Integer.toString(getCompositeKeyDepth());
    } else if (name.equals(IndexLeftBetaMemoryOption.PROPERTY_NAME)) {
      return Boolean.toString(isIndexLeftBetaMemory());
    } else if (name.equals(IndexRightBetaMemoryOption.PROPERTY_NAME)) {
      return Boolean.toString(isIndexRightBetaMemory());
    } else if (name.equals(IndexPrecedenceOption.PROPERTY_NAME)) {
      return getIndexPrecedenceOption().getValue();
    } else if (name.equals(EqualityBehaviorOption.PROPERTY_NAME)) {
      return getAssertBehaviour().toExternalForm();
    } else if (name.equals("drools.executorService")) {
      return getExecutorService();
    } else if (name.equals(ConsequenceExceptionHandlerOption.PROPERTY_NAME)) {
      return getConsequenceExceptionHandler();
    } else if (name.equals("drools.ruleBaseUpdateHandler")) {
      return getRuleBaseUpdateHandler();
    } else if (name.equals("drools.conflictResolver")) {
      return getConflictResolver().getClass().getName();
    } else if (name.equals("drools.advancedProcessRuleIntegration")) {
      return Boolean.toString(isAdvancedProcessRuleIntegration());
    } else if (name.equals(MultithreadEvaluationOption.PROPERTY_NAME)) {
      return Boolean.toString(isMultithreadEvaluation());
    } else if (name.equals(MaxThreadsOption.PROPERTY_NAME)) {
      return Integer.toString(getMaxThreads());
    } else if (name.equals(EventProcessingOption.PROPERTY_NAME)) {
      return getEventProcessingMode().getMode();
    } else if (name.equals(MBeansOption.PROPERTY_NAME)) {
      return isMBeansEnabled() ? "enabled" : "disabled";
    } else if (name.equals(ClassLoaderCacheOption.PROPERTY_NAME)) {
      return Boolean.toString(isClassLoaderCacheEnabled());
    } else if (name.equals(PhreakOption.PROPERTY_NAME)) {
      return Boolean.toString(isPhreakEnabled());
    }

    return null;
  }
 private void initPackageRegistries(Collection<CompositePackageDescr> packages) {
   for (CompositePackageDescr packageDescr : packages) {
     if (kBuilder.getPackageRegistry(packageDescr.getName()) == null) {
       if (StringUtils.isEmpty(packageDescr.getName())) {
         packageDescr.setName(kBuilder.getBuilderConfiguration().getDefaultPackageName());
       }
       kBuilder.createPackageRegistry(packageDescr);
     }
   }
 }
 protected void addGroupFromCallbackOperation(String groupId) {
   try {
     boolean groupExists = pm.find(GroupImpl.class, groupId) != null;
     if (!StringUtils.isEmpty(groupId) && !groupExists) {
       GroupImpl group = new GroupImpl(groupId);
       pm.persist(group);
     }
   } catch (Throwable t) {
     // logger.log(Level.WARNING, "UserGroupCallback has not been registered.");
   }
 }
 protected void addUserFromCallbackOperation(String userId) {
   try {
     boolean userExists = pm.find(UserImpl.class, userId) != null;
     if (!StringUtils.isEmpty(userId) && !userExists) {
       UserImpl user = new UserImpl(userId);
       pm.persist(user);
     }
   } catch (Throwable t) {
     // logger.log(Level.SEVERE, "Unable to add user " + userId);
   }
 }
Beispiel #12
0
 public void visitExprConstraintDescr(final ExprConstraintDescr descr) {
   this.template =
       "<expr>"
           + XmlDumper.eol
           + StringUtils.escapeXmlString(descr.getExpression())
           + XmlDumper.eol
           + "</expr>";
   //        if ( !descr.getRestrictions().isEmpty() ) {
   //            this.template = "<field-constraint field-name=\"" + descr.getFieldName() + "\"> "
   // + XmlDumper.eol + processFieldConstraint( descr.getRestrictions() ) + XmlDumper.eol +
   // "</field-constraint>";
   //        }
 }
Beispiel #13
0
  /**
   * 将规则注册入规则容器中 <功能详细描述>
   *
   * @param spRule [参数说明]
   * @return void [返回类型说明]
   * @exception throws [异常类型] [异常说明]
   * @see [类、类#方法、类#成员]
   */
  @Transactional
  public Rule registeRule(SimplePersistenceRule spRule) {
    if (spRule == null
        || StringUtils.isEmpty(spRule.getRule())
        || StringUtils.isEmpty(spRule.getServiceType())
        || spRule.getRuleType() == null) {
      throw new RuleRegisteException("spRule or rule or serviceType or ruleType is null");
    }

    RuleRegister<? extends Rule> ruleRegisterTemp = ruleRegisterMap.get(spRule.getRuleType());
    if (ruleRegisterTemp == null) {
      throw new RuleRegisteException(
          "ruleType:{} RuleRegister not exist.", spRule.getRuleType().toString());
    }

    // 调用对应注册器方法,将规则注册入容器中
    final Rule realRule = ruleRegisterTemp.registe(spRule);
    if (realRule != null) {
      if (TransactionSynchronizationManager.isSynchronizationActive()) {
        // 如果在事务逻辑中执行
        TransactionSynchronizationManager.registerSynchronization(
            new TransactionSynchronizationAdapter() {
              @Override
              public void afterCommit() {
                putInCache(realRule, true);
              }
            });
      } else {
        // 如果在非事务中执行
        putInCache(realRule, true);
      }
    } else {
      throw new RuleRegisteException(
          "ruleType:{} RuleRegister call registe return null realRule.",
          spRule.getRuleType().toString());
    }
    return realRule;
  }
  public boolean isDirectory() {
    try {
      URL url = getURL();

      if (!"file".equals(url.getProtocol())) {
        return false;
      }

      File file = new File(StringUtils.toURI(url.toString()).getSchemeSpecificPart());

      return file.isDirectory();
    } catch (Exception e) {
      return false;
    }
  }
Beispiel #15
0
 public void activateRuleFlowGroup(
     final InternalRuleFlowGroup group, long processInstanceId, String nodeInstanceId) {
   ((EventSupport) this.workingMemory)
       .getAgendaEventSupport()
       .fireBeforeRuleFlowGroupActivated(group, this.workingMemory);
   group.setActive(true);
   group.hasRuleFlowListener(true);
   if (!StringUtils.isEmpty(nodeInstanceId)) {
     group.addNodeInstance(processInstanceId, nodeInstanceId);
     group.setActive(true);
   }
   setFocus((InternalAgendaGroup) group);
   ((EventSupport) this.workingMemory)
       .getAgendaEventSupport()
       .fireAfterRuleFlowGroupActivated(group, this.workingMemory);
 }
  public Object start(String uri, String localName, Attributes attrs, ExtensibleXmlParser parser)
      throws SAXException {
    parser.startElementBuilder(localName, attrs);

    String type = attrs.getValue("input-type");
    String worksheetName = attrs.getValue("worksheet-name");

    emptyAttributeCheck(localName, "input-type", type, parser);

    DecisionTableConfiguration dtConf = new DecisionTableConfigurationImpl();
    dtConf.setInputType(DecisionTableInputType.valueOf(type));
    if (!StringUtils.isEmpty(worksheetName)) {
      dtConf.setWorksheetName(worksheetName);
    }

    return dtConf;
  }
 public void process(Exchange exchange) throws Exception {
   InputStream is = (InputStream) exchange.getIn().getBody();
   // Bad Hack - Need to remote it and fix it in Camel (if it's a camel problem)
   // I need to copy the results here because I loose them at the end of the method
   String results = StringUtils.toString(is);
   if (is != null) {
     SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
     SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();
     QName payloadName = new QName("http://soap.jax.drools.org/", "executeResponse", "ns1");
     QName responseName = new QName("http://soap.jax.drools.org/", "return", "ns1");
     SOAPBodyElement payload = body.addBodyElement(payloadName);
     SOAPElement response = payload.addChildElement(responseName);
     // Bad Hack - Need to remote it and fix it in Camel (if it's a camel problem)
     // response.addTextNode( StringUtils.toString( is ) );
     response.addTextNode(results);
     exchange.getOut().setBody(soapMessage);
   }
 }
  @Override
  public void saveOrUpdate(Ida[] idas) {
    boolean editFlag = true;
    for (Ida ida : idas) {
      if (StringUtils.isEmpty(ida.getHeadId())) {
        ida.setHeadId(null);
      }
      idaDAOImpl.save(ida);
      if (editFlag) {

        String interfaceId = ida.getInterfaceId();
        if (org.apache.commons.lang.StringUtils.isNotEmpty(interfaceId)) {
          Interface inter = interfaceDAO.findUniqueBy("interfaceId", interfaceId);
          // 更新版本,只更新一次
          versionServiceImpl.editVersion(inter.getVersionId());
          editFlag = false;
        }
      }
    }
  }
  public Collection<Resource> listResources() {
    try {
      URL url = getURL();

      if ("file".equals(url.getProtocol())) {
        File dir = new File(StringUtils.toURI(url.toString()).getSchemeSpecificPart());

        List<Resource> resources = new ArrayList<Resource>();

        for (File file : dir.listFiles()) {
          resources.add(new FileSystemResource(file));
        }

        return resources;
      }
    } catch (Exception e) {
      // swollow as we'll throw an exception anyway
    }

    throw new RuntimeException("This Resource cannot be listed, or is not a directory");
  }
  private static String getPomPropertiesFromZipFile(String rootPath) {
    File actualZipFile = new File(rootPath);
    if (!actualZipFile.exists()) {
      log.error(
          "Unable to load pom.properties from"
              + rootPath
              + " as jarPath cannot be found\n"
              + rootPath);
      return null;
    }

    ZipFile zipFile = null;

    try {
      zipFile = new ZipFile(actualZipFile);

      String file = KieBuilderImpl.findPomProperties(zipFile);
      if (file == null) {
        log.warn("Unable to find pom.properties in " + rootPath);
        return null;
      }
      ZipEntry zipEntry = zipFile.getEntry(file);

      String pomProps =
          StringUtils.readFileAsString(
              new InputStreamReader(zipFile.getInputStream(zipEntry), IoUtils.UTF8_CHARSET));
      log.debug("Found and used pom.properties " + file);
      return pomProps;
    } catch (Exception e) {
      log.error("Unable to load pom.properties from " + rootPath + "\n" + e.getMessage());
    } finally {
      try {
        zipFile.close();
      } catch (IOException e) {
        log.error("Error when closing InputStream to " + rootPath + "\n" + e.getMessage());
      }
    }
    return null;
  }
  @Override
  public OrganizationalEntity persistOrgEntity(OrganizationalEntity orgEntity) {
    check();

    if (!StringUtils.isEmpty(orgEntity.getId())) {
      try {
        this.em.persist(orgEntity);
        if (this.pessimisticLocking) {
          return this.em.find(
              OrganizationalEntityImpl.class,
              orgEntity.getId(),
              LockModeType.PESSIMISTIC_FORCE_INCREMENT);
        }
      } catch (EntityExistsException e) {
        throw new RuntimeException(
            "Organizational entity already exists with "
                + orgEntity
                + " id, please check that there is no group and user with same id");
      }
    }

    return orgEntity;
  }
    public void process(Exchange exchange) throws Exception {
      // Bad Hack - Need to remote it and fix it in Camel (if it's a camel problem)
      // I need to copy the body of the exachange because for some reason
      // the getContext().getEndpoint() erase the content/or loose the reference
      String body = exchange.getIn().getBody(String.class);
      if (dep == null) {

        this.dep = exchange.getContext().getEndpoint(this.droolsUri, DroolsEndpoint.class);
      }

      if (dep == null) {
        throw new RuntimeException("Could not find DroolsEndPoint for uri=" + this.droolsUri);
      }

      ClassLoader originalClassLoader = null;
      try {
        originalClassLoader = Thread.currentThread().getContextClassLoader();

        CommandExecutor exec = dep.executor;
        if (exec == null) {
          String lookup = exchange.getIn().getHeader(DroolsComponent.DROOLS_LOOKUP, String.class);
          if (StringUtils.isEmpty(lookup)) {
            // Bad Hack - Need to remote it and fix it in Camel (if it's a camel problem)
            lookup = dep.getLookup(body);
            // lookup = dep.getLookup( exchange.getIn().getBody( String.class ) );
          }

          if (StringUtils.isEmpty(lookup)) {
            throw new RuntimeException(
                "No Executor defined and no lookup information available for uri "
                    + this.dep.getEndpointUri());
          }
          exec = dep.getCommandExecutor(lookup);
        }

        if (exec == null) {
          throw new RuntimeException(
              "CommandExecutor cannot be found for uri " + this.dep.getEndpointUri());
        }
        ClassLoader localClassLoader = dep.getClassLoader(exec);
        if (localClassLoader == null) {
          throw new RuntimeException(
              "CommandExecutor Classloader cannot be null for uri " + this.dep.getEndpointUri());
        }

        // Set the classloader to the one used by the CommandExecutor
        Thread.currentThread().setContextClassLoader(localClassLoader);
        ExecutionNodePipelineContextImpl context =
            new ExecutionNodePipelineContextImpl(dep.node, localClassLoader);
        context.setCommandExecutor(exec);

        exchange.setProperty("drools-context", context);
        // Bad Hack - Need to remote it and fix it in Camel (if it's a camel problem)
        // I need to re set the Body because the exchange loose the content at
        // the begining of the method
        exchange.getIn().setBody(new ByteArrayInputStream(body.getBytes("UTF-8")));

        boolean soap = false;
        if (!augmented && exchange.getFromEndpoint() instanceof CxfSpringEndpoint) {
          new PreCxfTransportSoapProcessor().process(exchange);
          soap = true;
        }
        processor.process(exchange);
        if (soap) {
          new PostCxfTransportSoapProcessor().process(exchange);
        }
      } finally {
        Thread.currentThread().setContextClassLoader(originalClassLoader);
      }
    }
  @Override
  public void deploy(DeploymentUnit unit) {
    try {
      super.deploy(unit);
      if (!(unit instanceof KModuleDeploymentUnit)) {
        throw new IllegalArgumentException(
            "Invalid deployment unit provided - " + unit.getClass().getName());
      }
      KModuleDeploymentUnit kmoduleUnit = (KModuleDeploymentUnit) unit;
      DeployedUnitImpl deployedUnit = new DeployedUnitImpl(unit);

      // Create the release id
      KieContainer kieContainer = kmoduleUnit.getKieContainer();
      ReleaseId releaseId = null;
      if (kieContainer == null) {
        KieServices ks = KieServices.Factory.get();

        releaseId =
            ks.newReleaseId(
                kmoduleUnit.getGroupId(), kmoduleUnit.getArtifactId(), kmoduleUnit.getVersion());

        MavenRepository repository = getMavenRepository();
        repository.resolveArtifact(releaseId.toExternalForm());

        kieContainer = ks.newKieContainer(releaseId);

        kmoduleUnit.setKieContainer(kieContainer);
      }
      releaseId = kieContainer.getReleaseId();

      // retrieve the kbase name
      String kbaseName = kmoduleUnit.getKbaseName();
      if (StringUtils.isEmpty(kbaseName)) {
        KieBaseModel defaultKBaseModel =
            ((KieContainerImpl) kieContainer).getKieProject().getDefaultKieBaseModel();
        if (defaultKBaseModel != null) {
          kbaseName = defaultKBaseModel.getName();
        } else {
          kbaseName = DEFAULT_KBASE_NAME;
        }
      }
      InternalKieModule module =
          (InternalKieModule) ((KieContainerImpl) kieContainer).getKieModuleForKBase(kbaseName);
      if (module == null) {
        throw new IllegalStateException(
            "Cannot find kbase, either it does not exist or there are multiple default kbases in kmodule.xml");
      }

      KieBase kbase = kieContainer.getKieBase(kbaseName);
      Map<String, ProcessDescriptor> processDescriptors = new HashMap<String, ProcessDescriptor>();
      for (org.kie.api.definition.process.Process process : kbase.getProcesses()) {
        processDescriptors.put(
            process.getId(), (ProcessDescriptor) process.getMetaData().get("ProcessDescriptor"));
      }

      // TODO: add forms data?
      Collection<String> files = module.getFileNames();

      processResources(
          module, files, kieContainer, kmoduleUnit, deployedUnit, releaseId, processDescriptors);

      // process the files in the deployment
      if (module.getKieDependencies() != null) {
        Collection<InternalKieModule> dependencies = module.getKieDependencies().values();
        for (InternalKieModule depModule : dependencies) {

          logger.debug("Processing dependency module " + depModule.getReleaseId());
          files = depModule.getFileNames();

          processResources(
              depModule,
              files,
              kieContainer,
              kmoduleUnit,
              deployedUnit,
              depModule.getReleaseId(),
              processDescriptors);
        }
      }
      Collection<ReleaseId> dependencies =
          module.getJarDependencies(new DependencyFilter.ExcludeScopeFilter("test", "provided"));

      // process deployment dependencies
      if (dependencies != null && !dependencies.isEmpty()) {
        // Classes 2: classes added from project and dependencies added
        processClassloader(kieContainer, deployedUnit);
      }

      AuditEventBuilder auditLoggerBuilder =
          setupAuditLogger(identityProvider, unit.getIdentifier());

      RuntimeEnvironmentBuilder builder =
          boostrapRuntimeEnvironmentBuilder(
                  kmoduleUnit, deployedUnit, kieContainer, kmoduleUnit.getMergeMode())
              .knowledgeBase(kbase)
              .classLoader(kieContainer.getClassLoader());

      builder.registerableItemsFactory(
          getRegisterableItemsFactory(auditLoggerBuilder, kieContainer, kmoduleUnit));

      commonDeploy(unit, deployedUnit, builder.get(), kieContainer);
      kmoduleUnit.setDeployed(true);
    } catch (Throwable e) {
      logger.warn("Unexpected error while deploying unit {}", unit.getIdentifier(), e);
      // catch all possible errors to be able to report them to caller as RuntimeException
      throw new RuntimeException(e);
    }
  }
Beispiel #24
0
  public void setProperty(String name, String value) {
    name = name.trim();
    if (StringUtils.isEmpty(name)) {
      return;
    }

    if (name.equals(SequentialAgendaOption.PROPERTY_NAME)) {
      setSequentialAgenda(
          SequentialAgenda.determineSequentialAgenda(
              StringUtils.isEmpty(value) ? "sequential" : value));
    } else if (name.equals(SequentialOption.PROPERTY_NAME)) {
      setSequential(StringUtils.isEmpty(value) ? false : Boolean.valueOf(value));
    } else if (name.equals(RemoveIdentitiesOption.PROPERTY_NAME)) {
      setRemoveIdentities(StringUtils.isEmpty(value) ? false : Boolean.valueOf(value));
    } else if (name.equals(ShareAlphaNodesOption.PROPERTY_NAME)) {
      setShareAlphaNodes(StringUtils.isEmpty(value) ? false : Boolean.valueOf(value));
    } else if (name.equals(ShareBetaNodesOption.PROPERTY_NAME)) {
      setShareBetaNodes(StringUtils.isEmpty(value) ? false : Boolean.valueOf(value));
    } else if (name.equals(PermGenThresholdOption.PROPERTY_NAME)) {
      setPermGenThreshold(
          StringUtils.isEmpty(value)
              ? PermGenThresholdOption.DEFAULT_VALUE
              : Integer.parseInt(value));
    } else if (name.equals(AlphaThresholdOption.PROPERTY_NAME)) {
      setAlphaNodeHashingThreshold(StringUtils.isEmpty(value) ? 3 : Integer.parseInt(value));
    } else if (name.equals(CompositeKeyDepthOption.PROPERTY_NAME)) {
      setCompositeKeyDepth(StringUtils.isEmpty(value) ? 3 : Integer.parseInt(value));
    } else if (name.equals(IndexLeftBetaMemoryOption.PROPERTY_NAME)) {
      setIndexLeftBetaMemory(StringUtils.isEmpty(value) ? true : Boolean.valueOf(value));
    } else if (name.equals(IndexRightBetaMemoryOption.PROPERTY_NAME)) {
      setIndexRightBetaMemory(StringUtils.isEmpty(value) ? true : Boolean.valueOf(value));
    } else if (name.equals(IndexPrecedenceOption.PROPERTY_NAME)) {
      setIndexPrecedenceOption(
          StringUtils.isEmpty(value)
              ? IndexPrecedenceOption.EQUALITY_PRIORITY
              : IndexPrecedenceOption.determineIndexPrecedence(value));
    } else if (name.equals(EqualityBehaviorOption.PROPERTY_NAME)) {
      setAssertBehaviour(
          AssertBehaviour.determineAssertBehaviour(
              StringUtils.isEmpty(value) ? "identity" : value));
    } else if (name.equals(ConsequenceExceptionHandlerOption.PROPERTY_NAME)) {
      setConsequenceExceptionHandler(
          StringUtils.isEmpty(value) ? DefaultConsequenceExceptionHandler.class.getName() : value);
    } else if (name.equals("drools.ruleBaseUpdateHandler")) {
      setRuleBaseUpdateHandler(StringUtils.isEmpty(value) ? "" : value);
    } else if (name.equals("drools.conflictResolver")) {
      setConflictResolver(
          determineConflictResolver(
              StringUtils.isEmpty(value) ? DepthConflictResolver.class.getName() : value));
    } else if (name.equals("drools.advancedProcessRuleIntegration")) {
      setAdvancedProcessRuleIntegration(
          StringUtils.isEmpty(value) ? false : Boolean.valueOf(value));
    } else if (name.equals(MultithreadEvaluationOption.PROPERTY_NAME)) {
      setMultithreadEvaluation(StringUtils.isEmpty(value) ? false : Boolean.valueOf(value));
    } else if (name.equals(MaxThreadsOption.PROPERTY_NAME)) {
      setMaxThreads(StringUtils.isEmpty(value) ? 3 : Integer.parseInt(value));
    } else if (name.equals(EventProcessingOption.PROPERTY_NAME)) {
      setEventProcessingMode(
          EventProcessingOption.determineEventProcessingMode(
              StringUtils.isEmpty(value) ? "cloud" : value));
    } else if (name.equals(MBeansOption.PROPERTY_NAME)) {
      setMBeansEnabled(MBeansOption.isEnabled(value));
    } else if (name.equals(ClassLoaderCacheOption.PROPERTY_NAME)) {
      setClassLoaderCacheEnabled(StringUtils.isEmpty(value) ? true : Boolean.valueOf(value));
    } else if (name.equals(PhreakOption.PROPERTY_NAME)) {
      setPhreakEnabled(StringUtils.isEmpty(value) ? false : Boolean.valueOf(value));
    }
  }
  public static InternalFactHandle readFactHandle(MarshallerReaderContext context)
      throws IOException, ClassNotFoundException {
    int type = context.stream.readInt();
    int id = context.stream.readInt();
    long recency = context.stream.readLong();

    long startTimeStamp = 0;
    long duration = 0;
    boolean expired = false;
    long activationsCount = 0;
    if (type == 2) {
      startTimeStamp = context.stream.readLong();
      duration = context.stream.readLong();
      expired = context.stream.readBoolean();
      activationsCount = context.stream.readLong();
    }

    int strategyIndex = context.stream.readInt();
    Object object = null;
    ObjectMarshallingStrategy strategy = null;
    // This is the old way of de/serializing strategy objects
    if (strategyIndex >= 0) {
      strategy = context.resolverStrategyFactory.getStrategy(strategyIndex);
    }
    // This is the new way
    else if (strategyIndex == -2) {
      String strategyClassName = context.stream.readUTF();
      if (!StringUtils.isEmpty(strategyClassName)) {
        strategy = context.resolverStrategyFactory.getStrategyObject(strategyClassName);
        if (strategy == null) {
          throw new IllegalStateException(
              "No strategy of type " + strategyClassName + " available.");
        }
      }
    }

    // If either way retrieves a strategy, use it
    if (strategy != null) {
      object = strategy.read(context.stream);
    }

    WorkingMemoryEntryPoint entryPoint = null;
    if (context.readBoolean()) {
      String entryPointId = context.readUTF();
      if (entryPointId != null && !entryPointId.equals("")) {
        entryPoint = context.wm.getEntryPoints().get(entryPointId);
      }
    }
    InternalFactHandle handle = null;
    switch (type) {
      case 0:
        {
          handle = new DefaultFactHandle(id, object, recency, entryPoint);
          break;
        }
      case 1:
        {
          handle = new QueryElementFactHandle(object, id, recency);
          break;
        }
      case 2:
        {
          handle = new EventFactHandle(id, object, recency, startTimeStamp, duration, entryPoint);
          ((EventFactHandle) handle).setExpired(expired);
          ((EventFactHandle) handle).setActivationsCount(activationsCount);
          break;
        }
      default:
        {
          throw new IllegalStateException(
              "Unable to marshal FactHandle, as type does not exist:" + type);
        }
    }

    return handle;
  }
Beispiel #26
0
 public boolean isEmpty() {
   return StringUtils.isEmpty(value);
 }
  @Test
  public void testGlobal() throws Exception {
    Options xjcOpts = new Options();
    xjcOpts.setSchemaLanguage(Language.XMLSCHEMA);
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    JaxbConfiguration jaxbConf = KnowledgeBuilderFactory.newJaxbConfiguration(xjcOpts, "xsd");

    kbuilder.add(
        ResourceFactory.newClassPathResource("order.xsd", getClass()), ResourceType.XSD, jaxbConf);

    assertFalse(kbuilder.hasErrors());

    kbuilder.add(
        ResourceFactory.newClassPathResource("test_Jaxb.drl", getClass()), ResourceType.DRL);

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    assertFalse(kbuilder.hasErrors());

    assertFalse(kbuilder.hasErrors());

    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    KnowledgeRuntimeCommand setGlobalStage =
        PipelineFactory.newStatefulKnowledgeSessionSetGlobal("order");

    JAXBContext jaxbCtx =
        KnowledgeBuilderHelper.newJAXBContext(
            jaxbConf.getClasses().toArray(new String[jaxbConf.getClasses().size()]), kbase);

    Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
    Transformer transformer = PipelineFactory.newJaxbFromXmlTransformer(unmarshaller);
    transformer.setReceiver(setGlobalStage);

    Pipeline pipeline = PipelineFactory.newStatefulKnowledgeSessionPipeline(ksession);
    pipeline.setReceiver(transformer);

    String xml =
        StringUtils.readFileAsString(
            new InputStreamReader(getClass().getResourceAsStream("order.xml")));

    ResultHandlerImpl resultHandler = new ResultHandlerImpl();
    pipeline.insert(xml, resultHandler);

    // now round trip that global
    Action executeResult = PipelineFactory.newExecuteResultHandler();

    Action assignAsResult = PipelineFactory.newAssignObjectAsResult();
    assignAsResult.setReceiver(executeResult);

    // transformer = PipelineFactory.newXStreamToXmlTransformer( xstream );
    Marshaller marshaller = jaxbCtx.createMarshaller();
    transformer = PipelineFactory.newJaxbToXmlTransformer(marshaller);
    transformer.setReceiver(assignAsResult);

    KnowledgeRuntimeCommand getGlobalStage = PipelineFactory.newStatefulKnowledgeSessionGetGlobal();
    getGlobalStage.setReceiver(transformer);

    pipeline = PipelineFactory.newStatefulKnowledgeSessionPipeline(ksession);
    pipeline.setReceiver(getGlobalStage);

    resultHandler = new ResultHandlerImpl();
    pipeline.insert("order", resultHandler);

    assertEqualsIgnoreWhitespace(xml, (String) resultHandler.getObject());
  }
  @Override
  public void deploy(DeploymentUnit unit) {
    super.deploy(unit);
    if (!(unit instanceof KModuleDeploymentUnit)) {
      throw new IllegalArgumentException(
          "Invalid deployment unit provided - " + unit.getClass().getName());
    }
    KModuleDeploymentUnit kmoduleUnit = (KModuleDeploymentUnit) unit;
    DeployedUnitImpl deployedUnit = new DeployedUnitImpl(unit);
    KieServices ks = KieServices.Factory.get();
    MavenRepository repository = getMavenRepository();
    repository.resolveArtifact(kmoduleUnit.getIdentifier());

    ReleaseId releaseId =
        ks.newReleaseId(
            kmoduleUnit.getGroupId(), kmoduleUnit.getArtifactId(), kmoduleUnit.getVersion());
    KieContainer kieContainer = ks.newKieContainer(releaseId);

    String kbaseName = kmoduleUnit.getKbaseName();
    if (StringUtils.isEmpty(kbaseName)) {
      KieBaseModel defaultKBaseModel =
          ((KieContainerImpl) kieContainer).getKieProject().getDefaultKieBaseModel();
      if (defaultKBaseModel != null) {
        kbaseName = defaultKBaseModel.getName();
      } else {
        kbaseName = DEFAULT_KBASE_NAME;
      }
    }
    InternalKieModule module =
        (InternalKieModule) ((KieContainerImpl) kieContainer).getKieModuleForKBase(kbaseName);
    if (module == null) {
      throw new IllegalStateException("Cannot find kbase with name " + kbaseName);
    }

    Map<String, String> formsData = new HashMap<String, String>();
    Collection<String> files = module.getFileNames();
    for (String fileName : files) {
      if (fileName.matches(".+bpmn[2]?$")) {
        ProcessDesc process;
        try {
          String processString = new String(module.getBytes(fileName), "UTF-8");
          process = bpmn2Service.findProcessId(processString, kieContainer.getClassLoader());
          process.setEncodedProcessSource(Base64.encodeBase64String(processString.getBytes()));
          process.setDeploymentId(unit.getIdentifier());
          process.setForms(formsData);
          deployedUnit.addAssetLocation(process.getId(), process);
        } catch (UnsupportedEncodingException e) {
          logger.warn("Unable to load content for file '{}' : {}", fileName, e);
        }
      } else if (fileName.matches(".+ftl$")) {
        try {
          String formContent = new String(module.getBytes(fileName), "UTF-8");
          Pattern regex = Pattern.compile("(.{0}|.*/)([^/]*?)\\.ftl");
          Matcher m = regex.matcher(fileName);
          String key = fileName;
          while (m.find()) {
            key = m.group(2);
          }
          formsData.put(key, formContent);
        } catch (UnsupportedEncodingException e) {
          logger.warn("Unable to load content for form '{}' : {}", fileName, e);
        }
      } else if (fileName.matches(".+form$")) {
        try {
          String formContent = new String(module.getBytes(fileName), "UTF-8");
          Pattern regex = Pattern.compile("(.{0}|.*/)([^/]*?)\\.form");
          Matcher m = regex.matcher(fileName);
          String key = fileName;
          while (m.find()) {
            key = m.group(2);
          }
          formsData.put(key + ".form", formContent);
        } catch (UnsupportedEncodingException e) {
          logger.warn("Unable to load content for form '{}' : {}", fileName, e);
        }
      }
    }

    KieBase kbase = kieContainer.getKieBase(kbaseName);

    AbstractAuditLogger auditLogger = getAuditLogger();
    ServicesAwareAuditEventBuilder auditEventBuilder = new ServicesAwareAuditEventBuilder();
    auditEventBuilder.setIdentityProvider(identityProvider);
    auditEventBuilder.setDeploymentUnitId(unit.getIdentifier());
    auditLogger.setBuilder(auditEventBuilder);

    RuntimeEnvironmentBuilder builder =
        RuntimeEnvironmentBuilder.getDefault()
            .entityManagerFactory(getEmf())
            .knowledgeBase(kbase)
            .classLoader(kieContainer.getClassLoader());
    if (beanManager != null) {
      builder.registerableItemsFactory(
          InjectableRegisterableItemsFactory.getFactory(
              beanManager, auditLogger, kieContainer, kmoduleUnit.getKsessionName()));
    }
    commonDeploy(unit, deployedUnit, builder.get());
  }