we know this is a <code>&lt;process-application ... /&gt;</code> structure.
497794
@Override
  protected void parseRootElement() {

    List<ProcessEngineXml> processEngines = new ArrayList<ProcessEngineXml>();
    List<ProcessArchiveXml> processArchives = new ArrayList<ProcessArchiveXml>();

    for (Element element : rootElement.elements()) {

      if(PROCESS_ENGINE.equals(element.getTagName())) {
        parseProcessEngine(element, processEngines);

      } else if(PROCESS_ARCHIVE.equals(element.getTagName())) {
        parseProcessArchive(element, processArchives);

      }

    }

    processesXml = new ProcessesXmlImpl(processEngines, processArchives);

  }
387835
public boolean isAnyProcessInTreeAlive() {
    for (Integer pId : processTree.keySet()) {
      if (isAlive(pId.toString())) {
        return true;
      }
    }
    return false;
  }
563786
private boolean processTemplate(ApplicationRequest appRequest,
                                    ApplicationResponse appResponse)
        throws IOException {
        
        // check if redirect or erroring out
        if (appResponse.isRedirectOrError()) {
            return false;
        }

        // set initial content type and helper attributes
        appResponse.setContentType("text/html");
        appRequest.setAttribute(this.getClass().getName(), this);

        // lookup template
        Template template = (Template)appRequest.getTemplate();

        // process as resource if no template available
        if (template == null) {
            if (!processResource(appRequest, appResponse)) {
                appResponse.sendError(404);
                return false;
            }
            return true;
        }
        
        long endTime = 0L;
        long startTime = 0L;
        long contentLength = 0;

        TemplateStats templateStats = null; 
        if (mInstrumentationEnabled) {
            templateStats = mTeaServletRequestStats.getStats(template.getName());
        }
        
        try {
	        Object[] params = null;
	        try {    
	            if (templateStats != null) {
	                templateStats.incrementServicing();
	            }

	            // Fill in the parameters to pass to the template.
	            Class<?>[] paramTypes = template.getParameterTypes();
	            if (paramTypes.length == 0) {
	                params = NO_PARAMS;
	            }
	            else {
	                params = new Object[paramTypes.length];
	                String[] paramNames = template.getParameterNames();
	                for (int i=0; i<paramNames.length; i++) {
	                    String paramName = paramNames[i];
	                    if (paramName == null) {
	                        continue;
	                    }
	                
	                    Class<?> paramType = paramTypes[i];
	                
	                    if (!paramType.isArray()) {
	                        String value = appRequest.getParameter(paramName);
	                        if (value == null || paramType == String.class) {
	                            params[i] = value;
	                        }
	                        else {
	                            params[i] = convertParameter(value, paramType);
	                        }
	                    }
	                    else {
	                        String[] values =
	                            appRequest.getParameterValues(paramName);
	                        if (values == null || paramType == String[].class) {
	                            params[i] = values;
	                        }
	                        else {
	                            paramType = paramType.getComponentType();
	                            Object converted =
	                                Array.newInstance(paramType, values.length);
	                            params[i] = converted;
	                            for (int j=0; j<values.length; j++) {
	                                Array.set
	                                    (converted, j,
	                                     convertParameter(values[j], paramType));
	                            }
	                        }
	                    }
	                }
	            }
	
	            startTime = System.currentTimeMillis();
	            try {
	                try {
	                    appRequest.getTemplate()
	                        .execute(appResponse.getHttpContext(), params);
	                }
	                catch (ContextCreationException cce) {
	                    // unwrap the inner exception
	                    throw (Exception)cce.getUndeclaredThrowable();
	                }
	            }
	            catch (AbortTemplateException e) {
	                if (DEBUG) {
	                    mLog.debug("Template execution aborted!");
	                    mLog.debug(e);
	                }
	            }
	            catch (RuntimeException e) {
	                if (getEngine()
	                    .getTemplateSource().isExceptionGuardianEnabled()) {
	                    // Just log the error and use what the template wrote out.
	                    mLog.error(e);
	                }
	                else {
	                    throw new ServletException(e);
	                }
	            }
	            catch (IOException e) {
	            	// TODO: shouldn't we be throwing this as a ServletException?
	            	//       otherwise its not logged to the TeaLog.
	                throw e;
	            }
	            catch (ServletException e) {
	                throw e;
	            }
	            catch (Exception e) {
	                throw new ServletException(e);
	            }
	            // TODO: shouldn't we be catching errors and not just exceptions?
	        	//       otherwise its not logged to the TeaLog.
	            finally {
					endTime = System.currentTimeMillis();
					if (appRequest instanceof TeaServletStats) {
						long duration = endTime - startTime;
						((TeaServletStats)appRequest).setTemplateDuration(duration);
					}
	            }
	
	            if (DEBUG) {
	                mLog.debug("Finished executing template");
	            }
	        }
	        catch (ServletException e) {
	            // Log exception
	            StringBuffer msg = new StringBuffer();
	            msg.append("Error processing request for ");
	            msg.append(appRequest.getRequestURI());
	            if (appRequest.getQueryString() != null) {
	                msg.append('?');
	                msg.append(appRequest.getQueryString());
	            }
	            mLog.error(msg.toString());
	
	            Throwable t = e;
	            while (t instanceof ServletException) {
	                e = (ServletException)t;
	                if (e.getRootCause() != null) {
	                    String message = e.getMessage();
	                    if (message != null && message.length() > 0) {
	                        mLog.error(message);
	                    }
	                    mLog.error(t = e.getRootCause());
	                }
	                else {
	                    mLog.error(e);
	                    break;
	                }
	            }
	
	            // Internal server error unless header is already set
	            if (!appResponse.isRedirectOrError()) {
	                String displayMessage = e.getLocalizedMessage();
	                if (displayMessage == null || displayMessage.length() == 0) {
	                    appResponse.sendError
	                        (ApplicationResponse.SC_INTERNAL_SERVER_ERROR);
	                }
	                else {
	                    appResponse.sendError
	                        (ApplicationResponse.SC_INTERNAL_SERVER_ERROR, displayMessage);
	                }
	            }
	          
	        }
	        contentLength = appResponse.getResponseBuffer().getByteCount();
	        appResponse.finish();
	        if (templateStats != null) {
    	        templateStats.decrementServicing();
    	        templateStats.log(startTime, endTime, contentLength, params);
	        }
        } catch (Exception e) {
            if (templateStats != null) {
                templateStats.decrementServicing();
            }
        }
		return true;
    }
