Package access, to be called by DefaultClientCollection
496372
@Override
    void addToCollection(final ClientCollection col) throws ProponoException {
        setCollection(col);
        final EntityEnclosingMethod method = new PostMethod(col.getHrefResolved());
        getCollection().addAuthentication(method);
        try {
            final Content c = getContents().get(0);
            if (inputStream != null) {
                method.setRequestEntity(new InputStreamRequestEntity(inputStream));
            } else {
                method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(getBytes())));
            }
            method.setRequestHeader("Content-type", c.getType());
            method.setRequestHeader("Title", getTitle());
            method.setRequestHeader("Slug", getSlug());
            getCollection().getHttpClient().executeMethod(method);
            if (inputStream != null) {
                inputStream.close();
            }
            final InputStream is = method.getResponseBodyAsStream();
            if (method.getStatusCode() == 200 || method.getStatusCode() == 201) {
                final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(is), col.getHrefResolved(), Locale.US);
                BeanUtils.copyProperties(this, romeEntry);

            } else {
                throw new ProponoException("ERROR HTTP status-code=" + method.getStatusCode() + " status-line: " + method.getStatusLine());
            }
        } catch (final IOException ie) {
            throw new ProponoException("ERROR: saving media entry", ie);
        } catch (final JDOMException je) {
            throw new ProponoException("ERROR: saving media entry", je);
        } catch (final FeedException fe) {
            throw new ProponoException("ERROR: saving media entry", fe);
        } catch (final IllegalAccessException ae) {
            throw new ProponoException("ERROR: saving media entry", ae);
        } catch (final InvocationTargetException te) {
            throw new ProponoException("ERROR: saving media entry", te);
        }
        final Header locationHeader = method.getResponseHeader("Location");
        if (locationHeader == null) {
            LOG.warn("WARNING added entry, but no location header returned");
        } else if (getEditURI() == null) {
            final List<Link> links = getOtherLinks();
            final Link link = new Link();
            link.setHref(locationHeader.getValue());
            link.setRel("edit");
            links.add(link);
            setOtherLinks(links);
        }
    }
185205
private static BundleCapability getExportedPackage(BundleContext context, String packageName) {
        List<BundleCapability> packages = new ArrayList<BundleCapability>();
        for (Bundle bundle : context.getBundles()) {
            BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);
            for (BundleCapability packageCapability : bundleRevision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE)) {
                String pName = (String) packageCapability.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE);
                if (pName.equalsIgnoreCase(packageName)) {
                    packages.add(packageCapability);
                }
            }
        }

        Version max = Version.emptyVersion;
        BundleCapability maxVersion = null;
        for (BundleCapability aPackage : packages) {
            Version version = (Version) aPackage.getAttributes().get("version");
            if (max.compareTo(version) <= 0) {
                max = version;
                maxVersion = aPackage;
            }
        }

        return maxVersion;
    }
912909
public static int toIntAccess(String access) throws ApplicationException {
	access = StringUtil.toLowerCase(access.trim());
	if (access.equals("package")) return Component.ACCESS_PACKAGE;
	else if (access.equals("private")) return Component.ACCESS_PRIVATE;
	else if (access.equals("public")) return Component.ACCESS_PUBLIC;
	else if (access.equals("remote")) return Component.ACCESS_REMOTE;
	throw new ApplicationException("invalid access type [" + access + "], access types are remote, public, package, private");

    }
