idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
13,900 | @ SuppressWarnings ( "unused" ) private void printServerInfo ( ) { Context ctx ; try { ctx = new InitialContext ( ) ; MBeanServer server = ( MBeanServer ) ctx . lookup ( "java:comp/env/jmx/runtime" ) ; ObjectName service = new ObjectName ( "com.bea:Name=RuntimeService," + "Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean" ) ; ObjectName domainMBean = ( ObjectName ) server . getAttribute ( service , "DomainConfiguration" ) ; ObjectName [ ] servers = ( ObjectName [ ] ) server . getAttribute ( domainMBean , "Servers" ) ; for ( ObjectName one : servers ) { String name = ( String ) server . getAttribute ( one , "Name" ) ; String address = ( String ) server . getAttribute ( one , "ListenAddress" ) ; Integer port = ( Integer ) server . getAttribute ( one , "ListenPort" ) ; System . out . println ( "SERVER: " + name + " on " + address + ":" + port ) ; ObjectName machine = ( ObjectName ) server . getAttribute ( one , "Machine" ) ; ObjectName nodeManager = ( ObjectName ) server . getAttribute ( machine , "NodeManager" ) ; // above line need WLS admin!!! address = ( String ) server . getAttribute ( machine , "ListenAddress" ) ; System . out . println ( " - hostname: " + address ) ; } if ( ctx != null ) return ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } | tried to access machine but that need WLS admin credential so have not tried further | 365 | 17 |
13,901 | public List < Metric > getAverages ( int span ) { Map < String , Metric > accum = new LinkedHashMap <> ( ) ; int count = span / period ; if ( count > dataList . size ( ) ) count = dataList . size ( ) ; for ( int i = dataList . size ( ) - count ; i < dataList . size ( ) ; i ++ ) { MetricData metricData = dataList . get ( i ) ; for ( Metric metric : metricData . getMetrics ( ) ) { Metric total = accum . get ( metric . getName ( ) ) ; if ( total == null ) { total = new Metric ( metric . getId ( ) , metric . getName ( ) , metric . getValue ( ) ) ; accum . put ( metric . getName ( ) , total ) ; } else { total . setValue ( total . getValue ( ) + metric . getValue ( ) ) ; } } } for ( Metric metric : accum . values ( ) ) { metric . setValue ( Math . round ( ( double ) metric . getValue ( ) / count ) ) ; } return new ArrayList <> ( accum . values ( ) ) ; } | Accumulated averages . | 260 | 5 |
13,902 | public List < MetricData > getData ( int span ) { int count = span / period ; if ( dataList . size ( ) < count ) { if ( dataList . isEmpty ( ) ) { return dataList ; } else { // left-pad List < MetricData > padded = new ArrayList <> ( dataList ) ; MetricData first = dataList . get ( 0 ) ; List < Metric > pads = new ArrayList <> ( ) ; for ( Metric metric : first . getMetrics ( ) ) { pads . add ( new Metric ( metric . getId ( ) , metric . getName ( ) , 0 ) ) ; } LocalDateTime time = first . getTime ( ) ; while ( padded . size ( ) < count ) { time = time . minusSeconds ( period ) ; padded . add ( 0 , new MetricData ( time , pads ) ) ; } return padded ; } } else { return dataList . subList ( dataList . size ( ) - count , dataList . size ( ) - 1 ) ; } } | Returns a left - padded list . | 230 | 7 |
13,903 | public static String encrypt ( String input ) { try { return encrypt ( input , null ) ; } catch ( GeneralSecurityException e ) { e . printStackTrace ( ) ; return null ; } } | Encrypt a string using a default key | 42 | 8 |
13,904 | public static String encrypt ( String input , String strkey ) throws GeneralSecurityException { SecretKey key ; if ( strkey != null ) { if ( strkey . length ( ) > 56 ) strkey = strkey . substring ( 0 , 55 ) ; key = new SecretKeySpec ( strkey . getBytes ( ) , algorithm ) ; } else { if ( defaultKey == null ) defaultKey = new SecretKeySpec ( defaultKeyString . getBytes ( ) , algorithm ) ; key = defaultKey ; } Cipher cipher = Cipher . getInstance ( algorithm ) ; cipher . init ( Cipher . ENCRYPT_MODE , key ) ; byte [ ] inputBytes = input . getBytes ( ) ; byte [ ] encrypted = cipher . doFinal ( inputBytes ) ; return encodeAlpha ( encrypted ) ; } | Encrypt a string | 170 | 4 |
13,905 | public static String decrypt ( String encrypted ) { try { return decrypt ( encrypted , null ) ; } catch ( GeneralSecurityException e ) { e . printStackTrace ( ) ; return null ; } } | Decrypt a string using the default key | 42 | 8 |
13,906 | public File getHubOverride ( String path ) throws IOException { if ( getOverrideRoot ( ) != null ) { File hubOverride = new File ( getOverrideRoot ( ) + path ) ; if ( hubOverride . isFile ( ) ) return hubOverride ; } if ( getDevOverrideRoot ( ) != null && isDev ( ) ) { File devOverride = new File ( getDevOverrideRoot ( ) + path ) ; if ( devOverride . isFile ( ) ) return devOverride ; } return null ; } | Finds overridden hub artifacts among assets . Core dev override is also supported for vanilla hub development . | 108 | 20 |
13,907 | protected String getRequestData ( ) throws ActivityException { Object request = null ; String requestVarName = getAttributeValue ( REQUEST_VARIABLE ) ; if ( requestVarName == null ) throw new ActivityException ( "Missing attribute: " + REQUEST_VARIABLE ) ; String requestVarType = getParameterType ( requestVarName ) ; request = getParameterValue ( requestVarName ) ; if ( ! hasPreScript ( ) ) { if ( request == null ) throw new ActivityException ( "Request data is null: " + requestVarName ) ; if ( ! ( request instanceof DocumentReference ) ) throw new ActivityException ( "Request data must be a DocumentReference: " + requestVarName ) ; } try { Object requestObj = request == null ? null : getDocument ( ( DocumentReference ) request , requestVarType ) ; if ( hasPreScript ( ) ) { Object ret = executePreScript ( requestObj ) ; if ( ret == null ) { // nothing returned; requestVar may have been assigned by script Object req = getParameterValue ( requestVarName ) ; if ( req == null ) throw new ActivityException ( "Request data is null: " + requestVarName ) ; requestObj = getDocument ( ( DocumentReference ) req , requestVarType ) ; } else { requestObj = ret ; setParameterValueAsDocument ( requestVarName , this . getProcessDefinition ( ) . getVariable ( requestVarName ) . getType ( ) , requestObj ) ; } } soapRequest = createSoapRequest ( requestObj ) ; return DomHelper . toXml ( soapRequest . getSOAPPart ( ) . getDocumentElement ( ) ) ; } catch ( TransformerException ex ) { throw new ActivityException ( ex . getMessage ( ) , ex ) ; } } | Builds the request XML . | 380 | 6 |
13,908 | @ Override public void onSuccess ( String response ) throws ActivityException , ConnectionException , AdapterException { try { // set the variable value based on the unwrapped soap content soapResponse = getSoapResponse ( response ) ; Node childElem = unwrapSoapResponse ( soapResponse ) ; String responseXml = DomHelper . toXml ( childElem ) ; String responseVarName = getAttributeValue ( RESPONSE_VARIABLE ) ; if ( responseVarName == null ) throw new AdapterException ( "Missing attribute: " + RESPONSE_VARIABLE ) ; String responseVarType = getParameterType ( responseVarName ) ; if ( ! VariableTranslator . isDocumentReferenceVariable ( getPackage ( ) , responseVarType ) ) throw new AdapterException ( "Response variable must be a DocumentReference: " + responseVarName ) ; if ( responseVarType . equals ( StringDocument . class . getName ( ) ) ) { setParameterValueAsDocument ( responseVarName , responseVarType , responseXml ) ; } else { com . centurylink . mdw . variable . VariableTranslator varTrans = VariableTranslator . getTranslator ( getPackage ( ) , responseVarType ) ; if ( ! ( varTrans instanceof XmlDocumentTranslator ) ) throw new AdapterException ( "Unsupported response variable type: " + responseVarType + " (must implement XmlDocumentTranslator)" ) ; XmlDocumentTranslator xmlDocTrans = ( XmlDocumentTranslator ) varTrans ; Object responseObj = xmlDocTrans . fromDomNode ( childElem ) ; setParameterValueAsDocument ( responseVarName , responseVarType , responseObj ) ; } } catch ( Exception ex ) { throw new ActivityException ( ex . getMessage ( ) , ex ) ; } } | Overriding this method affords the opportunity to parse the response and populate process variables as needed . | 384 | 20 |
13,909 | protected String getSoapAction ( ) { String soapAction = null ; try { soapAction = getAttributeValueSmart ( SOAP_ACTION ) ; } catch ( PropertyException ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; } if ( soapAction == null ) { // required by SOAP 1.1 (http://www.w3.org/TR/soap11/#_Toc478383528) String soapVersion = getSoapVersion ( ) ; if ( soapVersion != null && soapVersion . equals ( SOAP_VERSION_11 ) ) soapAction = "" ; } return soapAction ; } | The SOAPAction HTTP request header value . | 137 | 9 |
13,910 | protected void processMessage ( String message ) throws ActivityException { try { String rcvdMsgDocVar = getAttributeValueSmart ( RECEIVED_MESSAGE_DOC_VAR ) ; if ( rcvdMsgDocVar != null && ! rcvdMsgDocVar . isEmpty ( ) ) { Process processVO = getProcessDefinition ( ) ; Variable variableVO = processVO . getVariable ( rcvdMsgDocVar ) ; if ( variableVO == null ) throw new ActivityException ( "Received Message Variable '" + rcvdMsgDocVar + "' is not defined or is not Document Type for process " + processVO . getFullLabel ( ) ) ; if ( message != null ) { this . setParameterValueAsDocument ( rcvdMsgDocVar , variableVO . getType ( ) , message ) ; } } return ; } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; return ; } } | You should override this method to process event messages . | 203 | 10 |
13,911 | protected void updateSLA ( int seconds ) throws ActivityException { try { ProcessExecutor engine = this . getEngine ( ) ; super . loginfo ( "Update activity timeout as " + seconds + " seconds" ) ; InternalEvent delayMsg = InternalEvent . createActivityDelayMessage ( this . getActivityInstance ( ) , this . getMasterRequestId ( ) ) ; String eventName = ScheduledEvent . INTERNAL_EVENT_PREFIX + this . getActivityInstanceId ( ) + "timeout" ; engine . sendDelayedInternalEvent ( delayMsg , seconds , eventName , true ) ; } catch ( Exception e ) { throw new ActivityException ( - 1 , "Failed to update SLA for activity instance" + this . getActivityInstanceId ( ) , e ) ; } } | Update SLA of this | 170 | 5 |
13,912 | @ Override @ Path ( "/{ownerType}/{ownerId}" ) @ ApiOperation ( value = "Retrieve values for an ownerType and ownerId" , notes = "Response is a generic JSON object with names/values." ) public JSONObject get ( String path , Map < String , String > headers ) throws ServiceException , JSONException { Map < String , String > parameters = getParameters ( headers ) ; String ownerType = getSegment ( path , 1 ) ; if ( ownerType == null ) // fall back to parameter ownerType = parameters . get ( "ownerType" ) ; if ( ownerType == null ) throw new ServiceException ( "Missing path segment: {ownerType}" ) ; String ownerId = getSegment ( path , 2 ) ; if ( ownerId == null ) // fall back to parameter ownerId = parameters . get ( "ownerId" ) ; if ( ownerId == null ) throw new ServiceException ( "Missing path segment: {ownerId}" ) ; JSONObject valuesJson = new JsonObject ( ) ; Map < String , String > values = ServiceLocator . getWorkflowServices ( ) . getValues ( ownerType , ownerId ) ; if ( values != null ) { for ( String name : values . keySet ( ) ) valuesJson . put ( name , values . get ( name ) ) ; } return valuesJson ; } | Retrieve values . | 295 | 4 |
13,913 | @ Override @ Path ( "/{ownerType}/{ownerId}" ) @ ApiOperation ( value = "Create values for an ownerType and ownerId" , response = StatusMessage . class ) @ ApiImplicitParams ( { @ ApiImplicitParam ( name = "Values" , paramType = "body" ) } ) public JSONObject post ( String path , JSONObject content , Map < String , String > headers ) throws ServiceException , JSONException { return put ( path , content , headers ) ; } | Create values for owner type and id . | 112 | 8 |
13,914 | @ Override @ Path ( "/{ownerType}/{ownerId}" ) @ ApiOperation ( value = "Update values for an ownerType and ownerId" , response = StatusMessage . class ) @ ApiImplicitParams ( { @ ApiImplicitParam ( name = "Values" , paramType = "body" ) } ) public JSONObject put ( String path , JSONObject content , Map < String , String > headers ) throws ServiceException , JSONException { Map < String , String > parameters = getParameters ( headers ) ; String ownerType = getSegment ( path , 1 ) ; if ( ownerType == null ) ownerType = parameters . get ( "ownerType" ) ; if ( ownerType == null ) throw new ServiceException ( "Missing parameter: ownerType" ) ; String ownerId = getSegment ( path , 2 ) ; if ( ownerId == null ) ownerId = parameters . get ( "ownerId" ) ; if ( ownerId == null ) throw new ServiceException ( "Missing parameter: ownerId" ) ; String updateOnly = getSegment ( path , 3 ) ; if ( updateOnly == null ) updateOnly = parameters . get ( "updateOnly" ) ; if ( content == null ) throw new ServiceException ( "Missing JSON object: attributes" ) ; try { Map < String , String > values = new HashMap < String , String > ( ) ; String [ ] names = JSONObject . getNames ( content ) ; if ( names != null ) { for ( String name : names ) values . put ( name , content . getString ( name ) ) ; } WorkflowServices workflowServices = ServiceLocator . getWorkflowServices ( ) ; if ( updateOnly != null ) { // update values, without deleting all other values for that ownerId workflowServices . updateValues ( ownerType , ownerId , values ) ; } else { workflowServices . setValues ( ownerType , ownerId , values ) ; } return null ; } catch ( JSONException ex ) { throw new ServiceException ( ex . getMessage ( ) , ex ) ; } } | Update values for owner type and id . Existing values are always overwritten . | 441 | 16 |
13,915 | @ Override @ Path ( "/{ownerType}/{ownerId}" ) @ ApiOperation ( value = "Delete values for an ownerType and ownerId" , response = StatusMessage . class ) public JSONObject delete ( String path , JSONObject content , Map < String , String > headers ) throws ServiceException , JSONException { JSONObject empty = new JsonObject ( ) ; return put ( path , empty , headers ) ; } | Delete values for owner type and id . | 92 | 8 |
13,916 | private void authorize ( HttpSession session , Action action , Entity entity , String location ) throws AuthorizationException , DataAccessException { AuthenticatedUser user = ( AuthenticatedUser ) session . getAttribute ( "authenticatedUser" ) ; if ( user == null && ApplicationContext . getServiceUser ( ) != null ) { String cuid = ApplicationContext . getServiceUser ( ) ; user = new AuthenticatedUser ( UserGroupCache . getUser ( cuid ) ) ; } if ( user == null ) throw new AuthorizationException ( AuthorizationException . NOT_AUTHORIZED , "Authentication failure" ) ; if ( action == Action . Create || action == Action . Delete ) { if ( ! user . hasRole ( Role . PROCESS_EXECUTION ) ) { throw new AuthorizationException ( AuthorizationException . FORBIDDEN , "User " + user . getCuid ( ) + " not authorized for " + action + " on " + location ) ; } logger . info ( "Asset mod request received from user: " + user . getCuid ( ) + " for: " + location ) ; UserAction userAction = new UserAction ( user . getCuid ( ) , action , entity , 0L , location ) ; userAction . setSource ( getClass ( ) . getSimpleName ( ) ) ; ServiceLocator . getUserServices ( ) . auditLog ( userAction ) ; } } | Also audit logs create and delete . | 297 | 7 |
13,917 | public PackageAssets getAssets ( String packageName , boolean withVcsInfo ) throws ServiceException { try { PackageDir pkgDir = getPackageDir ( packageName ) ; if ( pkgDir == null ) { pkgDir = getGhostPackage ( packageName ) ; if ( pkgDir == null ) throw new DataAccessException ( "Missing package metadata directory: " + packageName ) ; } List < AssetInfo > assets = new ArrayList <> ( ) ; if ( ! DiffType . MISSING . equals ( pkgDir . getVcsDiffType ( ) ) ) { for ( File file : pkgDir . listFiles ( ) ) { if ( file . isFile ( ) ) { AssetFile assetFile = pkgDir . getAssetFile ( file ) ; if ( ! MdwIgnore . isIgnore ( assetFile ) ) assets . add ( new AssetInfo ( assetFile ) ) ; } } } PackageAssets pkgAssets = new PackageAssets ( pkgDir ) ; pkgAssets . setAssets ( assets ) ; if ( withVcsInfo ) { CodeTimer timer = new CodeTimer ( "AssetServices" , true ) ; addVersionControlInfo ( pkgAssets ) ; pkgAssets . sort ( ) ; timer . stopAndLogTiming ( "addVersionControlInfo(PackageAssets)" ) ; } return pkgAssets ; } catch ( Exception ex ) { throw new ServiceException ( ex . getMessage ( ) , ex ) ; } } | Returns all the assets for the specified package . Does not use the AssetCache . | 324 | 16 |
13,918 | private List < PackageDir > findPackageDirs ( List < File > dirs , List < File > excludes ) throws IOException , DataAccessException { List < PackageDir > pkgSubDirs = new ArrayList <> ( ) ; List < File > allSubDirs = new ArrayList <> ( ) ; for ( File dir : dirs ) { MdwIgnore mdwIgnore = new MdwIgnore ( dir ) ; for ( File sub : dir . listFiles ( ) ) { if ( sub . isDirectory ( ) && ! sub . equals ( getArchiveDir ( ) ) && ! excludes . contains ( sub ) && ! mdwIgnore . isIgnore ( sub ) ) { if ( new File ( sub + "/.mdw" ) . isDirectory ( ) ) { PackageDir pkgSubDir = new PackageDir ( getAssetRoot ( ) , sub , getAssetVersionControl ( ) ) ; if ( pkgSubDir . parse ( ) ) pkgSubDirs . add ( pkgSubDir ) ; } allSubDirs . add ( sub ) ; } } } if ( ! allSubDirs . isEmpty ( ) ) pkgSubDirs . addAll ( findPackageDirs ( allSubDirs , excludes ) ) ; return pkgSubDirs ; } | Finds the next level of sibling PackageDirs under a set of non - package dirs . | 282 | 20 |
13,919 | private VersionControl getAssetVersionControl ( ) throws IOException , DataAccessException { VersionControl vc = getVersionControl ( ) ; if ( vc == null ) vc = DataAccess . getAssetVersionControl ( assetRoot ) ; return vc ; } | Falls back to DataAccess version control for asset versioning . | 55 | 13 |
13,920 | public AssetInfo getImplAsset ( String className ) throws ServiceException { int lastDot = className . lastIndexOf ( ' ' ) ; if ( lastDot > 0 && lastDot < className . length ( ) - 1 ) { String assetRoot = className . substring ( 0 , lastDot ) + "/" + className . substring ( lastDot + 1 ) ; AssetInfo implAsset = getAsset ( assetRoot + ".java" ) ; if ( implAsset == null ) return getAsset ( assetRoot + ".kt" ) ; } return null ; } | Returns either Java or Kotlin asset implementor for a class . Null if not found . | 126 | 18 |
13,921 | private String getValue ( String name ) { for ( YamlProperties yamlProp : yamlProps ) { String value = yamlProp . getString ( name ) ; if ( value != null ) return value ; } if ( javaProps != null ) { for ( Properties javaProp : javaProps ) { String value = javaProp . getProperty ( name ) ; if ( value != null ) return value ; } } return null ; } | Reads flat or structured values from yaml . If not found fall back to java properties . | 95 | 19 |
13,922 | public static void putScript ( String name , KotlinCompiledScript script ) { getInstance ( ) . scripts . put ( name , script ) ; } | Must be public for access from Kotlin . | 32 | 9 |
13,923 | protected void handleConnectionException ( int errorCode , Throwable originalCause ) throws ActivityException { InternalEvent message = InternalEvent . createActivityStartMessage ( getActivityId ( ) , getProcessInstanceId ( ) , getWorkTransitionInstanceId ( ) , getMasterRequestId ( ) , COMPCODE_AUTO_RETRY ) ; ScheduledEventQueue eventQueue = ScheduledEventQueue . getSingleton ( ) ; int retry_interval = this . getRetryInterval ( ) ; Date scheduledTime = new Date ( DatabaseAccess . getCurrentTime ( ) + retry_interval * 1000 ) ; super . loginfo ( "The activity failed, set to retry at " + StringHelper . dateToString ( scheduledTime ) ) ; eventQueue . scheduleInternalEvent ( ScheduledEvent . INTERNAL_EVENT_PREFIX + this . getActivityInstanceId ( ) , scheduledTime , message . toString ( ) , "procinst:" + this . getProcessInstanceId ( ) . toString ( ) ) ; this . setReturnCode ( COMPCODE_AUTO_RETRY ) ; // the above is to prevent engine from making transitions (typically to exception handler) throw new ActivityException ( errorCode , originalCause . getMessage ( ) , originalCause ) ; } | Typically you should not override this method . ConnectionPoolAdapter does override this with internal MDW logic . | 275 | 20 |
13,924 | public Response directInvoke ( String request , int timeout , Map < String , String > meta_data ) throws AdapterException , ConnectionException { init ( ) ; if ( logger == null ) logger = LoggerUtil . getStandardLogger ( ) ; Object connection = null ; try { connection = openConnection ( ) ; return doInvoke ( connection , new Request ( request ) , timeout , meta_data ) ; } finally { if ( connection != null ) closeConnection ( connection ) ; } } | This method is used for directly invoke the adapter activity from code rather than as part of process execution flow . | 104 | 21 |
13,925 | public TransitionInstance createTransitionInstance ( Transition transition , Long pProcessInstId ) throws DataAccessException { TransactionWrapper transaction = null ; try { transaction = startTransaction ( ) ; return engineImpl . createTransitionInstance ( transition , pProcessInstId ) ; } catch ( DataAccessException e ) { if ( canRetryTransaction ( e ) ) { transaction = ( TransactionWrapper ) initTransactionRetry ( transaction ) ; return ( ( ProcessExecutor ) getTransactionRetrier ( ) ) . createTransitionInstance ( transition , pProcessInstId ) ; } else throw e ; } finally { stopTransaction ( transaction ) ; } } | Creates a new instance of the WorkTransationInstance entity | 134 | 12 |
13,926 | public Integer lockActivityInstance ( Long actInstId ) throws DataAccessException { try { if ( ! isInTransaction ( ) ) throw new DataAccessException ( "Cannot lock activity instance without a transaction" ) ; return engineImpl . getDataAccess ( ) . lockActivityInstance ( actInstId ) ; } catch ( SQLException e ) { throw new DataAccessException ( 0 , "Failed to lock activity instance" , e ) ; } } | This method must be called within the same transaction scope ( namely engine is already started | 96 | 16 |
13,927 | public Integer lockProcessInstance ( Long procInstId ) throws DataAccessException { try { if ( ! isInTransaction ( ) ) throw new DataAccessException ( "Cannot lock activity instance without a transaction" ) ; return engineImpl . getDataAccess ( ) . lockProcessInstance ( procInstId ) ; } catch ( SQLException e ) { throw new DataAccessException ( 0 , "Failed to lock process instance" , e ) ; } } | this method must be called within the same transaction scope ( namely engine is already started | 96 | 16 |
13,928 | @ Override @ Path ( "{package}/{asset}" ) public JSONObject get ( String assetPath , Map < String , String > headers ) throws ServiceException , JSONException { AssetServices assetServices = ServiceLocator . getAssetServices ( ) ; AssetInfo asset = assetServices . getAsset ( assetPath . substring ( 7 ) , true ) ; if ( asset == null ) throw new ServiceException ( ServiceException . NOT_FOUND , "Asset not found: " + assetPath ) ; if ( asset . getCommitInfo ( ) == null ) throw new ServiceException ( ServiceException . NOT_FOUND , "Commit Info not found: " + assetPath ) ; return asset . getCommitInfo ( ) . getJson ( ) ; } | Retrieves commit info for an asset . | 162 | 9 |
13,929 | public long getDurationMicro ( ) { if ( startNano != 0 ) { if ( running ) return ( ( long ) ( System . nanoTime ( ) - startNano ) ) / 1000 ; else if ( stopNano != startNano ) return ( ( long ) ( stopNano - startNano ) ) / 1000 ; } return 0 ; } | Timer duration in microseconds . | 76 | 6 |
13,930 | public static TaskTemplate getTemplateForName ( String taskName ) { for ( int i = 0 ; i < taskVoCache . size ( ) ; i ++ ) { TaskTemplate task = taskVoCache . get ( i ) ; if ( task . getTaskName ( ) . equals ( taskName ) ) { return task ; } } return null ; } | Return the latest task for the given name . | 74 | 9 |
13,931 | public static TaskTemplate getTaskTemplate ( String logicalId ) { for ( int i = 0 ; i < taskVoCache . size ( ) ; i ++ ) { TaskTemplate task = taskVoCache . get ( i ) ; if ( logicalId . equals ( task . getLogicalId ( ) ) ) { return task ; } } return null ; } | Return the latest task id for the given logical ID | 74 | 10 |
13,932 | public static TaskTemplate getTaskTemplate ( AssetVersionSpec assetVersionSpec ) throws Exception { TaskTemplate taskTemplate = templateVersions . get ( assetVersionSpec . toString ( ) ) ; if ( taskTemplate == null ) { if ( assetVersionSpec . getPackageName ( ) != null ) { List < Package > pkgVOs = PackageCache . getAllPackages ( assetVersionSpec . getPackageName ( ) ) ; for ( Package pkgVO : pkgVOs ) { for ( TaskTemplate template : pkgVO . getTaskTemplates ( ) ) { if ( assetVersionSpec . getName ( ) . equals ( template . getName ( ) ) ) { if ( template . meetsVersionSpec ( assetVersionSpec . getVersion ( ) ) && ( taskTemplate == null || template . getVersion ( ) > taskTemplate . getVersion ( ) ) ) taskTemplate = template ; } } } } // If didn't find, check ASSET_REF DB table to retrieve from git history if ( taskTemplate == null && ! assetVersionSpec . getVersion ( ) . equals ( "0" ) ) { AssetRef ref = AssetRefCache . getAssetRef ( assetVersionSpec ) ; if ( ref != null ) { taskTemplate = AssetRefConverter . getTaskTemplate ( ref ) ; if ( taskTemplate != null ) taskVoCache . add ( taskTemplate ) ; } } if ( taskTemplate != null ) templateVersions . put ( assetVersionSpec . toString ( ) , taskTemplate ) ; } return taskTemplate ; } | Get the latest task template that matched the assetVersionSpec . Uses the task logicalId to match to the taskVoCache so if the logical ID in the matching asset is not unique then the latest template with this logicalId will be returned regardless of assetVersionSpec . So CHANGE THE LOGICAL_ID if you want in - flight tasks to use a different template . | 324 | 74 |
13,933 | public static void read ( Swagger swagger , Set < Class < ? > > classes ) { final SwaggerAnnotationsReader reader = new SwaggerAnnotationsReader ( swagger ) ; for ( Class < ? > cls : classes ) { final ReaderContext context = new ReaderContext ( swagger , cls , "" , null , false , new ArrayList <> ( ) , new ArrayList <> ( ) , new ArrayList <> ( ) , new ArrayList <> ( ) ) ; reader . read ( context ) ; } } | Scans a set of classes for Swagger annotations . | 114 | 11 |
13,934 | @ Override public InputStream getResourceAsStream ( String name ) { byte [ ] b = null ; try { Asset resource = AssetCache . getAsset ( mdwPackage . getName ( ) + "/" + name ) ; if ( resource != null ) b = resource . getRawContent ( ) ; if ( b == null ) b = findInJarAssets ( name ) ; if ( b == null ) b = findInFileSystem ( name ) ; } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; } if ( b == null ) return super . getResourceAsStream ( name ) ; else return new ByteArrayInputStream ( b ) ; } | This is used by XMLBeans for loading the type system . | 149 | 13 |
13,935 | private EventParameters createEventParameters ( Map < String , String > pParams ) { EventParameters evParams = EventParameters . Factory . newInstance ( ) ; for ( String name : pParams . keySet ( ) ) { String val = pParams . get ( name ) ; if ( val == null ) { continue ; } Parameter evParam = evParams . addNewParameter ( ) ; evParam . setName ( name ) ; evParam . setStringValue ( val ) ; } return evParams ; } | Method that creates the event params based on the passed in Map | 112 | 12 |
13,936 | public static InternalEvent createActivityNotifyMessage ( ActivityInstance ai , Integer eventType , String masterRequestId , String compCode ) { InternalEvent event = new InternalEvent ( ) ; event . workId = ai . getActivityId ( ) ; event . transitionInstanceId = null ; event . eventType = eventType ; event . ownerType = OwnerType . PROCESS_INSTANCE ; event . ownerId = ai . getProcessInstanceId ( ) ; event . masterRequestId = masterRequestId ; event . workInstanceId = ai . getId ( ) ; event . completionCode = compCode ; return event ; } | create activity FINISH ABORT RESUME CORRECT ERROR and any event type that can be specified in designer configuration for events . | 134 | 25 |
13,937 | public Transaction getTransaction ( ) { try { return getTransactionManager ( ) . getTransaction ( ) ; } catch ( Exception ex ) { StandardLogger logger = LoggerUtil . getStandardLogger ( ) ; logger . severeException ( ex . getMessage ( ) , ex ) ; return null ; } } | Returns the current transaction | 65 | 4 |
13,938 | public TransactionManager getTransactionManager ( ) { TransactionManager transMgr = null ; try { String jndiName = ApplicationContext . getNamingProvider ( ) . getTransactionManagerName ( ) ; Object txMgr = ApplicationContext . getNamingProvider ( ) . lookup ( null , jndiName , TransactionManager . class ) ; transMgr = ( TransactionManager ) txMgr ; } catch ( Exception ex ) { StandardLogger logger = LoggerUtil . getStandardLogger ( ) ; logger . severeException ( ex . getMessage ( ) , ex ) ; } return transMgr ; } | Returns transaction manager | 130 | 3 |
13,939 | public boolean belongsToGroup ( String groupName ) { if ( workgroups == null || workgroups . length == 0 ) { return false ; } for ( Workgroup g : workgroups ) { if ( g . getName ( ) . equals ( groupName ) ) return true ; } return false ; } | Check whether user belongs to the specified group | 63 | 8 |
13,940 | public void addRoleForGroup ( String groupName , String roleName ) { if ( workgroups == null ) { workgroups = new Workgroup [ 1 ] ; workgroups [ 0 ] = new Workgroup ( null , groupName , null ) ; } List < String > roles = workgroups [ 0 ] . getRoles ( ) ; if ( roles == null ) { roles = new ArrayList < String > ( ) ; workgroups [ 0 ] . setRoles ( roles ) ; } roles . add ( roleName ) ; } | This is only used when UserVO is a member of UserGroupVO . Only that group is populated as a substructure to store roles . | 112 | 28 |
13,941 | public void parseName ( ) { if ( getName ( ) != null ) { String name = getName ( ) . trim ( ) ; int firstSp = name . indexOf ( ' ' ) ; if ( firstSp > 0 ) { setFirst ( name . substring ( 0 , firstSp ) ) ; int lastSp = name . lastIndexOf ( ' ' ) ; setLast ( name . substring ( lastSp + 1 ) ) ; } else { setFirst ( name ) ; } } } | Set first and last name based on full name . | 106 | 10 |
13,942 | public void putreq ( String msg ) throws SoccomException { byte msgbytes [ ] = SoccomMessage . makeMessage ( msg , null ) ; logline ( "SEND: " + new String ( msgbytes ) ) ; copy_msgid ( _msgid , msgbytes ) ; try { // _out.print(msg); _out . write ( msgbytes ) ; } catch ( IOException e ) { throw new SoccomException ( SoccomException . REQUEST ) ; } } | Send a request message . | 104 | 5 |
13,943 | public void putreq_vheader ( String endmark ) throws SoccomException { if ( endmark . length ( ) != 4 ) throw new SoccomException ( SoccomException . ENDM_LENGTH ) ; byte msgbytes [ ] = SoccomMessage . makeMessageSpecial ( "ENDM" + endmark , null ) ; logline ( "SEND: " + new String ( msgbytes ) ) ; copy_msgid ( _msgid , msgbytes ) ; try { _out . write ( msgbytes ) ; } catch ( IOException e ) { throw new SoccomException ( SoccomException . REQUEST ) ; } } | Send the header part of a variable - size request message . | 135 | 12 |
13,944 | public void putreq_vline ( String msg ) throws SoccomException { int length = msg . length ( ) ; if ( msg . charAt ( length - 1 ) == ' ' ) { logline ( "SEND: " + msg . substring ( 0 , length - 1 ) ) ; } else { logline ( "SEND: " + msg ) ; msg += "\n" ; } byte msgbytes [ ] = msg . getBytes ( ) ; try { _out . write ( msgbytes ) ; } catch ( IOException e ) { throw new SoccomException ( SoccomException . REQUEST ) ; } } | Send a line as a part of a variable - size request message . | 133 | 14 |
13,945 | public void putreq_vfooter ( String endmark ) throws SoccomException { if ( endmark . length ( ) != 4 ) throw new SoccomException ( SoccomException . ENDM_LENGTH ) ; String msg = endmark + "\n" ; byte msgbytes [ ] = msg . getBytes ( ) ; logline ( "SEND: " + endmark ) ; try { _out . write ( msgbytes ) ; } catch ( IOException e ) { throw new SoccomException ( SoccomException . REQUEST ) ; } } | Mark the end of a variable - size message . | 117 | 10 |
13,946 | public String getresp ( int timeout ) throws SoccomException { int size , n ; String sizestr ; try { byte [ ] _header = new byte [ SoccomMessage . HEADER_SIZE ] ; _socket . setSoTimeout ( timeout * 1000 ) ; n = _in . read ( _header , 0 , SoccomMessage . HEADER_SIZE ) ; if ( n != SoccomMessage . HEADER_SIZE ) throw new SoccomException ( SoccomException . RECV_HEADER ) ; logline ( "RECV HDR: " + new String ( _header ) ) ; check_msgid ( _msgid , _header ) ; sizestr = new String ( _header , SoccomMessage . MSGSIZE_OFFSET , 8 ) ; if ( sizestr . startsWith ( "ENDM" ) ) size = - 1 ; else size = Integer . parseInt ( sizestr ) ; } catch ( InterruptedIOException e ) { throw new SoccomException ( SoccomException . POLL_TIMEOUT ) ; } catch ( IOException e ) { throw new SoccomException ( SoccomException . RECV_HEADER ) ; } try { String msg ; if ( size == - 1 ) { String endm = sizestr . substring ( 4 , 8 ) ; String line ; StringBuffer sb = new StringBuffer ( ) ; byte [ ] buffer = new byte [ 1024 ] ; int k ; boolean done = false ; while ( ! done ) { k = readLine ( _in , buffer , 0 , 1024 ) ; line = new String ( buffer , 0 , k ) ; if ( k == 5 && line . startsWith ( endm ) ) done = true ; else sb . append ( line ) ; } msg = sb . toString ( ) ; } else { byte [ ] buffer = new byte [ size + SoccomMessage . HEADER_SIZE ] ; int got = 0 ; while ( got < size ) { n = _in . read ( buffer , got , size - got ) ; if ( n > 0 ) got += n ; else if ( n == - 1 ) throw new SoccomException ( SoccomException . SOCKET_CLOSED ) ; else throw new SoccomException ( SoccomException . RECV_ERROR ) ; } msg = new String ( buffer , 0 , size ) ; } logline ( "RECV MSG: " + msg ) ; return msg ; } catch ( InterruptedIOException e ) { throw new SoccomException ( SoccomException . RECV_ERROR ) ; } catch ( IOException e ) { throw new SoccomException ( SoccomException . RECV_ERROR ) ; } } | Get the response from the server after sending a request . | 573 | 11 |
13,947 | public String getresp_first ( int maxbytes , int timeout ) throws SoccomException { int n ; String sizestr , msg ; _resp_read = - 1 ; try { byte [ ] _header = new byte [ SoccomMessage . HEADER_SIZE ] ; _socket . setSoTimeout ( timeout * 1000 ) ; n = _in . read ( _header , 0 , SoccomMessage . HEADER_SIZE ) ; if ( n != SoccomMessage . HEADER_SIZE ) throw new SoccomException ( SoccomException . RECV_HEADER ) ; logline ( "RECV HDR: " + new String ( _header ) ) ; check_msgid ( _msgid , _header ) ; sizestr = new String ( _header , SoccomMessage . MSGSIZE_OFFSET , 8 ) ; if ( sizestr . startsWith ( "ENDM" ) ) _resp_size = - 1 ; else _resp_size = Integer . parseInt ( sizestr ) ; } catch ( InterruptedIOException e ) { throw new SoccomException ( SoccomException . RECV_HEADER ) ; } catch ( IOException e ) { throw new SoccomException ( SoccomException . RECV_HEADER ) ; } try { if ( maxbytes == 0 ) { if ( _resp_size == - 1 ) { _endm = sizestr . substring ( 4 , 8 ) ; } _resp_read = 0 ; if ( getresp_hasmore ( ) ) msg = getresp_next ( maxbytes ) ; else msg = "" ; } else if ( _resp_size == - 1 ) { _endm = sizestr . substring ( 4 , 8 ) ; byte [ ] buffer = new byte [ maxbytes ] ; int k = 0 ; boolean done = false ; while ( ! done && k < maxbytes ) { n = readLine ( _in , buffer , k , maxbytes ) ; if ( n == 5 && _endm . equals ( new String ( buffer , k , 4 ) ) ) { done = true ; } else k += n ; } if ( done ) _resp_read = - 1 ; else _resp_read = k ; msg = new String ( buffer , 0 , k ) ; logline ( "RECV MSG: " + msg ) ; } else { byte [ ] buffer = new byte [ maxbytes ] ; if ( _resp_size <= maxbytes ) { n = _in . read ( buffer , 0 , _resp_size ) ; } else { n = _in . read ( buffer , 0 , maxbytes ) ; } if ( n >= 0 ) { _resp_read = n ; msg = new String ( buffer , 0 , n ) ; } else if ( n == - 1 ) throw new SoccomException ( SoccomException . SOCKET_CLOSED ) ; else throw new SoccomException ( SoccomException . RECV_ERROR ) ; logline ( "RECV MSG: " + msg ) ; } return msg ; } catch ( InterruptedIOException e ) { throw new SoccomException ( SoccomException . RECV_ERROR ) ; } catch ( IOException e ) { throw new SoccomException ( SoccomException . RECV_ERROR ) ; } } | The method receives the first part of response message from the server up to maxbytes bytes . Use getresp_hasmore and getresp_next to get getresp_rest to get the remaining part of messages . When the server sends the message using ENDM the string returned may be longer than maxbytes but only till the first line after that . When maxbytes is 0 the procedure reads the first line . | 704 | 82 |
13,948 | public void close ( ) { if ( _socket != null ) { try { _socket . close ( ) ; _socket = null ; } catch ( IOException e ) { System . err . println ( "Exception: " + e ) ; // throw new SoccomException(SoccomException.RECV_ERROR); } _in = null ; _out = null ; } } | Close the connection . This is automatically called at garbage collection but it is a good idea to voluntarily call it as soon as the connection is not needed any more . | 79 | 32 |
13,949 | protected TextService getServiceInstance ( Map < String , String > headers ) throws ServiceException { try { String requestPath = headers . get ( Listener . METAINFO_REQUEST_PATH ) ; String [ ] pathSegments = requestPath != null ? requestPath . split ( "/" ) : null ; if ( pathSegments == null ) throw new ServiceException ( ServiceException . INTERNAL_ERROR , "Unable to find a service or handler for request path: " + requestPath ) ; String contentType = headers . get ( Listener . METAINFO_CONTENT_TYPE ) ; String serviceClassName = MDW_REST_SERVICE_PROVIDER_PACKAGE + "." + pathSegments [ 0 ] ; try { // normal classloader -- built-in service Class < ? extends TextService > serviceClass = Class . forName ( serviceClassName ) . asSubclass ( TextService . class ) ; return serviceClass . newInstance ( ) ; } catch ( ClassNotFoundException ex ) { // try dynamic based on annotations eg: api/Users/dxoakes Class < ? extends RegisteredService > serviceType = Listener . CONTENT_TYPE_JSON . equals ( contentType ) ? JsonService . class : XmlService . class ; MdwServiceRegistry registry = MdwServiceRegistry . getInstance ( ) ; String pkgName = null ; for ( int i = 0 ; i < pathSegments . length ; i ++ ) { String pathSegment = pathSegments [ i ] ; if ( i == 0 ) pkgName = pathSegment ; else pkgName += "." + pathSegment ; Package pkg = PackageCache . getPackage ( pkgName ) ; if ( pkg != null ) { // try without any subpath first (@Path="/") TextService service = ( TextService ) registry . getDynamicServiceForPath ( pkg , serviceType , "/" ) ; if ( service == null && i < pathSegments . length - 1 ) { service = ( TextService ) registry . getDynamicServiceForPath ( pkg , serviceType , "/" + pathSegments [ i + 1 ] ) ; } if ( service != null ) return service ; } } // lastly, try process invoker mapping AssetRequest processRequest = ProcessRequests . getRequest ( headers . get ( Listener . METAINFO_HTTP_METHOD ) , requestPath ) ; if ( processRequest != null ) { return new ProcessInvoker ( processRequest ) ; } return null ; } } catch ( Exception ex ) { throw new ServiceException ( ServiceException . INTERNAL_ERROR , ex . getMessage ( ) , ex ) ; } } | Returns the service instance consulting the service registry if necessary . | 572 | 11 |
13,950 | protected Format getFormat ( Map < String , String > metaInfo ) { Format format = Format . json ; metaInfo . put ( Listener . METAINFO_CONTENT_TYPE , Listener . CONTENT_TYPE_JSON ) ; String formatParam = ( String ) metaInfo . get ( "format" ) ; if ( formatParam != null ) { if ( formatParam . equals ( "xml" ) ) { format = Format . xml ; metaInfo . put ( Listener . METAINFO_CONTENT_TYPE , Listener . CONTENT_TYPE_XML ) ; } else if ( formatParam . equals ( "text" ) ) { format = Format . text ; metaInfo . put ( Listener . METAINFO_CONTENT_TYPE , Listener . CONTENT_TYPE_TEXT ) ; } } else { if ( Listener . CONTENT_TYPE_XML . equals ( metaInfo . get ( Listener . METAINFO_CONTENT_TYPE ) ) || Listener . CONTENT_TYPE_XML . equals ( metaInfo . get ( Listener . METAINFO_CONTENT_TYPE . toLowerCase ( ) ) ) ) { format = Format . xml ; metaInfo . put ( Listener . METAINFO_CONTENT_TYPE , Listener . CONTENT_TYPE_XML ) ; } else if ( Listener . CONTENT_TYPE_TEXT . equals ( metaInfo . get ( Listener . METAINFO_CONTENT_TYPE ) ) || Listener . CONTENT_TYPE_TEXT . equals ( metaInfo . get ( Listener . METAINFO_CONTENT_TYPE . toLowerCase ( ) ) ) ) { format = Format . text ; metaInfo . put ( Listener . METAINFO_CONTENT_TYPE , Listener . CONTENT_TYPE_JSON ) ; } } return format ; } | Default format is now JSON . | 397 | 6 |
13,951 | @ Override @ Path ( "/{ownerType}/{ownerId}" ) @ ApiOperation ( value = "Retrieve attributes for an ownerType and ownerId" , notes = "Response is a generic JSON object with names/values." ) public JSONObject get ( String path , Map < String , String > headers ) throws ServiceException , JSONException { Map < String , String > parameters = getParameters ( headers ) ; String ownerType = getSegment ( path , 1 ) ; if ( ownerType == null ) // fall back to parameter ownerType = parameters . get ( "ownerType" ) ; if ( ownerType == null ) throw new ServiceException ( "Missing path segment: {ownerType}" ) ; String ownerId = getSegment ( path , 2 ) ; if ( ownerId == null ) // fall back to parameter ownerId = parameters . get ( "ownerId" ) ; if ( ownerId == null ) throw new ServiceException ( "Missing path segment: {ownerId}" ) ; try { Map < String , String > attrs = ServiceLocator . getWorkflowServices ( ) . getAttributes ( ownerType , Long . parseLong ( ownerId ) ) ; JSONObject attrsJson = new JsonObject ( ) ; for ( String name : attrs . keySet ( ) ) attrsJson . put ( name , attrs . get ( name ) ) ; return attrsJson ; } catch ( Exception ex ) { throw new ServiceException ( "Error loading attributes for " + ownerType + ": " + ownerId , ex ) ; } } | Retrieve attributes . | 334 | 4 |
13,952 | public void importAssetsFromGit ( ProgressMonitor ... monitors ) throws IOException { if ( inProgress ) throw new IOException ( "Asset import already in progress..." ) ; try { inProgress = true ; getOut ( ) . println ( "Importing from Git into: " + getProjectDir ( ) + "...(branch: " + branch + ")(Hard Reset: " + ( hardReset ? "YES)" : "NO)" ) ) ; // Check Asset inconsistencies Vercheck vercheck = new Vercheck ( ) ; vercheck . setConfigLoc ( getConfigLoc ( ) ) ; vercheck . setAssetLoc ( getAssetLoc ( ) ) ; vercheck . setGitRoot ( getGitRoot ( ) ) ; vercheck . setForImport ( true ) ; vercheck . setDebug ( true ) ; vercheck . run ( ) ; if ( vercheck . getErrorCount ( ) > 0 ) { throw new IOException ( "Asset version conflict(s). See log for details" ) ; } // Perform import (Git pull) versionControl . hardCheckout ( branch , hardReset ) ; // Clear cached previous asset revisions versionControl . clear ( ) ; // Capture new Refs in ASSET_REF after import (Git pull) and insert/update VALUE table Checkpoint checkpoint = new Checkpoint ( getEngineAssetRoot ( ) , versionControl , versionControl . getCommit ( ) , pooledConn ) ; try { checkpoint . updateRefs ( true ) ; } catch ( SQLException ex ) { throw new IOException ( ex . getMessage ( ) , ex ) ; } } catch ( Throwable ex ) { if ( ex instanceof IOException ) throw ( IOException ) ex ; else throw new IOException ( ex . getMessage ( ) , ex ) ; } finally { inProgress = false ; } } | This is for importing project assets from Git into an environment . | 392 | 12 |
13,953 | public void importGit ( ProgressMonitor ... monitors ) throws IOException { if ( inProgress ) throw new IOException ( "Asset already in progress..." ) ; try { inProgress = true ; Props props = new Props ( this ) ; VcInfo vcInfo = new VcInfo ( getGitRoot ( ) , props ) ; getOut ( ) . println ( "Importing from Git into: " + getProjectDir ( ) + "..." ) ; // CLI dependencies Git git = new Git ( getReleasesUrl ( ) , vcInfo , "checkVersionConsistency" , vcInfo . getBranch ( ) , getAssetLoc ( ) ) ; git . run ( monitors ) ; // Check Asset inconsistencies Vercheck vercheck = new Vercheck ( ) ; vercheck . setConfigLoc ( getConfigLoc ( ) ) ; vercheck . setAssetLoc ( getAssetLoc ( ) ) ; vercheck . setGitRoot ( getGitRoot ( ) ) ; vercheck . setDebug ( true ) ; vercheck . run ( ) ; if ( vercheck . getErrorCount ( ) > 0 ) { throw new IOException ( "Asset version conflict(s). See log for details" ) ; } // perform import (Git pull) git = new Git ( getReleasesUrl ( ) , vcInfo , "hardCheckout" , vcInfo . getBranch ( ) , isHardReset ( ) ) ; git . run ( monitors ) ; // capture new Refs in ASSET_REF after import (Git pull) DbInfo dbInfo = new DbInfo ( props ) ; Checkpoint checkpoint = new Checkpoint ( getReleasesUrl ( ) , vcInfo , getAssetRoot ( ) , dbInfo ) ; try { checkpoint . run ( monitors ) . updateRefs ( ) ; } catch ( SQLException ex ) { throw new IOException ( ex . getMessage ( ) , ex ) ; } } catch ( Throwable ex ) { if ( ex instanceof IOException ) throw ex ; else throw new IOException ( ex . getMessage ( ) , ex ) ; } finally { inProgress = false ; } } | This is for importing newly - discovered assets . | 461 | 9 |
13,954 | public < T extends RegisteredService > T getDynamicService ( Package pkg , Class < T > serviceInterface , String className ) { if ( dynamicServices . containsKey ( serviceInterface . getName ( ) ) && dynamicServices . get ( serviceInterface . getName ( ) ) . contains ( className ) ) { try { ClassLoader parentClassLoader = pkg == null ? getClass ( ) . getClassLoader ( ) : pkg . getClassLoader ( ) ; Class < ? > clazz = CompiledJavaCache . getClassFromAssetName ( parentClassLoader , className ) ; if ( clazz == null ) return null ; RegisteredService rs = ( RegisteredService ) ( clazz ) . newInstance ( ) ; T drs = serviceInterface . cast ( rs ) ; return drs ; } catch ( Exception ex ) { logger . severeException ( "Failed to get the dynamic registered service : " + className + " \n " + ex . getMessage ( ) , ex ) ; } } return null ; } | Get the Dynamic java instance for Registered Service | 217 | 8 |
13,955 | public void addDynamicService ( String serviceInterface , String className ) { if ( dynamicServices . containsKey ( serviceInterface ) ) { dynamicServices . get ( serviceInterface ) . add ( className ) ; } else { Set < String > classNamesSet = new HashSet < String > ( ) ; classNamesSet . add ( className ) ; dynamicServices . put ( serviceInterface , classNamesSet ) ; } } | Add Dynamic Java Registered Service class names for each service | 88 | 10 |
13,956 | public String [ ] getArrayFilter ( String key ) { String value = filters . get ( key ) ; if ( value == null ) return null ; String [ ] array = new String [ 0 ] ; if ( value . startsWith ( "[" ) ) { if ( value . length ( ) > 2 ) array = value . substring ( 1 , value . length ( ) - 1 ) . split ( "," ) ; } else if ( value . length ( ) > 1 ) { array = value . split ( "," ) ; } for ( int i = 0 ; i < array . length ; i ++ ) { String item = array [ i ] ; if ( ( item . startsWith ( "\"" ) && item . endsWith ( "\"" ) ) || ( item . startsWith ( "'" ) && item . endsWith ( "'" ) ) && item . length ( ) > 1 ) array [ i ] = item . substring ( 1 , item . length ( ) - 2 ) ; } return array ; } | Empty list returns null ; | 215 | 5 |
13,957 | public Map < String , String > getMapFilter ( String name ) { String value = filters . get ( name ) ; if ( value == null ) return null ; Map < String , String > map = new LinkedHashMap <> ( ) ; if ( value . startsWith ( "{" ) && value . endsWith ( "}" ) ) { for ( String entry : value . substring ( 1 , value . length ( ) - 1 ) . split ( "," ) ) { int eq = entry . indexOf ( ' ' ) ; if ( eq > 0 && eq < entry . length ( ) - 1 ) { String key = entry . substring ( 0 , eq ) . trim ( ) ; String val = entry . substring ( eq + 1 ) ; if ( ( val . startsWith ( "\"" ) && val . endsWith ( "\"" ) ) || ( val . startsWith ( "'" ) && val . endsWith ( "'" ) ) && val . length ( ) > 1 ) { val = val . substring ( 1 , val . length ( ) - 1 ) ; } else { val = val . trim ( ) ; } map . put ( key , val ) ; } } } return map . isEmpty ( ) ? null : map ; } | Empty map returns null as does invalid format . | 268 | 9 |
13,958 | public String getServiceSummaryVariableName ( Process processDefinition ) { for ( Activity activity : processDefinition . getActivities ( ) ) { String attr = activity . getAttribute ( "serviceSummaryVariable" ) ; if ( attr != null ) return attr ; } return null ; } | Walks through all activities looking for the attribute . | 60 | 10 |
13,959 | public JSONObject getJson ( ) throws JSONException { JSONObject json = create ( ) ; json . put ( "id" , getLogicalId ( ) ) ; json . put ( "to" , "A" + toId ) ; if ( completionCode != null ) json . put ( "resultCode" , completionCode ) ; if ( eventType != null ) json . put ( "event" , EventType . getEventTypeName ( eventType ) ) ; if ( attributes != null && ! attributes . isEmpty ( ) ) json . put ( "attributes" , Attribute . getAttributesJson ( attributes ) ) ; return json ; } | Does not populate from field since JSON transitions are children of activities . | 139 | 13 |
13,960 | private static void initializeJavaSourceArtifacts ( ) throws DataAccessException , IOException , CachingException { logger . info ( "Initializing Java source assets..." ) ; long before = System . currentTimeMillis ( ) ; for ( Asset javaSource : AssetCache . getAssets ( Asset . JAVA ) ) { Package pkg = PackageCache . getAssetPackage ( javaSource . getId ( ) ) ; String packageName = pkg == null ? null : JavaNaming . getValidPackageName ( pkg . getName ( ) ) ; String className = JavaNaming . getValidClassName ( javaSource . getName ( ) ) ; File dir = createNeededDirs ( packageName ) ; File file = new File ( dir + "/" + className + ".java" ) ; if ( file . exists ( ) ) file . delete ( ) ; String javaCode = javaSource . getStringContent ( ) ; if ( javaCode != null ) { javaCode = doCompatibilityCodeSubstitutions ( packageName + "." + className , javaCode ) ; FileWriter writer = new FileWriter ( file ) ; writer . write ( javaCode ) ; writer . close ( ) ; } } if ( logger . isDebugEnabled ( ) ) logger . debug ( "Time to initialize Java source assets: " + ( System . currentTimeMillis ( ) - before ) + " ms" ) ; } | Writes the java - language assets into the temporary directory . This is only needed for compilation dependencies . | 301 | 20 |
13,961 | private static void preCompileJavaSourceArtifacts ( ) { if ( preCompiled != null ) { for ( String preCompClass : preCompiled ) { logger . info ( "Precompiling dynamic Java asset class: " + preCompClass ) ; try { Asset javaAsset = AssetCache . getAsset ( preCompClass , Asset . JAVA ) ; Package pkg = PackageCache . getAssetPackage ( javaAsset . getId ( ) ) ; String packageName = pkg == null ? null : JavaNaming . getValidPackageName ( pkg . getName ( ) ) ; String className = ( pkg == null ? "" : packageName + "." ) + JavaNaming . getValidClassName ( javaAsset . getName ( ) ) ; getClass ( null , pkg , className , javaAsset . getStringContent ( ) ) ; } catch ( Exception ex ) { // let other classes continue to process logger . severeException ( ex . getMessage ( ) , ex ) ; } } } } | Precompile designated Java Source artifacts . | 217 | 8 |
13,962 | public static int unitsToSeconds ( String interval , String unit ) { if ( interval == null || interval . isEmpty ( ) ) return 0 ; else if ( unit == null ) return ( int ) ( Double . parseDouble ( interval ) ) ; else if ( unit . equals ( INTERVAL_DAYS ) ) return ( int ) ( Double . parseDouble ( interval ) * 86400 ) ; else if ( unit . equals ( INTERVAL_HOURS ) ) return ( int ) ( Double . parseDouble ( interval ) * 3600 ) ; else if ( unit . equals ( INTERVAL_MINUTES ) ) return ( int ) ( Double . parseDouble ( interval ) * 60 ) ; else return ( int ) ( Double . parseDouble ( interval ) ) ; } | Convert interval of specified unit to seconds | 162 | 8 |
13,963 | public static String secondsToUnits ( int seconds , String unit ) { if ( unit == null ) return String . valueOf ( seconds ) ; else if ( unit . equals ( INTERVAL_DAYS ) ) return String . valueOf ( Math . round ( seconds / 86400 ) ) ; else if ( unit . equals ( INTERVAL_HOURS ) ) return String . valueOf ( Math . round ( seconds / 3600 ) ) ; else if ( unit . equals ( INTERVAL_MINUTES ) ) return String . valueOf ( Math . round ( seconds / 60 ) ) ; else return String . valueOf ( seconds ) ; } | Convert seconds to specified units | 135 | 6 |
13,964 | @ SuppressWarnings ( "unused" ) public String getAssetPath ( ) { String relPath = getRelPath ( ) ; return relPath . substring ( 0 , relPath . length ( ) - getAsset ( ) . getName ( ) . length ( ) - 1 ) . replace ( ' ' , ' ' ) + "/" + getAsset ( ) . getName ( ) ; } | Accessed in react default index . html substitution . | 86 | 10 |
13,965 | @ Override @ Path ( "/{documentId}" ) public JSONObject get ( String path , Map < String , String > headers ) throws ServiceException , JSONException { WorkflowServices workflowServices = ServiceLocator . getWorkflowServices ( ) ; String docId = getSegment ( path , 1 ) ; if ( docId == null ) { throw new ServiceException ( ServiceException . BAD_REQUEST , "Invalid path: " + path ) ; } try { JSONObject json = new JSONObject ( ) ; json . put ( "value" , workflowServices . getDocumentStringValue ( Long . valueOf ( docId ) ) ) ; return json ; } catch ( NumberFormatException e ) { throw new ServiceException ( ServiceException . BAD_REQUEST , "Invalid path: " + path , e ) ; } } | Retrieve a document string value | 173 | 6 |
13,966 | protected URL getRequestUrl ( Map < String , String > headers ) throws ServiceException { String requestUrl = headers . get ( Listener . METAINFO_REQUEST_URL ) ; if ( requestUrl == null ) throw new ServiceException ( "Missing header: " + Listener . METAINFO_REQUEST_URL ) ; String queryStr = "" ; if ( ! StringHelper . isEmpty ( headers . get ( Listener . METAINFO_REQUEST_QUERY_STRING ) ) ) queryStr = "?" + headers . get ( Listener . METAINFO_REQUEST_QUERY_STRING ) ; try { return new URL ( requestUrl + queryStr ) ; } catch ( MalformedURLException ex ) { throw new ServiceException ( ServiceException . INTERNAL_ERROR , ex . getMessage ( ) , ex ) ; } } | Includes query string . | 185 | 4 |
13,967 | protected UserAction getUserAction ( User user , String path , Object content , Map < String , String > headers ) { Action action = getAction ( path , content , headers ) ; Entity entity = getEntity ( path , content , headers ) ; Long entityId = getEntityId ( path , content , headers ) ; String descrip = getEntityDescription ( path , content , headers ) ; if ( descrip . length ( ) > 1000 ) descrip = descrip . substring ( 0 , 999 ) ; UserAction userAction = new UserAction ( user . getCuid ( ) , action , entity , entityId , descrip ) ; userAction . setSource ( getSource ( ) ) ; return userAction ; } | For audit logging . | 151 | 4 |
13,968 | protected Long getEntityId ( String path , Object content , Map < String , String > headers ) { return 0L ; } | Override if entity has a meaningful ID . | 26 | 8 |
13,969 | protected String getSub ( String path ) { int slash = path . indexOf ( ' ' ) ; if ( slash > 0 && slash < path . length ( ) - 1 ) // the first part of the path is what got us here return path . substring ( slash + 1 ) ; else return null ; } | Minus the base path that triggered this service . | 65 | 10 |
13,970 | protected Entity getEntity ( String path , Object content , Map < String , String > headers ) { return Entity . Other ; } | Should be overridden . Avoid using Entity . Other . | 26 | 11 |
13,971 | protected String getAuthUser ( Map < String , String > headers ) { return headers . get ( Listener . AUTHENTICATED_USER_HEADER ) ; } | returns authenticated user cuid | 35 | 6 |
13,972 | protected void authorizeExport ( Map < String , String > headers ) throws AuthorizationException { String path = headers . get ( Listener . METAINFO_REQUEST_PATH ) ; User user = authorize ( path , new JsonObject ( ) , headers ) ; Action action = Action . Export ; Entity entity = getEntity ( path , null , headers ) ; Long entityId = new Long ( 0 ) ; String descrip = path ; if ( descrip . length ( ) > 1000 ) descrip = descrip . substring ( 0 , 999 ) ; UserAction exportAction = new UserAction ( user == null ? "unknown" : user . getName ( ) , action , entity , entityId , descrip ) ; exportAction . setSource ( getSource ( ) ) ; auditLog ( exportAction ) ; } | Also audit logs . | 170 | 4 |
13,973 | public Map < String , String > getRequestHeaders ( ) { // If we already set the headers when logging request metadata, use them if ( super . getRequestHeaders ( ) != null ) return super . getRequestHeaders ( ) ; try { Map < String , String > headers = null ; String headersVar = getAttributeValueSmart ( HEADERS_VARIABLE ) ; if ( headersVar != null ) { Process processVO = getProcessDefinition ( ) ; Variable variableVO = processVO . getVariable ( headersVar ) ; if ( variableVO == null ) throw new ActivityException ( "Headers variable '" + headersVar + "' is not defined for process " + processVO . getLabel ( ) ) ; if ( ! variableVO . getType ( ) . startsWith ( "java.util.Map" ) ) throw new ActivityException ( "Headers variable '" + headersVar + "' must be of type java.util.Map" ) ; Object headersObj = getVariableValue ( headersVar ) ; if ( headersObj != null ) { headers = new HashMap <> ( ) ; for ( Object key : ( ( Map < ? , ? > ) headersObj ) . keySet ( ) ) { headers . put ( key . toString ( ) , ( ( Map < ? , ? > ) headersObj ) . get ( key ) . toString ( ) ) ; } } } Object authProvider = getAuthProvider ( ) ; if ( authProvider instanceof AuthTokenProvider ) { if ( headers == null ) headers = new HashMap <> ( ) ; URL endpoint = new URL ( getEndpointUri ( ) ) ; String user = getAttribute ( AUTH_USER ) ; String password = getAttribute ( AUTH_PASSWORD ) ; String appId = getAttribute ( AUTH_APP_ID ) ; if ( appId != null && appId . length ( ) > 0 ) { Map < String , String > options = new HashMap <> ( ) ; options . put ( "appId" , appId ) ; ( ( AuthTokenProvider ) authProvider ) . setOptions ( options ) ; } String token = new String ( ( ( AuthTokenProvider ) authProvider ) . getToken ( endpoint , user , password ) ) ; headers . put ( "Authorization" , "Bearer " + token ) ; } // Set the headers so that we don't try and set them next time this method gets called super . setRequestHeaders ( headers ) ; return headers ; } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; return null ; } } | Override to specify HTTP request headers . | 552 | 7 |
13,974 | public static String getConfigLocation ( ) { if ( configLocation == null ) { String configLoc = System . getProperty ( MDW_CONFIG_LOCATION ) ; if ( configLoc != null ) { if ( ! configLoc . endsWith ( "/" ) ) configLoc = configLoc + "/" ; configLocation = configLoc ; System . out . println ( "Loading configuration files from '" + new File ( configLoc ) . getAbsolutePath ( ) + "'" ) ; } } return configLocation ; } | Directory where MDW config files can be found . | 111 | 10 |
13,975 | public static PropertyManager getInstance ( ) { if ( instance == null ) { try { initializePropertyManager ( ) ; } catch ( StartupException e ) { // should not reach here, as the property manager should be // initialized by now throw new RuntimeException ( e ) ; } // container property manager will never hit this } return instance ; } | returns the handle to the property manager | 70 | 8 |
13,976 | public static String locate ( String className , ClassLoader classLoader ) { String resource = new String ( className ) ; // format the file name into a valid resource name if ( ! resource . startsWith ( "/" ) ) { resource = "/" + resource ; } resource = resource . replace ( ' ' , ' ' ) ; resource = resource + ".class" ; // attempt to locate the file using the class loader URL classUrl = classLoader . getResource ( resource ) ; if ( classUrl == null && classLoader == ClasspathUtil . class . getClassLoader ( ) ) { // Apparently clazz.getResource() works sometimes when clazz.getClassLoader().getResource() does not. // TODO: why? classUrl = ClasspathUtil . class . getResource ( resource ) ; } if ( classUrl == null ) { return "\nClass not found: [" + className + "]" ; } else { return classUrl . getFile ( ) ; } } | Finds the location of the version of a particular class that will be used by the Java runtime . Output goes to standard out . | 208 | 26 |
13,977 | public JSONObject getJson ( ) throws JSONException { JSONObject json = create ( ) ; json . put ( "type" , type ) ; json . put ( "category" , getCategory ( ) ) ; if ( label != null && ! label . isEmpty ( ) ) json . put ( "label" , label ) ; if ( displaySequence != null && displaySequence > 0 ) json . put ( "sequence" , displaySequence ) ; if ( display != null ) json . put ( "display" , display . toString ( ) ) ; return json ; } | Serialized as an object so name is not included . | 123 | 11 |
13,978 | public static String initializeLogging ( ) throws IOException { System . setProperty ( "org.slf4j.simpleLogger.logFile" , "System.out" ) ; System . setProperty ( "org.slf4j.simpleLogger.showDateTime" , "true" ) ; System . setProperty ( "org.slf4j.simpleLogger.dateTimeFormat" , "yyyyMMdd.HH:mm:ss.SSS" ) ; // Peek at mdw.yaml to find default logging level, but do not initialize PropertyManager // which could initialize slf4j prematurely. (Works only with yaml config file). String mdwLogLevel = null ; File mdwYaml = getConfigurationFile ( "mdw.yaml" ) ; if ( mdwYaml . exists ( ) ) { YamlProperties yamlProps = new YamlProperties ( "mdw" , mdwYaml ) ; mdwLogLevel = yamlProps . getString ( "mdw.logging.level" ) ; if ( mdwLogLevel != null ) { if ( mdwLogLevel . equals ( "MDW_DEBUG" ) ) mdwLogLevel = "TRACE" ; System . setProperty ( "org.slf4j.simpleLogger.log.com.centurylink.mdw" , mdwLogLevel . toLowerCase ( ) ) ; } } return mdwLogLevel ; } | For Spring Boot with slf4j SimpleLogger an opportunity to initialize logging before Spring starts logging . Otherwise for slf4j properties have already been defaulted before we have a chance to set them . | 321 | 42 |
13,979 | public List < TaskInstance > getSubtaskInstances ( Long masterTaskInstId ) throws DataAccessException { try { db . openConnection ( ) ; String query = "select " + getTaskInstanceSelect ( ) + " from TASK_INSTANCE ti where TASK_INST_SECONDARY_OWNER = ? and TASK_INST_SECONDARY_OWNER_ID = ?" ; Object [ ] args = new Object [ 2 ] ; args [ 0 ] = OwnerType . TASK_INSTANCE ; args [ 1 ] = masterTaskInstId ; ResultSet rs = db . runSelect ( query , args ) ; List < TaskInstance > taskInsts = new ArrayList < TaskInstance > ( ) ; while ( rs . next ( ) ) { taskInsts . add ( getTaskInstanceSub ( rs , false ) ) ; } return taskInsts ; } catch ( Exception e ) { throw new DataAccessException ( 0 , "failed to get task instances" , e ) ; } finally { db . closeConnection ( ) ; } } | Returns shallow TaskInstances . | 228 | 6 |
13,980 | public void setTaskInstanceGroups ( Long taskInstId , String [ ] groups ) throws DataAccessException { try { db . openConnection ( ) ; // get group IDs StringBuffer sb = new StringBuffer ( ) ; sb . append ( "select USER_GROUP_ID from USER_GROUP where GROUP_NAME in (" ) ; for ( int i = 0 ; i < groups . length ; i ++ ) { if ( i > 0 ) sb . append ( "," ) ; sb . append ( "'" ) . append ( groups [ i ] ) . append ( "'" ) ; } sb . append ( ")" ) ; ResultSet rs = db . runSelect ( sb . toString ( ) ) ; List < Long > groupIds = new ArrayList < Long > ( ) ; while ( rs . next ( ) ) { groupIds . add ( rs . getLong ( 1 ) ) ; } // delete existing groups String query = "" ; if ( db . isMySQL ( ) ) query = "delete TG1 from TASK_INST_GRP_MAPP TG1 join TASK_INST_GRP_MAPP TG2 " + "using (TASK_INSTANCE_ID, USER_GROUP_ID) " + "where TG2.TASK_INSTANCE_ID=?" ; else query = "delete from TASK_INST_GRP_MAPP where TASK_INSTANCE_ID=?" ; db . runUpdate ( query , taskInstId ) ; if ( db . isMySQL ( ) ) db . commit ( ) ; // MySQL will lock even when no rows were deleted and using unique index, so commit so that multiple session inserts aren't deadlocked // insert groups query = "insert into TASK_INST_GRP_MAPP " + "(TASK_INSTANCE_ID,USER_GROUP_ID,CREATE_DT) values (?,?," + now ( ) + ")" ; db . prepareStatement ( query ) ; Object [ ] args = new Object [ 2 ] ; args [ 0 ] = taskInstId ; for ( Long group : groupIds ) { args [ 1 ] = group ; db . runUpdateWithPreparedStatement ( args ) ; } db . commit ( ) ; } catch ( Exception e ) { db . rollback ( ) ; throw new DataAccessException ( 0 , "failed to associate task instance groups" , e ) ; } finally { db . closeConnection ( ) ; } } | new task instance group mapping | 537 | 5 |
13,981 | public void setTaskInstanceIndices ( Long taskInstId , Map < String , String > indices ) throws DataAccessException { try { db . openConnection ( ) ; // delete existing indices String query = "delete from INSTANCE_INDEX where INSTANCE_ID=? and OWNER_TYPE='TASK_INSTANCE'" ; // insert new ones db . runUpdate ( query , taskInstId ) ; query = "insert into INSTANCE_INDEX " + "(INSTANCE_ID,OWNER_TYPE,INDEX_KEY,INDEX_VALUE,CREATE_DT) values (?,'TASK_INSTANCE',?,?," + now ( ) + ")" ; db . prepareStatement ( query ) ; Object [ ] args = new Object [ 3 ] ; args [ 0 ] = taskInstId ; for ( String key : indices . keySet ( ) ) { args [ 1 ] = key ; args [ 2 ] = indices . get ( key ) ; if ( ! StringHelper . isEmpty ( ( String ) args [ 2 ] ) ) db . runUpdateWithPreparedStatement ( args ) ; } db . commit ( ) ; } catch ( Exception e ) { db . rollback ( ) ; throw new DataAccessException ( 0 , "failed to add task instance indices" , e ) ; } finally { db . closeConnection ( ) ; } } | new task instance indices | 290 | 4 |
13,982 | @ Override @ Path ( "/{solutionId}" ) @ ApiOperation ( value = "Retrieve a solution or all solutions" , notes = "If {solutionId} is not present, returns all solutions." , response = Solution . class , responseContainer = "List" ) public JSONObject get ( String path , Map < String , String > headers ) throws ServiceException , JSONException { SolutionServices solutionServices = ServiceLocator . getSolutionServices ( ) ; String id = getSegment ( path , 1 ) ; if ( id != null ) { Solution solution = solutionServices . getSolution ( id ) ; if ( solution == null ) throw new ServiceException ( 404 , "Solution not found: " + id ) ; else return solution . getJson ( ) ; } else { Query query = getQuery ( path , headers ) ; return solutionServices . getSolutions ( query ) . getJson ( ) ; } } | Retrieve a solution or the solutions list . | 196 | 9 |
13,983 | protected List < Value > getDefinedValues ( TaskRuntimeContext runtimeContext ) { List < Value > values = new ArrayList < Value > ( ) ; String varAttr = runtimeContext . getTaskAttribute ( TaskAttributeConstant . VARIABLES ) ; if ( ! StringHelper . isEmpty ( varAttr ) ) { List < String [ ] > parsed = StringHelper . parseTable ( varAttr , ' ' , ' ' , 5 ) ; for ( String [ ] one : parsed ) { String name = one [ 0 ] ; Value value = new Value ( name ) ; if ( one [ 1 ] != null && ! one [ 1 ] . isEmpty ( ) ) value . setLabel ( one [ 1 ] ) ; value . setDisplay ( Value . getDisplay ( one [ 2 ] ) ) ; if ( one [ 3 ] != null && ! one [ 3 ] . isEmpty ( ) ) value . setSequence ( Integer . parseInt ( one [ 3 ] ) ) ; if ( one [ 4 ] != null && ! one [ 4 ] . isEmpty ( ) ) value . setIndexKey ( one [ 4 ] ) ; if ( value . isExpression ( ) ) { value . setType ( String . class . getName ( ) ) ; } else { Variable var = runtimeContext . getProcess ( ) . getVariable ( name ) ; if ( var != null ) value . setType ( var . getType ( ) ) ; } values . add ( value ) ; } } return values ; } | Minus runtime values . | 322 | 5 |
13,984 | private String getCallingClassName ( ) { StackTraceElement [ ] stack = ( new Throwable ( ) ) . getStackTrace ( ) ; String className = stack [ 4 ] . getClassName ( ) ; if ( className == null || ! ( className . startsWith ( "com.centurylink" ) || className . startsWith ( "com.qwest" ) ) ) { className = stack [ 3 ] . getClassName ( ) ; // try next level up if ( className == null || ! ( className . startsWith ( "com.centurylink" ) || className . startsWith ( "com.qwest" ) ) ) { selfLogger . debug ( "Unfamiliar Log4J Logger: '" + className + "'; using Default '" + DEFAULT_LOGGER_NAME + "'" ) ; className = DEFAULT_LOGGER_NAME ; } } return className ; } | Get the name of the class to use as the Logger name | 203 | 13 |
13,985 | protected HttpResponse readInput ( ) throws IOException { InputStream is = null ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; try { byte [ ] buffer = new byte [ 2048 ] ; try { is = connection . getInputStream ( ) ; while ( maxBytes == - 1 || baos . size ( ) < maxBytes ) { int bytesRead = is . read ( buffer ) ; if ( bytesRead == - 1 ) break ; baos . write ( buffer , 0 , bytesRead ) ; } response = new HttpResponse ( baos . toByteArray ( ) ) ; return response ; } catch ( IOException ex ) { InputStream eis = null ; try { eis = connection . getErrorStream ( ) ; while ( maxBytes == - 1 || baos . size ( ) < maxBytes ) { int bytesRead = eis . read ( buffer ) ; if ( bytesRead == - 1 ) break ; baos . write ( buffer , 0 , bytesRead ) ; } response = new HttpResponse ( baos . toByteArray ( ) ) ; return response ; } catch ( Exception ex2 ) { // throw original exception } finally { if ( eis != null ) { eis . close ( ) ; } } throw ex ; } } finally { if ( is != null ) is . close ( ) ; connection . disconnect ( ) ; if ( response != null ) { response . setCode ( connection . getResponseCode ( ) ) ; response . setMessage ( connection . getResponseMessage ( ) ) ; } headers = new HashMap < String , String > ( ) ; for ( String headerKey : connection . getHeaderFields ( ) . keySet ( ) ) { if ( headerKey == null ) headers . put ( "HTTP" , connection . getHeaderField ( headerKey ) ) ; else headers . put ( headerKey , connection . getHeaderField ( headerKey ) ) ; } } } | Populates the response member . Closes the connection . | 410 | 11 |
13,986 | public static String [ ] extractBasicAuthCredentials ( String authHeader ) { return new String ( Base64 . decodeBase64 ( authHeader . substring ( "Basic " . length ( ) ) . getBytes ( ) ) ) . split ( ":" ) ; } | In return array zeroth element is user and first is password . | 57 | 14 |
13,987 | public AssetRef retrieveRef ( String name ) throws IOException , SQLException { String select = "select definition_id, name, ref from ASSET_REF where name = ?" ; try ( Connection conn = getDbConnection ( ) ; PreparedStatement stmt = conn . prepareStatement ( select ) ) { stmt . setString ( 1 , name ) ; try ( ResultSet rs = stmt . executeQuery ( ) ) { if ( rs . next ( ) ) { return new AssetRef ( name , rs . getLong ( "definition_id" ) , rs . getString ( "ref" ) ) ; } } } return null ; } | Finds an asset ref from the database by asset name . | 139 | 12 |
13,988 | public AssetRef retrieveRef ( Long id ) throws IOException , SQLException { String select = "select definition_id, name, ref from ASSET_REF where definition_id = ?" ; try ( Connection conn = getDbConnection ( ) ; PreparedStatement stmt = conn . prepareStatement ( select ) ) { stmt . setLong ( 1 , id ) ; try ( ResultSet rs = stmt . executeQuery ( ) ) { if ( rs . next ( ) ) { return new AssetRef ( rs . getString ( "name" ) , id , rs . getString ( "ref" ) ) ; } } } return null ; } | Finds an asset ref from the database by definitionID . | 139 | 12 |
13,989 | public List < AssetRef > retrieveAllRefs ( Date cutoffDate ) throws IOException , SQLException { List < AssetRef > assetRefList = null ; String select = "select definition_id, name, ref from ASSET_REF " ; if ( cutoffDate != null ) select += "where ARCHIVE_DT >= ? " ; select += "order by ARCHIVE_DT desc" ; try ( Connection conn = getDbConnection ( ) ; PreparedStatement stmt = conn . prepareStatement ( select ) ) { if ( cutoffDate != null ) stmt . setTimestamp ( 1 , new Timestamp ( cutoffDate . getTime ( ) ) ) ; try ( ResultSet rs = stmt . executeQuery ( ) ) { assetRefList = new ArrayList < AssetRef > ( ) ; while ( rs . next ( ) ) { String name = rs . getString ( "name" ) ; if ( name != null && ! name . endsWith ( "v0" ) ) // Ignore version 0 assets assetRefList . add ( new AssetRef ( rs . getString ( "name" ) , rs . getLong ( "definition_id" ) , rs . getString ( "ref" ) ) ) ; } } } return assetRefList ; } | Finds all asset refs from the database since cutoffDate or all if cutoffDate is null . | 270 | 20 |
13,990 | public void updateRefs ( boolean assetImport ) throws SQLException , IOException { List < AssetRef > refs = getCurrentRefs ( ) ; if ( refs == null || refs . isEmpty ( ) ) getOut ( ) . println ( "Skipping ASSET_REF table insert/update due to empty current assets" ) ; else { String select = "select name, ref from ASSET_REF where definition_id = ?" ; try ( Connection conn = getDbConnection ( ) ; PreparedStatement stmt = conn . prepareStatement ( select ) ) { for ( AssetRef ref : refs ) { stmt . setLong ( 1 , ref . getDefinitionId ( ) ) ; try ( ResultSet rs = stmt . executeQuery ( ) ) { // DO NOT update existing refs with newer commitID // Doing so can obliterate previous commitID from ASSET_REF table // which will prevent auto-import detection in cluster envs if ( ! rs . next ( ) ) { String insert = "insert into ASSET_REF (definition_id, name, ref) values (?, ?, ?)" ; try ( PreparedStatement insertStmt = conn . prepareStatement ( insert ) ) { insertStmt . setLong ( 1 , ref . getDefinitionId ( ) ) ; insertStmt . setString ( 2 , ref . getName ( ) ) ; insertStmt . setString ( 3 , ref . getRef ( ) ) ; insertStmt . executeUpdate ( ) ; if ( ! conn . getAutoCommit ( ) ) conn . commit ( ) ; } } } } if ( assetImport ) updateRefValue ( ) ; } } } | Update refs in db . | 356 | 6 |
13,991 | public static Tracing getTracing ( String serviceName , CurrentTraceContext context ) { Tracing tracing = Tracing . current ( ) ; if ( tracing == null ) { // TODO reporter based on prop/config tracing = getBuilder ( serviceName , context ) . build ( ) ; } return tracing ; } | Get or build tracing . | 66 | 5 |
13,992 | public boolean match ( String accessPath ) { if ( extension != null ) { for ( int i = accessPath . length ( ) - 1 ; i >= 0 ; i -- ) { if ( accessPath . charAt ( i ) == ' ' ) { String ext = accessPath . substring ( i + 1 ) ; if ( extension . equals ( ext ) ) { return true ; } break ; } } } if ( accessPath . equals ( path ) ) { return true ; } if ( prefix != null && accessPath . startsWith ( prefix ) ) { return true ; } return false ; } | Checks for a match . | 125 | 6 |
13,993 | public boolean send ( String topic , String message ) throws IOException { List < Session > sessions = topicSubscribers . get ( topic ) ; if ( sessions != null ) { for ( Session session : sessions ) { session . getBasicRemote ( ) . sendText ( message ) ; } } return sessions != null ; } | Returns true if any subscribers . | 67 | 6 |
13,994 | @ GET public JSONObject get ( String path , Map < String , String > headers ) throws ServiceException , JSONException { throw new ServiceException ( ServiceException . NOT_ALLOWED , "GET not implemented" ) ; } | Retrieve an existing entity or relationship . | 47 | 8 |
13,995 | @ POST public JSONObject post ( String path , JSONObject content , Map < String , String > headers ) throws ServiceException , JSONException { throw new ServiceException ( ServiceException . NOT_ALLOWED , "POST not implemented" ) ; } | Create a new entity or relationship . Or perform other action requests that cannot be categorized into put or delete . | 51 | 21 |
13,996 | @ PUT public JSONObject put ( String path , JSONObject content , Map < String , String > headers ) throws ServiceException , JSONException { throw new ServiceException ( ServiceException . NOT_ALLOWED , "PUT not implemented" ) ; } | Update an existing entity with different data . | 52 | 8 |
13,997 | @ DELETE public JSONObject delete ( String path , JSONObject content , Map < String , String > headers ) throws ServiceException , JSONException { throw new ServiceException ( ServiceException . NOT_ALLOWED , "DELETE not implemented" ) ; } | Delete an existing entity or relationship . | 55 | 7 |
13,998 | public String export ( String downloadFormat , Map < String , String > headers ) throws ServiceException { try { JsonExport exporter = getExporter ( headers ) ; if ( Listener . DOWNLOAD_FORMAT_EXCEL . equals ( downloadFormat ) ) return exporter . exportXlsxBase64 ( ) ; else if ( Listener . DOWNLOAD_FORMAT_ZIP . equals ( downloadFormat ) ) return exporter . exportZipBase64 ( ) ; else throw new ServiceException ( HTTP_400_BAD_REQUEST , "Unsupported download format: " + downloadFormat ) ; } catch ( ServiceException ex ) { throw ex ; } catch ( Exception ex ) { throw new ServiceException ( HTTP_500_INTERNAL_ERROR , ex . getMessage ( ) , ex ) ; } } | Binary content must be Base64 encoded for API compatibility . | 174 | 12 |
13,999 | protected JSONObject invokeServiceProcess ( String name , Object request , String requestId , Map < String , Object > parameters , Map < String , String > headers ) throws ServiceException { JSONObject responseJson ; Map < String , String > responseHeaders = new HashMap <> ( ) ; Object responseObject = ServiceLocator . getWorkflowServices ( ) . invokeServiceProcess ( name , request , requestId , parameters , headers , responseHeaders ) ; if ( responseObject instanceof JSONObject ) responseJson = ( JSONObject ) responseObject ; else if ( responseObject instanceof Jsonable ) responseJson = ( ( Jsonable ) responseObject ) . getJson ( ) ; else throw new ServiceException ( HTTP_500_INTERNAL_ERROR , "Unsupported response type: " + ( responseObject == null ? null : responseObject . getClass ( ) ) ) ; for ( String key : responseHeaders . keySet ( ) ) headers . put ( key , responseHeaders . get ( key ) ) ; return responseJson ; } | Helper method for invoking a service process . Populates response headers from variable value . | 225 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.