Java Code Examples for org.drools.core.util.StringUtils

The following examples show how to use org.drools.core.util.StringUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: kogito-runtimes   Source File: JavaRuleBuilderHelper.java    License: Apache License 2.0 6 votes vote down vote up
private static void generateInvokerTemplate(final String invokerTemplate,
                                            final RuleBuildContext context,
                                            final String className,
                                            final Map vars,
                                            final Object invokerLookup,
                                            final BaseDescr descrLookup) {
    TemplateRegistry registry = getInvokerTemplateRegistry(context.getKnowledgeBuilder().getRootClassLoader());
    final String invokerClassName = context.getPkg().getName() + "." + context.getRuleDescr().getClassName() + StringUtils.ucFirst( className ) + "Invoker";

    context.addInvoker( invokerClassName,
                        (String) TemplateRuntime.execute( registry.getNamedTemplate( invokerTemplate ),
                                                          null,
                                                          new MapVariableResolverFactory( vars ),
                                                          registry ) );

    context.addInvokerLookup( invokerClassName, invokerLookup );
    context.addDescrLookups( invokerClassName, descrLookup );
}
 
Example 2
Source Project: kogito-runtimes   Source File: MessageProducerGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public MessageProducerGenerator(
        WorkflowProcess process,
        String modelfqcn,
        String processfqcn,
        String messageDataEventClassName,
        TriggerMetaData trigger) {
    this.process = process;
    this.trigger = trigger;
    this.packageName = process.getPackageName();
    this.processId = process.getId();
    this.processName = processId.substring(processId.lastIndexOf('.') + 1);
    String classPrefix = StringUtils.capitalize(processName);
    this.resourceClazzName = classPrefix + "MessageProducer_" + trigger.getOwnerId();
    this.relativePath = packageName.replace(".", "/") + "/" + resourceClazzName + ".java";
    this.messageDataEventClassName = messageDataEventClassName;
}
 
Example 3
Source Project: kogito-runtimes   Source File: SessionConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
public final String getProperty(String name) {
    name = name.trim();
    if ( StringUtils.isEmpty( name ) ) {
        return null;
    }

    if ( name.equals( KeepReferenceOption.PROPERTY_NAME ) ) {
        return Boolean.toString(isKeepReference());
    } else if ( name.equals( ClockTypeOption.PROPERTY_NAME ) ) {
        return getClockType().toExternalForm();
    } else if ( name.equals( TimerJobFactoryOption.PROPERTY_NAME ) ) {
        return getTimerJobFactoryType().toExternalForm();
    } else if ( name.equals( QueryListenerOption.PROPERTY_NAME ) ) {
        return getQueryListenerOption().getAsString();
    } else if ( name.equals( BeliefSystemTypeOption.PROPERTY_NAME ) ) {
        return getBeliefSystemType().getId();
    }
    return null;
}
 
Example 4
Source Project: kogito-runtimes   Source File: JavaDialectRuntimeData.java    License: Apache License 2.0 6 votes vote down vote up
public void removeRule( KnowledgePackageImpl pkg,
                        RuleImpl rule ) {

    if (!( rule instanceof QueryImpl)) {
        // Query's don't have a consequence, so skip those
        final String consequenceName = rule.getConsequence().getClass().getName();

        // check for compiled code and remove if present.
        if (remove( consequenceName )) {
            removeClasses( rule.getLhs() );

            // Now remove the rule class - the name is a subset of the consequence name
            String sufix = StringUtils.ucFirst( rule.getConsequence().getName() ) + "ConsequenceInvoker";
            remove( consequenceName.substring( 0,
                                               consequenceName.indexOf( sufix ) ) );
        }
    }
}
 
Example 5
Source Project: kogito-runtimes   Source File: DefaultAgenda.java    License: Apache License 2.0 6 votes vote down vote up
@Override
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;
}
 
Example 6
Source Project: kogito-runtimes   Source File: InsertElementsCommand.java    License: Apache License 2.0 6 votes vote down vote up
public Collection<FactHandle> execute(Context context) {
    KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );
    List<FactHandle> handles = new ArrayList<FactHandle>();
    
    EntryPoint wmep;
    if ( StringUtils.isEmpty( this.entryPoint ) ) {
        wmep = ksession;
    } else {
        wmep = ksession.getEntryPoint( this.entryPoint );
    }

    for ( Object object : objects ) {
        handles.add( wmep.insert( object ) );
    }

    if ( outIdentifier != null ) {
        if ( this.returnObject ) {
            ((RegistryContext) context).lookup( ExecutionResultImpl.class ).setResult( this.outIdentifier, objects );
        }
        ((RegistryContext) context).lookup( ExecutionResultImpl.class ).getFactHandles().put( this.outIdentifier, handles );
    }
    return handles;
}
 
