/* package-visible for testing
175972
Token clearXAuth(Response response) {
        if (response.getCode() == 200 || response.getCode() == 201) {
            return parseXAuthResponse(response);
        } else {
            throw new JumblrException(response);
        }
    }
937995
function stopPackage(packageName, cb) {
   var packageRuntime = packageRuntimes[packageName];

   if (isUndefined(packageRuntime) || isUndefined(packageRuntime.process)) {
      cb();
      return;
   }

   if (!isUndefined(packageRuntime.killTimer)) {
      cb(new Error('already attempting to stop package ' + packageName));
      return;
   }

   if (!isUndefined(packageRuntime.startupTimer)) {
      clearTimeout(packageRuntime.startupTimer);
      packageRuntime.startupTimer = null;
   }

   packageRuntime.killedCallback = cb;
   packageRuntime.killTimer = setTimeout(function() {
      packageRuntime.killedCallback = null; 
      packageRuntime.killTimer = null;
      cb(new Error('unable to stop package ' + packageName));
   }, killTimout * 1000);

   packageRuntime.process.kill();
}
1241496
function(sandbox) {

    function stat(filename) {
        filename = path._makeLong(filename);
        const cache = stat.cache;
        if (cache !== null) {
            const result = cache.get(filename);
            if (result !== undefined) return result;
        }
        const result = internalModuleStat(filename);
        if (cache !== null) cache.set(filename, result);
        return result;
    }
    stat.cache = null;


    function Module(id, parent) {
        this.id = id;
        this.exports = {};
        this.parent = parent;
        if (parent && parent.children) {
            parent.children.push(this);
        }

        this.filename = null;
        this.loaded = false;
        this.children = [];
    }

    Module._cache = {};
    Module._pathCache = {};
    Module._extensions = {};
    var modulePaths = [];
    Module.globalPaths = [];

    Module.wrapper = ['(function (exports, require, module, __filename, __dirname) { ', '\n});'];
    Module.wrap = function (script) {
        return Module.wrapper[0] + script + Module.wrapper[1];
    };

// given a module name, and a list of paths to test, returns the first
// matching file in the following precedence.
//
// require("a.<ext>")
//   -> a.<ext>
//
// require("a")
//   -> a
//   -> a.<ext>
//   -> a/index.<ext>

// check if the directory is a package.json dir
    const packageMainCache = {};

    function readPackage(requestPath) {
        if (hasOwnProperty(packageMainCache, requestPath)) {
            return packageMainCache[requestPath];
        }

        const jsonPath = path.resolve(requestPath, 'package.json');
        const json = internalModuleReadFile(path._makeLong(jsonPath));

        if (json === undefined) {
            return false;
        }

        try {
            var pkg = packageMainCache[requestPath] = JSON.parse(json).main;
        } catch (e) {
            e.path = jsonPath;
            e.message = 'Error parsing ' + jsonPath + ': ' + e.message;
            throw e;
        }
        return pkg;
    }

    function tryPackage(requestPath, exts, isMain) {
        var pkg = readPackage(requestPath);

        if (!pkg) return false;

        var filename = path.resolve(requestPath, pkg);
        return tryFile(filename, isMain) ||
            tryExtensions(filename, exts, isMain) ||
            tryExtensions(path.resolve(filename, 'index'), exts, isMain);
    }

// check if the file exists and is not a directory
// if using --preserve-symlinks and isMain is false,
// keep symlinks intact, otherwise resolve to the
// absolute realpath.
    function tryFile(requestPath, isMain) {
        const rc = stat(requestPath);
        if (preserveSymlinks && !isMain) {
            return rc === 0 && path.resolve(requestPath);
        }
        return rc === 0 && fs.realpathSync(requestPath);
    }

// given a path check a the file exists with any of the set extensions
    function tryExtensions(p, exts, isMain) {
        for (var i = 0; i < exts.length; i++) {
            const filename = tryFile(p + exts[i], isMain);

            if (filename) {
                return filename;
            }
        }
        return false;
    }

    var warned = false;
    Module._findPath = function (request, paths, isMain) {
        if (path.isAbsolute(request)) {
            paths = [''];
        } else if (!paths || paths.length === 0) {
            return false;
        }

        const cacheKey = JSON.stringify({request: request, paths: paths});
        if (Module._pathCache[cacheKey]) {
            return Module._pathCache[cacheKey];
        }

        var exts;
        const trailingSlash = request.length > 0 &&
            request.charCodeAt(request.length - 1) === 47/*/*/;

        // For each path
        for (var i = 0; i < paths.length; i++) {
            // Don't search further if path doesn't exist
            const curPath = paths[i];
            if (curPath && stat(curPath) < 1) continue;
            var basePath = path.resolve(curPath, request);
            var filename;

            if (!trailingSlash) {
                const rc = stat(basePath);
                if (rc === 0) {  // File.
                    if (preserveSymlinks && !isMain) {
                        filename = path.resolve(basePath);
                    } else {
                        filename = fs.realpathSync(basePath);
                    }
                } else if (rc === 1) {  // Directory.
                    if (exts === undefined)
                        exts = Object.keys(Module._extensions);
                    filename = tryPackage(basePath, exts, isMain);
                }

                if (!filename) {
                    // try it with each of the extensions
                    if (exts === undefined)
                        exts = Object.keys(Module._extensions);
                    filename = tryExtensions(basePath, exts, isMain);
                }
            }

            if (!filename) {
                if (exts === undefined)
                    exts = Object.keys(Module._extensions);
                filename = tryPackage(basePath, exts, isMain);
            }

            if (!filename) {
                // try it with each of the extensions at "index"
                if (exts === undefined)
                    exts = Object.keys(Module._extensions);
                filename = tryExtensions(path.resolve(basePath, 'index'), exts, isMain);
            }

            if (filename) {
                Module._pathCache[cacheKey] = filename;
                return filename;
            }
        }
        return false;
    };

