public void testRepodata() throws Exception {

    OutputStream st = new ByteArrayOutputStream();
    SimpleContentHandler tmpHandler = getTemporaryHandler(st);

    SimpleAttributesImpl attr = new SimpleAttributesImpl();
    attr.addAttribute("type", "rpm");
    tmpHandler.startDocument();

    tmpHandler.startElement("package", attr);

    SimpleAttributesImpl secattr = new SimpleAttributesImpl();
    attr.addAttribute("bar", "&>><<");
    tmpHandler.startElement("foo", secattr);
    tmpHandler.addCharacters("&&&&");
    tmpHandler.endElement("foo");

    tmpHandler.endElement("package");
    tmpHandler.endDocument();

    // st.flush();
    String test = st.toString();
    System.out.println(test);

    Package p = PackageTest.createTestPackage();
    Channel c = ChannelFactoryTest.createTestChannel();
    c.addPackage(p);
    ChannelFactory.save(c);

    PackageManager.createRepoEntrys(c.getId());

    PackageManager.updateRepoPrimary(p.getId(), test);
    DataResult dr = PackageManager.getRepoData(p.getId());
    PackageDto dto = (PackageDto) dr.get(0);
    String prim = dto.getPrimaryXml();
    String other = dto.getOtherXml();
    assertEquals(prim, test);
  }
  public void testLookupCustomPackagesForChannel() throws Exception {
    Channel channel1 = ChannelFactoryTest.createTestChannel(user);
    Package pack = PackageTest.createTestPackage(user.getOrg());
    List test =
        PackageManager.lookupCustomPackagesForChannel(channel1.getId(), user.getOrg().getId());

    assertTrue(test.size() == 1);
    PackageOverview packOver = (PackageOverview) test.get(0);
    assertEquals(pack.getId(), packOver.getId());

    channel1.addPackage(pack);
    test = PackageManager.lookupCustomPackagesForChannel(channel1.getId(), user.getOrg().getId());

    assertTrue(test.size() == 0);
  }
  /**
   * Add a kickstart package with the given name to the given channel.
   *
   * @param packageName
   * @param channel
   * @throws Exception
   */
  public static void addKickstartPackageToChannel(String packageName, Channel channel)
      throws Exception {
    PackageCapability kickstartCapability = findOrCreateKickstartCapability();
    com.redhat.rhn.domain.rhnpackage.Package kickstartPkg =
        PackageManagerTest.addPackageToChannel(packageName, channel);

    WriteMode m = ModeFactory.getWriteMode("test_queries", "insert_into_rhnPackageProvides");
    Map params = new HashMap();
    params.put("pkg_id", kickstartPkg.getId());
    params.put("capability_id", kickstartCapability.getId());
    params.put("sense_id", "8");
    m.executeUpdate(params);

    // Repeast for another sense:
    params.put("sense_id", "268435464");
    m.executeUpdate(params);
  }
  /**
   * Adds packages associated to the errata
   *
   * @param erratum erratum to be added
   * @param channel channel info
   * @throws SAXException
   */
  private void addErratumPkgList(Errata erratum, Channel channel) throws SAXException {
    handler.startElement("pkglist");

    SimpleAttributesImpl attr = new SimpleAttributesImpl();
    attr.addAttribute("short", channel.getLabel());
    handler.startElement("collection", attr);

    handler.addElementWithCharacters("name", channel.getName());

    Iterator iter = erratum.getPackages().iterator();

    while (iter.hasNext()) {
      Package pkg = (Package) iter.next();
      if (channel.getPackages().contains(pkg)) {
        long pkgId = pkg.getId();
        String epoch = pkg.getPackageEvr().getEpoch();
        if (epoch == null || epoch.length() == 0) {
          epoch = "0";
        }
        attr.clear();
        attr.addAttribute("name", sanitize(pkgId, pkg.getPackageName().getName()));
        attr.addAttribute("version", sanitize(pkgId, pkg.getPackageEvr().getVersion()));
        attr.addAttribute("release", sanitize(pkgId, pkg.getPackageEvr().getRelease()));
        attr.addAttribute("epoch", sanitize(pkgId, epoch));
        attr.addAttribute("arch", sanitize(pkgId, pkg.getPackageArch().getLabel()));
        attr.addAttribute("src", sanitize(pkgId, pkg.getSourceRpm().getName()));
        handler.startElement("package", attr);

        handler.addElementWithCharacters("filename", sanitize(pkgId, pkg.getFilename()));

        attr.clear();
        attr.addAttribute("type", sanitize(pkgId, pkg.getChecksum().getChecksumType().getLabel()));
        handler.startElement("sum", attr);
        handler.addCharacters(sanitize(pkgId, pkg.getChecksum().getChecksum()));
        handler.endElement("sum");

        handler.endElement("package");
      }
    }

    handler.endElement("collection");

    handler.endElement("pkglist");
  }
  public void testDeletePackages() throws Exception {
    // Configuration
    final int numPackagesToDelete = 50;

    // Setup
    user.addRole(RoleFactory.ORG_ADMIN);

    Set<Long> doomedPackageIds = new HashSet<Long>(numPackagesToDelete);
    for (int ii = 0; ii < numPackagesToDelete; ii++) {
      Package pack = PackageTest.createTestPackage(user.getOrg());
      doomedPackageIds.add(pack.getId());
    }

    int numPackagesBeforeDelete = PackageFactory.lookupOrphanPackages(user.getOrg()).size();
    assertTrue(numPackagesBeforeDelete >= numPackagesToDelete);

    // Test
    PackageManager.deletePackages(doomedPackageIds, user);

    // Verify
    int numPackagesAfterDelete = PackageFactory.lookupOrphanPackages(user.getOrg()).size();
    assertEquals(numPackagesBeforeDelete - numPackagesToDelete, numPackagesAfterDelete);
  }
  /** {@inheritDoc} */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);
    User user = requestContext.getLoggedInUser();

    // If this is an easy one and we have the pid
    if (request.getParameter("pid") != null) {
      long pid = requestContext.getRequiredParam("pid");
      Package pkg = PackageFactory.lookupByIdAndUser(pid, user);

      // show permission error if pid is invalid like we did before
      if (pkg == null) {
        throw new PermissionException("Invalid pid");
      }

      if (pkg instanceof Patch) {
        request.setAttribute("type", "patch");
        request.setAttribute(PACKAGE_NAME, pkg.getPackageName().getName());
        request.setAttribute(
            "readme_url", DownloadManager.getPatchReadmeDownloadPath((Patch) pkg, user));
      } else if (pkg instanceof PatchSet) {
        request.setAttribute("type", "patchset");
        request.setAttribute(PACKAGE_NAME, pkg.getNameEvra());
        request.setAttribute(
            "readme_url", DownloadManager.getPatchSetReadmeDownloadPath((PatchSet) pkg, user));
      } else {
        request.setAttribute("type", "rpm");
        request.setAttribute(PACKAGE_NAME, pkg.getFilename());
        if (!pkg.getPackageKeys().isEmpty()) {
          request.setAttribute(PACKAGE_KEY, pkg.getPackageKeys().iterator().next().getKey());
        }
        boolean isDebug = pkg.getPackageName().getName().contains("debuginfo");

        request.setAttribute("isDebuginfo", isDebug);
        if (!isDebug) {
          Package debugPkg = PackageManager.findDebugInfo(user, pkg);
          String ftpUrl = PackageManager.generateFtpDebugPath(pkg);
          if (debugPkg != null) {
            request.setAttribute(
                "debugUrl", DownloadManager.getPackageDownloadPath(debugPkg, user));
          } else if (ftpUrl != null) {
            request.setAttribute("debugUrl", ftpUrl);
            request.setAttribute("debugFtp", true);
          }
        }
      }

      if (DownloadManager.isFileAvailable(pkg.getPath())) {
        request.setAttribute("url", DownloadManager.getPackageDownloadPath(pkg, user));
      }

      List<PackageSource> src = PackageFactory.lookupPackageSources(pkg);

      if (!src.isEmpty() && DownloadManager.isFileAvailable(src.get(0).getPath())) {
        request.setAttribute(
            "srpm_url", DownloadManager.getPackageSourceDownloadPath(pkg, src.get(0), user));
        request.setAttribute("srpm_path", src.get(0).getFile());
      }

      request.setAttribute("pack", pkg);
      // description can be null.
      if (pkg.getDescription() != null) {
        request.setAttribute("description", pkg.getDescription().replace("\n", "<BR>\n"));
      } else {
        request.setAttribute("description", pkg.getDescription());
      }
      request.setAttribute("packArches", PackageFactory.findPackagesWithDifferentArch(pkg));
      request.setAttribute("pid", pid);

      return mapping.findForward("default");
    } else { // we have to guess
      PackageListItem item = PackageListItem.parse(request.getParameter("id_combo"));
      Package pkg;
      long nameId = item.getIdOne();
      long evrId = item.getIdTwo();
      long archId = 0;
      if (item.getIdThree() != null) {
        archId = item.getIdThree();
      }

      Long cid = requestContext.getParamAsLong("cid");
      Long sid = requestContext.getParamAsLong("sid");
      if (cid != null) {
        pkg = PackageManager.guestimatePackageByChannel(cid, nameId, evrId, user.getOrg());

      } else if (sid != null) {
        pkg = PackageManager.guestimatePackageBySystem(sid, nameId, evrId, archId, user.getOrg());

      } else {
        throw new BadParameterException("pid, cid, or sid");
      }

      // show permission error if pid is invalid like we did before
      if (pkg == null) {
        throw new NoSuchPackageException();
      }

      Map params = new HashMap();
      params.put("pid", pkg.getId());
      return getStrutsDelegate().forwardParams(mapping.findForward("package"), params);
    }
  }