Example 7
Source Project: kogito-runtimes   Source File: InsertObjectCommand.java    License: Apache License 2.0 6 votes vote down vote up
public FactHandle execute(Context context) {
    KieSession ksession = ((RegistryContext)context).lookup( KieSession.class );
    
    FactHandle factHandle;
    if ( StringUtils.isEmpty( this.entryPoint ) ) {
        factHandle = ksession.insert( object );
    } else {
        factHandle = ksession.getEntryPoint( this.entryPoint ).insert( object );
    }

    if ( outIdentifier != null ) {
        if ( this.returnObject ) {
            ((RegistryContext) context).lookup( ExecutionResultImpl.class ).setResult( this.outIdentifier, object );
        }
        ((RegistryContext) context).lookup( ExecutionResultImpl.class ).getFactHandles().put( this.outIdentifier, factHandle );
    }

    if ( disconnected ) {
        DefaultFactHandle disconnectedHandle = ((DefaultFactHandle)factHandle).clone();
        disconnectedHandle.disconnect();
        return disconnectedHandle;
    }
    return factHandle;
}
 
Example 8
Source Project: kogito-runtimes   Source File: UrlResource.java    License: Apache License 2.0 6 votes vote down vote up
public boolean isDirectory() {
    try {
        URL url = getURL();

        if ("file".equals(url.getProtocol())) {

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

            return file.isDirectory();
        }
    } catch (Exception e) {
        // swallow as returned false
    }

    return false;
}
 
Example 9
Source Project: kogito-runtimes   Source File: JavaDialect.java    License: Apache License 2.0 5 votes vote down vote up
public void init(final RuleDescr ruleDescr) {
    final String ruleClassName = DialectUtil.getUniqueLegalName(this.pkg.getName(),
                                                                ruleDescr.getName(),
                                                                ruleDescr.getConsequence().hashCode(),
                                                                "java",
                                                                "Rule",
                                                                this.src);
    ruleDescr.setClassName(StringUtils.ucFirst(ruleClassName));
}
 
Example 10
Source Project: kogito-runtimes   Source File: JavaDialect.java    License: Apache License 2.0 5 votes vote down vote up
public void init(final ProcessDescr processDescr) {
    final String processDescrClassName = DialectUtil.getUniqueLegalName(this.pkg.getName(),
                                                                        processDescr.getName(),
                                                                        processDescr.getProcessId().hashCode(),
                                                                        "java",
                                                                        "Process",
                                                                        this.src);
    processDescr.setClassName(StringUtils.ucFirst(processDescrClassName));
}
 
Example 11
Source Project: hacep   Source File: RulesManager.java    License: Apache License 2.0 5 votes vote down vote up
public KieSession newKieSession(KieContainer kieContainer) {
    checkStatus();
    if (!StringUtils.isEmpty(rulesConfiguration.getKieSessionName())) {
        return kieContainer.newKieSession(rulesConfiguration.getKieSessionName());
    }
    return kieContainer.newKieSession();
}
 
Example 12
Source Project: hacep   Source File: RulesManager.java    License: Apache License 2.0 5 votes vote down vote up
public KieContainer newKieContainer(String version) {
    ReleaseId releaseId = kieServices.newReleaseId(
            rulesConfiguration.getGroupId(),
            rulesConfiguration.getArtifactId(),
            StringUtils.isEmpty(version) ? rulesConfiguration.getVersion() : version);
    return kieServices.newKieContainer(releaseId);
}
 
Example 13
Source Project: kogito-runtimes   Source File: JavaDialect.java    License: Apache License 2.0 5 votes vote down vote up
public void postCompileAddFunction(FunctionDescr functionDescr,
                                   TypeResolver typeResolver) {
    final String functionClassName = this.pkg.getName() + "." + StringUtils.ucFirst(functionDescr.getName());
    ImportDescr importDescr = new ImportDescr(functionClassName + "." + functionDescr.getName());
    importDescr.setResource(functionDescr.getResource());
    importDescr.setNamespace(functionDescr.getNamespace());
    this.packageRegistry.addStaticImport(importDescr);
}
 
Example 14
Source Project: kogito-runtimes   Source File: MVELDialect.java    License: Apache License 2.0 5 votes vote down vote up
public void init(RuleDescr ruleDescr) {
    // MVEL:test null to Fix failing test on
    // org.kie.rule.builder.dialect.
    // mvel.MVELConsequenceBuilderTest.testImperativeCodeError()

    // @todo: why is this here, MVEL doesn't compile anything? mdp
    String pkgName = this.pkg == null ? "" : this.pkg.getName();
    final String ruleClassName = DialectUtil.getUniqueLegalName(pkgName,
                                                                ruleDescr.getName(),
                                                                ruleDescr.getConsequence().hashCode(),
                                                                "mvel",
                                                                "Rule",
                                                                this.src);
    ruleDescr.setClassName(StringUtils.ucFirst(ruleClassName));
}
 