// 'node_modules' character codes reversed
    var nmChars = [115, 101, 108, 117, 100, 111, 109, 95, 101, 100, 111, 110];
    var nmLen = nmChars.length;
    if (process.platform === 'win32') {
        // 'from' is the __dirname of the module.
        Module._nodeModulePaths = function (from) {
            // guarantee that 'from' is absolute.
            from = path.resolve(from);

            // note: this approach *only* works when the path is guaranteed
            // to be absolute.  Doing a fully-edge-case-correct path.split
            // that works on both Windows and Posix is non-trivial.
            const paths = [];
            var p = 0;
            var last = from.length;
            for (var i = from.length - 1; i >= 0; --i) {
                const code = from.charCodeAt(i);
                if (code === 92/*\*/ || code === 47/*/*/) {
                    if (p !== nmLen)
                        paths.push(from.slice(0, last) + '\\node_modules');
                    last = i;
                    p = 0;
                } else if (p !== -1 && p < nmLen) {
                    if (nmChars[p] === code) {
                        ++p;
                    } else {
                        p = -1;
                    }
                }
            }

            return paths;
        };
    } else { // posix
        // 'from' is the __dirname of the module.
        Module._nodeModulePaths = function (from) {
            // guarantee that 'from' is absolute.
            from = path.resolve(from);
            // Return early not only to avoid unnecessary work, but to *avoid* returning
            // an array of two items for a root: [ '//node_modules', '/node_modules' ]
            if (from === '/')
                return ['/node_modules'];

            // note: this approach *only* works when the path is guaranteed
            // to be absolute.  Doing a fully-edge-case-correct path.split
            // that works on both Windows and Posix is non-trivial.
            const paths = [];
            var p = 0;
            var last = from.length;
            for (var i = from.length - 1; i >= 0; --i) {
                const code = from.charCodeAt(i);
                if (code === 47/*/*/) {
                    if (p !== nmLen)
                        paths.push(from.slice(0, last) + '/node_modules');
                    last = i;
                    p = 0;
                } else if (p !== -1 && p < nmLen) {
                    if (nmChars[p] === code) {
                        ++p;
                    } else {
                        p = -1;
                    }
                }
            }

            return paths;
        };
    }


// 'index.' character codes
    var indexChars = [105, 110, 100, 101, 120, 46];
    var indexLen = indexChars.length;
    Module._resolveLookupPaths = function (request, parent) {
        if (_NATIVE_MODULES.indexOf(request) >= 0) {
            return [request, []];
        }

        var reqLen = request.length;
        // Check for relative path
        if (reqLen < 2 ||
            request.charCodeAt(0) !== 46/*.*/ ||
            (request.charCodeAt(1) !== 46/*.*/ &&
            request.charCodeAt(1) !== 47/*/*/)) {
            var paths = modulePaths;
            if (parent) {
                if (!parent.paths)
                    paths = parent.paths = [];
                else
                    paths = parent.paths.concat(paths);
            }

            // Maintain backwards compat with certain broken uses of require('.')
            // by putting the module's directory in front of the lookup paths.
            if (request === '.') {
                if (parent && parent.filename) {
                    paths.unshift(path.dirname(parent.filename));
                } else {
                    paths.unshift(path.resolve(request));
                }
            }

            return [request, paths];
        }

        // with --eval, parent.id is not set and parent.filename is null
        if (!parent || !parent.id || !parent.filename) {
            // make require('./path/to/foo') work - normally the path is taken
            // from realpath(__filename) but with eval there is no filename
            var mainPaths = ['.'].concat(Module._nodeModulePaths('.'), modulePaths);
            return [request, mainPaths];
        }

        // Is the parent an index module?
        // We can assume the parent has a valid extension,
        // as it already has been accepted as a module.
        const base = path.basename(parent.filename);
        var parentIdPath;
        if (base.length > indexLen) {
            var i = 0;
            for (; i < indexLen; ++i) {
                if (indexChars[i] !== base.charCodeAt(i))
                    break;
            }
            if (i === indexLen) {
                // We matched 'index.', let's validate the rest
                for (; i < base.length; ++i) {
                    const code = base.charCodeAt(i);
                    if (code !== 95/*_*/ &&
                        (code < 48/*0*/ || code > 57/*9*/) &&
                        (code < 65/*A*/ || code > 90/*Z*/) &&
                        (code < 97/*a*/ || code > 122/*z*/))
                        break;
                }
                if (i === base.length) {
                    // Is an index module
                    parentIdPath = parent.id;
                } else {
                    // Not an index module
                    parentIdPath = path.dirname(parent.id);
                }
            } else {
                // Not an index module
                parentIdPath = path.dirname(parent.id);
            }
        } else {
            // Not an index module
            parentIdPath = path.dirname(parent.id);
        }
        var id = path.resolve(parentIdPath, request);

        // make sure require('./path') and require('path') get distinct ids, even
        // when called from the toplevel js file
        if (parentIdPath === '.' && id.indexOf('/') === -1) {
            id = './' + id;
        }

        return [id, [path.dirname(parent.filename)]];
    };


