private String getTitle(final ContentResource content) {
   String title = content.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
   if (title == null) {
     title = content.getId();
   }
   return Validator.escapeHtml(title);
 }
  /**
   * Apparently, the ContentResource object gives a url, but it doesn't escape any special
   * characters. So, need to do some escaping just for the name portion of the url. So, find the
   * string "attachment" and escape anything after it.
   */
  private String resourceUrlEscaping(String url) {
    int attIndex = url.indexOf("attachment");
    String leftOfAttachment = url.substring(0, attIndex);
    String rightOfAttachment = url.substring(attIndex);

    String finalUrl = leftOfAttachment.concat(Validator.escapeUrl(rightOfAttachment));
    return finalUrl;
  }
 @Override
 public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res, Session session)
     throws PortalHandlerException {
   if ((parts.length > 2) && (parts[1].equals(SiteResetHandler.URL_FRAGMENT))) {
     try {
       String siteUrl = req.getContextPath() + "/site" + Web.makePath(parts, 2, parts.length);
       // Make sure to add the parameters such as panel=Main
       String queryString = Validator.generateQueryString(req);
       if (queryString != null) {
         siteUrl = siteUrl + "?" + queryString;
       }
       portalService.setResetState("true");
       res.sendRedirect(siteUrl);
       return RESET_DONE;
     } catch (Exception ex) {
       throw new PortalHandlerException(ex);
     }
   } else {
     return NEXT;
   }
 }
  /** Format the collection as an HTML display. */
  @SuppressWarnings({"unchecked"})
  public static void format(
      ContentCollection x,
      Reference ref,
      HttpServletRequest req,
      HttpServletResponse res,
      ResourceLoader rb,
      String accessPointTrue,
      String accessPointFalse) {
    // do not allow directory listings for /attachments and its subfolders
    if (ContentHostingService.isAttachmentResource(x.getId())) {
      try {
        res.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      } catch (java.io.IOException e) {
        return;
      }
    }

    PrintWriter out = null;

    // don't set the writer until we verify that
    // getallresources is going to work.
    boolean printedHeader = false;
    boolean printedDiv = false;

    try {
      res.setContentType("text/html; charset=UTF-8");

      out = res.getWriter();

      ResourceProperties pl = x.getProperties();
      String webappRoot = ServerConfigurationService.getServerUrl();
      String skinRepo = ServerConfigurationService.getString("skin.repo", "/library/skin");
      String skinName = "default";
      String[] parts = StringUtils.split(x.getId(), Entity.SEPARATOR);

      // Is this a site folder (Resources or Dropbox)? If so, get the site skin

      if (x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_SITE)
          || x.getId()
              .startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_DROPBOX)) {
        if (parts.length > 1) {
          String siteId = parts[1];
          try {
            Site site = SiteService.getSite(siteId);
            if (site.getSkin() != null) {
              skinName = site.getSkin();
            }
          } catch (IdUnusedException e) {
            // Cannot get site - ignore it
          }
        }
      }

      // Output the headers

      out.println(
          "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
      out.println("<html><head>");
      out.println(
          "<title>"
              + rb.getFormattedMessage(
                  "colformat.pagetitle",
                  new Object[] {
                    Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
                  })
              + "</title>");
      out.println(
          "<link href=\""
              + webappRoot
              + skinRepo
              + "/"
              + skinName
              + "/access.css\" type=\"text/css\" rel=\"stylesheet\" media=\"screen\">");
      out.println(
          "<script src=\"" + webappRoot + "/library/js/jquery.js\" type=\"text/javascript\">");
      out.println("</script>");
      out.println("</head><body class=\"specialLink\">");

      out.println("<script type=\"text/javascript\" src=\"/library/js/access.js\"></script>");
      out.println("<div class=\"directoryIndex\">");

      // for content listing it's best to use a real title
      out.println(
          "<h3>"
              + Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
              + "</h3>");
      out.println(
          "<p id=\"toggle\"><a id=\"toggler\" href=\"#\">"
              + rb.getString("colformat.showhide")
              + "</a></p>");
      String folderdesc = pl.getProperty(ResourceProperties.PROP_DESCRIPTION);
      if (folderdesc != null && !folderdesc.equals(""))
        out.println("<div class=\"textPanel\">" + folderdesc + "</div>");

      out.println("<ul>");
      out.println("<li style=\"display:none\">");
      out.println("</li>");

      printedHeader = true;
      printedDiv = true;

      if (parts.length > 2) {
        // go up a level
        out.println(
            "<li class=\"upfolder\"><a href=\"../\"><img src=\"/library/image/sakai/folder-up.gif\" alt=\""
                + rb.getString("colformat.uplevel.alttext")
                + "\"/>"
                + rb.getString("colformat.uplevel")
                + "</a></li>");
      }

      // Sort the collection items

      List<ContentEntity> members = x.getMemberResources();

      boolean hasCustomSort = false;
      try {
        hasCustomSort =
            x.getProperties().getBooleanProperty(ResourceProperties.PROP_HAS_CUSTOM_SORT);
      } catch (Exception e) {
        // use false that's already there
      }

      if (hasCustomSort)
        Collections.sort(
            members, new ContentHostingComparator(ResourceProperties.PROP_CONTENT_PRIORITY, true));
      else
        Collections.sort(
            members, new ContentHostingComparator(ResourceProperties.PROP_DISPLAY_NAME, true));

      // Iterate through content items

      URI baseUri = new URI(x.getUrl());

      for (ContentEntity content : members) {

        ResourceProperties properties = content.getProperties();
        boolean isCollection = content.isCollection();
        String xs = content.getId();
        String contentUrl = content.getUrl();

        // These both perform the same check in the implementation but we should observe the API.
        // This also checks to see if a resource is hidden or time limited.
        if (isCollection) {
          if (!ContentHostingService.allowGetCollection(xs)) {
            continue;
          }
        } else {
          if (!ContentHostingService.allowGetResource(xs)) {
            continue;
          }
        }

        if (isCollection) {
          xs = xs.substring(0, xs.length() - 1);
          xs = xs.substring(xs.lastIndexOf('/') + 1) + '/';
        } else {
          xs = xs.substring(xs.lastIndexOf('/') + 1);
        }

        try {
          // Relativize the URL (canonical item URL relative to canonical collection URL).
          // Inter alias this will preserve alternate access paths via aliases, e.g. /web/

          URI contentUri = new URI(contentUrl);
          URI relativeUri = baseUri.relativize(contentUri);
          contentUrl = relativeUri.toString();

          if (isCollection) {
            // Folder

            String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
            if ((desc == null) || desc.equals("")) desc = "";
            else desc = "<div class=\"textPanel\">" + desc + "</div>";
            out.println(
                "<li class=\"folder\"><a href=\""
                    + contentUrl
                    + "\">"
                    + Validator.escapeHtml(
                        properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
                    + "</a>"
                    + desc
                    + "</li>");
          } else {
            // File

            /*
            String createdBy = getUserProperty(properties, ResourceProperties.PROP_CREATOR).getDisplayName();
            Time modTime = properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
            String modifiedTime = modTime.toStringLocalShortDate() + " " + modTime.toStringLocalShort();

            ContentResource contentResource = (ContentResource) content;

            long filesize = ((contentResource.getContentLength() - 1) / 1024) + 1;
            String filetype = contentResource.getContentType();
             */

            String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
            if ((desc == null) || desc.equals("")) desc = "";
            else desc = "<div class=\"textPanel\">" + Validator.escapeHtml(desc) + "</div>";
            String resourceType = content.getResourceType().replace('.', '_');
            out.println(
                "<li class=\"file\"><a href=\""
                    + contentUrl
                    + "\" target=_blank class=\""
                    + resourceType
                    + "\">"
                    + Validator.escapeHtml(
                        properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
                    + "</a>"
                    + desc
                    + "</li>");
          }
        } catch (Exception ignore) {
          // TODO - what types of failures are being caught here?

          out.println(
              "<li class=\"file\"><a href=\""
                  + contentUrl
                  + "\" target=_blank>"
                  + Validator.escapeHtml(xs)
                  + "</a></li>");
        }
      }

    } catch (Exception e) {
      M_log.warn("Problem formatting HTML for collection: " + x.getId(), e);
    }

    if (out != null && printedHeader) {
      out.println("</ul>");

      if (printedDiv) out.println("</div>");
      out.println("</body></html>");
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.sakaiproject.service.legacy.entity.ResourceService#merge(java.lang.String,
   *      org.w3c.dom.Element, java.lang.String, java.lang.String, java.util.Map, java.util.HashMap,
   *      java.util.Set)
   */
  public String merge(
      String siteId,
      Element root,
      String archivePath,
      String fromSiteId,
      Map attachmentNames,
      Map userIdTrans,
      Set userListAllowImport) {
    // buffer for the results log
    StringBuilder results = new StringBuilder();
    // populate SyllabusItem
    int syDataCount = 0;
    SyllabusItem syItem = null;
    if (siteId != null && siteId.trim().length() > 0) {
      try {
        NodeList allChildrenNodes = root.getChildNodes();
        int length = allChildrenNodes.getLength();
        for (int i = 0; i < length; i++) {
          Node siteNode = allChildrenNodes.item(i);
          if (siteNode.getNodeType() == Node.ELEMENT_NODE) {
            Element siteElement = (Element) siteNode;
            if (siteElement.getTagName().equals(SITE_ARCHIVE)) {
              // sakai2              NodeList pageNodes = siteElement.getChildNodes();
              //              int lengthPageNodes = pageNodes.getLength();
              //              for (int p = 0; p < lengthPageNodes; p++)
              //              {
              //                Node pageNode = pageNodes.item(p);
              //                if (pageNode.getNodeType() == Node.ELEMENT_NODE)
              //                {
              //                  Element pageElement = (Element) pageNode;
              //                  if (pageElement.getTagName().equals(PAGE_ARCHIVE))
              //                  {
              //                    NodeList syllabusNodes = pageElement.getChildNodes();
              NodeList syllabusNodes = siteElement.getChildNodes();
              int lengthSyllabusNodes = syllabusNodes.getLength();
              for (int sn = 0; sn < lengthSyllabusNodes; sn++) {
                Node syNode = syllabusNodes.item(sn);
                if (syNode.getNodeType() == Node.ELEMENT_NODE) {
                  Element syElement = (Element) syNode;
                  if (syElement.getTagName().equals(SYLLABUS)) {
                    // create a page and all syllabus tool to the page
                    // sakai2                          String page =
                    // addSyllabusToolToPage(siteId,pageElement
                    //                              .getAttribute(PAGE_NAME));
                    //                          SyllabusItem syllabusItem = syllabusManager
                    //                          .createSyllabusItem(UserDirectoryService
                    //                              .getCurrentUser().getId(), page, syElement
                    //                              .getAttribute(SYLLABUS_REDIRECT_URL));
                    String page =
                        addSyllabusToolToPage(siteId, siteElement.getAttribute(SITE_NAME));
                    // sakai2                          SyllabusItem syllabusItem = syllabusManager
                    //                          .createSyllabusItem(UserDirectoryService
                    //                              .getCurrentUser().getId(), page, syElement
                    //                              .getAttribute(SYLLABUS_REDIRECT_URL));
                    // sakai2 add--
                    SyllabusItem syllabusItem = syllabusManager.getSyllabusItemByContextId(page);
                    if (syllabusItem == null) {
                      syllabusItem =
                          syllabusManager.createSyllabusItem(
                              UserDirectoryService.getCurrentUser().getId(),
                              page,
                              syElement.getAttribute(SYLLABUS_REDIRECT_URL));
                    }
                    // added htripath: get imported redirecturl, even if syllabus item is existing.
                    else {
                      if (syElement.getAttribute(SYLLABUS_REDIRECT_URL) != null) {
                        syllabusItem.setRedirectURL(syElement.getAttribute(SYLLABUS_REDIRECT_URL));
                        syllabusManager.saveSyllabusItem(syllabusItem);
                      }
                    }
                    //
                    NodeList allSyllabiNodes = syElement.getChildNodes();
                    int lengthSyllabi = allSyllabiNodes.getLength();
                    for (int j = 0; j < lengthSyllabi; j++) {
                      Node child2 = allSyllabiNodes.item(j);
                      if (child2.getNodeType() == Node.ELEMENT_NODE) {

                        Element syDataElement = (Element) child2;
                        if (syDataElement.getTagName().equals(SYLLABUS_DATA)) {
                          List attachStringList = new ArrayList();

                          syDataCount = syDataCount + 1;
                          SyllabusData syData = new SyllabusDataImpl();
                          syData.setView(syDataElement.getAttribute(SYLLABUS_DATA_VIEW));
                          syData.setTitle(syDataElement.getAttribute(SYLLABUS_DATA_TITLE));
                          syData.setStatus(syDataElement.getAttribute(SYLLABUS_DATA_STATUS));
                          syData.setEmailNotification(
                              syDataElement.getAttribute(SYLLABUS_DATA_EMAIL_NOTIFICATION));

                          NodeList allAssetNodes = syDataElement.getChildNodes();
                          int lengthSyData = allAssetNodes.getLength();
                          for (int k = 0; k < lengthSyData; k++) {
                            Node child3 = allAssetNodes.item(k);
                            if (child3.getNodeType() == Node.ELEMENT_NODE) {
                              Element assetEle = (Element) child3;
                              if (assetEle.getTagName().equals(SYLLABUS_DATA_ASSET)) {
                                String charset = trimToNull(assetEle.getAttribute("charset"));
                                if (charset == null) charset = "UTF-8";

                                String body =
                                    trimToNull(assetEle.getAttribute("syllabus_body-html"));
                                if (body != null) {
                                  try {
                                    byte[] decoded = Base64.decodeBase64(body.getBytes("UTF-8"));
                                    body = new String(decoded, charset);
                                  } catch (Exception e) {
                                    logger.warn("Decode Syllabus: " + e);
                                  }
                                }

                                if (body == null) body = "";

                                String ret;
                                ret = trimToNull(body);

                                syData.setAsset(ret);
                                /*decode
                                NodeList assetStringNodes = assetEle
                                    .getChildNodes();
                                int lengthAssetNodes = assetStringNodes
                                    .getLength();
                                for (int l = 0; l < lengthAssetNodes; l++)
                                {
                                  Node child4 = assetStringNodes.item(l);
                                  if (child4.getNodeType() == Node.TEXT_NODE)
                                  {
                                    Text textNode = (Text) child4;
                                    syData.setAsset(textNode.getData());
                                  }
                                }*/
                              }
                              if (assetEle.getTagName().equals(SYLLABUS_ATTACHMENT)) {
                                Element attachElement = (Element) child3;
                                String oldUrl = attachElement.getAttribute("relative-url");
                                if (oldUrl.startsWith("/content/attachment/")) {
                                  String newUrl = (String) attachmentNames.get(oldUrl);
                                  if (newUrl != null) {
                                    //// if (newUrl.startsWith("/attachment/"))
                                    //// newUrl = "/content".concat(newUrl);

                                    attachElement.setAttribute(
                                        "relative-url", Validator.escapeQuestionMark(newUrl));

                                    attachStringList.add(Validator.escapeQuestionMark(newUrl));
                                  }
                                } else if (oldUrl.startsWith(
                                    "/content/group/" + fromSiteId + "/")) {
                                  String newUrl =
                                      "/content/group/"
                                          + siteId
                                          + oldUrl.substring(15 + fromSiteId.length());
                                  attachElement.setAttribute(
                                      "relative-url", Validator.escapeQuestionMark(newUrl));

                                  attachStringList.add(Validator.escapeQuestionMark(newUrl));
                                }
                              }
                            }
                          }

                          int initPosition =
                              syllabusManager.findLargestSyllabusPosition(syllabusItem).intValue()
                                  + 1;
                          syData =
                              syllabusManager.createSyllabusDataObject(
                                  syData.getTitle(),
                                  (new Integer(initPosition)),
                                  syData.getAsset(),
                                  syData.getView(),
                                  syData.getStatus(),
                                  syData.getEmailNotification());
                          Set attachSet = new TreeSet();
                          for (int m = 0; m < attachStringList.size(); m++) {
                            ContentResource cr =
                                contentHostingService.getResource((String) attachStringList.get(m));
                            ResourceProperties rp = cr.getProperties();
                            //                            			SyllabusAttachment tempAttach =
                            // syllabusManager.createSyllabusAttachmentObject(
                            //
                            //	(String)attachStringList.get(m),rp.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
                            SyllabusAttachment tempAttach =
                                syllabusManager.createSyllabusAttachmentObject(
                                    cr.getId(),
                                    rp.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
                            tempAttach.setName(
                                rp.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
                            tempAttach.setSize(
                                rp.getProperty(ResourceProperties.PROP_CONTENT_LENGTH));
                            tempAttach.setType(
                                rp.getProperty(ResourceProperties.PROP_CONTENT_TYPE));
                            tempAttach.setUrl(cr.getUrl());
                            tempAttach.setAttachmentId(cr.getId());

                            attachSet.add(tempAttach);
                          }
                          syData.setAttachments(attachSet);

                          syllabusManager.addSyllabusToSyllabusItem(syllabusItem, syData);
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
        results.append("merging syllabus " + siteId + " (" + syDataCount + ") syllabus items.\n");

      } catch (DOMException e) {
        logger.error(e.getMessage(), e);
        results.append("merging " + getLabel() + " failed during xml parsing.\n");

      } catch (Exception e) {
        logger.error(e.getMessage(), e);
        results.append("merging " + getLabel() + " failed.\n");
      }
    }

    return results.toString();
  }