11092
protected void parseProcessArchive(Element element, List<ProcessArchiveXml> parsedProcessArchives) {

    ProcessArchiveXmlImpl processArchive = new ProcessArchiveXmlImpl();

    processArchive.setName(element.attribute(NAME));
    processArchive.setTenantId(element.attribute(TENANT_ID));

    List<String> processResourceNames = new ArrayList<String>();

    Map<String, String> properties = new HashMap<String, String>();
    for (Element childElement : element.elements()) {
      if(PROCESS_ENGINE.equals(childElement.getTagName())) {
        processArchive.setProcessEngineName(childElement.getText());

      } else if(PROCESS.equals(childElement.getTagName()) || RESOURCE.equals(childElement.getTagName())) {
        processResourceNames.add(childElement.getText());

      } else if(PROPERTIES.equals(childElement.getTagName())) {
        parseProperties(childElement, properties);

      }
    }

    // set properties
    processArchive.setProperties(properties);

    // add collected resource names.
    processArchive.setProcessResourceNames(processResourceNames);

    // add process archive to list of parsed archives.
    parsedProcessArchives.add(processArchive);

  }
455160
void processServerContentRequest() {

        File installRoot = new File(locationService.resolveString("${wlp.install.dir}"));

        final Set<String> absPathsForLibertyContent = new HashSet<String>();
        final Map<String, List<String>> specificPlatformPathsByPlatform = new HashMap<String, List<String>>();
        Set<String> discoveredFeatures = new HashSet<String>();
        Collection<FeatureResource> fixes = new ArrayList<FeatureResource>();

        // We need ALL Kernel features (even the ones that aren't active in the system)
        // as well as all installed features.
        List<ProvisioningFeatureDefinition> allFeatureDefs = new ArrayList<ProvisioningFeatureDefinition>();
        allFeatureDefs.addAll(KernelFeatureDefinitionImpl.getAllKernelFeatures(bundleContext, locationService));
        allFeatureDefs.addAll(featureResolver.getInstalledFeatureDefinitions());

        //keep a list of product extensions being used in the server
        List<String> extensionRepos = new ArrayList<String>();

        for (ProvisioningFeatureDefinition fd : allFeatureDefs) {

            BundleRepositoryHolder brh = BundleRepositoryRegistry.getRepositoryHolder(fd.getBundleRepositoryType());
            ContentBasedLocalBundleRepository br = brh.getBundleRepository();
            Collection<FeatureResource> frs = fd.getConstituents(null);

            /*
             * lib/fixes processing needs to happen here, to filter the xml down to just the current in use set.
             * made slightly more complex, because the locations tracked for minify are absolute, so we have to identify and trim installroot
             * to identify lib/fixes/* content, which we process afterward
             */
            File libFixes = new File(installRoot, "lib/fixes");

            for (FeatureResource fr : frs) {
                switch (fr.getType()) {
                    case FEATURE_TYPE: {
                        //type = feature, no paths to worry about, we are processing the list of all installed features
                        //                which will include nested features.
                        discoveredFeatures.add(fr.getSymbolicName());
                        break;
                    }

                    case BUNDLE_TYPE:
                    case JAR_TYPE:
                    case BOOT_JAR_TYPE: {
                        //type = bundle, need to query the bundle repository for this feature def, to find which
                        //               files are being used.
                        //type = jar, basically same as type=bundle.. for minify purposes.
                        //type = boot.jar, basically same as type=bundle.. for minify purposes.
                        File b = br.selectBundle(fr.getLocation(), fr.getSymbolicName(), fr.getVersionRange());
                        File bb = br.selectBaseBundle(fr.getLocation(), fr.getSymbolicName(), fr.getVersionRange());
                        //b & bb will be the same bundle if the base was the selected.. 
                        if (b != null && bb != null) {
                            boolean pathsSame = b.getAbsolutePath().equals(bb.getAbsolutePath());
                            absPathsForLibertyContent.add(b.getAbsolutePath());
                            if (!pathsSame) {
                                absPathsForLibertyContent.add(bb.getAbsolutePath());
                            }
                            List<String> osList = fr.getOsList();
                            if (osList != null) {
                                for (String os : osList) {
                                    List<String> pathsForOs = specificPlatformPathsByPlatform.get(os);
                                    if (pathsForOs == null) {
                                        pathsForOs = new ArrayList<String>();
                                        specificPlatformPathsByPlatform.put(os, pathsForOs);
                                    }
                                    pathsForOs.add(b.getAbsolutePath());
                                    if (!pathsSame) {
                                        pathsForOs.add(bb.getAbsolutePath());
                                    }
                                }
                            }
                        } else {
                            //b & bb were null, we have no match for this resource.. 
                            //maybe the resource was minfiied out?
                            List<String> osList = fr.getOsList();
                            if (osList != null) {
                                //ignore the missing resource, as the file is tagged for specific os's,
                                //and will be reported missing based on the os filters later.
                                //(if the user has no os filter set, they meant 'all currently supported by the install')
                                //(so this can still be ignored).
                            } else {
                                //use match string for error message, it provides best chance for being helpful.
                                Tr.warning(tc, "ERROR_MISSING_FEATURE_RESOURCE", new Object[] { fd.getFeatureName(), fr.getMatchString() });
                            }
                        }
                        break;
                    }

                    case FILE_TYPE: {
                        //file uses loc as a relative path from install root.
                        String locString = fr.getLocation();
                        if (locString != null) {
                            String[] locs;
                            if (locString.contains(",")) {
                                locs = locString.split(",");
                            } else {
                                locs = new String[] { locString };
                            }

                            for (String loc : locs) {
                                File test = new File(loc);
                                if (!test.isAbsolute()) {
                                    test = new File(brh.getInstallDir(), loc);
                                }
                                loc = test.getAbsolutePath();
                                //filter fixes content into the fixes set, all other content is remembered.
                                if (loc.startsWith(libFixes.getAbsolutePath() + File.separator)) {
                                    fixes.add(fr);
                                } else {
                                    absPathsForLibertyContent.add(loc);
                                }

                                List<String> osList = fr.getOsList();
                                if (osList != null) {
                                    for (String os : osList) {
                                        List<String> pathsForOs = specificPlatformPathsByPlatform.get(os);
                                        if (pathsForOs == null) {
                                            pathsForOs = new ArrayList<String>();
                                            specificPlatformPathsByPlatform.put(os, pathsForOs);
                                        }
                                        pathsForOs.add(loc);
                                    }
                                }
                            }
                        } else {
                            //a file type without a loc is bad, means misuse of the type.
                            Tr.warning(tc, "ERROR_UNKNOWN_FEATURE_RESOURCE_TYPE", new Object[] { fd.getFeatureName(), fr.getSymbolicName(), "file" });
                        }
                        break;
                    }

                    case UNKNOWN: {
                        //if its not jar,bundle,feature, or file.. then something is wrong.
                        Tr.warning(tc, "ERROR_UNKNOWN_FEATURE_RESOURCE_TYPE", new Object[] { fd.getFeatureName(),
                                                                                            fr.getSymbolicName(),
                                                                                            fr.getRawType() });
                        //we assume that other types will use the location field as something useful.
                        String loc = fr.getLocation();
                        if (loc != null) {
                            File test = new File(loc);
                            if (!test.isAbsolute()) {
                                test = new File(installRoot, loc);
                            }
                            absPathsForLibertyContent.add(test.getAbsolutePath());

                            List<String> osList = fr.getOsList();
                            if (osList != null) {
                                for (String os : osList) {
                                    List<String> pathsForOs = specificPlatformPathsByPlatform.get(os);
                                    if (pathsForOs == null) {
                                        pathsForOs = new ArrayList<String>();
                                        specificPlatformPathsByPlatform.put(os, pathsForOs);
                                    }
                                    pathsForOs.add(test.getAbsolutePath());
                                }
                            }
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
            //add in (all) the NLS files for this featuredef.. if any..
            for (File nls : fd.getLocalizationFiles()) {
                if (nls.exists()) {
                    absPathsForLibertyContent.add(nls.getAbsolutePath());
                }
            }

            //add in the manifest for the feature itself .. 
            File featureFile = fd.getFeatureDefinitionFile();
            if (featureFile != null) {
                absPathsForLibertyContent.add(featureFile.getAbsolutePath());
            }
            File checksumFile = fd.getFeatureChecksumFile();
            if (checksumFile != null) {
                absPathsForLibertyContent.add(checksumFile.getAbsolutePath());
            }

            String repoType = fd.getBundleRepositoryType();
            //work out if this content is a product extension and if it is include its properties file
            if (repoType != null && !ExtensionConstants.CORE_EXTENSION.equals(repoType)
                && !ExtensionConstants.USER_EXTENSION.equals(repoType)) {
                //not core or user, must be a product extension
                extensionRepos.add(repoType);
            }

            // Add in any Icon files
            File featureDefinitionFile = fd.getFeatureDefinitionFile();
            if (featureDefinitionFile != null) {
                File featureDefinitionParent = featureDefinitionFile.getParentFile();
                Collection<String> expectedIcons = fd.getIcons();
                if (featureDefinitionParent != null && expectedIcons != null) {
                    File iconsFolder = new File(featureDefinitionParent, "icons/" + fd.getSymbolicName());
                    scanFolderForIcons(absPathsForLibertyContent, iconsFolder.getAbsolutePath(), iconsFolder, expectedIcons);
                }
            }

        }

        //if there are any extensions in use we need to bring their wlp/etc/extensions/*.properties file along
        for (String extensionRepo : extensionRepos) {
            WsResource extensionProperties = locationService.getRuntimeResource("etc/extensions/" + extensionRepo + ".properties");
            absPathsForLibertyContent.add(locationService.resolveResource(extensionProperties.toRepositoryPath()).asFile().getAbsolutePath());
        }

        //this odd looking bit of code will take the current list of files identified,
        //and if any are jars, will look in them to see if they have manifest classpaths
        //if so, the jars referenced by the manifest classpaths are added to the manifestJars
        //argument.
        //We have to start by passing both args as the current set of content (but using different set instances).
        Set<String> manifestJars = new HashSet<String>();
        manifestJars.addAll(absPathsForLibertyContent);
        gatherManifestClasspathJars(absPathsForLibertyContent, manifestJars);
        manifestJars.removeAll(absPathsForLibertyContent);

        //now manifestJars contains any jars that we didn't already know about, discovered via manifests.
        absPathsForLibertyContent.addAll(manifestJars);

        //process the fixes set of fix xml's, and add the required ones to the set of files to keep.
        addRequiredFixFiles(installRoot, absPathsForLibertyContent, fixes);

        final String OS_REMOVE_CHAR = "-";

        //publish the service that will be used by the launcher to read back the data.
        final Dictionary<String, Object> d = new Hashtable<String, Object>();
        final String[] pathArray = absPathsForLibertyContent.toArray(new String[] {});

        bundleContext.registerService(ServerContent.class, new ServerContent() {
            @Override
            public String[] getServerContentPaths(String osRequest) throws IOException {
                if (osRequest == null || osRequest.isEmpty() || "all".equals(osRequest))
                    return pathArray;
                else {
                    //filter paths as required.. then return them..                                       
                    String[] osNames = osRequest.split(",");
                    boolean add = true;

                    //check if this is an add, or a remove.
                    //if both are specified, remove wins ;p
                    for (String osName : osNames) {
                        if (osName.startsWith(OS_REMOVE_CHAR)) {
                            add = false;
                        }
                    }

                    if (add) {
                        //someone has named an os (or os's) they want
                        //so we remove everything, and add back just those os's.
                        for (Map.Entry<String, List<String>> me : specificPlatformPathsByPlatform.entrySet()) {
                            absPathsForLibertyContent.removeAll(me.getValue());
                        }
                        for (String osName : osNames) {
                            if (!osName.startsWith(OS_REMOVE_CHAR)) {
                                List<String> osPaths = specificPlatformPathsByPlatform.get(osName);
                                if (osPaths != null && !osPaths.isEmpty()) {
                                    absPathsForLibertyContent.addAll(osPaths);

                                    //verify the requested paths File.exists .. otherwise 
                                    //this could be an error ?
                                    for (String osPath : osPaths) {
                                        if (!FileUtils.fileExists(new File(osPath))) {
                                            throw new FileNotFoundException(osPath);
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        //user request 'all except this platform' type filter..
                        for (String osName : osNames) {
                            if (osName.startsWith(OS_REMOVE_CHAR)) {
                                osName = osName.substring(1);
                                List<String> osPaths = specificPlatformPathsByPlatform.get(osName);
                                if (osPaths != null && !osPaths.isEmpty()) {
                                    absPathsForLibertyContent.removeAll(osPaths);
                                    //in this kind of filter, we don't need to test at all.
                                }
                            } else {
                                List<String> osPaths = specificPlatformPathsByPlatform.get(osName);
                                if (osPaths != null && !osPaths.isEmpty()) {
                                    //verify the requested paths File.exists .. otherwise 
                                    //this could be an error.
                                    for (String osPath : osPaths) {
                                        if (!FileUtils.fileExists(new File(osPath))) {
                                            throw new FileNotFoundException(osPath);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //return newly filtered data
                    return absPathsForLibertyContent.toArray(new String[] {});
                }
            }
        }, d);

        //we're done here.. let liberty proceed to declare itself 'started' =)
    }
1201891
public <T extends ViewHandler<R>> T processing(boolean flag) {
        lock.lock();
        try {
            setProcessing(flag);
            return (T)this;
        }
        finally {
            lock.unlock();
        }
    }
325876
private function processLinkbases()
	{
		// Begin processing any in the appinfo element
		$this->xbrlDocument->registerXPathNamespace( 'link', XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_LINK ] );
		$this->xbrlDocument->registerXPathNamespace( 'xlink', XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_XLINK ] );
		$this->xbrlDocument->registerXPathNamespace( 'xs', SCHEMA_NAMESPACE );
		$linkbases = $this->xbrlDocument->xpath("/xs:schema/xs:annotation/xs:appinfo/link:linkbase");

		foreach ( $linkbases as $linkbase )
		{
			// Look inside

			$arcRole = XBRL_Constants::$arcRoleAll;
			$title = "Custom linkbase";
			$function = 'processCustomLinkbaseXml';
			$usedOn = '';

			foreach ( XBRL_Constants::$standardLinkElements as $linkElement => $value )
			{
				if ( ! count( $linkbase->children( XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_LINK ] )->$linkElement ) ) continue;

				switch ( $linkElement )
				{
					case 'definitionLink':

						$arcRole = XBRL_Constants::$DefinitionLinkbaseRef;
						$title = 'Definition linkbase';
						$function = 'processDefinitionLinkbaseXml';
						$usedOn = 'link:definitionLink';

						break;

					case 'calculationLink':

						$arcRole = XBRL_Constants::$CalculationLinkbaseRef;
						$title = 'Calculation linkbase';
						$function = 'processCalculationLinkbaseXml';
						$usedOn = 'link:calculationLink';

						break;

					case 'presentationLink':

						$arcRole = XBRL_Constants::$PresentationLinkbaseRef;
						$title = 'Presentation linkbase';
						$function = 'processPresentationLinkbaseXml';
						$usedOn = 'link:presentationLink';

						break;

					case 'labelLink':

						$arcRole = XBRL_Constants::$LabelLinkbaseRef;
						$title = 'Label linkbase';
						$function = 'processLabelLinkbaseXml';
						$usedOn = 'link:label';

						break;

					case 'referenceLink':

						$arcRole = XBRL_Constants::$ReferenceLinkbaseRef;
						$title = 'Reference linkbase';
						$function = 'processReferenceLinkbaseXml';
						$usedOn = 'link:referenceLink';

						break;
				}
			}

			$linkbaseRef = array(
				'type' => 'simple',
				'href' => $this->schemaLocation,
				'role' => XBRL_Constants::$defaultLinkRole,
				'arcrole' => $arcRole,
				'title' => $title,
				'base' => "",
			);

			$this->$function( $linkbaseRef, $linkbase, basename( $linkbaseRef['href'] ), $usedOn );
		}

		foreach ( $this->linkbaseTypes as $linkbaseTypesKey => &$linkbaseType )
		{
			switch ( $linkbaseTypesKey )
			{
				case XBRL_Constants::$anyLinkbaseRef:
					$this->processPresentationLinkbases( $linkbaseType );
					$this->processLabelLinkbases( $linkbaseType );
					$this->processDefinitionLinkbases( $linkbaseType );
					$this->processCalculationLinkbases( $linkbaseType );
					$this->processReferenceLinkbases( $linkbaseType );
					// Handle custom linkbases
					$this->processCustomLinkbases( $linkbaseType );
					break;

				case XBRL_Constants::$PresentationLinkbaseRef:
					$this->processPresentationLinkbases( $linkbaseType );
					break;

				case XBRL_Constants::$LabelLinkbaseRef:
					$this->processLabelLinkbases( $linkbaseType );
					break;

				case XBRL_Constants::$DefinitionLinkbaseRef:
					$this->processDefinitionLinkbases( $linkbaseType );
					break;

				case XBRL_Constants::$CalculationLinkbaseRef:
					$this->processCalculationLinkbases( $linkbaseType );
					break;

				case XBRL_Constants::$ReferenceLinkbaseRef:
					$this->processReferenceLinkbases( $linkbaseType );
					break;

				default:
					// Handle custom linkbases
					$this->processCustomLinkbases( $linkbaseType );
					break;
			}
		}
	}
1146551
public static <T> T executeWithinProcessApplication(Callable<T> callback, ProcessApplicationReference processApplicationReference) {
    return executeWithinProcessApplication(callback, processApplicationReference, null);
  }
723645
protected function processControlStructure()
	{
		// Save the index so we can rewind back to it in case of failure
		$savedIndex = $this->i;

		// Count this control structure in this context's statements unless it's an elseif/else
		// in which case it's already been counted as part of the if
		if (!in_array($this->tokens[$this->i][0], [T_ELSE, T_ELSEIF], true))
		{
			++$this->context['statements'];
		}

		// If the control structure is anything but an "else", skip its condition to reach the first
		// brace or statement
		if ($this->tokens[$this->i][0] !== T_ELSE)
		{
			$this->skipCondition();
		}

		$this->skipWhitespace();

		// Abort if this control structure does not use braces
		if ($this->tokens[$this->i] !== '{')
		{
			// Rewind all the way to the original token
			$this->i = $savedIndex;

			return;
		}

		++$this->braces;

		// Replacement for the first brace
		$replacement = [T_WHITESPACE, ''];

		// Add a space after "else" if the brace is removed and it's not followed by whitespace or a
		// variable
		if ($this->tokens[$savedIndex][0]  === T_ELSE
		 && $this->tokens[$this->i + 1][0] !== T_VARIABLE
		 && $this->tokens[$this->i + 1][0] !== T_WHITESPACE)
		{
			$replacement = [T_WHITESPACE, ' '];
		}

		// Record the token of the control structure (T_IF, T_WHILE, etc...) in the current context
		$this->context['lastBlock'] = $this->tokens[$savedIndex][0];

		// Create a new context
		$this->context = [
			'braces'      => $this->braces,
			'index'       => $this->i,
			'lastBlock'   => null,
			'parent'      => $this->context,
			'replacement' => $replacement,
			'savedIndex'  => $savedIndex,
			'statements'  => 0
		];
	}
1209631
protected void applyParseHandlers() {
    sequenceFlows = new HashMap<String, SequenceFlow>();
    for (Process process : bpmnModel.getProcesses()) {
      currentProcess = process;
      if (process.isExecutable()) {
        bpmnParserHandlers.parseElement(this, process);
      }
    }
  }
719710
protected function define_structure() {

        // are we including userinfo?
        $userinfo = $this->get_setting_value('userinfo');

        ////////////////////////////////////////////////////////////////////////
        // XML nodes declaration - non-user data
        ////////////////////////////////////////////////////////////////////////

        // root element describing workshop instance
        $workshop = new backup_nested_element('workshop', array('id'), array(
            'name', 'intro', 'introformat', 'instructauthors',
            'instructauthorsformat', 'instructreviewers',
            'instructreviewersformat', 'timemodified', 'phase', 'useexamples',
            'usepeerassessment', 'useselfassessment', 'grade', 'gradinggrade',
            'strategy', 'evaluation', 'gradedecimals', 'submissiontypetext', 'submissiontypefile', 'nattachments',
            'submissionfiletypes', 'latesubmissions', 'maxbytes', 'examplesmode', 'submissionstart',
            'submissionend', 'assessmentstart', 'assessmentend',
            'conclusion', 'conclusionformat', 'overallfeedbackmode',
            'overallfeedbackfiles', 'overallfeedbackfiletypes', 'overallfeedbackmaxbytes'));

        // assessment forms definition
        $this->add_subplugin_structure('workshopform', $workshop, true);

        // grading evaluations data
        $this->add_subplugin_structure('workshopeval', $workshop, true);

        // example submissions
        $examplesubmissions = new backup_nested_element('examplesubmissions');
        $examplesubmission  = new backup_nested_element('examplesubmission', array('id'), array(
            'timecreated', 'timemodified', 'title', 'content', 'contentformat',
            'contenttrust', 'attachment'));

        // reference assessment of the example submission
        $referenceassessment  = new backup_nested_element('referenceassessment', array('id'), array(
            'timecreated', 'timemodified', 'grade', 'feedbackauthor', 'feedbackauthorformat',
            'feedbackauthorattachment'));

        // dimension grades for the reference assessment (that is how the form is filled)
        $this->add_subplugin_structure('workshopform', $referenceassessment, true);

        ////////////////////////////////////////////////////////////////////////
        // XML nodes declaration - user data
        ////////////////////////////////////////////////////////////////////////

        // assessments of example submissions
        $exampleassessments = new backup_nested_element('exampleassessments');
        $exampleassessment  = new backup_nested_element('exampleassessment', array('id'), array(
            'reviewerid', 'weight', 'timecreated', 'timemodified', 'grade',
            'gradinggrade', 'gradinggradeover', 'gradinggradeoverby',
            'feedbackauthor', 'feedbackauthorformat', 'feedbackauthorattachment',
            'feedbackreviewer', 'feedbackreviewerformat'));

        // dimension grades for the assessment of example submission (that is assessment forms are filled)
        $this->add_subplugin_structure('workshopform', $exampleassessment, true);

        // submissions
        $submissions = new backup_nested_element('submissions');
        $submission  = new backup_nested_element('submission', array('id'), array(
            'authorid', 'timecreated', 'timemodified', 'title', 'content',
            'contentformat', 'contenttrust', 'attachment', 'grade',
            'gradeover', 'gradeoverby', 'feedbackauthor',
            'feedbackauthorformat', 'timegraded', 'published', 'late'));

        // allocated assessments
        $assessments = new backup_nested_element('assessments');
        $assessment  = new backup_nested_element('assessment', array('id'), array(
            'reviewerid', 'weight', 'timecreated', 'timemodified', 'grade',
            'gradinggrade', 'gradinggradeover', 'gradinggradeoverby',
            'feedbackauthor', 'feedbackauthorformat', 'feedbackauthorattachment',
            'feedbackreviewer', 'feedbackreviewerformat'));

        // dimension grades for the assessment (that is assessment forms are filled)
        $this->add_subplugin_structure('workshopform', $assessment, true);

        // aggregations of grading grades in this workshop
        $aggregations = new backup_nested_element('aggregations');
        $aggregation = new backup_nested_element('aggregation', array('id'), array(
            'userid', 'gradinggrade', 'timegraded'));

        ////////////////////////////////////////////////////////////////////////
        // build the tree in the order needed for restore
        ////////////////////////////////////////////////////////////////////////
        $workshop->add_child($examplesubmissions);
        $examplesubmissions->add_child($examplesubmission);

        $examplesubmission->add_child($referenceassessment);

        $examplesubmission->add_child($exampleassessments);
        $exampleassessments->add_child($exampleassessment);

        $workshop->add_child($submissions);
        $submissions->add_child($submission);

        $submission->add_child($assessments);
        $assessments->add_child($assessment);

        $workshop->add_child($aggregations);
        $aggregations->add_child($aggregation);

        ////////////////////////////////////////////////////////////////////////
        // data sources - non-user data
        ////////////////////////////////////////////////////////////////////////

        $workshop->set_source_table('workshop', array('id' => backup::VAR_ACTIVITYID));

        $examplesubmission->set_source_sql("
            SELECT *
              FROM {workshop_submissions}
             WHERE workshopid = ? AND example = 1",
            array(backup::VAR_PARENTID));

        $referenceassessment->set_source_sql("
            SELECT *
              FROM {workshop_assessments}
             WHERE weight = 1 AND submissionid = ?",
            array(backup::VAR_PARENTID));

        ////////////////////////////////////////////////////////////////////////
        // data sources - user related data
        ////////////////////////////////////////////////////////////////////////

        if ($userinfo) {

            $exampleassessment->set_source_sql("
                SELECT *
                  FROM {workshop_assessments}
                 WHERE weight = 0 AND submissionid = ?",
                array(backup::VAR_PARENTID));

            $submission->set_source_sql("
                SELECT *
                  FROM {workshop_submissions}
                 WHERE workshopid = ? AND example = 0",
                 array(backup::VAR_PARENTID));  // must use SQL here, for the same reason as above

            $assessment->set_source_table('workshop_assessments', array('submissionid' => backup::VAR_PARENTID));

            $aggregation->set_source_table('workshop_aggregations', array('workshopid' => backup::VAR_PARENTID));
        }

        ////////////////////////////////////////////////////////////////////////
        // id annotations
        ////////////////////////////////////////////////////////////////////////

        $exampleassessment->annotate_ids('user', 'reviewerid');
        $submission->annotate_ids('user', 'authorid');
        $submission->annotate_ids('user', 'gradeoverby');
        $assessment->annotate_ids('user', 'reviewerid');
        $assessment->annotate_ids('user', 'gradinggradeoverby');
        $aggregation->annotate_ids('user', 'userid');

        ////////////////////////////////////////////////////////////////////////
        // file annotations
        ////////////////////////////////////////////////////////////////////////

        $workshop->annotate_files('mod_workshop', 'intro', null); // no itemid used
        $workshop->annotate_files('mod_workshop', 'instructauthors', null); // no itemid used
        $workshop->annotate_files('mod_workshop', 'instructreviewers', null); // no itemid used
        $workshop->annotate_files('mod_workshop', 'conclusion', null); // no itemid used

        $examplesubmission->annotate_files('mod_workshop', 'submission_content', 'id');
        $examplesubmission->annotate_files('mod_workshop', 'submission_attachment', 'id');

        $referenceassessment->annotate_files('mod_workshop', 'overallfeedback_content', 'id');
        $referenceassessment->annotate_files('mod_workshop', 'overallfeedback_attachment', 'id');

        $exampleassessment->annotate_files('mod_workshop', 'overallfeedback_content', 'id');
        $exampleassessment->annotate_files('mod_workshop', 'overallfeedback_attachment', 'id');

        $submission->annotate_files('mod_workshop', 'submission_content', 'id');
        $submission->annotate_files('mod_workshop', 'submission_attachment', 'id');

        $assessment->annotate_files('mod_workshop', 'overallfeedback_content', 'id');
        $assessment->annotate_files('mod_workshop', 'overallfeedback_attachment', 'id');

        // return the root element (workshop), wrapped into standard activity structure
        return $this->prepare_activity_structure($workshop);
    }
806461
private ProcessDefinition processProcess(ProcessTextProvider textProvider)
    {
    	int start = textProvider.getPos();
        if (!JavaClass(textProvider))
        {
            throw new ParserException("Missing class name",textProvider);
        }
        textProvider.accumulate(" ");
        String className = textProvider.getLastToken();

//        if (className.indexOf('.') == -1) {
//        	className = textProvider.getPackageName()+className;
//        }
        textProvider.setCurrentScope(className);
    	String processName = getProcessName(textProvider);
        textProvider.addTOCElement(null, processName, start, textProvider.getPos(), TYPE_PROCESS);
    	String launchForm = null;
    	String queueName = null;
    	String description = "";
		if (quotedString('"',textProvider))
		{
			description = textProvider.getLastToken();
		}

        if (exact("launchForm", textProvider)) {
        	exactOrError("=", textProvider);
            if (!CVariable(textProvider))
            {
                throw new ParserException("Missing launch form name",textProvider);
            }
            launchForm = textProvider.getLastToken();
            if (exact("queue", textProvider)) {
            	exactOrError("=", textProvider);
	            if (!quotedString('"', textProvider))
	            {
	                throw new ParserException("Missing queue name",textProvider);
	            }
	            queueName = textProvider.getLastToken();
	            if (textProvider.getWorkflowManager().getQueue(queueName)==null) {
	            	throw new ParserException("Missing queue definition for "+queueName,textProvider);		            	
	            }
            }
        }

        ProcessDefinition ret = new ProcessDefinition(processName, className, textProvider.getWorkflowManager(), launchForm, queueName, textProvider.getPackageName(), description);
        ret.addTask(new TaskStart(ret));
        
        log.debug(ret.getName());
        textProvider.accumulate("\n");
        processTaskList(ret,textProvider);
		commit(textProvider);

        return ret;
    }
567117
@Override
  public void process(Node externsRoot, Node jsRoot) {
    Node externsAndJs = jsRoot.getParent();
    checkState(externsAndJs != null);
    checkState(externsRoot == null || externsAndJs.hasChild(externsRoot));

    inferAllScopes(externsAndJs);
  }
1035006
public ProcessDefinitionEntity parseProcess(Element processElement) {
    // reset all mappings that are related to one process definition
    sequenceFlows = new HashMap<String, TransitionImpl>();

    ProcessDefinitionEntity processDefinition = new ProcessDefinitionEntity();

    /*
     * Mapping object model - bpmn xml: processDefinition.id -> generated by
     * processDefinition.key -> bpmn id (required) processDefinition.name ->
     * bpmn name (optional)
     */
    processDefinition.setKey(processElement.attribute("id"));
    processDefinition.setName(processElement.attribute("name"));
    processDefinition.setCategory(rootElement.attribute("targetNamespace"));
    processDefinition.setProperty(PROPERTYNAME_DOCUMENTATION, parseDocumentation(processElement));
    processDefinition.setTaskDefinitions(new HashMap<String, TaskDefinition>());
    processDefinition.setDeploymentId(deployment.getId());
    processDefinition.setProperty(PROPERTYNAME_JOB_PRIORITY, parsePriority(processElement, PROPERTYNAME_JOB_PRIORITY));
    processDefinition.setProperty(PROPERTYNAME_TASK_PRIORITY, parsePriority(processElement, PROPERTYNAME_TASK_PRIORITY));
    processDefinition.setVersionTag(processElement.attributeNS(CAMUNDA_BPMN_EXTENSIONS_NS, "versionTag"));

    try {
      String historyTimeToLive = processElement.attributeNS(CAMUNDA_BPMN_EXTENSIONS_NS, "historyTimeToLive",
          Context.getProcessEngineConfiguration().getHistoryTimeToLive());
      processDefinition.setHistoryTimeToLive(ParseUtil.parseHistoryTimeToLive(historyTimeToLive));
    }
    catch (Exception e) {
      addError(new BpmnParseException(e.getMessage(), processElement, e));
    }

    boolean isStartableInTasklist = isStartable(processElement);
    processDefinition.setStartableInTasklist(isStartableInTasklist);

    LOG.parsingElement("process", processDefinition.getKey());

    parseScope(processElement, processDefinition);

    // Parse any laneSets defined for this process
    parseLaneSets(processElement, processDefinition);

    for (BpmnParseListener parseListener : parseListeners) {
      parseListener.parseProcess(processElement, processDefinition);
    }

    // now we have parsed anything we can validate some stuff
    validateActivities(processDefinition.getActivities());

    //unregister delegates
    for (ActivityImpl activity : processDefinition.getActivities()) {
      activity.setDelegateAsyncAfterUpdate(null);
      activity.setDelegateAsyncBeforeUpdate(null);
    }
    return processDefinition;
  }
1181069
void init(KProcess process) {
		process.markings = new Object[this.elements.size()];
		for (KElement element : this.elements) {
			element.init(process);
		}
	}
517359
protected void parseProcessEngine(Element element, List<ProcessEngineXml> parsedProcessEngines) {

    ProcessEngineXmlImpl processEngine = new ProcessEngineXmlImpl();

    // set name
    processEngine.setName(element.attribute(NAME));

    // set default
    String defaultValue = element.attribute(DEFAULT);
    if(defaultValue == null || defaultValue.isEmpty()) {
      processEngine.setDefault(false);
    } else {
      processEngine.setDefault(Boolean.parseBoolean(defaultValue));
    }

    Map<String, String> properties = new HashMap<String, String>();
    List<ProcessEnginePluginXml> plugins = new ArrayList<ProcessEnginePluginXml>();

    for (Element childElement : element.elements()) {
      if(CONFIGURATION.equals(childElement.getTagName())) {
        processEngine.setConfigurationClass(childElement.getText());

      } else if(DATASOURCE.equals(childElement.getTagName())) {
        processEngine.setDatasource(childElement.getText());

      } else if(JOB_ACQUISITION.equals(childElement.getTagName())) {
        processEngine.setJobAcquisitionName(childElement.getText());

      } else if(PROPERTIES.equals(childElement.getTagName())) {
        parseProperties(childElement, properties);

      } else if(PLUGINS.equals(childElement.getTagName())) {
        parseProcessEnginePlugins(childElement, plugins);

      }
    }

    // set collected properties
    processEngine.setProperties(properties);
    // set plugins
    processEngine.setPlugins(plugins);
    // add the process engine to the list of parsed engines.
    parsedProcessEngines.add(processEngine);

  }
1234454
public void processDI() {

    if (processDefinitions.isEmpty()) {
      return;
    }

    if (!bpmnModel.getLocationMap().isEmpty()) {

      // Verify if all referenced elements exist
      for (String bpmnReference : bpmnModel.getLocationMap().keySet()) {
        if (bpmnModel.getFlowElement(bpmnReference) == null) {
          // ACT-1625: don't warn when artifacts are referenced from DI
          if (bpmnModel.getArtifact(bpmnReference) == null) {
            // Check if it's a Pool or Lane, then DI is ok
            if (bpmnModel.getPool(bpmnReference) == null && bpmnModel.getLane(bpmnReference) == null) {
              LOGGER.warn("Invalid reference in diagram interchange definition: could not find " + bpmnReference);
            }
          }
        } else if (!(bpmnModel.getFlowElement(bpmnReference) instanceof FlowNode)) {
          LOGGER.warn("Invalid reference in diagram interchange definition: " + bpmnReference + " does not reference a flow node");
        }
      }
      
      for (String bpmnReference : bpmnModel.getFlowLocationMap().keySet()) {
        if (bpmnModel.getFlowElement(bpmnReference) == null) {
          // ACT-1625: don't warn when artifacts are referenced from DI
          if (bpmnModel.getArtifact(bpmnReference) == null) {
            LOGGER.warn("Invalid reference in diagram interchange definition: could not find " + bpmnReference);
          }
        } else if (!(bpmnModel.getFlowElement(bpmnReference) instanceof SequenceFlow)) {
          LOGGER.warn("Invalid reference in diagram interchange definition: " + bpmnReference + " does not reference a sequence flow");
        }
      }

      for (Process process : bpmnModel.getProcesses()) {
        if (!process.isExecutable()) {
          continue;
        }

        // Parse diagram interchange information
        ProcessDefinitionEntity processDefinition = getProcessDefinition(process.getId());
        if (processDefinition != null) {
          processDefinition.setGraphicalNotationDefined(true);
          
          for (String edgeId : bpmnModel.getFlowLocationMap().keySet()) {
            if (bpmnModel.getFlowElement(edgeId) != null) {
              createBPMNEdge(edgeId, bpmnModel.getFlowLocationGraphicInfo(edgeId));
            }
          }
        }
      }
    }
  }