// Check the cache for the requested file.
// 1. If a module already exists in the cache: return its exports object.
// 2. If the module is native: call `NativeModule.require()` with the
//    filename and return the result.
// 3. Otherwise, create a new module for the file and save it to the cache.
//    Then have it load  the file contents before returning its exports
//    object.
    Module._load = function (request, parent, isMain) {

        var filename = Module._resolveFilename(request, parent, isMain);

        events.emit('require', request, filename);

        if (!userOptions.reload) {
            var cachedModule = Module._cache[filename];
            if (cachedModule) {
                if (_NATIVE_MODULES.indexOf(filename) >= 0) return cachedModule;
                else return cachedModule.exports;
            }
        }

//************************** override list

        if (_NATIVE_MODULES.indexOf(filename) >= 0) {
            var res = NativeModuleRequire(filename);
            if (_.isArray(userOptions._useNativeModulesCopyList)) {
                if (userOptions._useNativeModulesCopyList.indexOf(filename) >= 0)
                    res = _.cloneDeep(res);
            }
            Module._cache[filename] = res;
            return res;
        }

        var module = new Module(filename, parent);

        if (isMain) {
            process.mainModule = module;
            module.id = '.';
        }

        Module._cache[filename] = module;

        tryModuleLoad(module, filename);

        return module.exports;
    };

    function tryModuleLoad(module, filename) {
        var threw = true;
        try {
            module.load(filename);
            threw = false;
        } finally {
            if (threw) {
                delete Module._cache[filename];
            }
        }
    }

    Module._resolveFilename = function (request, parent, isMain) {
        if (_NATIVE_MODULES.indexOf(request) >= 0) {
            return request;
        }

        var resolvedModule = Module._resolveLookupPaths(request, parent);
        var id = resolvedModule[0];
        var paths = resolvedModule[1];

        var filename = Module._findPath(request, paths, isMain);
        if (!filename) {
            var err = new Error("Cannot find module '" + request + "'");
            err.code = 'MODULE_NOT_FOUND';
            throw err;
        }
        return filename;
    };


// Given a file name, pass it to the proper extension handler.
    Module.prototype.load = function (filename) {

        assert(!this.loaded);
        this.filename = filename;
        this.paths = Module._nodeModulePaths(path.dirname(filename));

        var extension = path.extname(filename) || '.js';
        if (!Module._extensions[extension]) extension = '.js';
        Module._extensions[extension](this, filename);
        this.loaded = true;
    };


// Loads a module at the given file path. Returns that module's
// `exports` property.
    Module.prototype.require = function (path) {

        assert(path, 'missing path');
        assert(typeof path === 'string', 'path must be a string');

        // This is the require we need to change !!!!!!
        events.emit('beforeRequire', path);

        if (userOptions.Blacklist.indexOf(path) >= 0) {
            throw new Error('Use of module (' + path + ') is restricted.');
        }
        if (userOptions.Whitelist.length > 0 && userOptions.Whitelist.indexOf(path) < 0) {
            throw new Error('Module (' + path + ') is not available.');
        }
        if (!userOptions.allowExternalModules && _NATIVE_MODULES.indexOf(path) < 0) {
            throw new Error('Use of external modules is restricted, have (' + path + ')');
        }

        var resultModule = Module._load(path, this, /* isMain */ false);

        events.emit('afterRequire', resultModule);

        return resultModule;
    };


// Resolved path to process.argv[1] will be lazily placed here
// (needed for setting breakpoint when called with --debug-brk)
    var resolvedArgv;