Example 15
Source Project: kogito-runtimes   Source File: MVELDialect.java    License: Apache License 2.0 5 votes vote down vote up
public void init(final ProcessDescr processDescr) {
    final String processDescrClassName = DialectUtil.getUniqueLegalName(this.pkg.getName(),
                                                                        processDescr.getName(),
                                                                        processDescr.getProcessId().hashCode(),
                                                                        "mvel",
                                                                        "Process",
                                                                        this.src);
    processDescr.setClassName(StringUtils.ucFirst(processDescrClassName));
}
 
Example 16
Source Project: kogito-runtimes   Source File: MVELDialect.java    License: Apache License 2.0 5 votes vote down vote up
public void addRule(RuleBuildContext context) {
    // MVEL: Compiler change
    final RuleDescr ruleDescr = context.getRuleDescr();

    // setup the line mappins for this rule
    final String name = this.pkg.getName() + "." + StringUtils.ucFirst(ruleDescr.getClassName());
    final LineMappings mapping = new LineMappings(name);
    mapping.setStartLine(ruleDescr.getConsequenceLine());
    mapping.setOffset(ruleDescr.getConsequenceOffset());

    context.getPkg().getDialectRuntimeRegistry().getLineMappings().put(name,
                                                                       mapping);
}
 
Example 17
Source Project: kogito-runtimes   Source File: ModelMetaData.java    License: Apache License 2.0 5 votes vote down vote up
public MethodCallExpr callSetter(String targetVar, String destField, Expression value) {
    String name = variableScope.getTypes().get(destField).getSanitizedName();
    String type = variableScope.getType(destField);
    String setter = "set" + StringUtils.capitalize(name); // todo cache FieldDeclarations in compilationUnit()
    return new MethodCallExpr(new NameExpr(targetVar), setter).addArgument(
            new CastExpr(
                    new ClassOrInterfaceType(null, type),
                    new EnclosedExpr(value)));
}
 
Example 18
Source Project: kogito-runtimes   Source File: ClasspathKieProject.java    License: Apache License 2.0 5 votes vote down vote up
private static String getPomPropertiesFromFileSystem(String rootPath) {
    File file = KieBuilderImpl.findPomProperties( new File( rootPath ) );
    if ( file == null ) {
        log.warn( "Unable to find pom.properties in " + rootPath );
        return null;
    }
    log.debug( "Found and used pom.properties " + file);
    try (Reader reader = new InputStreamReader( new FileInputStream( file ), IoUtils.UTF8_CHARSET )) {
        return StringUtils.toString( reader );
    } catch ( Exception e ) {
        log.warn( "Unable to load pom.properties tried recursing down from " + rootPath + "\n" + e.getMessage() );
    }
    return null;
}
 
Example 19
Source Project: kogito-runtimes   Source File: Variable.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return a valid unique Java identifier based on the given @param name. It consider valid characters and
 * reserved words.
 * In case the input is valid it is returned itself otherwise a valid identifier is generated prefixing v$ based
 * on the @param input excluding invalid characters.
 * @param name the input
 * @return the output valid Java identifier
 */
private static String sanitizeIdentifier(String name) {
    return Optional.ofNullable(name)
                    .filter(SourceVersion::isName)
                    .orElseGet(() -> {
                        String identifier = StringUtils.extractFirstIdentifier(name, 0);
                        return Optional.ofNullable(identifier)
                                .filter(s -> !StringUtils.isEmpty(s))
                                .filter(SourceVersion::isName)
                                // prepend v$ in front of the variable name to prevent clashing with reserved keywords
                                .orElseGet(() -> String.format("v$%s", identifier));
                    });
}
 
Example 20
Source Project: kogito-runtimes   Source File: ReleaseIdImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static ReleaseId getReleaseIdFromProperties( Properties props, String path ) {
    String groupId = props.getProperty("groupId");
    String artifactId = props.getProperty("artifactId");
    String version = props.getProperty("version");
    if (StringUtils.isEmpty(groupId) || StringUtils.isEmpty(artifactId) || StringUtils.isEmpty(version)) {
        throw new RuntimeException("pom.properties exists but ReleaseId content is malformed\n" + path);
    }
    return new ReleaseIdImpl( groupId, artifactId, version);
}
 