303249
@Override
    @Path("/packages")
    @ApiOperation(value="Import discovered asset packages", response=StatusMessage.class)
    @ApiImplicitParams({
        @ApiImplicitParam(name="discoveryUrl", paramType="query", dataType="string"),
        @ApiImplicitParam(name="branch", paramType="query", dataType="string"),
        @ApiImplicitParam(name="discoveryType", paramType="query", required=true),
        @ApiImplicitParam(name="groupId", paramType="query", dataType="string"),
        @ApiImplicitParam(name="packages", paramType="body", required=true, dataType="List")})
    public JSONObject put(String path, JSONObject content, Map<String,String> headers)
            throws ServiceException, JSONException {
        Query query = getQuery(path, headers);
        String discoveryType = query.getFilter("discoveryType");
        if (discoveryType == null)
            throw new ServiceException(ServiceException.BAD_REQUEST, "Missing param: discoveryType");
        List<String> pkgs = new JsonArray(content.getJSONArray("packages")).getList();
        Query discQuery = new Query(path);
        discQuery.setArrayFilter("packages", pkgs.toArray(new String[0]));
        File assetRoot = ApplicationContext.getAssetRoot();
        Bulletin bulletin = null;
        try {
            // central discovery
            if (!discoveryType.isEmpty() && discoveryType.equals("central")) {
                String groupId = query.getFilter("groupId");
                if (groupId == null)
                    throw new ServiceException(ServiceException.BAD_REQUEST, "Missing param: groupId");
                bulletin = SystemMessages.bulletinOn("Asset import in progress...");
                Import importer = new Import(groupId, pkgs);
                importer.setAssetLoc(assetRoot.getPath());
                importer.setForce(true);
                importer.run();
                SystemMessages.bulletinOff(bulletin, "Asset import completed");
                bulletin = null;
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        this.setName("AssetsCacheRefresh-thread");
                        CacheRegistration.getInstance().refreshCaches(null);
                    }
                };
                thread.start();
            }
            else {
                String discoveryUrl = query.getFilter("discoveryUrl");
                if ("https://github.com/CenturyLinkCloud/mdw.git".equals(discoveryUrl)) {
                    Update update = new Update(null);
                    update.setAssetLoc(assetRoot.getPath());
                    update.setBaseAssetPackages(pkgs);
                    update.setMdwVersion(ApplicationContext.getMdwVersion());
                    update.run();
                }
                else {
                    String branch = query.getFilter("branch");
                    if (branch == null)
                        throw new ServiceException(ServiceException.BAD_REQUEST, "Missing param: groupId");
                    File gitLocalPath = new File(PropertyManager.getProperty(PropertyNames.MDW_GIT_LOCAL_PATH));
                    VersionControlGit vcGit = new VersionControlGit();
                    AssetServices assetServices = ServiceLocator.getAssetServices();
                    GitDiscoverer discoverer = assetServices.getDiscoverer(discoveryUrl);
                    discoverer.setRef(branch);
                    String assetPath = discoverer.getAssetPath();
                    if (discoveryUrl.indexOf('?') != -1)
                        discoveryUrl = discoveryUrl.substring(0, discoveryUrl.indexOf('?'));
                    URL url = new URL(discoveryUrl);
                    String[] userInfo = url.getUserInfo().split(":");
                    File test = new File(gitLocalPath.getAbsolutePath()).getParentFile();
                    if (test != null && gitLocalPath.getPath().length() <= 3)
                        test = new File( gitLocalPath.getAbsolutePath()).getParentFile().getParentFile().getParentFile();
                    File tempfile = new File ( test.getAbsolutePath() + "/" + "mdw_git_discovery_" + java.lang.System.currentTimeMillis());
                    vcGit.connect(discoveryUrl, null, null, tempfile);
                    vcGit.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userInfo[0], userInfo[1]));
                    vcGit.cloneBranch(branch);
                    for (String pkg : pkgs) {
                        String pkgPath = pkg.replace(".", "/");
                        String src = tempfile.getAbsolutePath() + "/" + assetPath + "/" + pkgPath;
                        String dest = ApplicationContext.getAssetRoot().getAbsolutePath() + "/" + pkgPath;
                        Files.createDirectories(Paths.get(dest));
                        Files.move(Paths.get(src), Paths.get(dest), StandardCopyOption.REPLACE_EXISTING);
                    }
                    new Delete(tempfile).run();
                }
            }
        }
        catch (Exception ex) {
            SystemMessages.bulletinOff(bulletin, Level.Error, "Asset import failed: " + ex.getMessage());
            throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex);
        }

        return null;
    }
844627
@SuppressWarnings("unchecked")
  private boolean handleCollection(
    final ConfigurationContext ctx,
    final Class<?> _type,
    final Object cfg,
    final ParsedConfiguration _parsedCfg) {
    String _containerName = _parsedCfg.getContainer();
    Method m;
    try {
      m = cfg.getClass().getMethod(constructGetterName(_containerName));
    } catch (NoSuchMethodException ex) {
      return false;
    }
    if (!Collection.class.isAssignableFrom(m.getReturnType())) {
      return false;
    }
    Collection c;
    try {
      c = (Collection) m.invoke(cfg);
    } catch (Exception ex) {
      throw new ConfigurationException("Cannot access collection for '" + _containerName + "' " + ex, _parsedCfg);
    }
    Object _bean = createBeanAndApplyConfiguration(ctx, _type, _parsedCfg);
    try {
      c.add(_bean);
    } catch (IllegalArgumentException ex) {
      throw new ConfigurationException("Rejected add '" + _containerName + "': " + ex.getMessage(), _parsedCfg);
    }
    return true;
  }
