idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
13,700 | 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 . | 69 | 4 |
13,701 | 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 . | 132 | 5 |
13,702 | 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 . | 278 | 13 |
13,703 | 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 . | 125 | 12 |
13,704 | 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 . | 150 | 12 |
13,705 | 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 . | 115 | 12 |
13,706 | 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 . | 58 | 12 |
13,707 | 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 . | 166 | 10 |
13,708 | public Output compile ( FileContext context , ImportStack importStack ) throws CompilationException { NativeFileContext nativeContext = convertToNativeContext ( context , importStack ) ; return compileFile ( nativeContext ) ; } | Compile a file context . | 44 | 6 |
13,709 | 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 | 81 | 5 |
13,710 | 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 . | 134 | 11 |
13,711 | 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 ( ) ; // id to escaped name map is for backward compatibility idToEscapedName . put ( logicalId , escape ( act . getName ( ) ) ) ; sync . setCompletionCode ( logicalId ) ; incomingTransitions . add ( sync ) ; } } return incomingTransitions ; } | reuse WorkTransitionVO for sync info | 194 | 9 |
13,712 | 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 . | 431 | 8 |
13,713 | protected Node unwrapSoapResponse ( SOAPMessage soapResponse ) throws ActivityException , AdapterException { try { // unwrap the soap content from the message 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" ) ; // extract soap response headers 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 . | 324 | 11 |
13,714 | @ Override public void applyImplicitParameters ( ReaderContext context , Operation operation , Method method ) { // copied from io.swagger.servlet.extensions.ServletReaderExtension 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 . | 184 | 14 |
13,715 | 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 { // asset-driven 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 . | 627 | 5 |
13,716 | private void adjustWidgets ( String implCategory ) { // adjust to add script language options param 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 . | 314 | 6 |
13,717 | 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 . | 170 | 11 |
13,718 | 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 | 219 | 27 |
13,719 | 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 . | 197 | 6 |
13,720 | 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 . | 70 | 6 |
13,721 | 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 . | 44 | 9 |
13,722 | 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 | 82 | 9 |
13,723 | public Process getSubProcessVO ( Long id ) { if ( this . getId ( ) != null && this . getId ( ) . equals ( id ) ) // Id field is null for instance definitions 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 . | 90 | 23 |
13,724 | 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 | 87 | 4 |
13,725 | 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 | 91 | 6 |
13,726 | 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 | 140 | 12 |
13,727 | 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 ; // look for default transition 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 ; // look for resume transition 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 | 251 | 36 |
13,728 | public Transition getTransition ( Long id ) { for ( Transition transition : getTransitions ( ) ) { if ( transition . getId ( ) . equals ( id ) ) return transition ; } return null ; // not found } | Find a work transition based on its id value | 47 | 9 |
13,729 | 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 . | 148 | 6 |
13,730 | 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 . | 83 | 10 |
13,731 | 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 . | 54 | 10 |
13,732 | 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 ( ) ) { /** * Default it to application/octet-stream if nothing has been specified */ 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 ( ' ' ) ; } 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 | 435 | 8 |
13,733 | 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 . | 117 | 12 |
13,734 | 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 | 109 | 7 |
13,735 | 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 | 426 | 31 |
13,736 | 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 . | 246 | 8 |
13,737 | 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 | 91 | 10 |
13,738 | 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 | 110 | 10 |
13,739 | @ Override 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 . | 160 | 12 |
13,740 | 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 . | 314 | 15 |
13,741 | 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 | 123 | 10 |
13,742 | 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 | 124 | 12 |
13,743 | 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 | 134 | 14 |
13,744 | @ 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 . | 94 | 8 |
13,745 | 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 . | 63 | 9 |
13,746 | public void onStartup ( ) throws StartupException { if ( monitor == null ) { monitor = this ; thread = new Thread ( ) { @ Override public void run ( ) { this . setName ( "UserGroupMonitor-thread" ) ; monitor . start ( ) ; } } ; thread . start ( ) ; } } | Invoked when the server starts up . | 69 | 8 |
13,747 | 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 . | 51 | 12 |
13,748 | 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 ) ; // } // catch(ServiceLocatorException ex) { // logger.severeException(ex.getMessage(), ex); // JMSException jmsEx = new JMSException(ex.getMessage()); // jmsEx.setLinkedException(ex); // throw jmsEx; } finally { closeResources ( connection , session , sender ) ; } } } | Sends a JMS text message . | 490 | 8 |
13,749 | 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 . | 128 | 15 |
13,750 | public Queue getQueue ( String contextUrl , String queueName ) throws ServiceLocatorException { try { String jndiName = null ; if ( contextUrl == null ) { jndiName = namingProvider . qualifyJmsQueueName ( queueName ) ; } else { jndiName = queueName ; // don't qualify remote queue names } 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 . | 128 | 9 |
13,751 | 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 { // if (logger.isDebugEnabled()) logger.debug("broadcast JMS // message: " + // textMessage); // cannot log above - causing recursive broadcasting tFactory = getTopicConnectionFactory ( null ) ; tConnection = tFactory . createTopicConnection ( ) ; tSession = tConnection . createTopicSession ( false , Session . AUTO_ACKNOWLEDGE ) ; Topic topic = getTopic ( topicName ) ; tPublisher = tSession . createPublisher ( topic ) ; // TODO: platform-independent delay // WLMessageProducer wlMessageProducer = // (WLMessageProducer)tPublisher; // long delayInMilliSec = 0; // if(pMinDelay > 0){ // delayInMilliSec = delaySeconds*1000; // } // wlMessageProducer.setTimeToDeliver(delayInMilliSec); TextMessage message = tSession . createTextMessage ( ) ; tConnection . start ( ) ; message . setText ( textMessage ) ; tPublisher . publish ( message , DeliveryMode . PERSISTENT , TextMessage . DEFAULT_DELIVERY_MODE , TextMessage . DEFAULT_TIME_TO_LIVE ) ; // }catch(ServiceLocatorException ex){ // ex.printStackTrace(); // never log exception here!!! infinite loop when publishing log // messages // throw new JMSException(ex.getMessage()); } finally { closeResources ( tConnection , tSession , tPublisher ) ; } } } | Sends the passed in text message to a local topic | 417 | 11 |
13,752 | 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 . | 109 | 21 |
13,753 | protected KieBase getKnowledgeBase ( String name , String version ) throws ActivityException { return getKnowledgeBase ( name , version , null ) ; } | Get knowledge base with no modifiers . | 33 | 7 |
13,754 | 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 | 79 | 17 |
13,755 | 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 . | 45 | 17 |
13,756 | @ Override 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 . | 80 | 16 |
13,757 | 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 . | 102 | 16 |
13,758 | 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 ) { // wrap search idx = searchTo ( startLine - 1 ) ; } return idx ; } } catch ( UncheckedIOException ex ) { throw ex . getCause ( ) ; } } | Search pass locates line index of first match . | 160 | 10 |
13,759 | @ Override 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 | 35 | 19 |
13,760 | 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 | 309 | 11 |
13,761 | 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 { // action/options request SlackRequest request = new SlackRequest ( content ) ; String userId = getAuthUser ( headers ) ; // TODO: ability to map request.getUser() to corresponding MDW user 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 . | 358 | 7 |
13,762 | @ Override public JSONObject get ( String path , Map < String , String > headers ) throws ServiceException , JSONException { // we trust this header value because only MDW can set it 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 . | 231 | 7 |
13,763 | 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 . | 146 | 12 |
13,764 | 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 ; // _type has not been set, so serialization would fail 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 . | 449 | 31 |
13,765 | 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 . | 205 | 16 |
13,766 | 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 . | 112 | 16 |
13,767 | private static boolean exclude ( String host , java . nio . file . Path path ) { List < PathMatcher > exclusions = getExcludes ( host ) ; if ( exclusions == null && host != null ) { exclusions = getExcludes ( null ) ; // check global config } if ( exclusions != null ) { for ( PathMatcher matcher : exclusions ) { if ( matcher . matches ( path ) ) return true ; } } return false ; } | Checks for matching exclude patterns . | 101 | 7 |
13,768 | 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 | 75 | 7 |
13,769 | 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 . | 143 | 10 |
13,770 | 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 . | 75 | 14 |
13,771 | 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 . | 99 | 23 |
13,772 | 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 . | 274 | 9 |
13,773 | @ Override 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 ) { // customize span name 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 . | 280 | 4 |
13,774 | 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 . | 79 | 7 |
13,775 | 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 ) ; } // create instance groups for template based tasks 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 ) ; // notification/observer/auto-assign 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 . | 360 | 20 |
13,776 | 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 . | 229 | 30 |
13,777 | public List < TaskAction > filterStandardActions ( List < TaskAction > standardTaskActions ) throws ServiceException , DataAccessException { CodeTimer timer = new CodeTimer ( "TaskManager.filterStandardTaskActions()" , true ) ; List < TaskAction > filteredTaskActions = standardTaskActions ; try { ActivityInstance activityInstance = getActivityInstance ( true ) ; if ( activityInstance != null ) { Long processInstanceId = activityInstance . getProcessInstanceId ( ) ; ProcessInstance processInstance = ServiceLocator . getWorkflowServices ( ) . getProcess ( processInstanceId ) ; if ( processInstance . isEmbedded ( ) ) { // remove RETRY since no default behavior is defined for inline tasks TaskAction retryAction = null ; for ( TaskAction taskAction : standardTaskActions ) { if ( taskAction . getTaskActionName ( ) . equalsIgnoreCase ( "Retry" ) ) retryAction = taskAction ; } if ( retryAction != null ) standardTaskActions . remove ( retryAction ) ; } Process processVO = null ; if ( processInstance . getProcessInstDefId ( ) > 0L ) processVO = ProcessCache . getProcessInstanceDefiniton ( processInstance . getProcessId ( ) , processInstance . getProcessInstDefId ( ) ) ; if ( processVO == null ) processVO = ProcessCache . getProcess ( processInstance . getProcessId ( ) ) ; if ( processInstance . isEmbedded ( ) ) processVO = processVO . getSubProcessVO ( new Long ( processInstance . getComment ( ) ) ) ; List < Transition > outgoingWorkTransVOs = processVO . getAllTransitions ( activityInstance . getActivityId ( ) ) ; boolean foundNullResultCode = false ; for ( Transition workTransVO : outgoingWorkTransVOs ) { Integer eventType = workTransVO . getEventType ( ) ; if ( ( eventType . equals ( EventType . FINISH ) || eventType . equals ( EventType . RESUME ) ) && workTransVO . getCompletionCode ( ) == null ) { foundNullResultCode = true ; break ; } } if ( ! foundNullResultCode ) { TaskAction cancelAction = null ; TaskAction completeAction = null ; for ( TaskAction taskAction : standardTaskActions ) { if ( taskAction . getTaskActionName ( ) . equalsIgnoreCase ( "Cancel" ) ) cancelAction = taskAction ; if ( taskAction . getTaskActionName ( ) . equalsIgnoreCase ( "Complete" ) ) completeAction = taskAction ; } if ( cancelAction != null ) standardTaskActions . remove ( cancelAction ) ; if ( completeAction != null ) standardTaskActions . remove ( completeAction ) ; } } } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; } timer . stopAndLogTiming ( "" ) ; return filteredTaskActions ; } | Filters according to what s applicable depending on the context of the task activity instance . | 633 | 17 |
13,778 | public List < TaskAction > getCustomActions ( ) throws ServiceException , DataAccessException { CodeTimer timer = new CodeTimer ( "getCustomActions()" , true ) ; List < TaskAction > dynamicTaskActions = new ArrayList < TaskAction > ( ) ; try { ActivityInstance activityInstance = getActivityInstance ( true ) ; if ( activityInstance != null ) { Long processInstanceId = activityInstance . getProcessInstanceId ( ) ; ProcessInstance processInstance = ServiceLocator . getWorkflowServices ( ) . getProcess ( processInstanceId ) ; Process processVO = null ; if ( processInstance . getProcessInstDefId ( ) > 0L ) processVO = ProcessCache . getProcessInstanceDefiniton ( processInstance . getProcessId ( ) , processInstance . getProcessInstDefId ( ) ) ; if ( processVO == null ) processVO = ProcessCache . getProcess ( processInstance . getProcessId ( ) ) ; if ( processInstance . isEmbedded ( ) ) processVO = processVO . getSubProcessVO ( new Long ( processInstance . getComment ( ) ) ) ; List < Transition > outgoingWorkTransVOs = processVO . getAllTransitions ( activityInstance . getActivityId ( ) ) ; for ( Transition workTransVO : outgoingWorkTransVOs ) { String resultCode = workTransVO . getCompletionCode ( ) ; if ( resultCode != null ) { Integer eventType = workTransVO . getEventType ( ) ; if ( eventType . equals ( EventType . FINISH ) || eventType . equals ( EventType . RESUME ) || TaskAction . FORWARD . equals ( resultCode ) ) { TaskAction taskAction = new TaskAction ( ) ; taskAction . setTaskActionName ( resultCode ) ; taskAction . setCustom ( true ) ; dynamicTaskActions . add ( taskAction ) ; } } } } } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; } timer . stopAndLogTiming ( "" ) ; return dynamicTaskActions ; } | Gets the custom task actions associated with a task instance as determined by the result codes for the possible outgoing work transitions from the associated activity . | 443 | 28 |
13,779 | protected URL getRoutingStrategyDestination ( Object request , Map < String , String > headers ) { for ( RequestRoutingStrategy routingStrategy : MdwServiceRegistry . getInstance ( ) . getRequestRoutingStrategies ( ) ) { URL destination = routingStrategy . getDestination ( request , headers ) ; if ( destination != null ) { // Only return a destination if it is not itself (identical call) - Avoid infinite loop // int queryIdx = destination.toString().indexOf("?"); URL origRequestUrl = null ; try { origRequestUrl = new URL ( headers . get ( Listener . METAINFO_REQUEST_URL ) ) ; } catch ( MalformedURLException e ) { logger . severeException ( "Malformed original RequestURL" , e ) ; } String origHost = origRequestUrl . getHost ( ) . indexOf ( "." ) > 0 ? origRequestUrl . getHost ( ) . substring ( 0 , origRequestUrl . getHost ( ) . indexOf ( "." ) ) : origRequestUrl . getHost ( ) ; int origPort = origRequestUrl . getPort ( ) == 80 || origRequestUrl . getPort ( ) == 443 ? - 1 : origRequestUrl . getPort ( ) ; String origQuery = headers . get ( Listener . METAINFO_REQUEST_QUERY_STRING ) == null ? "" : headers . get ( Listener . METAINFO_REQUEST_QUERY_STRING ) ; String newHost = destination . getHost ( ) . indexOf ( "." ) > 0 ? destination . getHost ( ) . substring ( 0 , destination . getHost ( ) . indexOf ( "." ) ) : destination . getHost ( ) ; int newPort = destination . getPort ( ) == 80 || destination . getPort ( ) == 443 ? - 1 : destination . getPort ( ) ; String newQuery = destination . getQuery ( ) == null ? "" : destination . getQuery ( ) ; if ( ! newHost . equalsIgnoreCase ( origHost ) || ! ( newPort == origPort ) || ! newQuery . equalsIgnoreCase ( origQuery ) || ! origRequestUrl . getPath ( ) . equals ( destination . getPath ( ) ) ) return destination ; } } return null ; } | Returns an instance of the first applicable routing strategy found based on priority of each strategy or null if none return a URL . | 500 | 24 |
13,780 | public User getUser ( String cuid ) { User user = UserGroupCache . getUser ( cuid ) ; if ( user == null ) return null ; // add empty attributes if ( user . getAttributes ( ) == null ) user . setAttributes ( new HashMap < String , String > ( ) ) ; for ( String name : UserGroupCache . getUserAttributeNames ( ) ) { if ( ! user . getAttributes ( ) . containsKey ( name ) ) user . setAttribute ( name , null ) ; // substitute friendly attribute names if ( user . getAttributes ( ) . containsKey ( User . OLD_EMAIL ) ) { String oldEmail = user . getAttributes ( ) . remove ( User . OLD_EMAIL ) ; if ( user . getAttribute ( User . EMAIL ) == null ) user . setAttribute ( User . EMAIL , oldEmail ) ; } if ( user . getAttributes ( ) . containsKey ( User . OLD_PHONE ) ) { String oldPhone = user . getAttributes ( ) . remove ( User . OLD_PHONE ) ; if ( user . getAttribute ( User . PHONE ) == null ) user . setAttribute ( User . PHONE , oldPhone ) ; } } return user ; } | Does not include non - public attributes . Includes empty values for all public attributes . | 268 | 16 |
13,781 | public boolean validate ( ) { _validationError = null ; List < XmlError > errors = new ArrayList < XmlError > ( ) ; boolean valid = _xmlBean . validate ( new XmlOptions ( ) . setErrorListener ( errors ) ) ; if ( ! valid ) { _validationError = "" ; for ( int i = 0 ; i < errors . size ( ) ; i ++ ) { _validationError += errors . get ( i ) . toString ( ) ; if ( i < errors . size ( ) - 1 ) _validationError += ' ' ; } } return valid ; } | Performs validation on the XmlBean populating the error message if failed . | 132 | 17 |
13,782 | static ProgressMonitor getMonitor ( ) { return new ProgressMonitor ( ) { @ Override public void message ( String msg ) { System . out . println ( msg + "..." ) ; } @ Override public void progress ( int prog ) { if ( "\\" . equals ( System . getProperty ( "file.separator" ) ) ) { System . out . print ( "\b\b\b\b\b\b\b\b\b" ) ; } else { System . out . print ( "\r \r" ) ; } if ( prog >= 100 ) System . out . println ( " --> Done" ) ; else if ( prog <= 0 ) // don't report zero progress since it may indicate unknown System . out . print ( " ... " ) ; else System . out . printf ( " --> %3d%%" , prog ) ; } } ; } | Every call with > = 100% progress will print a new line . | 186 | 14 |
13,783 | public List < String > getExcludedTables ( ) { List < String > dbTables = project . readDataList ( "data.excluded.tables" ) ; if ( dbTables == null ) dbTables = DEFAULT_EXCLUDED_TABLES ; return dbTables ; } | Tables excluded from export which need to be purged on import . | 67 | 14 |
13,784 | @ Override @ Path ( "/{roleName}" ) @ ApiOperation ( value = "Retrieve a role or all roles" , notes = "If roleName is not present, returns all roles." , response = Role . class , responseContainer = "List" ) public JSONObject get ( String path , Map < String , String > headers ) throws ServiceException , JSONException { UserServices userServices = ServiceLocator . getUserServices ( ) ; Map < String , String > parameters = getParameters ( headers ) ; try { String roleName = parameters . get ( "name" ) ; if ( roleName == null ) // use request path roleName = getSegment ( path , 1 ) ; if ( roleName != null ) { Role role = userServices . getRole ( roleName ) ; if ( role == null ) throw new ServiceException ( HTTP_404_NOT_FOUND , "Role not found: " + roleName ) ; return role . getJson ( ) ; } else { return userServices . getRoles ( ) . getJson ( ) ; } } catch ( DataAccessException ex ) { throw new ServiceException ( ex . getMessage ( ) , ex ) ; } } | Retrieve a user role or the list of all roles . | 254 | 12 |
13,785 | public static Package getProcessPackage ( Long processId ) { try { if ( processId != null ) { for ( Package pkg : getPackageList ( ) ) { if ( pkg . containsProcess ( processId ) ) return pkg ; } } return Package . getDefaultPackage ( ) ; } catch ( CachingException ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; return null ; } } | Returns the design - time package for a specified process ID . Returns the first match so does not support the same process in multiple packages . Also assumes the processId is not for an embedded subprocess . | 91 | 40 |
13,786 | public static Package getTaskTemplatePackage ( Long taskId ) { try { for ( Package pkg : getPackageList ( ) ) { if ( pkg . containsTaskTemplate ( taskId ) ) return pkg ; } return Package . getDefaultPackage ( ) ; } catch ( CachingException ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; return null ; } } | Returns the design - time package for a specified task ID . Returns the first match so does not support the same template in multiple packages . | 84 | 27 |
13,787 | public String getPath ( ) { Matcher matcher = pathPattern . matcher ( name ) ; if ( matcher . find ( ) ) { String match = matcher . group ( 1 ) ; int lastDot = match . lastIndexOf ( ' ' ) ; if ( lastDot == - 1 ) throw new IllegalStateException ( "Bad asset path: " + match ) ; return match . substring ( 0 , lastDot ) . replace ( ' ' , ' ' ) + match . substring ( lastDot ) ; } else { return null ; } } | File path corresponding to name . | 122 | 6 |
13,788 | @ Override public Object onRequest ( Object request , Map < String , String > headers ) { if ( headers . containsKey ( Listener . METAINFO_HTTP_METHOD ) ) { Tracing tracing = TraceHelper . getTracing ( "mdw-service" ) ; HttpTracing httpTracing = HttpTracing . create ( tracing ) ; handler = HttpServerHandler . create ( httpTracing , new ServerAdapter ( ) ) ; extractor = httpTracing . tracing ( ) . propagation ( ) . extractor ( ServerAdapter . ServerRequest :: getHeader ) ; span = handler . handleReceive ( extractor , new ServerAdapter . ServerRequest ( headers ) ) ; scope = httpTracing . tracing ( ) . tracer ( ) . withSpanInScope ( span ) ; } return null ; } | Only for HTTP services . | 176 | 5 |
13,789 | public static List < Process > getProcessesSmart ( AssetVersionSpec spec ) throws DataAccessException { if ( spec . getPackageName ( ) == null ) throw new DataAccessException ( "Spec must be package-qualified: " + spec ) ; List < Process > matches = new ArrayList <> ( ) ; for ( Process process : getAllProcesses ( ) ) { if ( spec . getQualifiedName ( ) . equals ( process . getQualifiedName ( ) ) ) { if ( process . meetsVersionSpec ( spec . getVersion ( ) ) ) matches . add ( process ) ; } } return matches ; } | Find all definitions matching the specified version spec . Returns shallow processes . | 132 | 13 |
13,790 | protected ConnectionFactory retrieveConnectionFactory ( String name ) throws JMSException { if ( name == null && defaultConnectionFactory != null ) { return defaultConnectionFactory ; // injected } else { try { // autowiring did not occur return ( ConnectionFactory ) SpringAppContext . getInstance ( ) . getBean ( name ) ; } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; throw new JMSException ( "JMS ConnectionFactory not found: " + name ) ; } } } | Pooling and remote queues are configured via Spring in broker config XML . | 112 | 14 |
13,791 | private Process getPackageHandler ( ProcessInstance masterInstance , Integer eventType ) { Process process = getProcessDefinition ( masterInstance ) ; Process handler = getPackageHandler ( process . getPackageName ( ) , eventType ) ; if ( handler != null && handler . getName ( ) . equals ( process . getName ( ) ) ) { logger . warn ( "Package handler recursion is not allowed. " + "Define an embedded handler in package handler: " + handler . getLabel ( ) ) ; } return handler ; } | Finds the relevant package handler for a master process instance . | 110 | 12 |
13,792 | public String invokeService ( Long processId , String ownerType , Long ownerId , String masterRequestId , String masterRequest , Map < String , String > parameters , String responseVarName , Map < String , String > headers ) throws Exception { return invokeService ( processId , ownerType , ownerId , masterRequestId , masterRequest , parameters , responseVarName , 0 , null , null , headers ) ; } | Invoke a real - time service process . | 86 | 9 |
13,793 | public Map < String , String > invokeServiceAsSubprocess ( Long processId , Long parentProcInstId , String masterRequestId , Map < String , String > parameters , int performance_level ) throws Exception { long startMilli = System . currentTimeMillis ( ) ; if ( performance_level <= 0 ) performance_level = getProcessDefinition ( processId ) . getPerformanceLevel ( ) ; if ( performance_level <= 0 ) performance_level = default_performance_level_service ; EngineDataAccess edao = EngineDataAccessCache . getInstance ( true , performance_level ) ; InternalMessenger msgBroker = MessengerFactory . newInternalMessenger ( ) ; msgBroker . setCacheOption ( InternalMessenger . CACHE_ONLY ) ; ProcessExecutor engine = new ProcessExecutor ( edao , msgBroker , true ) ; ProcessInstance mainProcessInst = executeServiceProcess ( engine , processId , OwnerType . PROCESS_INSTANCE , parentProcInstId , masterRequestId , parameters , null , null , null ) ; boolean completed = mainProcessInst . getStatusCode ( ) . equals ( WorkStatus . STATUS_COMPLETED ) ; Map < String , String > resp = completed ? engine . getOutPutParameters ( mainProcessInst . getId ( ) , processId ) : null ; long stopMilli = System . currentTimeMillis ( ) ; logger . info ( "Synchronous process executed in " + ( ( stopMilli - startMilli ) / 1000.0 ) + " seconds at performance level " + performance_level ) ; if ( completed ) return resp ; if ( lastException == null ) throw new Exception ( "Process instance not completed" ) ; throw lastException ; } | Called internally by invoke subprocess activities to call service processes as subprocesses of regular processes . | 368 | 20 |
13,794 | private ProcessInstance executeServiceProcess ( ProcessExecutor engine , Long processId , String ownerType , Long ownerId , String masterRequestId , Map < String , String > parameters , String secondaryOwnerType , Long secondaryOwnerId , Map < String , String > headers ) throws Exception { Process procdef = getProcessDefinition ( processId ) ; Long startActivityId = procdef . getStartActivity ( ) . getId ( ) ; if ( masterRequestId == null ) masterRequestId = genMasterRequestId ( ) ; ProcessInstance mainProcessInst = engine . createProcessInstance ( processId , ownerType , ownerId , secondaryOwnerType , secondaryOwnerId , masterRequestId , parameters ) ; mainProcessInstanceId = mainProcessInst . getId ( ) ; engine . updateProcessInstanceStatus ( mainProcessInst . getId ( ) , WorkStatus . STATUS_PENDING_PROCESS ) ; if ( OwnerType . DOCUMENT . equals ( ownerType ) && ownerId != 0L ) { setOwnerDocumentProcessInstanceId ( engine , ownerId , mainProcessInst . getId ( ) , masterRequestId ) ; bindRequestVariable ( procdef , ownerId , engine , mainProcessInst ) ; } if ( headers != null ) { bindRequestHeadersVariable ( procdef , headers , engine , mainProcessInst ) ; } logger . info ( logtag ( processId , mainProcessInst . getId ( ) , masterRequestId ) , WorkStatus . LOGMSG_PROC_START + " - " + procdef . getQualifiedName ( ) + "/" + procdef . getVersionString ( ) ) ; engine . notifyMonitors ( mainProcessInst , WorkStatus . LOGMSG_PROC_START ) ; // setProcessInstanceStatus will really set to STATUS_IN_PROGRESS - hint to set START_DT as well InternalEvent event = InternalEvent . createActivityStartMessage ( startActivityId , mainProcessInst . getId ( ) , 0L , masterRequestId , EventType . EVENTNAME_START ) ; InternalMessenger msgBroker = engine . getInternalMessenger ( ) ; lastException = null ; processEvent ( engine , event , mainProcessInst ) ; while ( ( event = msgBroker . getNextMessageFromQueue ( engine ) ) != null ) { ProcessInstance procInst = this . findProcessInstance ( engine , event ) ; processEvent ( engine , event , procInst ) ; } mainProcessInst = engine . getProcessInstance ( mainProcessInst . getId ( ) ) ; return mainProcessInst ; } | execute service process using asynch engine | 546 | 8 |
13,795 | public Long startProcess ( Long processId , String masterRequestId , String ownerType , Long ownerId , Map < String , String > vars , Map < String , String > headers ) throws Exception { return startProcess ( processId , masterRequestId , ownerType , ownerId , vars , null , null , headers ) ; } | Start a process . | 70 | 4 |
13,796 | public Long startProcess ( Long processId , String masterRequestId , String ownerType , Long ownerId , Map < String , String > vars , String secondaryOwnerType , Long secondaryOwnerId , Map < String , String > headers ) throws Exception { Process procdef = getProcessDefinition ( processId ) ; int performance_level = procdef . getPerformanceLevel ( ) ; if ( performance_level <= 0 ) performance_level = default_performance_level_regular ; EngineDataAccess edao = EngineDataAccessCache . getInstance ( false , performance_level ) ; InternalMessenger msgBroker = MessengerFactory . newInternalMessenger ( ) ; // do not set internal messenger with cache options, as this engine does not process it directly - Unless PL 9 if ( performance_level >= 9 ) msgBroker . setCacheOption ( InternalMessenger . CACHE_ONLY ) ; if ( masterRequestId == null ) masterRequestId = genMasterRequestId ( ) ; ProcessExecutor engine = new ProcessExecutor ( edao , msgBroker , false ) ; ProcessInstance processInst = engine . createProcessInstance ( processId , ownerType , ownerId , secondaryOwnerType , secondaryOwnerId , masterRequestId , vars ) ; if ( ownerType . equals ( OwnerType . DOCUMENT ) && ownerId != 0L ) { setOwnerDocumentProcessInstanceId ( engine , ownerId , processInst . getId ( ) , masterRequestId ) ; bindRequestVariable ( procdef , ownerId , engine , processInst ) ; } if ( headers != null ) { bindRequestHeadersVariable ( procdef , headers , engine , processInst ) ; } // Delay for ensuring document document content is available for the processing thread // It is also needed to ensure the message is really sent, instead of cached int delay = PropertyManager . getIntegerProperty ( PropertyNames . MDW_PROCESS_LAUNCH_DELAY , 2 ) ; engine . startProcessInstance ( processInst , delay ) ; return processInst . getId ( ) ; } | Starting a regular process . | 431 | 5 |
13,797 | public static Asset getAsset ( AssetVersionSpec spec , Map < String , String > attributeValues ) { Asset match = null ; try { for ( Asset asset : getAllAssets ( ) ) { if ( spec . getName ( ) . equals ( asset . getName ( ) ) ) { if ( asset . meetsVersionSpec ( spec . getVersion ( ) ) && ( match == null || asset . getVersion ( ) > match . getVersion ( ) ) ) { boolean attrsMatch = true ; for ( String attrName : attributeValues . keySet ( ) ) { String attrValue = attributeValues . get ( attrName ) ; String rsValue = asset . getAttribute ( attrName ) ; if ( rsValue == null || ! rsValue . equals ( attrValue ) ) { attrsMatch = false ; break ; } } if ( attrsMatch && ( match == null || match . getVersion ( ) < asset . getVersion ( ) ) ) { if ( ! asset . isLoaded ( ) ) { Asset loaded = getAsset ( asset . getId ( ) ) ; asset . setStringContent ( loaded . getStringContent ( ) ) ; } match = asset ; } } } } // TODO If match == null, check ASSET_REF DB table to retrieve from git history - For when Asset attributes are implemented } catch ( DataAccessException ex ) { logger . severeException ( "Failed to load asset: " + spec . toString ( ) + " : " + ex . getMessage ( ) , ex ) ; } return match ; } | Get the asset based on version spec whose name and custom attributes match the parameters . | 332 | 16 |
13,798 | public static synchronized List < Asset > getJarAssets ( ) { if ( jarAssets == null ) { jarAssets = getAssets ( Asset . JAR ) ; } return jarAssets ; } | This is used by CloudClassLoader to search all JAR file assets | 44 | 14 |
13,799 | public List < String > getNotifierSpecs ( Long taskId , String outcome ) throws ObserverException { TaskTemplate taskVO = TaskTemplateCache . getTaskTemplate ( taskId ) ; if ( taskVO != null ) { String noticesAttr = taskVO . getAttribute ( TaskAttributeConstant . NOTICES ) ; if ( ! StringHelper . isEmpty ( noticesAttr ) && ! "$DefaultNotices" . equals ( noticesAttr ) ) { return parseNoticiesAttr ( noticesAttr , outcome ) ; } } return null ; } | Returns a list of notifier class name and template name pairs delimited by colon | 117 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.