/* package-private
180468
final PullResponse pull(
      String subscription, boolean returnImmediately, int maxMessages) {

    PullRequest request =
        PullRequest.newBuilder()
            .setSubscription(subscription)
            .setReturnImmediately(returnImmediately)
            .setMaxMessages(maxMessages)
            .build();
    return pull(request);
  }
1050256
@Override
    public T deletePackage(Package pack) throws IllegalArgumentException {
        Validate.notNull(pack, "Package name must be specified");

        return deletePackages(false, pack);
    }
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;
    }
805121
static Fix createFix(
      ImmutableList<ImportTree> wildcardImports,
      Set<TypeToImport> typesToImport,
      VisitorState state) {
    Map<Symbol, List<TypeToImport>> toFix =
        typesToImport.stream().collect(Collectors.groupingBy(TypeToImport::owner));
    final SuggestedFix.Builder fix = SuggestedFix.builder();
    for (ImportTree importToDelete : wildcardImports) {
      String importSpecification = importToDelete.getQualifiedIdentifier().toString();
      if (importToDelete.isStatic()) {
        fix.removeStaticImport(importSpecification);
      } else {
        fix.removeImport(importSpecification);
      }
    }
    for (Map.Entry<Symbol, List<TypeToImport>> entry : toFix.entrySet()) {
      final Symbol owner = entry.getKey();
      if (entry.getKey().getKind() != ElementKind.PACKAGE
          && entry.getValue().size() > MAX_MEMBER_IMPORTS) {
        qualifiedNameFix(fix, owner, state);
      } else {
        for (TypeToImport toImport : entry.getValue()) {
          toImport.addFix(fix);
        }
      }
    }
    return fix.build();
  }
1335698
function(o) {
        this.__base(o);
        this.root = o.root;
        this.target = o.target;
        this.npmPackages = o.npmPackages === undefined? ['package.json']: o.npmPackages;
    }
579360
function buildJSONSource() {

  var data = getModularSource();

  addCorePackage();
  prepareData();
  outputJSON('source.json', data);

  function addCorePackage() {
    data.modules.unshift({
      name: 'Core'
    });
    data.packages.unshift({
      name: 'Sugar',
      type: 'core',
      module: 'Core',
      dependencies: [],
      bodyWithComments: readFile('lib/core.js').trim()
    });
  }

  function bundleSetPackages() {
    var packages = [], handledSets = {}, p;

    for (var i = 0; i < data.packages.length; i++) {
      p = data.packages[i];
      if (p.set) {
        // If the package has been handled already then just skip.
        if (!handledSets[p.namespace + p.setName]) {
          packages.push({
            setName: p.setName,
            name: p.setName.replace(/[\[\]]/g, ''),
            sample: p.set.slice(0, 3).concat('...').join(', '),
            type: p.type,
            alias: p.alias,
            module: p.module,
            namespace: p.namespace,
            dependencies: p.dependencies,
            bodyWithComments: p.bodyWithComments
          });
          handledSets[p.namespace + p.setName] = true;
        }
      } else {
        packages.push(p);
      }
    }

    return packages;
  }

  function prepareData() {
    var bundledPackages = bundleSetPackages();
    data.modules.forEach(function(m) {
      indentField(m, 'comment');
    });
    bundledPackages.forEach(function(p) {

      // Pre-indenting all packages rather than doing it on compile to
      // save some cycles and also correctly calculate the package size.
      indentField(p, 'blockStart');
      indentField(p, 'blockEnd');
      indentField(p, 'bodyWithComments');

      cleanSourcePackage(p);
    });
    data.packages = bundledPackages;
  }

  function indentField(p, field) {
    if (p[field]) {
      p[field] = p[field].replace(/^(?=.)/gm, '  ');
    }
  }

  function cleanSourcePackage(p) {
    if (sourcePackageIsDependency(p)) {
      delete p.type;
    }
    delete p.vars;
    delete p.target;
    delete p.body;
    delete p.path;
    delete p.assigns;
    delete p.comments;
    delete p.defineMethod;
    delete p.varDependencies;
    compactField(p, 'bodyWithComments');
    compactField(p, 'dependencies');
  }

  function compactField(p, field) {
    var val = p[field];
    if (!val || (Array.isArray(val) && !val.length)) {
      delete p[field];
    }
  }

}
670361
protected void code(String template, String packageName, String className, Supplier<Map<String, Object>> context) {
        StringBuffer code = generate(template, context);
        writeCode(packageName, className, code);
    }
1277232
private Map<String,List<JavaFileObject>> searchSubPackages(
            List<String> subPackages,
            ListBuffer<String> packages,
            List<String> excludedPackages)
            throws IOException {
        Map<String,List<JavaFileObject>> packageFiles =
                new HashMap<String,List<JavaFileObject>>();

        Map<String,Boolean> includedPackages = new HashMap<String,Boolean>();
        includedPackages.put("", true);
        for (String p: excludedPackages)
            includedPackages.put(p, false);

        StandardLocation path = docenv.fileManager.hasLocation(StandardLocation.SOURCE_PATH)
                ? StandardLocation.SOURCE_PATH : StandardLocation.CLASS_PATH;

        searchSubPackages(subPackages,
                includedPackages,
                packages, packageFiles,
                path,
                EnumSet.of(JavaFileObject.Kind.SOURCE));

        return packageFiles;
    }
1190150
function(next) {
            core.allowPackages.forEach(function(pkg) {
                try {
                    var mod = path.dirname(require.resolve(pkg)).replace(/\/lib$/, "");
                    core.packages[pkg] = { path: mod };
                    if (lib.statSync(mod + "/etc").isDirectory()) {
                        core.packages[pkg].etc = 1;
                        var cfg = lib.readFileSync(mod + "/etc/config");
                        if (cfg) {
                            config = cfg + "\n" + config;
                            core.packages[pkg].config = 1;
                            core.parseConfig(cfg, 1);
                        }
                    }
                    ["modules","locales","views","web"].forEach(function(x) {
                        if (lib.statSync(mod + "/" + x).isDirectory()) {
                            core.path[x].unshift(mod + "/" + x);
                            core.packages[pkg][x] = 1;
                        }
                    });
                    logger.debug("init:", "npm package:", pkg, core.packages[pkg]);
                } catch(e) {
                    logger.error("init:", "npm package:", pkg, e);
                }
            });
            next();
        }
207177
@Override
    public T addPackage(String pack) throws IllegalArgumentException {
        Validate.notNull(pack, "Package must be specified");

        return addPackages(false, pack);
    }
857481
@Override
    @Path("/{package}")
    @ApiOperation(value="Export JSON content for a package or list of packages",
        response=Package.class)
    @ApiImplicitParams({
        @ApiImplicitParam(name="packages", paramType="query", allowMultiple=true, dataType="com.centurylink.mdw.model.workflow.Package")})
    public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {

        Query query = getQuery(path, headers);
        boolean nonVersioned = query.getBooleanFilter("nonVersioned");
        if (nonVersioned) {
            // designer request for unversioned and (optionally) archived packages in a remote project
            boolean archive = query.getBooleanFilter("archive");
            try {
                File pkgDir = new File(
                        PropertyManager.getProperty(PropertyNames.MDW_ASSET_LOCATION));
                AssetServices assetServices = new AssetServicesImpl();
                List<String> extraPackages = assetServices.getExtraPackageNames();
                if (archive) {
                    File archiveDir = new File(pkgDir + "/" + PackageDir.ARCHIVE_SUBDIR);
                    if (archiveDir.isDirectory())
                        extraPackages.add(archiveDir.getName());
                }
                if (extraPackages.isEmpty()) {
                    return new JsonObject();
                }
                else {
                    String url = ApplicationContext.getServicesUrl() + "/asset/packages?packages="
                            + String.join(",", extraPackages);
                    Download download = new Download(url);
                    return download.getJson();
                }
            }
            catch (Exception ex) {
                logger.severeException(ex.getMessage(), ex);
                throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage());
            }
        }
        else {
            List<String> pkgNames = new ArrayList<String>();
            String pkgName = getSegment(path, 1);
            if (pkgName != null) {
                pkgNames.add(pkgName);
            }
            else {
                String[] pkgs = query.getArrayFilter("packages");
                if (pkgs != null)
                    pkgNames.addAll(Arrays.asList(pkgs));
            }
            if (pkgNames.isEmpty())
                throw new ServiceException(ServiceException.BAD_REQUEST, "One of {package} path element or 'packages' query param required");

            try {
                // get the package vos from the loader
                ProcessLoader loader = DataAccess.getProcessLoader();
                List<Package> packages = new ArrayList<Package>();
                for (String name : pkgNames) {

                    Package pkg = loader.getPackage(name);
                    if (pkg == null)
                        throw new ServiceException(ServiceException.NOT_FOUND, "Package " + name + " not found"); // cannot be archived
                    pkg = loader.loadPackage(pkg.getId(), true); // deep load
                    packages.add(pkg);
                }

                JSONObject json = new JsonObject(new ImporterExporterJson().exportPackages(packages));
                Jsonable mdw = new Mdw();
                json.put(mdw.getJsonName(), mdw.getJson());
                return json;
            }
            catch (Exception ex) {
                logger.severeException(ex.getMessage(), ex);
                throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage());
            }
        }
    }
934646
function ()
		{
			var nmPath = this.modulePath + 'node_modules/';
			var pkgJson;
			var pkgName;
			var pkgInfo;
			var packageList = {};
			var validScript = /[\w|\W]+\.[js|coffee]+$/;
			if (fs.existsSync(nmPath))
			{
				this.e.log&&this.e.log('Importing packages...','system');
				var packages = fs.readdirSync(nmPath);
				for (p in packages)
				{
					try {
						if (packages[p].indexOf('wns')!==-1 &&
							(packages[p].indexOf('pkg') !== -1 || packages[p].indexOf('package') !== -1))
						{
							pkgName = packages[p];
							pkgDir = nmPath + pkgName;
							pkgJson = pkgDir + '/package.json';
							if (fs.existsSync(pkgJson))
							{
								pkgInfo = JSON.parse(fs.readFileSync(pkgJson));
								pkgInfo.require = pkgInfo.require||{};
								Object.defineProperty(pkgInfo,'classes',{ value: {}, enumerable: false })
								var files = fs.readdirSync(pkgDir);
								for (f in files)
								{
									var fileName = files[f].split('/').pop();
									if (validScript.test(fileName))
									{
										var className = fileName.split('.');
										className.splice(-1);
										pkgInfo.classes[className] = pkgDir+'/'+fileName;
									}
								}
								packageList[pkgInfo.name]=pkgInfo;
							}
						}
					} catch (e)
					{
						console.error('Error on loading package `'+pkgName+"`.")
						throw e;
					}
				}
			}

			this.removeInvalidPackages(packageList);
			this.loadPackages(packageList);
		}
340686
function &_buildFrame(&$package)
    {
        ob_start();

        echo '<body id="frame">', "\n\n";

        echo '<h1><a href="package-summary.html" target="main">', $package->name(), "</a></h1>\n\n";

        $classes =& $package->ordinaryClasses();
        if ($classes && is_array($classes)) {
            ksort($classes);
            echo "<h2>Classes</h2>\n";
            echo "<ul>\n";
            foreach ($classes as $name => $class) {
                echo '<li><a href="', str_repeat('../', $package->depth() + 1), $classes[$name]->asPath(), '" target="main">', $classes[$name]->name(), "</a></li>\n";
            }
            echo "</ul>\n\n";
        }

        $interfaces =& $package->interfaces();
        if ($interfaces && is_array($interfaces)) {
            ksort($interfaces);
            echo "<h2>Interfaces</h2>\n";
            echo "<ul>\n";
            foreach ($interfaces as $name => $interface) {
                echo '<li><a href="', str_repeat('../', $package->depth() + 1), $interfaces[$name]->asPath(), '" target="main">', $interfaces[$name]->name(), "</a></li>\n";
            }
            echo "</ul>\n\n";
        }

        $traits =& $package->traits();
        if ($traits && is_array($traits)) {
            ksort($traits);
            echo "<h2>Traits</h2>\n";
            echo "<ul>\n";
            foreach ($traits as $name => $trait) {
                echo '<li><a href="', str_repeat('../', $package->depth() + 1), $traits[$name]->asPath(), '" target="main">', $traits[$name]->name(), "</a></li>\n";
            }
            echo "</ul>\n\n";
        }

        $exceptions =& $package->exceptions();
        if ($exceptions && is_array($exceptions)) {
            ksort($exceptions);
            echo "<h2>Exceptions</h2>\n";
            echo "<ul>\n";
            foreach ($exceptions as $name => $exception) {
                echo '<li><a href="', str_repeat('../', $package->depth() + 1), $exceptions[$name]->asPath(), '" target="main">', $exceptions[$name]->name(), "</a></li>\n";
            }
            echo "</ul>\n\n";
        }

        $functions =& $package->functions();
        if ($functions && is_array($functions)) {
            ksort($functions);
            echo "<h2>Functions</h2>\n";
            echo "<ul>\n";
            foreach ($functions as $name => $function) {
                echo '<li><a href="', str_repeat('../', $package->depth() + 1), $functions[$name]->asPath(), '" target="main">', $functions[$name]->name(), "</a></li>\n";
            }
            echo "</ul>\n\n";
        }

        $globals =& $package->globals();
        if ($globals && is_array($globals)) {
            ksort($globals);
            echo "<h2>Globals</h2>\n";
            echo "<ul>\n";
            foreach ($globals as $name => $global) {
                echo '<li><a href="', str_repeat('../', $package->depth() + 1), $globals[$name]->asPath(), '" target="main">', $globals[$name]->name(), "</a></li>\n";
            }
            echo "</ul>\n\n";
        }

        echo '</body>', "\n\n";

        $output = ob_get_contents();
        ob_end_clean();

        return $output;
    }
545350
function Package(name)
    {
        var dotBowerJson = Package._readBowerJson(name) || {};
        var overrides = globalOverrides[name] || {};

        this.name         = name;
        this.installed    = !! dotBowerJson.name;
        this.main         = overrides.main || dotBowerJson.main || [];
        this.dependencies = overrides.dependencies || dotBowerJson.dependencies || [];
    }
304285
public boolean performJavaCompilations(File binDir,
                                           String serverSettings,
                                           String[] args,
                                           Set<String> recentlyCompiled,
                                           boolean[] rcValue) {
        Map<String,Transformer> suffixRules = new HashMap<String,Transformer>();
        suffixRules.put(".java", compileJavaPackages);
        compileJavaPackages.setExtra(serverSettings);
        compileJavaPackages.setExtra(args);

        rcValue[0] = perform(binDir, suffixRules);
        recentlyCompiled.addAll(taintedPackages());
        clearTaintedPackages();
        boolean again = !packagesWithChangedPublicApis.isEmpty();
        taintPackagesDependingOnChangedPackages(packagesWithChangedPublicApis, recentlyCompiled);
        packagesWithChangedPublicApis = new HashSet<String>();
        return again && rcValue[0];
    }
1330094
function mapByDepth(rootPackage) {
    var depth = 0
      , allDeps = {}
      , superDepsList = {}
      ;

    function traverseDeps(childPackage) {
      depth += 1;

      childPackage.dependencyTree = childPackage.dependencyTree || {};
      Object.keys(childPackage.dependencyTree).forEach(function (depName) {
        var childDeps = (childPackage.dependencyTree[depName] || {}) || {}
          ;

        if (superDepsList[depName]) {
          // a dependency can't (meaning shouldn't) have a path in which it depends on itself
          // this kind of resolution isn't as important as it once was
          // since the modules can be loaded out-of-order
          return;
        }

        superDepsList[depName] = true;

        allDeps[depth] = allDeps[depth] || [];
        allDeps[depth].push(depName);

        if (childDeps) {
          traverseDeps(childDeps);
        }

        superDepsList[depName] = false;
      });

      depth -= 1;
    }

    traverseDeps(rootPackage);

    return allDeps;
  }
230727
function (options, dir, callback) {
  options.logger('Creating contents of package')

  async.parallel([
    async.apply(createDesktop, options, dir),
    async.apply(createIcon, options, dir),
    async.apply(createCopyright, options, dir),
    async.apply(createApplication, options, dir)
  ], function (err) {
    callback(err, dir)
  })
}