idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
13,700
public void remove ( boolean doDispose ) { if ( active ) { rayHandler . lightList . removeValue ( this , false ) ; } else { rayHandler . disabledLights . removeValue ( this , false ) ; } rayHandler = null ; if ( doDispose ) dispose ( ) ; }
Removes light from specified RayHandler and disposes it if requested
13,701
void setRayNum ( int rays ) { if ( rays < MIN_RAYS ) rays = MIN_RAYS ; rayNum = rays ; vertexNum = rays + 1 ; segments = new float [ vertexNum * 8 ] ; mx = new float [ vertexNum ] ; my = new float [ vertexNum ] ; f = new float [ vertexNum ] ; }
Internal method for mesh update depending on ray number
13,702
public void setContactFilter ( short categoryBits , short groupIndex , short maskBits ) { filterA = new Filter ( ) ; filterA . categoryBits = categoryBits ; filterA . groupIndex = groupIndex ; filterA . maskBits = maskBits ; }
Creates new contact filter for this light with given parameters
13,703
static public void setGlobalContactFilter ( short categoryBits , short groupIndex , short maskBits ) { globalFilterA = new Filter ( ) ; globalFilterA . categoryBits = categoryBits ; globalFilterA . groupIndex = groupIndex ; globalFilterA . maskBits = maskBits ; }
Creates new contact filter for ALL LIGHTS with give parameters
13,704
public void debugRender ( ShapeRenderer shapeRenderer ) { shapeRenderer . setColor ( Color . YELLOW ) ; FloatArray vertices = Pools . obtain ( FloatArray . class ) ; vertices . clear ( ) ; for ( int i = 0 ; i < rayNum ; i ++ ) { vertices . addAll ( mx [ i ] , my [ i ] ) ; } for ( int i = rayNum - 1 ; i > - 1 ; i -- ) { vertices . addAll ( startX [ i ] , startY [ i ] ) ; } shapeRenderer . polygon ( vertices . shrink ( ) ) ; Pools . free ( vertices ) ; }
Draws a polygon using ray start and end points as vertices
13,705
public void attachToBody ( Body body , float degrees ) { this . body = body ; this . bodyPosition . set ( body . getPosition ( ) ) ; bodyAngleOffset = MathUtils . degreesToRadians * degrees ; bodyAngle = body . getAngle ( ) ; applyAttachment ( ) ; if ( staticLight ) dirty = true ; }
Attaches light to specified body with relative direction offset
13,706
void applyAttachment ( ) { if ( body == null || staticLight ) return ; restorePosition . setToTranslation ( bodyPosition ) ; rotateAroundZero . setToRotationRad ( bodyAngle + bodyAngleOffset ) ; for ( int i = 0 ; i < rayNum ; i ++ ) { tmpVec . set ( startX [ i ] , startY [ i ] ) . mul ( rotateAroundZero ) . mul ( restorePosition ) ; startX [ i ] = tmpVec . x ; startY [ i ] = tmpVec . y ; tmpVec . set ( endX [ i ] , endY [ i ] ) . mul ( rotateAroundZero ) . mul ( restorePosition ) ; endX [ i ] = tmpVec . x ; endY [ i ] = tmpVec . y ; } }
Applies attached body initial transform to all lights rays
13,707
public void attachToBody ( Body body , float offsetX , float offSetY , float degrees ) { this . body = body ; bodyOffsetX = offsetX ; bodyOffsetY = offSetY ; bodyAngleOffset = degrees ; if ( staticLight ) dirty = true ; }
Attaches light to specified body with relative offset and direction
13,708
public static String escape ( String value , char quote ) { Map < CharSequence , CharSequence > lookupMap = new HashMap < > ( ) ; lookupMap . put ( Character . toString ( quote ) , "\\" + quote ) ; lookupMap . put ( "\\" , "\\\\" ) ; final CharSequenceTranslator escape = new LookupTranslator ( lookupMap ) . with ( new LookupTranslator ( EntityArrays . JAVA_CTRL_CHARS_ESCAPE ) ) . with ( JavaUnicodeEscaper . outsideOf ( 32 , 0x7f ) ) ; return quote + escape . translate ( value ) + quote ; }
Escape the string with given quote character .
13,709
public List < FunctionWrapper > compileFunctions ( ImportStack importStack , Context context , List < ? > objects ) { List < FunctionWrapper > callbacks = new LinkedList < > ( ) ; for ( Object object : objects ) { List < FunctionWrapper > objectCallbacks = compileFunctions ( importStack , context , object ) ; callbacks . addAll ( objectCallbacks ) ; } return callbacks ; }
Compile methods from all objects into libsass functions .
13,710
public List < FunctionWrapper > compileFunctions ( ImportStack importStack , Context context , Object object ) { Class < ? > functionClass = object . getClass ( ) ; Method [ ] methods = functionClass . getDeclaredMethods ( ) ; List < FunctionDeclaration > declarations = new LinkedList < > ( ) ; for ( Method method : methods ) { int modifiers = method . getModifiers ( ) ; if ( ! Modifier . isPublic ( modifiers ) ) { continue ; } FunctionDeclaration declaration = createDeclaration ( importStack , context , object , method ) ; declarations . add ( declaration ) ; } return declarations . stream ( ) . map ( FunctionWrapper :: new ) . collect ( Collectors . toList ( ) ) ; }
Compile methods from an object into libsass functions .
13,711
public FunctionDeclaration createDeclaration ( ImportStack importStack , Context context , Object object , Method method ) { StringBuilder signature = new StringBuilder ( ) ; Parameter [ ] parameters = method . getParameters ( ) ; List < ArgumentConverter > argumentConverters = new ArrayList < > ( method . getParameterCount ( ) ) ; signature . append ( method . getName ( ) ) . append ( "(" ) ; int parameterCount = 0 ; for ( Parameter parameter : parameters ) { ArgumentConverter argumentConverter = createArgumentConverter ( object , method , parameter ) ; argumentConverters . add ( argumentConverter ) ; List < FunctionArgumentSignature > list = argumentConverter . argumentSignatures ( object , method , parameter , functionArgumentSignatureFactory ) ; for ( FunctionArgumentSignature functionArgumentSignature : list ) { String name = functionArgumentSignature . getName ( ) ; Object defaultValue = functionArgumentSignature . getDefaultValue ( ) ; if ( parameterCount > 0 ) { signature . append ( ", " ) ; } signature . append ( "$" ) . append ( name ) ; if ( null != defaultValue ) { signature . append ( ": " ) . append ( formatDefaultValue ( defaultValue ) ) ; } parameterCount ++ ; } } signature . append ( ")" ) ; if ( method . isAnnotationPresent ( WarnFunction . class ) ) { signature . setLength ( 0 ) ; signature . append ( "@warn" ) ; } else if ( method . isAnnotationPresent ( ErrorFunction . class ) ) { signature . setLength ( 0 ) ; signature . append ( "@error" ) ; } else if ( method . isAnnotationPresent ( DebugFunction . class ) ) { signature . setLength ( 0 ) ; signature . append ( "@debug" ) ; } return new FunctionDeclaration ( importStack , context , signature . toString ( ) , object , method , argumentConverters ) ; }
Create a function declaration from an object method .
13,712
private String formatDefaultValue ( Object value ) { if ( value instanceof Boolean ) { return ( ( Boolean ) value ) ? "true" : "false" ; } if ( value instanceof Number ) { return value . toString ( ) ; } if ( value instanceof Collection ) { return formatCollectionValue ( ( Collection ) value ) ; } String string = value . toString ( ) ; if ( string . startsWith ( "$" ) ) { return string ; } return SassString . escape ( string ) ; }
Format a default value for libsass function signature .
13,713
public SassValue invoke ( List < ? > arguments ) { try { ArrayList < Object > values = new ArrayList < > ( argumentConverters . size ( ) ) ; for ( ArgumentConverter argumentConverter : argumentConverters ) { Object value = argumentConverter . convert ( arguments , importStack , context ) ; values . add ( value ) ; } Object result = method . invoke ( object , values . toArray ( ) ) ; return TypeUtils . convertToSassValue ( result ) ; } catch ( Throwable throwable ) { StringWriter stringWriter = new StringWriter ( ) ; PrintWriter printWriter = new PrintWriter ( stringWriter ) ; String message = throwable . getMessage ( ) ; if ( StringUtils . isNotEmpty ( message ) ) { printWriter . append ( message ) . append ( System . lineSeparator ( ) ) ; } throwable . printStackTrace ( printWriter ) ; return new SassError ( stringWriter . toString ( ) ) ; } }
Invoke the method with the given list of arguments .
13,714
public Output compileFile ( URI inputPath , URI outputPath , Options options ) throws CompilationException { FileContext context = new FileContext ( inputPath , outputPath , options ) ; return compile ( context ) ; }
Compile file .
13,715
public Output compile ( Context context ) throws CompilationException { Objects . requireNonNull ( context , "Parameter context must not be null" ) ; if ( context instanceof FileContext ) { return compile ( ( FileContext ) context ) ; } if ( context instanceof StringContext ) { return compile ( ( StringContext ) context ) ; } throw new UnsupportedContextException ( context ) ; }
Compile context .
13,716
public List < FunctionArgumentSignature > createDefaultArgumentSignature ( Parameter parameter ) { List < FunctionArgumentSignature > list = new LinkedList < > ( ) ; String name = getParameterName ( parameter ) ; Object defaultValue = getDefaultValue ( parameter ) ; list . add ( new FunctionArgumentSignature ( name , defaultValue ) ) ; return list ; }
Create a new factory .
13,717
public String getParameterName ( Parameter parameter ) { Name annotation = parameter . getAnnotation ( Name . class ) ; if ( null == annotation ) { return parameter . getName ( ) ; } return annotation . value ( ) ; }
Determine annotated name of a method parameter .
13,718
public Object getDefaultValue ( Parameter parameter ) { Class < ? > type = parameter . getType ( ) ; if ( TypeUtils . isaString ( type ) ) { return getStringDefaultValue ( parameter ) ; } if ( TypeUtils . isaByte ( type ) ) { return getByteDefaultValue ( parameter ) ; } if ( TypeUtils . isaShort ( type ) ) { return getShortDefaultValue ( parameter ) ; } if ( TypeUtils . isaInteger ( type ) ) { return getIntegerDefaultValue ( parameter ) ; } if ( TypeUtils . isaLong ( type ) ) { return getLongDefaultValue ( parameter ) ; } if ( TypeUtils . isaFloat ( type ) ) { return getFloatDefaultValue ( parameter ) ; } if ( TypeUtils . isaDouble ( type ) ) { return getDoubleDefaultValue ( parameter ) ; } if ( TypeUtils . isaCharacter ( type ) ) { return getCharacterDefaultValue ( parameter ) ; } if ( TypeUtils . isaBoolean ( type ) ) { return getBooleanDefaultValue ( parameter ) ; } return null ; }
Determine annotated default parameter value .
13,719
public int register ( Import importSource ) { int id = registry . size ( ) + 1 ; registry . put ( id , importSource ) ; return id ; }
Register a new import return the registration ID .
13,720
public static SassValue convertToSassValue ( Object value ) { if ( null == value ) { return SassNull . SINGLETON ; } if ( value instanceof SassValue ) { return ( SassValue ) value ; } Class cls = value . getClass ( ) ; if ( isaBoolean ( cls ) ) { return new SassBoolean ( ( Boolean ) value ) ; } if ( isaNumber ( cls ) ) { return new SassNumber ( ( ( Number ) value ) . doubleValue ( ) , "" ) ; } if ( isaString ( cls ) || isaCharacter ( cls ) ) { return new SassString ( value . toString ( ) ) ; } if ( value instanceof Collection ) { return new SassList ( ( ( Collection < ? > ) value ) . stream ( ) . map ( TypeUtils :: convertToSassValue ) . collect ( Collectors . toList ( ) ) ) ; } if ( value instanceof Map ) { return ( ( Map < ? , ? > ) value ) . entrySet ( ) . stream ( ) . collect ( Collectors . toMap ( entry -> entry . getKey ( ) . toString ( ) , entry -> TypeUtils . convertToSassValue ( entry . getValue ( ) ) , ( origin , duplicate ) -> origin , SassMap :: new ) ) ; } if ( value instanceof Throwable ) { Throwable throwable = ( Throwable ) value ; StringWriter stringWriter = new StringWriter ( ) ; PrintWriter printWriter = new PrintWriter ( stringWriter ) ; String message = throwable . getMessage ( ) ; if ( StringUtils . isNotEmpty ( message ) ) { printWriter . append ( message ) . append ( System . lineSeparator ( ) ) ; } throwable . printStackTrace ( printWriter ) ; return new SassError ( stringWriter . toString ( ) ) ; } return new SassError ( String . format ( "Could not convert object of type %s into a sass value" , value . getClass ( ) . toString ( ) ) ) ; }
Try to convert any java object into a responsible sass value .
13,721
private Collection < Import > resolveImport ( Path path ) throws IOException , URISyntaxException { URL resource = resolveResource ( path ) ; if ( null == resource ) { return null ; } final URI uri = new URI ( Paths . get ( "/" ) . resolve ( Paths . get ( getServletContext ( ) . getResource ( "/" ) . toURI ( ) ) . relativize ( Paths . get ( resource . toURI ( ) ) ) ) . toString ( ) ) ; final String source = IOUtils . toString ( resource , StandardCharsets . UTF_8 ) ; final Import scssImport = new Import ( uri , uri , source ) ; return Collections . singleton ( scssImport ) ; }
Try to determine the import object for a given path .
13,722
private URL resolveResource ( Path path ) throws MalformedURLException { final Path dir = path . getParent ( ) ; final String basename = path . getFileName ( ) . toString ( ) ; for ( String prefix : new String [ ] { "_" , "" } ) { for ( String suffix : new String [ ] { ".scss" , ".css" , "" } ) { final Path target = dir . resolve ( prefix + basename + suffix ) ; final URL resource = getServletContext ( ) . getResource ( target . toString ( ) ) ; if ( null != resource ) { return resource ; } } } return null ; }
Try to find a resource for this path .
13,723
public SassValue apply ( SassValue value ) { SassList sassList ; if ( value instanceof SassList ) { sassList = ( SassList ) value ; } else { sassList = new SassList ( ) ; sassList . add ( value ) ; } return declaration . invoke ( sassList ) ; }
Call the function .
13,724
static void loadLibrary ( ) { try { File dir = Files . createTempDirectory ( "libjsass-" ) . toFile ( ) ; dir . deleteOnExit ( ) ; if ( System . getProperty ( "os.name" ) . toLowerCase ( ) . startsWith ( "win" ) ) { System . load ( saveLibrary ( dir , "sass" ) ) ; } System . load ( saveLibrary ( dir , "jsass" ) ) ; } catch ( Exception exception ) { LOG . warn ( exception . getMessage ( ) , exception ) ; throw new LoaderException ( exception ) ; } }
Load the shared libraries .
13,725
private static URL findLibraryResource ( final String libraryFileName ) { String osName = System . getProperty ( "os.name" ) . toLowerCase ( ) ; String osArch = System . getProperty ( "os.arch" ) . toLowerCase ( ) ; String resourceName = null ; LOG . trace ( "Load library \"{}\" for os {}:{}" , libraryFileName , osName , osArch ) ; if ( osName . startsWith ( OS_WIN ) ) { resourceName = determineWindowsLibrary ( libraryFileName , osName , osArch ) ; } else if ( osName . startsWith ( OS_LINUX ) ) { resourceName = determineLinuxLibrary ( libraryFileName , osName , osArch ) ; } else if ( osName . startsWith ( OS_FREEBSD ) ) { resourceName = determineFreebsdLibrary ( libraryFileName , osName , osArch ) ; } else if ( osName . startsWith ( OS_MAC ) ) { resourceName = determineMacLibrary ( libraryFileName ) ; } else { unsupportedPlatform ( osName , osArch ) ; } URL resource = NativeLoader . class . getResource ( resourceName ) ; if ( null == resource ) { unsupportedPlatform ( osName , osArch , resourceName ) ; } return resource ; }
Find the right shared library depending on the operating system and architecture .
13,726
private static String determineWindowsLibrary ( final String library , final String osName , final String osArch ) { String resourceName ; String platform ; String fileExtension = "dll" ; switch ( osArch ) { case ARCH_AMD64 : case ARCH_X86_64 : platform = "windows-x64" ; break ; default : throw new UnsupportedOperationException ( "Platform " + osName + ":" + osArch + " not supported" ) ; } resourceName = "/" + platform + "/" + library + "." + fileExtension ; return resourceName ; }
Determine the right windows library depending on the architecture .
13,727
private static String determineLinuxLibrary ( final String library , final String osName , final String osArch ) { String resourceName ; String platform = null ; String fileExtension = "so" ; switch ( osArch ) { case ARCH_AMD64 : case ARCH_X86_64 : platform = "linux-x64" ; break ; case ARCH_ARM : platform = "linux-armhf32" ; break ; case ARCH_AARCH64 : platform = "linux-aarch64" ; break ; default : unsupportedPlatform ( osName , osArch ) ; } resourceName = "/" + platform + "/" + library + "." + fileExtension ; return resourceName ; }
Determine the right linux library depending on the architecture .
13,728
private static String determineFreebsdLibrary ( final String library , final String osName , final String osArch ) { String resourceName ; String platform = null ; String fileExtension = "so" ; switch ( osArch ) { case ARCH_AMD64 : case ARCH_X86_64 : platform = "freebsd-x64" ; break ; default : unsupportedPlatform ( osName , osArch ) ; } resourceName = "/" + platform + "/" + library + "." + fileExtension ; return resourceName ; }
Determine the right FreeBSD library depending on the architecture .
13,729
private static String determineMacLibrary ( final String library ) { String resourceName ; String platform = "darwin" ; String fileExtension = "dylib" ; resourceName = "/" + platform + "/" + library + "." + fileExtension ; return resourceName ; }
Determine the right mac library depending on the architecture .
13,730
static String saveLibrary ( final File dir , final String libraryName ) throws IOException { String libraryFileName = "lib" + libraryName ; URL libraryResource = findLibraryResource ( libraryFileName ) ; String basename = FilenameUtils . getName ( libraryResource . getPath ( ) ) ; File file = new File ( dir , basename ) ; file . deleteOnExit ( ) ; try ( InputStream in = libraryResource . openStream ( ) ; OutputStream out = new FileOutputStream ( file ) ) { IOUtils . copy ( in , out ) ; } LOG . trace ( "Library \"{}\" copied to \"{}\"" , libraryName , file . getAbsolutePath ( ) ) ; return file . getAbsolutePath ( ) ; }
Save the shared library in the given temporary directory .
13,731
public Output compile ( FileContext context , ImportStack importStack ) throws CompilationException { NativeFileContext nativeContext = convertToNativeContext ( context , importStack ) ; return compileFile ( nativeContext ) ; }
Compile a file context .
13,732
public void execute ( ) throws ActivityException { isSynchronized = checkIfSynchronized ( ) ; if ( ! isSynchronized ) { EventWaitInstance received = registerWaitEvents ( false , true ) ; if ( received != null ) resume ( getExternalEventInstanceDetails ( received . getMessageDocumentId ( ) ) , received . getCompletionCode ( ) ) ; } }
Executes the controlled activity
13,733
private String escape ( String rawActivityName ) { boolean lastIsUnderScore = false ; StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < rawActivityName . length ( ) ; i ++ ) { char ch = rawActivityName . charAt ( i ) ; if ( Character . isLetterOrDigit ( ch ) ) { sb . append ( ch ) ; lastIsUnderScore = false ; } else if ( ! lastIsUnderScore ) { sb . append ( UNDERSCORE ) ; lastIsUnderScore = true ; } } return sb . toString ( ) ; }
Replaces space characters in the activity name with underscores .
13,734
private List < Transition > getIncomingTransitions ( Process procdef , Long activityId , Map < String , String > idToEscapedName ) { List < Transition > incomingTransitions = new ArrayList < Transition > ( ) ; for ( Transition trans : procdef . getTransitions ( ) ) { if ( trans . getToId ( ) . equals ( activityId ) ) { Transition sync = new Transition ( ) ; sync . setId ( trans . getId ( ) ) ; Activity act = procdef . getActivityVO ( trans . getFromId ( ) ) ; String logicalId = act . getLogicalId ( ) ; idToEscapedName . put ( logicalId , escape ( act . getName ( ) ) ) ; sync . setCompletionCode ( logicalId ) ; incomingTransitions . add ( sync ) ; } } return incomingTransitions ; }
reuse WorkTransitionVO for sync info
13,735
protected SOAPMessage createSoapRequest ( Object requestObj ) throws ActivityException { try { MessageFactory messageFactory = getSoapMessageFactory ( ) ; SOAPMessage soapMessage = messageFactory . createMessage ( ) ; Map < Name , String > soapReqHeaders = getSoapRequestHeaders ( ) ; if ( soapReqHeaders != null ) { SOAPHeader header = soapMessage . getSOAPHeader ( ) ; for ( Name name : soapReqHeaders . keySet ( ) ) { header . addHeaderElement ( name ) . setTextContent ( soapReqHeaders . get ( name ) ) ; } } SOAPBody soapBody = soapMessage . getSOAPBody ( ) ; Document requestDoc = null ; if ( requestObj instanceof String ) { requestDoc = DomHelper . toDomDocument ( ( String ) requestObj ) ; } else { Variable reqVar = getProcessDefinition ( ) . getVariable ( getAttributeValue ( REQUEST_VARIABLE ) ) ; XmlDocumentTranslator docRefTrans = ( XmlDocumentTranslator ) VariableTranslator . getTranslator ( getPackage ( ) , reqVar . getType ( ) ) ; requestDoc = docRefTrans . toDomDocument ( requestObj ) ; } SOAPBodyElement bodyElem = soapBody . addBodyElement ( getOperation ( ) ) ; String requestLabel = getRequestLabelPartName ( ) ; if ( requestLabel != null ) { SOAPElement serviceNameElem = bodyElem . addChildElement ( requestLabel ) ; serviceNameElem . addTextNode ( getRequestLabel ( ) ) ; } SOAPElement requestDetailsElem = bodyElem . addChildElement ( getRequestPartName ( ) ) ; requestDetailsElem . addTextNode ( "<![CDATA[" + DomHelper . toXml ( requestDoc ) + "]]>" ) ; return soapMessage ; } catch ( Exception ex ) { throw new ActivityException ( ex . getMessage ( ) , ex ) ; } }
Populate the SOAP request message .
13,736
protected Node unwrapSoapResponse ( SOAPMessage soapResponse ) throws ActivityException , AdapterException { try { SOAPBody soapBody = soapResponse . getSOAPBody ( ) ; Node childElem = null ; Iterator < ? > it = soapBody . getChildElements ( ) ; while ( it . hasNext ( ) ) { Node node = ( Node ) it . next ( ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE && node . getLocalName ( ) . equals ( getOutputMessageName ( ) ) ) { NodeList childNodes = node . getChildNodes ( ) ; for ( int i = 0 ; i < childNodes . getLength ( ) ; i ++ ) { if ( getResponsePartName ( ) . equals ( childNodes . item ( i ) . getLocalName ( ) ) ) { String content = childNodes . item ( i ) . getTextContent ( ) ; childElem = DomHelper . toDomNode ( content ) ; } } } } if ( childElem == null ) throw new SOAPException ( "SOAP body child element not found" ) ; SOAPHeader header = soapResponse . getSOAPHeader ( ) ; if ( header != null ) { extractSoapResponseHeaders ( header ) ; } return childElem ; } catch ( Exception ex ) { throw new ActivityException ( ex . getMessage ( ) , ex ) ; } }
Unwrap the SOAP response into a DOM Node .
13,737
public void applyImplicitParameters ( ReaderContext context , Operation operation , Method method ) { final ApiImplicitParams implicitParams = method . getAnnotation ( ApiImplicitParams . class ) ; if ( implicitParams != null && implicitParams . value ( ) . length > 0 ) { for ( ApiImplicitParam param : implicitParams . value ( ) ) { final Parameter p = readImplicitParam ( context . getSwagger ( ) , param ) ; if ( p != null ) { if ( p instanceof BodyParameter && param . format ( ) != null ) p . getVendorExtensions ( ) . put ( "format" , param . format ( ) ) ; operation . parameter ( p ) ; } } } }
Implemented to allow loading of custom types using CloudClassLoader .
13,738
private String translateType ( String type , Map < String , String > attrs ) { String translated = type . toLowerCase ( ) ; if ( "select" . equals ( type ) ) translated = "radio" ; else if ( "boolean" . equals ( type ) ) translated = "checkbox" ; else if ( "list" . equals ( type ) ) { translated = "picklist" ; String lbl = attrs . get ( "label" ) ; if ( lbl == null ) lbl = attrs . get ( "name" ) ; if ( "Output Documents" . equals ( lbl ) ) { attrs . put ( "label" , "Documents" ) ; attrs . put ( "unselectedLabel" , "Read-Only" ) ; attrs . put ( "selectedLabel" , "Writable" ) ; } } else if ( "hyperlink" . equals ( type ) ) { if ( attrs . containsKey ( "url" ) ) translated = "link" ; else translated = "text" ; } else if ( "rule" . equals ( type ) ) { if ( "EXPRESSION" . equals ( attrs . get ( "type" ) ) ) { translated = "expression" ; } else if ( "TRANSFORM" . equals ( attrs . get ( "type" ) ) ) { translated = "edit" ; attrs . put ( "label" , "Transform" ) ; } else { translated = "edit" ; attrs . put ( "label" , "Script" ) ; } attrs . remove ( "type" ) ; } else if ( "Java" . equals ( attrs . get ( "name" ) ) ) { translated = "edit" ; } else { String source = attrs . get ( "source" ) ; if ( "Process" . equals ( source ) ) { translated = "asset" ; attrs . put ( "source" , "proc" ) ; } else if ( "TaskTemplates" . equals ( source ) ) { translated = "asset" ; attrs . put ( "source" , "task" ) ; } else if ( "RuleSets" . equals ( source ) ) { String format = attrs . get ( "type" ) ; if ( format != null ) { String exts = "" ; String [ ] formats = format . split ( "," ) ; for ( int i = 0 ; i < formats . length ; i ++ ) { String ext = Asset . getFileExtension ( formats [ i ] ) ; if ( ext != null ) { if ( exts . length ( ) > 0 ) exts += "," ; exts += ext . substring ( 1 ) ; } } if ( exts . length ( ) > 0 ) { translated = "asset" ; attrs . put ( "source" , exts ) ; } } } } return translated ; }
Translate widget type .
13,739
private void adjustWidgets ( String implCategory ) { Map < Integer , Widget > companions = new HashMap < > ( ) ; for ( int i = 0 ; i < widgets . size ( ) ; i ++ ) { Widget widget = widgets . get ( i ) ; if ( "expression" . equals ( widget . type ) || ( "edit" . equals ( widget . type ) && ! "Java" . equals ( widget . name ) ) ) { Widget companion = new Widget ( "SCRIPT" , "dropdown" ) ; companion . setAttribute ( "label" , "Language" ) ; companion . options = Arrays . asList ( widget . getAttribute ( "languages" ) . split ( "," ) ) ; if ( companion . options . contains ( "Groovy" ) ) companion . setAttribute ( "default" , "Groovy" ) ; else if ( companion . options . contains ( "Kotlin Script" ) ) companion . setAttribute ( "default" , "Kotlin Script" ) ; String section = widget . getAttribute ( "section" ) ; if ( section != null ) companion . setAttribute ( "section" , section ) ; companions . put ( i , companion ) ; } } int offset = 0 ; for ( int idx : companions . keySet ( ) ) { widgets . add ( idx + offset , companions . get ( idx ) ) ; offset ++ ; } }
Adds companion widgets as needed .
13,740
public static String substitute ( String input , Map < String , Object > values ) { StringBuilder output = new StringBuilder ( input . length ( ) ) ; int index = 0 ; Matcher matcher = SUBST_PATTERN . matcher ( input ) ; while ( matcher . find ( ) ) { String match = matcher . group ( ) ; output . append ( input . substring ( index , matcher . start ( ) ) ) ; Object value = values . get ( match . substring ( 2 , match . length ( ) - 2 ) ) ; output . append ( value == null ? "" : String . valueOf ( value ) ) ; index = matcher . end ( ) ; } output . append ( input . substring ( index ) ) ; return output . toString ( ) ; }
Simple substitution mechanism . Missing values substituted with empty string .
13,741
protected String extractFormData ( JSONObject datadoc ) throws ActivityException , JSONException { String varstring = this . getAttributeValue ( TaskActivity . ATTRIBUTE_TASK_VARIABLES ) ; List < String [ ] > parsed = StringHelper . parseTable ( varstring , ',' , ';' , 5 ) ; for ( String [ ] one : parsed ) { String varname = one [ 0 ] ; String displayOption = one [ 2 ] ; if ( displayOption . equals ( TaskActivity . VARIABLE_DISPLAY_NOTDISPLAYED ) ) continue ; if ( displayOption . equals ( TaskActivity . VARIABLE_DISPLAY_READONLY ) ) continue ; if ( varname . startsWith ( "#{" ) || varname . startsWith ( "${" ) ) continue ; String data = datadoc . has ( varname ) ? datadoc . getString ( varname ) : null ; setDataToVariable ( varname , data ) ; } return null ; }
This method is used to extract data from the message received from the task manager . The method updates all variables specified as non - readonly
13,742
public void onStartup ( ) throws StartupException { try { Map < String , Properties > fileListeners = getFileListeners ( ) ; for ( String listenerName : fileListeners . keySet ( ) ) { Properties listenerProps = fileListeners . get ( listenerName ) ; String listenerClassName = listenerProps . getProperty ( "ClassName" ) ; logger . info ( "Registering File Listener: " + listenerName + " Class: " + listenerClassName ) ; FileListener listener = getFileListenerInstance ( listenerClassName ) ; listener . setName ( listenerName ) ; registeredFileListeners . put ( listenerName , listener ) ; listener . listen ( listenerProps ) ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; logger . severeException ( ex . getMessage ( ) , ex ) ; throw new StartupException ( ex . getMessage ( ) ) ; } }
Startup the file listeners .
13,743
public void onShutdown ( ) { for ( String listenerName : registeredFileListeners . keySet ( ) ) { logger . info ( "Deregistering File Listener: " + listenerName ) ; FileListener listener = registeredFileListeners . get ( listenerName ) ; listener . stopListening ( ) ; } }
Shutdown the file listeners .
13,744
public boolean hasRole ( String roleName ) { if ( roles != null ) { for ( String r : roles ) { if ( r . equals ( roleName ) ) return true ; } } return false ; }
Check whether the group has the specified role .
13,745
public boolean isWorkActivity ( Long pWorkId ) { if ( this . activities == null ) { return false ; } for ( int i = 0 ; i < activities . size ( ) ; i ++ ) { if ( pWorkId . longValue ( ) == activities . get ( i ) . getId ( ) . longValue ( ) ) { return true ; } } return false ; }
checks if the passed in workId is Activity
13,746
public Process getSubProcessVO ( Long id ) { if ( this . getId ( ) != null && this . getId ( ) . equals ( id ) ) return this ; if ( this . subprocesses == null ) return null ; for ( Process ret : subprocesses ) { if ( ret . getId ( ) . equals ( id ) ) return ret ; } return null ; }
returns the process VO identified by the passed in work id It is also possible the sub process is referencing self .
13,747
public Activity getActivityVO ( Long pWorkId ) { if ( this . activities == null ) { return null ; } for ( int i = 0 ; i < activities . size ( ) ; i ++ ) { if ( pWorkId . longValue ( ) == activities . get ( i ) . getId ( ) . longValue ( ) ) { return activities . get ( i ) ; } } return null ; }
Returns the Activity VO
13,748
public Transition getWorkTransitionVO ( Long pWorkTransId ) { if ( this . transitions == null ) { return null ; } for ( int i = 0 ; i < transitions . size ( ) ; i ++ ) { if ( pWorkTransId . longValue ( ) == transitions . get ( i ) . getId ( ) . longValue ( ) ) { return transitions . get ( i ) ; } } return null ; }
Returns the WorkTransitionVO
13,749
public Transition getTransition ( Long fromId , Integer eventType , String completionCode ) { Transition ret = null ; for ( Transition transition : getTransitions ( ) ) { if ( transition . getFromId ( ) . equals ( fromId ) && transition . match ( eventType , completionCode ) ) { if ( ret == null ) ret = transition ; else { throw new IllegalStateException ( "Multiple matching work transitions when one expected:\n" + " processId: " + getId ( ) + " fromId: " + fromId + " eventType: " + eventType + "compCode: " + completionCode ) ; } } } return ret ; }
Finds one work transition for this process matching the specified parameters
13,750
public List < Transition > getTransitions ( Long fromWorkId , Integer eventType , String completionCode ) { List < Transition > allTransitions = getAllTransitions ( fromWorkId ) ; List < Transition > returnSet = findTransitions ( allTransitions , eventType , completionCode ) ; if ( returnSet . size ( ) > 0 ) return returnSet ; boolean noLabelIsDefault = getTransitionWithNoLabel ( ) . equals ( TRANSITION_ON_DEFAULT ) ; if ( noLabelIsDefault ) returnSet = findTransitions ( allTransitions , eventType , null ) ; else returnSet = findTransitions ( allTransitions , eventType , ActivityResultCodeConstant . RESULT_DEFAULT ) ; if ( returnSet . size ( ) > 0 ) return returnSet ; if ( eventType . equals ( EventType . FINISH ) ) { returnSet = new ArrayList < Transition > ( ) ; for ( Transition trans : allTransitions ) { if ( trans . getEventType ( ) . equals ( EventType . RESUME ) ) returnSet . add ( trans ) ; } } return returnSet ; }
Finds the work transitions from the given activity that match the event type and completion code . A DEFAULT completion code matches any completion code if and only if there is no other matches
13,751
public Transition getTransition ( Long id ) { for ( Transition transition : getTransitions ( ) ) { if ( transition . getId ( ) . equals ( id ) ) return transition ; } return null ; }
Find a work transition based on its id value
13,752
public Activity getActivityById ( String logicalId ) { for ( Activity activityVO : getActivities ( ) ) { if ( activityVO . getLogicalId ( ) . equals ( logicalId ) ) { activityVO . setProcessName ( getName ( ) ) ; return activityVO ; } } for ( Process subProc : this . subprocesses ) { for ( Activity activityVO : subProc . getActivities ( ) ) { if ( activityVO . getLogicalId ( ) . equals ( logicalId ) ) { activityVO . setProcessName ( getName ( ) + ":" + subProc . getName ( ) ) ; return activityVO ; } } } return null ; }
Also searches subprocs .
13,753
public byte [ ] postBytes ( byte [ ] content ) throws IOException { if ( ! connection . isOpen ( ) ) connection . open ( ) ; connection . prepare ( "POST" ) ; OutputStream os = connection . getOutputStream ( ) ; os . write ( content ) ; response = connection . readInput ( ) ; os . close ( ) ; return getResponseBytes ( ) ; }
Perform an HTTP POST request to the URL .
13,754
public byte [ ] getBytes ( ) throws IOException { if ( ! connection . isOpen ( ) ) connection . open ( ) ; connection . prepare ( "GET" ) ; response = connection . readInput ( ) ; return getResponseBytes ( ) ; }
Perform an HTTP GET request against the URL .
13,755
public String put ( File file ) throws IOException { if ( ! connection . isOpen ( ) ) connection . open ( ) ; connection . prepare ( "PUT" ) ; String contentType = connection . getHeader ( "Content-Type" ) ; if ( contentType == null ) contentType = connection . getHeader ( "content-type" ) ; if ( contentType == null || contentType . isEmpty ( ) ) { connection . setHeader ( "Content-Type" , "application/octet-stream" ) ; } OutputStream outStream = connection . getOutputStream ( ) ; InputStream inStream = new FileInputStream ( file ) ; byte [ ] buf = new byte [ 1024 ] ; int len = 0 ; while ( len != - 1 ) { len = inStream . read ( buf ) ; if ( len > 0 ) outStream . write ( buf , 0 , len ) ; } inStream . close ( ) ; outStream . close ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( connection . getConnection ( ) . getInputStream ( ) ) ) ; StringBuffer responseBuffer = new StringBuffer ( ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { responseBuffer . append ( line ) . append ( '\n' ) ; } reader . close ( ) ; connection . getConnection ( ) . disconnect ( ) ; response = new HttpResponse ( responseBuffer . toString ( ) . getBytes ( ) ) ; response . setCode ( connection . getConnection ( ) . getResponseCode ( ) ) ; if ( response . getCode ( ) < 200 || response . getCode ( ) >= 300 ) { response . setMessage ( connection . getConnection ( ) . getResponseMessage ( ) ) ; throw new IOException ( "Error uploading file: " + response . getCode ( ) + " -- " + response . getMessage ( ) ) ; } return getResponse ( ) ; }
Upload a text file to the destination URL
13,756
public byte [ ] deleteBytes ( byte [ ] content ) throws IOException { if ( ! connection . isOpen ( ) ) connection . open ( ) ; connection . prepare ( "DELETE" ) ; OutputStream os = null ; if ( content != null ) { connection . getConnection ( ) . setDoOutput ( true ) ; os = connection . getOutputStream ( ) ; os . write ( content ) ; } response = connection . readInput ( ) ; if ( os != null ) os . close ( ) ; return getResponseBytes ( ) ; }
Perform an HTTP DELETE request to the URL .
13,757
public String [ ] getDistinctEventLogEventSources ( ) throws DataAccessException , EventException { TransactionWrapper transaction = null ; EngineDataAccessDB edao = new EngineDataAccessDB ( ) ; try { transaction = edao . startTransaction ( ) ; return edao . getDistinctEventLogEventSources ( ) ; } catch ( SQLException e ) { throw new EventException ( "Failed to notify events" , e ) ; } finally { edao . stopTransaction ( transaction ) ; } }
Method that returns distinct event log sources
13,758
public VariableInstance setVariableInstance ( Long procInstId , String name , Object value ) throws DataAccessException { TransactionWrapper transaction = null ; EngineDataAccessDB edao = new EngineDataAccessDB ( ) ; try { transaction = edao . startTransaction ( ) ; VariableInstance varInst = edao . getVariableInstance ( procInstId , name ) ; if ( varInst != null ) { if ( value instanceof String ) varInst . setStringValue ( ( String ) value ) ; else varInst . setData ( value ) ; edao . updateVariableInstance ( varInst ) ; } else { if ( value != null ) { ProcessInstance procInst = edao . getProcessInstance ( procInstId ) ; Process process = null ; if ( procInst . getProcessInstDefId ( ) > 0L ) process = ProcessCache . getProcessInstanceDefiniton ( procInst . getProcessId ( ) , procInst . getProcessInstDefId ( ) ) ; if ( process == null ) process = ProcessCache . getProcess ( procInst . getProcessId ( ) ) ; Variable variable = process . getVariable ( name ) ; if ( variable == null ) { throw new DataAccessException ( "Variable " + name + " is not defined for process " + process . getId ( ) ) ; } varInst = new VariableInstance ( ) ; varInst . setName ( name ) ; varInst . setVariableId ( variable . getId ( ) ) ; varInst . setType ( variable . getType ( ) ) ; if ( value instanceof String ) varInst . setStringValue ( ( String ) value ) ; else varInst . setData ( value ) ; edao . createVariableInstance ( varInst , procInstId ) ; } else varInst = null ; } return varInst ; } catch ( SQLException e ) { throw new DataAccessException ( - 1 , "Failed to set variable value" , e ) ; } finally { edao . stopTransaction ( transaction ) ; } }
create or update variable instance value . This does not take care of checking for embedded processes . For document variables the value must be DocumentReference not the document content
13,759
public void sendDelayEventsToWaitActivities ( String masterRequestId ) throws DataAccessException , ProcessException { TransactionWrapper transaction = null ; EngineDataAccessDB edao = new EngineDataAccessDB ( ) ; try { transaction = edao . startTransaction ( ) ; List < ProcessInstance > procInsts = edao . getProcessInstancesByMasterRequestId ( masterRequestId , null ) ; for ( ProcessInstance pi : procInsts ) { List < ActivityInstance > actInsts = edao . getActivityInstancesForProcessInstance ( pi . getId ( ) ) ; for ( ActivityInstance ai : actInsts ) { if ( ai . getStatusCode ( ) == WorkStatus . STATUS_WAITING . intValue ( ) ) { InternalEvent event = InternalEvent . createActivityDelayMessage ( ai , masterRequestId ) ; this . sendInternalEvent ( event , edao ) ; } } } } catch ( SQLException e ) { throw new ProcessException ( 0 , "Failed to send delay event wait activities runtime" , e ) ; } finally { edao . stopTransaction ( transaction ) ; } }
This is for regression tester only .
13,760
private boolean isProcessInstanceResumable ( ProcessInstance pInstance ) { int statusCd = pInstance . getStatusCode ( ) . intValue ( ) ; if ( statusCd == WorkStatus . STATUS_COMPLETED . intValue ( ) ) { return false ; } else if ( statusCd == WorkStatus . STATUS_CANCELLED . intValue ( ) ) { return false ; } return true ; }
Checks if the process inst is resumable
13,761
public ProcessInstance getProcessInstance ( Long procInstId ) throws ProcessException , DataAccessException { TransactionWrapper transaction = null ; EngineDataAccessDB edao = new EngineDataAccessDB ( ) ; try { transaction = edao . startTransaction ( ) ; return edao . getProcessInstance ( procInstId ) ; } catch ( SQLException e ) { throw new ProcessException ( 0 , "Failed to get process instance" , e ) ; } finally { edao . stopTransaction ( transaction ) ; } }
Returns the ProcessInstance identified by the passed in Id
13,762
public List < ProcessInstance > getProcessInstances ( String masterRequestId , String processName ) throws ProcessException , DataAccessException { TransactionWrapper transaction = null ; EngineDataAccessDB edao = new EngineDataAccessDB ( ) ; try { Process procdef = ProcessCache . getProcess ( processName , 0 ) ; if ( procdef == null ) return null ; transaction = edao . startTransaction ( ) ; return edao . getProcessInstancesByMasterRequestId ( masterRequestId , procdef . getId ( ) ) ; } catch ( SQLException e ) { throw new ProcessException ( 0 , "Failed to remove event waits" , e ) ; } finally { edao . stopTransaction ( transaction ) ; } }
Returns the process instances by process name and master request ID .
13,763
public List < ActivityInstance > getActivityInstances ( String masterRequestId , String processName , String activityLogicalId ) throws ProcessException , DataAccessException { TransactionWrapper transaction = null ; EngineDataAccessDB edao = new EngineDataAccessDB ( ) ; try { Process procdef = ProcessCache . getProcess ( processName , 0 ) ; if ( procdef == null ) return null ; Activity actdef = procdef . getActivityByLogicalId ( activityLogicalId ) ; if ( actdef == null ) return null ; transaction = edao . startTransaction ( ) ; List < ActivityInstance > actInstList = new ArrayList < ActivityInstance > ( ) ; List < ProcessInstance > procInstList = edao . getProcessInstancesByMasterRequestId ( masterRequestId , procdef . getId ( ) ) ; if ( procInstList . size ( ) == 0 ) return actInstList ; for ( ProcessInstance pi : procInstList ) { List < ActivityInstance > actInsts = edao . getActivityInstances ( actdef . getId ( ) , pi . getId ( ) , false , false ) ; for ( ActivityInstance ai : actInsts ) { actInstList . add ( ai ) ; } } return actInstList ; } catch ( SQLException e ) { throw new ProcessException ( 0 , "Failed to remove event waits" , e ) ; } finally { edao . stopTransaction ( transaction ) ; } }
Returns the activity instances by process name activity logical ID and master request ID .
13,764
public ActivityInstance getActivityInstance ( Long pActivityInstId ) throws ProcessException , DataAccessException { ActivityInstance ai ; TransactionWrapper transaction = null ; EngineDataAccessDB edao = new EngineDataAccessDB ( ) ; try { transaction = edao . startTransaction ( ) ; ai = edao . getActivityInstance ( pActivityInstId ) ; } catch ( SQLException e ) { throw new ProcessException ( 0 , "Failed to get activity instance" , e ) ; } finally { edao . stopTransaction ( transaction ) ; } return ai ; }
Returns the ActivityInstance identified by the passed in Id
13,765
public TransitionInstance getWorkTransitionInstance ( Long pId ) throws DataAccessException , ProcessException { TransitionInstance wti ; TransactionWrapper transaction = null ; EngineDataAccessDB edao = new EngineDataAccessDB ( ) ; try { transaction = edao . startTransaction ( ) ; wti = edao . getWorkTransitionInstance ( pId ) ; } catch ( SQLException e ) { throw new ProcessException ( 0 , "Failed to get work transition instance" , e ) ; } finally { edao . stopTransaction ( transaction ) ; } return wti ; }
Returns the WorkTransitionVO based on the passed in params
13,766
public JSONObject getJson ( ) throws JSONException { JSONObject json = create ( ) ; if ( value != null ) json . put ( "value" , value ) ; if ( label != null ) json . put ( "label" , label ) ; if ( type != null ) json . put ( "type" , type ) ; if ( display != null ) json . put ( "display" , display . toString ( ) ) ; if ( sequence != 0 ) json . put ( "sequence" , sequence ) ; if ( indexKey != null ) json . put ( "indexKey" , indexKey ) ; return json ; }
expects to be a json object named name so does not include name
13,767
@ ApiModelProperty ( hidden = true ) public static Display getDisplay ( String option ) { if ( "Optional" . equals ( option ) ) return Display . Optional ; else if ( "Required" . equals ( option ) ) return Display . Required ; else if ( "Read Only" . equals ( option ) ) return Display . ReadOnly ; else if ( "Hidden" . equals ( option ) ) return Display . Hidden ; else return null ; }
Maps Designer display option to Display type .
13,768
public static Display getDisplay ( int mode ) { if ( mode == 0 ) return Display . Required ; else if ( mode == 1 ) return Display . Optional ; else if ( mode == 2 ) return Display . ReadOnly ; else if ( mode == 3 ) return Display . Hidden ; else return null ; }
Maps VariableVO display mode to Display type .
13,769
public void onStartup ( ) throws StartupException { if ( monitor == null ) { monitor = this ; thread = new Thread ( ) { public void run ( ) { this . setName ( "UserGroupMonitor-thread" ) ; monitor . start ( ) ; } } ; thread . start ( ) ; } }
Invoked when the server starts up .
13,770
public void sendTextMessage ( String queueName , String message , int delaySeconds ) throws NamingException , JMSException , ServiceLocatorException { sendTextMessage ( null , queueName , message , delaySeconds , null ) ; }
Sends a JMS text message to a local queue .
13,771
public void sendTextMessage ( String contextUrl , String queueName , String message , int delaySeconds , String correlationId ) throws NamingException , JMSException , ServiceLocatorException { if ( logger . isDebugEnabled ( ) ) logger . debug ( "Send JMS message: " + message ) ; if ( mdwMessageProducer != null ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "Send JMS message: queue " + queueName + " corrId " + correlationId + " delay " + delaySeconds ) ; mdwMessageProducer . sendMessage ( message , queueName , correlationId , delaySeconds , DeliveryMode . NON_PERSISTENT ) ; } else { QueueConnection connection = null ; QueueSession session = null ; QueueSender sender = null ; Queue queue = null ; try { QueueConnectionFactory connectionFactory = getQueueConnectionFactory ( contextUrl ) ; connection = connectionFactory . createQueueConnection ( ) ; session = connection . createQueueSession ( false , QueueSession . AUTO_ACKNOWLEDGE ) ; if ( contextUrl == null ) queue = getQueue ( session , queueName ) ; else queue = getQueue ( contextUrl , queueName ) ; if ( queue == null ) queue = session . createQueue ( queueName ) ; sender = session . createSender ( queue ) ; TextMessage textMessage = session . createTextMessage ( message ) ; if ( delaySeconds > 0 ) jmsProvider . setMessageDelay ( sender , textMessage , delaySeconds ) ; if ( correlationId != null ) textMessage . setJMSCorrelationID ( correlationId ) ; connection . start ( ) ; if ( contextUrl == null ) sender . send ( textMessage , DeliveryMode . NON_PERSISTENT , sender . getPriority ( ) , sender . getTimeToLive ( ) ) ; else sender . send ( textMessage ) ; } finally { closeResources ( connection , session , sender ) ; } } }
Sends a JMS text message .
13,772
public Queue getQueue ( Session session , String commonName ) throws ServiceLocatorException { Queue queue = ( Queue ) queueCache . get ( commonName ) ; if ( queue == null ) { try { String name = namingProvider . qualifyJmsQueueName ( commonName ) ; queue = jmsProvider . getQueue ( session , namingProvider , name ) ; if ( queue != null ) queueCache . put ( commonName , queue ) ; } catch ( Exception ex ) { throw new ServiceLocatorException ( - 1 , ex . getMessage ( ) , ex ) ; } } return queue ; }
Uses the container - specific qualifier to look up a JMS queue .
13,773
public Queue getQueue ( String contextUrl , String queueName ) throws ServiceLocatorException { try { String jndiName = null ; if ( contextUrl == null ) { jndiName = namingProvider . qualifyJmsQueueName ( queueName ) ; } else { jndiName = queueName ; } return ( Queue ) namingProvider . lookup ( contextUrl , jndiName , Queue . class ) ; } catch ( Exception ex ) { throw new ServiceLocatorException ( - 1 , ex . getMessage ( ) , ex ) ; } }
Looks up and returns a JMS queue .
13,774
public void broadcastTextMessage ( String topicName , String textMessage , int delaySeconds ) throws NamingException , JMSException , ServiceLocatorException { if ( mdwMessageProducer != null ) { mdwMessageProducer . broadcastMessageToTopic ( topicName , textMessage ) ; } else { TopicConnectionFactory tFactory = null ; TopicConnection tConnection = null ; TopicSession tSession = null ; TopicPublisher tPublisher = null ; try { tFactory = getTopicConnectionFactory ( null ) ; tConnection = tFactory . createTopicConnection ( ) ; tSession = tConnection . createTopicSession ( false , Session . AUTO_ACKNOWLEDGE ) ; Topic topic = getTopic ( topicName ) ; tPublisher = tSession . createPublisher ( topic ) ; TextMessage message = tSession . createTextMessage ( ) ; tConnection . start ( ) ; message . setText ( textMessage ) ; tPublisher . publish ( message , DeliveryMode . PERSISTENT , TextMessage . DEFAULT_DELIVERY_MODE , TextMessage . DEFAULT_TIME_TO_LIVE ) ; } finally { closeResources ( tConnection , tSession , tPublisher ) ; } } }
Sends the passed in text message to a local topic
13,775
public ResultSet runSelect ( String logMessage , String query , Object [ ] arguments ) throws SQLException { long before = System . currentTimeMillis ( ) ; try { return runSelect ( query , arguments ) ; } finally { if ( logger . isDebugEnabled ( ) ) { long after = System . currentTimeMillis ( ) ; logger . debug ( logMessage + " (" + ( after - before ) + " ms): " + DbAccess . substitute ( query , arguments ) ) ; } } }
Ordinarily db query logging is at TRACE level . Use this method to log queries at DEBUG level .
13,776
protected KieBase getKnowledgeBase ( String name , String version ) throws ActivityException { return getKnowledgeBase ( name , version , null ) ; }
Get knowledge base with no modifiers .
13,777
protected ClassLoader getClassLoader ( ) { ClassLoader loader = null ; Package pkg = PackageCache . getProcessPackage ( getProcessId ( ) ) ; if ( pkg != null ) { loader = pkg . getCloudClassLoader ( ) ; } if ( loader == null ) { loader = getClass ( ) . getClassLoader ( ) ; } return loader ; }
Get the class loader based on package bundle version spec default is mdw - workflow loader
13,778
public List < String > getRoles ( String path ) { List < String > roles = super . getRoles ( path ) ; roles . add ( Role . ASSET_DESIGN ) ; return roles ; }
ASSET_DESIGN role can PUT in - memory config for running tests .
13,779
public String toApiImport ( String name ) { if ( ! apiPackage ( ) . isEmpty ( ) ) return apiPackage ( ) ; else if ( trimApiPaths ) return trimmedPaths . get ( name ) . substring ( 1 ) . replace ( '/' , '.' ) ; else return super . toApiImport ( name ) ; }
We use this for API package in our templates when trimmedPaths is true .
13,780
public static List < File > listOverrideFiles ( String type ) throws IOException { List < File > files = new ArrayList < File > ( ) ; if ( getMdw ( ) . getOverrideRoot ( ) . isDirectory ( ) ) { File dir = new File ( getMdw ( ) . getOverrideRoot ( ) + "/" + type ) ; if ( dir . isDirectory ( ) ) addFiles ( files , dir , type ) ; } return files ; }
Recursively list override files . Assumes dir path == ext == type .
13,781
private int search ( int startLine , boolean backward ) throws IOException { search = search . toLowerCase ( ) ; try ( Stream < String > stream = Files . lines ( path ) ) { if ( backward ) { int idx = - 1 ; if ( startLine > 0 ) idx = searchTo ( startLine - 1 , true ) ; if ( idx < 0 ) idx = searchFrom ( startLine , true ) ; return idx ; } else { int idx = searchFrom ( startLine ) ; if ( idx < 0 ) { idx = searchTo ( startLine - 1 ) ; } return idx ; } } catch ( UncheckedIOException ex ) { throw ex . getCause ( ) ; } }
Search pass locates line index of first match .
13,782
public String handleEventMessage ( String msg , Object msgdoc , Map < String , String > metainfo ) throws EventHandlerException { return null ; }
This is not used - the class extends ExternalEventHandlerBase only to get access to convenient methods
13,783
private static void initializeDynamicJavaAssets ( ) throws DataAccessException , IOException , CachingException { logger . info ( "Initializing Dynamic Java assets for Groovy..." ) ; for ( Asset java : AssetCache . getAssets ( Asset . JAVA ) ) { Package pkg = PackageCache . getAssetPackage ( java . getId ( ) ) ; String packageName = pkg == null ? null : JavaNaming . getValidPackageName ( pkg . getName ( ) ) ; File dir = createNeededDirs ( packageName ) ; String filename = dir + "/" + java . getName ( ) ; if ( filename . endsWith ( ".java" ) ) filename = filename . substring ( 0 , filename . length ( ) - 5 ) ; filename += ".groovy" ; File file = new File ( filename ) ; logger . mdwDebug ( " - writing " + file . getAbsoluteFile ( ) ) ; if ( file . exists ( ) ) file . delete ( ) ; String content = java . getStringContent ( ) ; if ( content != null ) { if ( Compatibility . hasCodeSubstitutions ( ) ) content = doCompatibilityCodeSubstitutions ( java . getLabel ( ) , content ) ; FileWriter writer = new FileWriter ( file ) ; writer . write ( content ) ; writer . close ( ) ; } } logger . info ( "Dynamic Java assets initialized for groovy." ) ; }
so that Groovy scripts can reference these assets during compilation
13,784
public JSONObject post ( String path , JSONObject content , Map < String , String > headers ) throws ServiceException , JSONException { String sub = getSegment ( path , 4 ) ; if ( "event" . equals ( sub ) ) { SlackEvent event = new SlackEvent ( content ) ; EventHandler eventHandler = getEventHandler ( event . getType ( ) , event ) ; if ( eventHandler == null ) { throw new ServiceException ( "Unsupported handler type: " + event . getType ( ) + ( event . getChannel ( ) == null ? "" : ( ":" + event . getChannel ( ) ) ) ) ; } return eventHandler . handleEvent ( event ) ; } else { SlackRequest request = new SlackRequest ( content ) ; String userId = getAuthUser ( headers ) ; String callbackId = request . getCallbackId ( ) ; if ( callbackId != null ) { int underscore = callbackId . lastIndexOf ( '_' ) ; if ( underscore > 0 ) { String handlerType = callbackId . substring ( 0 , underscore ) ; String id = callbackId . substring ( callbackId . lastIndexOf ( '/' ) + 1 ) ; ActionHandler actionHandler = getActionHandler ( handlerType , userId , id , request ) ; if ( actionHandler == null ) throw new ServiceException ( "Unsupported handler type: " + handlerType ) ; return actionHandler . handleRequest ( userId , id , request ) ; } } throw new ServiceException ( ServiceException . BAD_REQUEST , "Bad or missing callback_id" ) ; } }
Responds to requests from Slack .
13,785
public JSONObject get ( String path , Map < String , String > headers ) throws ServiceException , JSONException { String authUser = ( String ) headers . get ( Listener . AUTHENTICATED_USER_HEADER ) ; try { if ( authUser == null ) throw new ServiceException ( "Missing parameter: " + Listener . AUTHENTICATED_USER_HEADER ) ; UserServices userServices = ServiceLocator . getUserServices ( ) ; User userVO = userServices . getUser ( authUser ) ; if ( userVO == null ) throw new ServiceException ( HTTP_404_NOT_FOUND , "User not found: " + authUser ) ; return userVO . getJsonWithRoles ( ) ; } catch ( DataAccessException ex ) { throw new ServiceException ( ex . getCode ( ) , ex . getMessage ( ) , ex ) ; } catch ( Exception ex ) { throw new ServiceException ( "Error getting authenticated user: " + authUser , ex ) ; } }
Retrieve the current authenticated user .
13,786
public static String getEngineUrl ( String serverSpec ) throws NamingException { String url ; int at = serverSpec . indexOf ( '@' ) ; if ( at > 0 ) { url = serverSpec . substring ( at + 1 ) ; } else { int colonDashDash = serverSpec . indexOf ( "://" ) ; if ( colonDashDash > 0 ) { url = serverSpec ; } else { url = PropertyManager . getProperty ( PropertyNames . MDW_REMOTE_SERVER + "." + serverSpec ) ; if ( url == null ) throw new NamingException ( "Cannot find engine URL for " + serverSpec ) ; } } return url ; }
Returns engine URL for another server using server specification as input .
13,787
protected Object handleResult ( Result result ) throws ActivityException { ServiceValuesAccess serviceValues = getRuntimeContext ( ) . getServiceValues ( ) ; StatusResponse statusResponse ; if ( result . isError ( ) ) { logsevere ( "Validation error: " + result . getStatus ( ) . toString ( ) ) ; statusResponse = new StatusResponse ( result . getWorstCode ( ) , result . getStatus ( ) . getMessage ( ) ) ; String responseHeadersVarName = serviceValues . getResponseHeadersVariableName ( ) ; Map < String , String > responseHeaders = serviceValues . getResponseHeaders ( ) ; if ( responseHeaders == null ) { Variable responseHeadersVar = getMainProcessDefinition ( ) . getVariable ( responseHeadersVarName ) ; if ( responseHeadersVar == null ) throw new ActivityException ( "Missing response headers variable: " + responseHeadersVarName ) ; responseHeaders = new HashMap < > ( ) ; } responseHeaders . put ( Listener . METAINFO_HTTP_STATUS_CODE , String . valueOf ( statusResponse . getStatus ( ) . getCode ( ) ) ) ; setVariableValue ( responseHeadersVarName , responseHeaders ) ; } else { statusResponse = new StatusResponse ( com . centurylink . mdw . model . Status . OK , "Valid request" ) ; } String responseVariableName = serviceValues . getResponseVariableName ( ) ; Variable responseVariable = getMainProcessDefinition ( ) . getVariable ( responseVariableName ) ; if ( responseVariable == null ) throw new ActivityException ( "Missing response variable: " + responseVariableName ) ; Object responseObject ; if ( responseVariable . getType ( ) . equals ( Jsonable . class . getName ( ) ) ) responseObject = statusResponse ; else responseObject = serviceValues . fromJson ( responseVariableName , statusResponse . getJson ( ) ) ; setVariableValue ( responseVariableName , responseObject ) ; return ! result . isError ( ) ; }
Populates response variable with a default JSON status object . Can be overwritten by custom logic in a downstream activity or in a JsonRestService implementation .
13,788
private void deleteDynamicTemplates ( ) throws IOException { File codegenDir = new File ( getProjectDir ( ) + "/codegen" ) ; if ( codegenDir . exists ( ) ) { getOut ( ) . println ( "Deleting " + codegenDir ) ; new Delete ( codegenDir , true ) . run ( ) ; } File assetsDir = new File ( getProjectDir ( ) + "/assets" ) ; if ( assetsDir . exists ( ) ) { getOut ( ) . println ( "Deleting " + assetsDir ) ; new Delete ( assetsDir , true ) . run ( ) ; } File configuratorDir = new File ( getProjectDir ( ) + "/configurator" ) ; if ( configuratorDir . exists ( ) ) { getOut ( ) . println ( "Deleting " + configuratorDir ) ; new Delete ( configuratorDir , true ) . run ( ) ; } }
These will be retrieved just - in - time based on current mdw version .
13,789
public static void bulletinOff ( Bulletin bulletin , Level level , String message ) { if ( bulletin == null ) return ; synchronized ( bulletins ) { bulletins . remove ( bulletin . getId ( ) , bulletin ) ; } try { WebSocketMessenger . getInstance ( ) . send ( "SystemMessage" , bulletin . off ( message ) . getJson ( ) . toString ( ) ) ; } catch ( IOException ex ) { logger . warnException ( "Unable to publish to websocket" , ex ) ; } }
Should be the same instance or have the same id as the bulletinOn message .
13,790
private static boolean exclude ( String host , java . nio . file . Path path ) { List < PathMatcher > exclusions = getExcludes ( host ) ; if ( exclusions == null && host != null ) { exclusions = getExcludes ( null ) ; } if ( exclusions != null ) { for ( PathMatcher matcher : exclusions ) { if ( matcher . matches ( path ) ) return true ; } } return false ; }
Checks for matching exclude patterns .
13,791
public String getMdwVersion ( ) throws IOException { if ( mdwVersion == null ) { YamlProperties yaml = getProjectYaml ( ) ; if ( yaml != null ) { mdwVersion = yaml . getString ( Props . ProjectYaml . MDW_VERSION ) ; } } return mdwVersion ; }
Reads from project . yaml
13,792
public String findMdwVersion ( boolean snapshots ) throws IOException { URL url = new URL ( getReleasesUrl ( ) + MDW_COMMON_PATH ) ; if ( snapshots ) url = new URL ( getSnapshotsUrl ( ) + MDW_COMMON_PATH ) ; Crawl crawl = new Crawl ( url , snapshots ) ; crawl . run ( ) ; if ( crawl . getReleases ( ) . size ( ) == 0 ) throw new IOException ( "Unable to locate MDW releases: " + url ) ; return crawl . getReleases ( ) . get ( crawl . getReleases ( ) . size ( ) - 1 ) ; }
Crawls to find the latest stable version .
13,793
protected void initBaseAssetPackages ( ) throws IOException { baseAssetPackages = new ArrayList < > ( ) ; addBasePackages ( getAssetRoot ( ) , getAssetRoot ( ) ) ; if ( baseAssetPackages . isEmpty ( ) ) baseAssetPackages = Packages . DEFAULT_BASE_PACKAGES ; }
Checks for any existing packages . If none present adds the defaults .
13,794
public String getRelativePath ( File from , File to ) { Path fromPath = Paths . get ( from . getPath ( ) ) . normalize ( ) . toAbsolutePath ( ) ; Path toPath = Paths . get ( to . getPath ( ) ) . normalize ( ) . toAbsolutePath ( ) ; return fromPath . relativize ( toPath ) . toString ( ) . replace ( '\\' , '/' ) ; }
Returns to file or dir path relative to from dir . Result always uses forward slashes and has no trailing slash .
13,795
protected void downloadTemplates ( ProgressMonitor ... monitors ) throws IOException { File templateDir = getTemplateDir ( ) ; if ( ! templateDir . exists ( ) ) { if ( ! templateDir . mkdirs ( ) ) throw new IOException ( "Unable to create directory: " + templateDir . getAbsolutePath ( ) ) ; String templatesUrl = getTemplatesUrl ( ) ; getOut ( ) . println ( "Retrieving templates: " + templatesUrl ) ; File tempZip = Files . createTempFile ( "mdw-templates-" , ".zip" ) . toFile ( ) ; new Download ( new URL ( templatesUrl ) , tempZip ) . run ( monitors ) ; File tempDir = Files . createTempDirectory ( "mdw-templates-" ) . toFile ( ) ; new Unzip ( tempZip , tempDir , false ) . run ( ) ; File codegenDir = new File ( templateDir + "/codegen" ) ; new Copy ( new File ( tempDir + "/codegen" ) , codegenDir , true ) . run ( ) ; File assetsDir = new File ( templateDir + "/assets" ) ; new Copy ( new File ( tempDir + "/assets" ) , assetsDir , true ) . run ( ) ; } }
Downloads asset templates for codegen etc .
13,796
public Object onRequest ( ActivityRuntimeContext context , Object content , Map < String , String > headers , Object connection ) { if ( connection instanceof HttpConnection ) { HttpConnection httpConnection = ( HttpConnection ) connection ; Tracing tracing = TraceHelper . getTracing ( "mdw-adapter" ) ; HttpTracing httpTracing = HttpTracing . create ( tracing ) . toBuilder ( ) . clientParser ( new HttpClientParser ( ) { public < Req > void request ( HttpAdapter < Req , ? > adapter , Req req , SpanCustomizer customizer ) { customizer . name ( context . getActivity ( ) . oneLineName ( ) ) ; } } ) . build ( ) ; Tracer tracer = httpTracing . tracing ( ) . tracer ( ) ; handler = HttpClientHandler . create ( httpTracing , new ClientAdapter ( ) ) ; injector = httpTracing . tracing ( ) . propagation ( ) . injector ( ( httpRequest , key , value ) -> headers . put ( key , value ) ) ; span = handler . handleSend ( injector , new HttpRequest ( httpConnection ) ) ; scope = tracer . withSpanInScope ( span ) ; } return null ; }
Only for HTTP .
13,797
static TaskInstance createTaskInstance ( Long taskId , String masterRequestId , Long procInstId , String secOwner , Long secOwnerId , String title , String comments ) throws ServiceException , DataAccessException { return createTaskInstance ( taskId , masterRequestId , procInstId , secOwner , secOwnerId , title , comments , 0 , null , null ) ; }
Convenience method for below .
13,798
static TaskInstance createTaskInstance ( Long taskId , String masterOwnerId , String title , String comment , Instant due , Long userId , Long secondaryOwner ) throws ServiceException , DataAccessException { CodeTimer timer = new CodeTimer ( "createTaskInstance()" , true ) ; TaskTemplate task = TaskTemplateCache . getTaskTemplate ( taskId ) ; TaskInstance ti = createTaskInstance ( taskId , masterOwnerId , OwnerType . USER , userId , ( secondaryOwner != null ? OwnerType . DOCUMENT : null ) , secondaryOwner , task . getTaskName ( ) , title , comment , due , 0 ) ; TaskWorkflowHelper helper = new TaskWorkflowHelper ( ti ) ; if ( due != null ) { String alertIntervalString = task . getAttribute ( TaskAttributeConstant . ALERT_INTERVAL ) ; int alertInterval = StringHelper . isEmpty ( alertIntervalString ) ? 0 : Integer . parseInt ( alertIntervalString ) ; helper . scheduleTaskSlaEvent ( Date . from ( due ) , alertInterval , false ) ; } List < String > groups = helper . determineWorkgroups ( null ) ; if ( groups != null && groups . size ( ) > 0 ) new TaskDataAccess ( ) . setTaskInstanceGroups ( ti . getTaskInstanceId ( ) , StringHelper . toStringArray ( groups ) ) ; helper . notifyTaskAction ( TaskAction . CREATE , null , null ) ; helper . auditLog ( "Create" , "MDW" ) ; timer . stopAndLogTiming ( "" ) ; return ti ; }
This version is used by the task manager to create a task instance not associated with a process instance .
13,799
List < String > determineWorkgroups ( Map < String , String > indexes ) throws ServiceException { TaskTemplate taskTemplate = getTemplate ( ) ; String routingStrategyAttr = taskTemplate . getAttribute ( TaskAttributeConstant . ROUTING_STRATEGY ) ; if ( StringHelper . isEmpty ( routingStrategyAttr ) ) { return taskTemplate . getWorkgroups ( ) ; } else { try { RoutingStrategy strategy = TaskInstanceStrategyFactory . getRoutingStrategy ( routingStrategyAttr , OwnerType . PROCESS_INSTANCE . equals ( taskInstance . getOwnerType ( ) ) ? taskInstance . getOwnerId ( ) : null ) ; if ( strategy instanceof ParameterizedStrategy ) { populateStrategyParams ( ( ParameterizedStrategy ) strategy , getTemplate ( ) , taskInstance . getOwnerId ( ) , indexes ) ; } return strategy . determineWorkgroups ( taskTemplate , taskInstance ) ; } catch ( Exception ex ) { throw new ServiceException ( ex . getMessage ( ) , ex ) ; } } }
Determines a task instance s workgroups based on the defined strategy . If no strategy exists default to the workgroups defined in the task template .