59351
@Override
    public <E> CollectionAttribute<X, E> getDeclaredCollection(String paramString, Class<E> paramClass)
    {
        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramString);

        if (onCheckCollectionAttribute(declaredAttrib, paramClass))
        {
            return (CollectionAttribute<X, E>) declaredAttrib;
        }

        throw new IllegalArgumentException(
                "attribute of the given name and type is not present in the managed type, for name:" + paramString
                        + " , type:" + paramClass);
    }
1190952
def get_client(key, project):
    """"""
    cred = get_storage_credentials(key)
    return storage.Client(project=project, credentials=cred)
873159
@Override
    public void visitClassContext(ClassContext classContext) {
        try {
            stack = new OpcodeStack();
            toStringRegisters = new HashMap<>();
            packageName = classContext.getJavaClass().getPackageName();
            super.visitClassContext(classContext);
        } finally {
            stack = null;
            toStringRegisters = null;
        }
    }
1088609
@SuppressWarnings("unchecked")
    protected Collection<IClient> getClients() {
        if (!hasClients()) {
            // avoid creating new Collection object if no clients exist.
            return Collections.EMPTY_SET;
        }
        return Collections.unmodifiableCollection(clients.values());
    }
916264
function (collection, options) {
                var ret;
                if (collection && collection.$modelFactory) {
                    ret = this.getProcessorForModelClass(collection.$modelFactory, options);
                }

                return ret || this.$defaultProcessor;
            }
90870
public static void collectCollection(IndexReader reader,
      List<Integer> fullDocSet, ComponentCollection collectionInfo)
      throws IOException {
    if (collectionInfo != null) {
      CodecCollector.collectCollection(reader, fullDocSet, collectionInfo);
    }
  }
620730
public void updateComponentDataMemberDefaultAccess(String strAccess) throws SecurityException, ApplicationException {
	checkWriteAccess();

	boolean hasAccess = ConfigWebUtil.hasAccess(config, SecurityManager.TYPE_SETTING);
	if (!hasAccess) throw new SecurityException("no access to update component setting");

	Element scope = _getRootElement("component");

	if (StringUtil.isEmpty(strAccess)) {
	    scope.setAttribute("data-member-default-access", "");
	}
	else {
	    scope.setAttribute("data-member-default-access", ComponentUtil.toStringAccess(ComponentUtil.toIntAccess(strAccess)));
	}
    }
434133
private void addApiDocRoots(String packageListUrl) {
	BufferedReader br = null;
	packageListUrl = fixApiDocRoot(packageListUrl);
	try {
	    URL url = new URL(packageListUrl + "/package-list");
	    br = new BufferedReader(new InputStreamReader(url.openStream()));
	    String line;
	    while((line = br.readLine()) != null) {
		line = line + ".";
		Pattern pattern = Pattern.compile(line.replace(".", "\\.") + "[^\\.]*");
		apiDocMap.put(pattern, packageListUrl);
	    }
	} catch(IOException e) {
	    System.err.println("Errors happened while accessing the package-list file at "
		    + packageListUrl);
	} finally {
	    if(br != null)
		try {
		    br.close();
		} catch (IOException e) {}
	}
	
    }
438785
def get_collection(self, namespace):
        """"""
        database, coll = namespace.split(".", 1)
        return self.primary_client[database][coll]
53839
synchronized public static <T> Set<ClassInfo> getNonAbstractSubClassInfoSet(Class<T> parentClass, String... packageNames) {
        if (packageNames == null || packageNames.length == 0) {
            packageNames = defaultPackages();
        }
        try (ScanResult scanResult =
                     new ClassGraph()
                             .enableAllInfo()
                             .whitelistPackages(packageNames)
                             .scan()) {
            ClassInfoList classInfos = parentClass.isInterface() ?
                    scanResult.getClassesImplementing(parentClass.getName()) :
                    scanResult.getSubclasses(parentClass.getName());
            return classInfos
                    .stream()
                    .filter(classInfo -> !classInfo.isAbstract())
                    .collect(Collectors.toSet());
        }
    }
681828
protected void handleCollectionTypeNotAvailable(XCollectionLiteral literal, ITypeComputationState state, Class<?> clazz) {
		for(XExpression element: literal.getElements()) {
			state.withNonVoidExpectation().computeTypes(element);
		}
		state.acceptActualType(state.getReferenceOwner().newUnknownTypeReference(clazz.getName()));
	}
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());
            }
        }
    }