Example 21
public Map createVariableContext(final String className,
                                 final String text,
                                 final ProcessBuildContext context,
                                 final String[] globals) {
    final Map map = new HashMap();

    map.put("methodName",
            className);

    map.put("package",
            context.getPkg().getName());

    map.put("processClassName",
            StringUtils.ucFirst(context.getProcessDescr().getClassName()));

    map.put("invokerClassName",
            context.getProcessDescr().getClassName() + StringUtils.ucFirst(className) + "Invoker");

    if (text != null) {
        map.put("text",
                text);

        map.put("hashCode",
                new Integer(text.hashCode()));
    }

    final List globalTypes = new ArrayList(globals.length);
    for (int i = 0, length = globals.length; i < length; i++) {
        globalTypes.add(context.getPkg().getGlobals().get(globals[i]).getCanonicalName());
    }

    map.put("globals",
            globals);

    map.put("globalTypes",
            globalTypes);

    return map;
}
 
Example 22
Source Project: kogito-runtimes   Source File: ModelClassGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public ModelClassGenerator(GeneratorContext context, WorkflowProcess workFlowProcess) {
    String pid = workFlowProcess.getId();
    String name = ProcessToExecModelGenerator.extractProcessId(pid);
    this.modelClassName = workFlowProcess.getPackageName() + "." +
            StringUtils.capitalize(name) + "Model";

    this.context = context;
    this.workFlowProcess = workFlowProcess;
}
 
Example 23
Source Project: kogito-runtimes   Source File: QualifiedName.java    License: Apache License 2.0 5 votes vote down vote up
public String getFullName() {
    if ( StringUtils.isEmpty(namespace) ) {
        return name;
    } else {
        return namespace + "." + name;
    }
}
 
Example 24
Source Project: kogito-runtimes   Source File: KnowledgeBuilderImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void manageUnresolvedExtension(RuleDescr ruleDescr,
                                       Collection<RuleDescr> candidates) {
    List<String> candidateRules = new LinkedList<>();
    for (RuleDescr r : candidates) {
        if (StringUtils.stringSimilarity(ruleDescr.getParentName(), r.getName(), StringUtils.SIMILARITY_STRATS.DICE) >= 0.75) {
            candidateRules.add(r.getName());
        }
    }
    String msg = "Unresolved parent name " + ruleDescr.getParentName();
    if (!candidateRules.isEmpty()) {
        msg += " >> did you mean any of :" + candidateRules;
    }
    results.add(new RuleBuildError(ruleDescr.toRule(), ruleDescr, msg,
                                   "Unable to resolve parent rule, please check that both rules are in the same package"));
}
 
Example 25
Source Project: kogito-runtimes   Source File: UserTaskModelMetaData.java    License: Apache License 2.0 5 votes vote down vote up
private void addUserTaskAnnotation(ClassOrInterfaceDeclaration modelClass) {
    String taskName = (String) humanTaskNode.getWork().getParameter(TASK_NAME);
    if (taskName == null)
        taskName = humanTaskNode.getName();
    modelClass.addAndGetAnnotation(UserTask.class).addPair("taskName", new StringLiteralExpr(taskName)).addPair("processName", new StringLiteralExpr(StringUtils.capitalize(ProcessToExecModelGenerator
                                                                                                                                                                                                       .extractProcessId(processId))));
}
 
Example 26
Source Project: kogito-runtimes   Source File: DMNRestResourceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public DMNRestResourceGenerator(DMNModel model, String appCanonicalName) {
    this.dmnModel = model;
    this.packageName = CodegenStringUtil.escapeIdentifier(model.getNamespace());
    this.decisionId = model.getDefinitions().getId();
    this.decisionName = CodegenStringUtil.escapeIdentifier(model.getName());
    this.nameURL = URLEncoder.encode(model.getName()).replaceAll("\\+", "%20");
    this.appCanonicalName = appCanonicalName;
    String classPrefix = StringUtils.capitalize(decisionName);
    this.resourceClazzName = classPrefix + "Resource";
    this.relativePath = packageName.replace(".", "/") + "/" + resourceClazzName + ".java";
}
 
Example 27
Source Project: kogito-runtimes   Source File: MemoryFolder.java    License: Apache License 2.0 5 votes vote down vote up
public File getFile(String name) {
    if ( !StringUtils.isEmpty( path )) {
        return mfs.getFile( path + "/" + name );
    } else {
        return mfs.getFile( name );
    }
}
 
Example 28
Source Project: kogito-runtimes   Source File: MemoryFolder.java    License: Apache License 2.0 5 votes vote down vote up
public Folder getFolder(String name) {
    if ( !StringUtils.isEmpty( path )) {
        return mfs.getFolder( path + "/" + name );
    } else {
        return mfs.getFolder( name );
    }
}
 
Example 29
Source Project: kogito-runtimes   Source File: MemoryFolder.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 30
Source Project: kogito-runtimes   Source File: MemoryFile.java    License: Apache License 2.0 5 votes vote down vote up
public Path getRelativePath() {
    if ( !StringUtils.isEmpty( folder.getPath().toPortableString() ) ) {
        return new MemoryPath( folder.getPath().toPortableString() + "/" + name );
    } else {
        return new MemoryPath( name );
    }
}