// Run the file contents in the correct scope or sandbox. Expose
// the correct helper variables (require, module, exports) to
// the file.
// Returns exception, if any.
    Module.prototype._compile = function (content, filename) {
        // Remove shebang
        var contLen = content.length;
        if (contLen >= 2) {
            if (content.charCodeAt(0) === 35/*#*/ &&
                content.charCodeAt(1) === 33/*!*/) {
                if (contLen === 2) {
                    // Exact match
                    content = '';
                } else {
                    // Find end of shebang line and slice it off
                    var i = 2;
                    for (; i < contLen; ++i) {
                        var code = content.charCodeAt(i);
                        if (code === 10/*\n*/ || code === 13/*\r*/)
                            break;
                    }
                    if (i === contLen)
                        content = '';
                    else {
                        // Note that this actually includes the newline character(s) in the
                        // new output. This duplicates the behavior of the regular expression
                        // that was previously used to replace the shebang line
                        content = content.slice(i);
                    }
                }
            }
        }

        // create wrapper function
        var wrapper = Module.wrap(content);

        var compiledWrapper;
        if (userOptions.useSandbox && sandbox) {

            if (!vm.isContext(sandbox)) vm.createContext(sandbox);
            compiledWrapper = vm.runInContext(wrapper, sandbox,{
                filename: filename,
                lineOffset: 0,
                displayErrors: true
            });
        } else {

            compiledWrapper = vm.runInThisContext(wrapper, {
                filename: filename,
                lineOffset: 0,
                displayErrors: true
            });
        }

        var dirname = path.dirname(filename);
        var require = internalModule.makeRequireFunction.call(this);
        var args = [this.exports, require, this, filename, dirname];
        var depth = internalModule.requireDepth;
        if (depth === 0) stat.cache = new Map();
        var result = compiledWrapper.apply(this.exports, args);
        if (depth === 0) stat.cache = null;
        return result;
    };


// Native extension for .js
    Module._extensions['.js'] = function (module, filename) {
        var content = fs.readFileSync(filename, 'utf8');
        module._compile(internalModule.stripBOM(content), filename);
    };


// Native extension for .json
    Module._extensions['.json'] = function (module, filename) {
        var content = fs.readFileSync(filename, 'utf8');
        try {
            module.exports = JSON.parse(internalModule.stripBOM(content));
        } catch (err) {
            err.message = filename + ': ' + err.message;
            throw err;
        }
    };


//Native extension for .node
    Module._extensions['.node'] = function (module, filename) {
        return process.dlopen(module, path._makeLong(filename));
    };


    Module._initPaths = function () {
        const isWindows = process.platform === 'win32';

        var homeDir;
        if (isWindows) {
            homeDir = process.env.USERPROFILE;
        } else {
            homeDir = process.env.HOME;
        }

        var paths = [path.resolve(process.execPath, '..', '..', 'lib', 'node')];

        if (homeDir) {
            paths.unshift(path.resolve(homeDir, '.node_libraries'));
            paths.unshift(path.resolve(homeDir, '.node_modules'));
        }

        var nodePath = process.env['NODE_PATH'];
        if (nodePath) {
            paths = nodePath.split(path.delimiter).filter(function (path) {
                return !!path;
            }).concat(paths);
        }

        modulePaths = paths;

        // clone as a read-only copy, for introspection.
        Module.globalPaths = modulePaths.slice(0);
    };

    Module._initPaths();


//----- Apply New Extensions ----

    var extentionList = userOptions._extensions;
    for (var ext in extentionList) {

        Module._extensions[ext] = function (module, filename) {

            var source = stripBOM(fs.readFileSync(filename, 'utf8'));
            if (extentionList[ext].every(function (method) {
                    var userResult = null;
                    userResult = method(source, filename);

                    if (!userResult || userResult === null) userResult = source;

                    if (!util.isString(userResult)) {   // stop operation, return this value
                        module.exports = userResult;
                        return false;
                    } else {
                        source = userResult;   // set the newly set ret value
                        return true;
                    }
                })) module._compile(source, filename);
        };
    }

//------ Apply New Search Paths
    var paths = userOptions._pathList;

    if (paths.length > 0) {

        var nodePath = process.env['NODE_PATH'];
        var DefaultPaths = process.env['NODE_PATH'];
        if (!nodePath) nodePath = ""; else nodePath += path.delimiter;
        for (var i = 0; i < paths.length; i++) {
            nodePath += paths[i] + path.delimiter;
        }
        process.env['NODE_PATH'] = nodePath;
        Module._initPaths();
        process.env['NODE_PATH'] = DefaultPaths;
    }

