/*
//////////////////////////////////////////////////
Package methods:
//////////////////////////////////////////////////
182283
@Override
	public void writeStartElement(StartElement elem)
        throws XMLStreamException
    {
        QName name = elem.getName();
        writeStartElement(name.getLocalPart());
        @SuppressWarnings("unchecked")
        Iterator<Attribute> it = elem.getAttributes();
        while (it.hasNext()) {
            Attribute attr = it.next();
            name = attr.getName();
            writeAttribute(name.getLocalPart(), attr.getValue());
        }
    }
518485
function preparePackage() {
    var ignoreFiles = ['package.json', 'README.md', 'LICENSE.md', '.gitignore', '.npmignore'];
    var ignoreCopyFiles = [];
    var copyRecursiveSync = function(src, dest) {
        var exists = fs.existsSync(src);
        var stats = exists && fs.statSync(src);
        var isDirectory = exists && stats.isDirectory();
        if (exists && isDirectory) {
            if (!fs.existsSync(dest)) {
                fs.mkdirSync(dest);
            }
            fs.readdirSync(src).forEach(function(filename) {
                copyRecursiveSync(upath.join(src, filename),
                    upath.join(dest, filename));
            });
        } else {
            if (ignoreCopyFiles.indexOf(upath.basename(src)) === -1) {
                fs.linkSync(src, dest);
            }
        }
    };
    var srcPkg = upath.join(process.cwd(), 'src');
    if (fs.existsSync(srcPkg)) {
        fs.readdirSync(process.cwd()).forEach(function(filename) {
            var curPath = upath.join(process.cwd(), filename);
            if (ignoreFiles.indexOf(upath.basename(curPath)) === -1 && fs.statSync(curPath).isFile()) {
                fs.unlinkSync(curPath);
            }
        });
        copyRecursiveSync(srcPkg, process.cwd());
    }
    deleteFolderRecursive(srcPkg);
    deleteFolderRecursive(upath.join(process.cwd(), 'test'));
    deleteFolderRecursive(upath.join(process.cwd(), 'env'));
}
707460
private Set<PackageResourceReferenceWrapper> addFoundPackageResourceReferences(
		Set<PackageResourceReferenceWrapper> packageResourceReferences, final Class<?> iface)
	{
		final Set<PackageResourceReferenceWrapper> prr = PackageResourceReferences.getInstance()
			.getPackageResourceReferenceMap().get(iface);
		if ((packageResourceReferences != null) && !packageResourceReferences.isEmpty())
		{
			if ((prr != null) && !prr.isEmpty())
			{
				packageResourceReferences.addAll(prr);
			}
			else
			{

			}
		}
		else
		{
			if ((prr != null) && !prr.isEmpty())
			{
				packageResourceReferences = prr;
			}
		}
		return packageResourceReferences;
	}
1340909
static String getParentPackageName(final String packageOrClassName) {
        if (packageOrClassName.isEmpty()) {
            return null;
        }
        final int lastDotIdx = packageOrClassName.lastIndexOf('.');
        return lastDotIdx < 0 ? "" : packageOrClassName.substring(0, lastDotIdx);
    }
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;
    }
831591
static String fromPackageName(String packageName) {
        List<String> tokens = tokenOf(packageName);
        return fromTokens(tokens);
    }
436591
private void installPackage() {
        AndPermission.with(this)
            .install()
            .file(new File(Environment.getExternalStorageDirectory(), "android.apk"))
            .rationale(new InstallRationale())
            .onGranted(new Action<File>() {
                @Override
                public void onAction(File data) {
                    // Installing.
                    toast(R.string.successfully);
                }
            })
            .onDenied(new Action<File>() {
                @Override
                public void onAction(File data) {
                    // The user refused to install.
                    toast(R.string.failure);
                }
            })
            .start();
    }
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;

    }
532892
@Override
    protected ResolutionResult resolveDependencies(String projectFolder, String topLevelFolder, Set<String> paketDependenciesFiles) {
        boolean installSuccess = true;
        Collection<DependencyInfo> dependencies = new ArrayList<>();
        List<String> excludes = new LinkedList<>();
        if (paketRunPreStep) {
            File paket = new File(topLevelFolder + Constants.FORWARD_SLASH + PAKET_EXE);
            if (StringUtils.isNotEmpty(this.paketPath)) {
                paket = new File(this.paketPath);
            } else if (!paket.exists()) {
                paket = null;
            }
            installSuccess = !executePreparationStep(topLevelFolder, paket);
        }
        if (installSuccess) {
            String paketLockPath = topLevelFolder + Constants.FORWARD_SLASH + PAKET_LOCK;
            File paketLockFile = new File(paketLockPath);
            if (paketLockFile.exists()) {
                logger.debug("Found paket.lock file: {}", paketLockPath);
                Map<String, List<String>> groupToDirectDependenciesMap = getGroupToDirectDependencies(paketDependenciesFiles.iterator().next());
                if (groupToDirectDependenciesMap != null && !groupToDirectDependenciesMap.keySet().isEmpty()) {
                    Collection<AbstractPaketDependencyCollector> paketDependencyCollectors = new LinkedList<>();
                    for(String groupName : groupToDirectDependenciesMap.keySet()) {
                        if (groupName.equals(MAIN)) {
                            paketDependencyCollectors.add(new MainGroupPaketDependencyCollector(groupToDirectDependenciesMap.get(MAIN), this.paketIgnoredGroups));
                        } else {
                            paketDependencyCollectors.add(new GroupPaketDependencyCollector(groupToDirectDependenciesMap.get(groupName), this.paketIgnoredGroups, groupName));
                        }
                    }
                    logger.info("Start collecting paket dependencies");
                    paketDependencyCollectors.forEach(paketDependencyCollector -> {
                        Collection<AgentProjectInfo> prjectInfo = paketDependencyCollector.collectDependencies(topLevelFolder);
                        dependencies.addAll(prjectInfo.iterator().next().getDependencies());
                    });
                }

                // ignore all the nupkg files in order to not scan them again
                if (!dependencies.isEmpty()) {
                    if (this.ignoreSourceFiles) {
                        excludes.addAll(normalizeLocalPath(projectFolder, topLevelFolder,extensionPattern(PAKET_EXTENSIONS) , null));
                    } else {
                        excludes.addAll(normalizeLocalPath(projectFolder, topLevelFolder, extensionPattern(PAKET_EXTENSIONS), Constants.PACKAGES));
                    }
                }
            } else {
                logger.warn("Could not find paket.lock file in {}. Please execute 'paket install' first.", topLevelFolder);
            }
        } else {
            logger.warn("'paket install' command failed");
        }
        return new ResolutionResult(dependencies, excludes, getDependencyType(), topLevelFolder);
    }
512896
@Override
    public T addPackages(boolean recursive, Package... packages) throws IllegalArgumentException {
        Validate.notNull(packages, "Packages must be specified");

        return addPackages(recursive, Filters.includeAll(), packages);
    }
1168653
private RPCParameters packageParams(Object... params) {
        if (params == null) {
            return null;
        }
        
        if (params.length == 1 && params[0] instanceof RPCParameters) {
            return (RPCParameters) params[0];
        }
        
        return new RPCParameters(params);
    }
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;
        }
    }
1047194
@Override
    public T addPackage(Package pack) throws IllegalArgumentException {
        Validate.notNull(pack, "Pack must be specified");

        return addPackage(pack.getName());
    }
1099188
private String subPathBeforePackage(File file) {
		String filePath = file.getAbsolutePath();
		if (StrUtil.isNotEmpty(this.packageDirName)) {
			filePath = StrUtil.subBefore(filePath, this.packageDirName, true);
		}
		return StrUtil.addSuffixIfNot(filePath, File.separator);
	}
581869
private String packageAppend(String origPackage, String suffix) {
    if (origPackage == null) {
      return suffix;
    } else {
      return origPackage + "." + suffix;
    }
  }
426343
protected void initBaseAssetPackages() throws IOException {
        baseAssetPackages = new ArrayList<>();
        addBasePackages(getAssetRoot(), getAssetRoot());
        if (baseAssetPackages.isEmpty())
            baseAssetPackages = Packages.DEFAULT_BASE_PACKAGES;
    }
540412
public PackageDescriptor createPackageDescriptor(String packageName,
                                                     ClassLoader classLoader) {
        return PackageDescriptor.forName(packageName, classLoader);
    }