//---- End Apply New Paths
    function resolve(request) {
        return Module._resolveFilename(request, self);
    }
    var res = Module.prototype.require;
    res.resolve = resolve;
    res.main = process.mainModule;
    res.extensions = Module._extensions;
    res.cache = Module._cache;

    return res;
}
512253
@Override
    @Path("/{package}/{asset}")
    @ApiOperation(value="Retrieve an asset, an asset package, or all the asset packages",
        response=PackageList.class)
    @ApiImplicitParams({
        @ApiImplicitParam(name="discoveryUrls", paramType="query", dataType="array"),
        @ApiImplicitParam(name="branch", paramType="query", dataType="string"),
        @ApiImplicitParam(name="discoveryType", paramType="query", dataType="string"),
        @ApiImplicitParam(name="groupId", paramType="query", dataType="string"),
        @ApiImplicitParam(name="archiveDirs", paramType="query", dataType="string")})
    public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {

        try {
            AssetServices assetServices = ServiceLocator.getAssetServices();
            Query query = getQuery(path, headers);
            String discoveryType = query.getFilter("discoveryType");
            if (discoveryType != null) {
                if (!discoveryType.isEmpty() && discoveryType.equals("central")) {
                    String groupId = query.getFilter("groupId");
                    try {
                        Discover discover = new Discover(groupId, true);
                        return discover.run().getPackages();
                    }
                    catch (JSONException e) {
                        throw new ServiceException(ServiceException.INTERNAL_ERROR,
                                "Invalid response from maven central search query", e);
                    }
                }
                else if ("git".equals(discoveryType)){
                    String[] repoUrls = query.getArrayFilter("discoveryUrls");
                    String branch = query.getFilter("branch");
                    if (branch != null)
                        return assetServices.discoverGitAssets(repoUrls[0], branch);
                    else
                        return assetServices.getGitBranches(repoUrls);
                }
            }

            if (query.getBooleanFilter("archiveDirs")) {
                List<ArchiveDir> archiveDirs = assetServices.getArchiveDirs();
                JSONObject json = new JsonObject();
                json.put("root", assetServices.getArchiveDir().getAbsolutePath());
                for (ArchiveDir archiveDir : archiveDirs)
                    json.put(archiveDir.getJsonName(), archiveDir.getJson());
                return json;
            }

            String pkg = getSegment(path, 1);
            String asset = pkg == null ? null : getSegment(path, 2);

            if (pkg == null) {
                if (query.hasFilters()) {
                    return assetServices.getAssetPackageList(query).getJson();
                }
                else {
                    JSONObject json = getPackages(query).getJson();
                    if (assetServices.getArchiveDir().isDirectory())
                        json.put("hasArchive", true);
                    return json;
                }
            }
            else {
                if (asset == null) {
                    return getPackage(pkg).getJson();
                }
                else {
                    return getAssetInfo(pkg + "/" + asset).getJson();
                }
            }
        }
        catch (ServiceException ex) {
            throw ex;
        }
        catch (Exception ex) {
            throw new ServiceException(ex.getMessage(), ex);
        }
    }
1016800
@Override
    protected void extraFileActions(PackageSymbol pack, JavaFileObject fo) {
        if (fo.isNameCompatible("package", JavaFileObject.Kind.HTML)) {
            pack.sourcefile = fo;
        }
    }
1249560
public String build(final InternalKnowledgePackage pkg,
                        final FunctionDescr functionDescr,
                        final TypeResolver typeResolver,
                        final Map<String, LineMappings> lineMappings,
                        final List<KnowledgeBuilderResult> errors) {

        final Map<String, Object> vars = new HashMap<String, Object>();

        vars.put("package",
                 pkg.getName());

        vars.put("imports",
                 pkg.getImports().keySet());

        final List<String> staticImports = new LinkedList<String>();
        for (String staticImport : pkg.getStaticImports()) {
            if (!staticImport.endsWith(functionDescr.getName())) {
                staticImports.add(staticImport);
            }
        }

        vars.put("staticImports",
                 staticImports);

        vars.put("className",
                 StringUtils.ucFirst(functionDescr.getName()));

        vars.put("methodName",
                 functionDescr.getName());

        vars.put("returnType",
                 functionDescr.getReturnType());

        vars.put("parameterTypes",
                 functionDescr.getParameterTypes());

        vars.put("parameterNames",
                 functionDescr.getParameterNames());

        vars.put("hashCode",
                 functionDescr.getText().hashCode());

        // Check that all the parameters are resolvable
        final List<String> names = functionDescr.getParameterNames();
        final List<String> types = functionDescr.getParameterTypes();
        for (int i = 0, size = names.size(); i < size; i++) {
            try {
                typeResolver.resolveType(types.get(i));
            } catch (final ClassNotFoundException e) {
                errors.add(new FunctionError(functionDescr,
                                             e,
                                             "Unable to resolve type " + types.get(i) + " while building function."));
                break;
            }
        }

        vars.put("text",
                 functionDescr.getText());

        final String text = String.valueOf(TemplateRuntime.eval(template, null, new MapVariableResolverFactory(vars)));

        final BufferedReader reader = new BufferedReader(new StringReader(text));
        final String lineStartsWith = "    public static " + functionDescr.getReturnType() + " " + functionDescr.getName();
        try {
            String line;
            int offset = 0;
            while ((line = reader.readLine()) != null) {
                offset++;
                if (line.startsWith(lineStartsWith)) {
                    break;
                }
            }
            functionDescr.setOffset(offset);
        } catch (final IOException e) {
            // won't ever happen, it's just reading over a string.
            throw new RuntimeException("Error determining start offset with function");
        }

        final String name = pkg.getName() + "." + StringUtils.ucFirst(functionDescr.getName());
        final LineMappings mapping = new LineMappings(name);
        mapping.setStartLine(functionDescr.getLine());
        mapping.setOffset(functionDescr.getOffset());
        lineMappings.put(name,
                         mapping);

        return text;
    }
275387
@Override
	public URI locateModuleResource(String mid, boolean isJavaScript) {
		Location location = null;
		String remainder = null;

		// Now see if mid matches exactly a path
		if (getPaths().containsKey(mid)) {
			location = getPaths().get(mid);
		}
		// If the module is a package name, then resolve to the packag main id
		if (location == null && getPackages().containsKey(mid)) {
			mid = getPackages().get(mid).getMain();
		}
		if (location == null) {
			// Still no match.  Iterate through the paths and packages looking
			// for an entry that matches part of the module id
			String prefix = ""; //$NON-NLS-1$
			for (Map.Entry<String, Location> entry : getPaths().entrySet()) {
				if (mid.startsWith(entry.getKey()) && entry.getKey().length() > prefix.length()) {
					if (entry.getKey().endsWith("/") || mid.charAt(entry.getKey().length()) == '/') { //$NON-NLS-1$
						prefix = entry.getKey();
						location = entry.getValue();
					}
				}
			}
			for (Map.Entry<String, IPackage> entry : getPackages().entrySet()) {
				if (mid.startsWith(entry.getKey()) && entry.getKey().length() > prefix.length()) {
					if (entry.getKey().endsWith("/") || mid.charAt(entry.getKey().length()) == '/') { //$NON-NLS-1$
						prefix = entry.getKey();
						location = entry.getValue().getLocation();
					}
				}
			}
			if (prefix.length() > 0) {
				// We found a partial match.  Set the remainder
				remainder = mid.substring(prefix.length());
				if (remainder.startsWith("/")) { //$NON-NLS-1$
					remainder = remainder.substring(1);
				}
				// Check for illegal relative path. Throws exception if an
				// attempt is made to use relitive path components to go
				// outside the path defined by the entry.
				PathUtil.normalizePaths(prefix, new String[]{remainder});
			} else {
				// Check for illegal relative path. Throws exception if an
				// attempt is made to use relitive path components to go
				// outside the path defined by the base url.
				PathUtil.normalizePaths("", new String[]{mid});  //$NON-NLS-1$
				// not match.  Return a URI relative to the config base URI
				Location base = getBase();
				location = new Location(
						base.getPrimary().resolve(mid),
						base.getOverride() == null ? null : base.getOverride().resolve(mid)
						);
			}
		}
		URI result = null;
		try {
			URI override = toResourceUri(location.getOverride(), remainder, isJavaScript);
			result = (override != null && aggregator.newResource(override).exists()) ?
					override : toResourceUri(location.getPrimary(), remainder, isJavaScript);

		} catch (URISyntaxException e) {
			if (log.isLoggable(Level.WARNING)) {
				log.log(Level.WARNING, e.getMessage(), e);
			}
		}

		return result;
	}
437237
function (data) {

            if (!isLog()) {
                return undefined;
            }

            try {
                _fs.appendFileSync("pkgscript.log", (_utils.now() + "  " + data + "\n"), "utf8");

            } catch (e) {
                console.error(_utils.now + " [package-script] Package Script, ERROR:", e);
            }
        }
441106
@Override
    public R visitPackage(PackageTree node, P p) {
        R r = scan(node.getAnnotations(), p);
        r = scanAndReduce(node.getPackageName(), p, r);
        return r;
    }
108587
function(xdata, ndata) {
    try {
      const npkg = JSON.parse(ndata||'{}');
      const xpkg = xdata?JSON.parse(xdata):JSON.parse(ndata||'{}');
      _managePkg(npkg, xpkg);
      _initPkg(xpkg);
      xdata = JSON.stringify(xpkg, null, 2);
      _log('package.json managed: %s', xdata);
    } catch(err){
      console.error(err);
    }
    return xdata;
  }
1344898
void buildPackagePrefix(final String className) {
        // TODO test
        final int lastPackageSeparator = className.lastIndexOf('/');
        final String packageName = className.substring(0, lastPackageSeparator == -1 ? className.length() : lastPackageSeparator);
        final String[] splitPackage = packageName.split("/");

        if (splitPackage.length >= PROJECT_PACKAGE_HIERARCHIES) {
            projectPackagePrefix = IntStream.range(0, PROJECT_PACKAGE_HIERARCHIES).mapToObj(i -> splitPackage[i]).collect(Collectors.joining("/"));
        } else {
            projectPackagePrefix = packageName;
        }
    }
643360
function startPackage(package, cb) {
   if (isUndefined(packageRuntimes[package.packageName])) {
      packageRuntimes[package.packageName] = {};
   }

   var packageRuntime = packageRuntimes[package.packageName];

   if (!isUndefined(packageRuntime.process)) {
      cb(new Error('package already running'));
      return;
   }

   packageRuntime.startupTimer = setTimeout(function() { 
      packageRuntime.startupTimer = null;
      cb();
   }, startupTimout * 1000);

   packageRuntime.process = exec(package.launchCommand, { cwd: (!isUndefined(package.workingDirectory) ? path.resolve(package.workingDirectory) : undefined) }, function(err) {
      packageRuntime.process = null;
      if (!isUndefined(packageRuntime.startupTimer)) {
         clearTimeout(packageRuntime.startupTimer);
         packageRuntime.startupTimer = null;
         cb(err);
      } else if (!isUndefined(packageRuntime.killTimer)) {
         clearTimeout(packageRuntime.killTimer);
         packageRuntime.killTimer = null;
         packageRuntime.killedCallback();
         packageRuntime.killedCallback = null;
      }
   });
}
883838
function checkPackageJson(pth, cb) {
  var p = path.join(pth, 'package.json');
  checkStatFile(p, function(err, pack){
    if (err) return cb(err);
    if (!pack || !pack.strider) return cb(null, false);
    if (!pack.strider.id) {
      pack.strider.id = pack.name;
    }
    return cb(null, pack.strider);
  });
}
1012814
private Pair<ResourcePackage, PackageHeader> readPackage(PackageHeader packageHeader) {
        Pair<ResourcePackage, PackageHeader> pair = new Pair<>();
        //read packageHeader
        ResourcePackage resourcePackage = new ResourcePackage(packageHeader);
        pair.setLeft(resourcePackage);

        long beginPos = buffer.position();
        // read type string pool
        if (packageHeader.getTypeStrings() > 0) {
            Buffers.position(buffer, beginPos + packageHeader.getTypeStrings() - packageHeader.getHeaderSize());
            resourcePackage.setTypeStringPool(ParseUtils.readStringPool(buffer,
                    (StringPoolHeader) readChunkHeader()));
        }

        //read key string pool
        if (packageHeader.getKeyStrings() > 0) {
            Buffers.position(buffer, beginPos + packageHeader.getKeyStrings() - packageHeader.getHeaderSize());
            resourcePackage.setKeyStringPool(ParseUtils.readStringPool(buffer,
                    (StringPoolHeader) readChunkHeader()));
        }


        outer:
        while (buffer.hasRemaining()) {
            ChunkHeader chunkHeader = readChunkHeader();
            long chunkBegin = buffer.position();
            switch (chunkHeader.getChunkType()) {
                case ChunkType.TABLE_TYPE_SPEC:
                    TypeSpecHeader typeSpecHeader = (TypeSpecHeader) chunkHeader;
                    long[] entryFlags = new long[(int) typeSpecHeader.getEntryCount()];
                    for (int i = 0; i < typeSpecHeader.getEntryCount(); i++) {
                        entryFlags[i] = Buffers.readUInt(buffer);
                    }

                    TypeSpec typeSpec = new TypeSpec(typeSpecHeader);


                    typeSpec.setEntryFlags(entryFlags);
                    //id start from 1
                    typeSpec.setName(resourcePackage.getTypeStringPool()
                            .get(typeSpecHeader.getId() - 1));

                    resourcePackage.addTypeSpec(typeSpec);
                    Buffers.position(buffer, chunkBegin + typeSpecHeader.getBodySize());
                    break;
                case ChunkType.TABLE_TYPE:
                    TypeHeader typeHeader = (TypeHeader) chunkHeader;
                    // read offsets table
                    long[] offsets = new long[(int) typeHeader.getEntryCount()];
                    for (int i = 0; i < typeHeader.getEntryCount(); i++) {
                        offsets[i] = Buffers.readUInt(buffer);
                    }

                    Type type = new Type(typeHeader);
                    type.setName(resourcePackage.getTypeStringPool().get(typeHeader.getId() - 1));
                    long entryPos = chunkBegin + typeHeader.getEntriesStart() - typeHeader.getHeaderSize();
                    Buffers.position(buffer, entryPos);
                    ByteBuffer b = buffer.slice();
                    b.order(byteOrder);
                    type.setBuffer(b);
                    type.setKeyStringPool(resourcePackage.getKeyStringPool());
                    type.setOffsets(offsets);
                    type.setStringPool(stringPool);
                    resourcePackage.addType(type);
                    locales.add(type.getLocale());
                    Buffers.position(buffer, chunkBegin + typeHeader.getBodySize());
                    break;
                case ChunkType.TABLE_PACKAGE:
                    // another package. we should read next package here
                    pair.setRight((PackageHeader) chunkHeader);
                    break outer;
                case ChunkType.TABLE_LIBRARY:
                    // read entries
                    LibraryHeader libraryHeader = (LibraryHeader) chunkHeader;
                    for (long i = 0; i < libraryHeader.getCount(); i++) {
                        int packageId = buffer.getInt();
                        String name = Buffers.readZeroTerminatedString(buffer, 128);
                        LibraryEntry entry = new LibraryEntry(packageId, name);
                        //TODO: now just skip it..
                    }
                    Buffers.position(buffer, chunkBegin + chunkHeader.getBodySize());
                    break;
                case ChunkType.NULL:
//                    Buffers.position(buffer, chunkBegin + chunkHeader.getBodySize());
                    Buffers.position(buffer, buffer.position() + buffer.remaining());
                    break;
                default:
                    throw new ParserException("unexpected chunk type: 0x" + chunkHeader.getChunkType());
            }
        }

        return pair;

    }
326513
function processPackage(packageObject, computation) {
  if (packageObject.classes.class instanceof Array) {
    // Process each individual class
    packageObject.classes.class.forEach(function(clazz) {
      processClass(clazz, computation);
    });

  } else {
    // Single class to be processed
    processClass(packageObject.classes.class, computation);
  }
}
767704
function generateStepMap( $package, &$persistentData )
    {
        $steps = $this->attribute( 'steps' );
        $map = array();
        $lastStep = false;
        $currentSteps = array();
        for ( $i = 0; $i < count( $steps ); ++$i )
        {
            $step =& $steps[$i];
            if ( !isset( $step['previous_step'] ) )
            {
                if ( $lastStep )
                    $step['previous_step'] = $lastStep['id'];
                else
                    $step['previous_step'] = false;
            }
            if ( !isset( $step['next_step'] ) )
            {
                if ( $i + 1 < count( $steps ) )
                    $step['next_step'] = $steps[$i+1]['id'];
                else
                    $step['next_step'] = false;
            }
            if ( isset( $step['methods']['initialize'] ) )
                $this->InitializeStepMethodMap[$step['id']] = $step['methods']['initialize'];
            if( isset( $step['methods']['load'] ) )
                $this->LoadStepMethodMap[$step['id']] = $step['methods']['load'];
            if ( isset( $step['methods']['validate'] ) )
                $this->ValidateStepMethodMap[$step['id']] = $step['methods']['validate'];
            if ( isset( $step['methods']['commit'] ) )
                $this->CommitStepMethodMap[$step['id']] = $step['methods']['commit'];
            $isStepIncluded = true;
            if ( isset( $step['methods']['check'] ) )
            {
                $checkMethod = $step['methods']['check'];
                $isStepIncluded = $this->$checkMethod( $package, $persistentData );
            }
            if ( $isStepIncluded )
            {
                $map[$step['id']] =& $step;
                $lastStep =& $step;
                $currentSteps[] =& $step;
            }
        }
        $this->StepMap = array( 'first' => &$steps[0],
                                'map' => &$map,
                                'steps' => &$steps );
        $this->Attributes['step_map'] =& $this->StepMap;
        $this->Attributes['current_steps'] = $currentSteps;
    }
1090305
private void processPackage(File root, File dir) {
        getLog().debug("- package: " + dir);
        if (null != dir && dir.isDirectory()) {
            for (File f : dir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.isDirectory() || pathname.getName().endsWith(".class");
                }
            })) {
                if (f.isDirectory()) {
                    processPackage(root, f);
                } else if (f.getParentFile().getAbsolutePath().replace(File.separatorChar, '.').endsWith(basePackage + '.' + domainPackageName)) {
                    final String simpleName = f.getName().substring(0, f.getName().lastIndexOf(".class"));
                    final String className = String.format("%s.%s.%s", basePackage, domainPackageName, simpleName);
                    getLog().debug(String.format("--- class %s", className));
                    try {
                        Class clazz = loader.loadClass(className);
                        if (!Modifier.isAbstract(clazz.getModifiers()) && isEntity(clazz)) {
                            getLog().debug("@Entity " + clazz.getName());
                            final Entity entity = new Entity();
                            entity.setClazz(clazz);

                            final String packageName = clazz.getPackage().getName();
                            Group group = packages.get(packageName);
                            if (null == group) {
                                group = new Group();
                                group.setName(packageName);
                                packages.put(packageName, group);
                            }

                            group.getEntities().put(simpleName, entity);
                            entities.put(entity.getClassName(), entity);
                        }
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(ProcessDomainMojo.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }