/** {@inheritDoc} */
  public List getCollections(ContentCollection collection) {
    ContentHostingHandler chh = collection.getContentHandler();
    if (chh != null) {
      return chh.getCollections(collection);
    } else {
      List allCollections = storage.getCollections(collection); // the real collections

      // Find any virtual *resources* which are really *collections*
      List l = storage.getResources(collection);
      for (java.util.Iterator i = l.iterator(); i.hasNext(); ) {
        ContentResource o = (ContentResource) i.next();
        ContentResource cr = getResource(o.getId());
        if (cr != null) {
          ResourceProperties p = cr.getProperties();
          if (p != null
              && p.getProperty(CHH_BEAN_NAME) != null
              && p.getProperty(CHH_BEAN_NAME).length() > 0) {
            allCollections.add(
                getVirtualChild(
                    cr.getId() + Entity.SEPARATOR, cr, true)); // this one is a virtual collection!
          }
        }
      }
      return allCollections;
    }
  }
Example #2
0
  /**
   * @param n
   * @throws RepositoryException
   */
  private void addFile(ContentResource n) {
    ResourceProperties rp = n.getProperties();
    Calendar lastModified = new GregorianCalendar();
    try {
      Time lastModifiedTime = rp.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
      lastModified.setTimeInMillis(lastModifiedTime.getTime());
    } catch (EntityPropertyNotDefinedException e) {
      // default to now
    } catch (EntityPropertyTypeException e) {
      // default to now
    }
    long contentLength = n.getContentLength();
    String mimeType = n.getContentType();
    put("lastModified", lastModified.getTime());
    put("mimeType", mimeType);
    put("length", String.valueOf(contentLength));

    put("available", n.isAvailable());
    put("hidden", n.isHidden());
    if (!n.isHidden()) {
      Time releaseDate = n.getReleaseDate();
      if (releaseDate != null) {
        put("releaseDate", releaseDate.getTime());
      }
      Time retractDate = n.getRetractDate();
      if (retractDate != null) {
        put("retractDate", retractDate.getTime());
      }
    }
  }
 /**
  * Return current user locale.
  *
  * @return user's Locale object
  */
 private Locale getCurrentUserLocale() {
   Locale loc = null;
   try {
     // check if locale is requested for specific user
     String userId = M_sm.getCurrentSessionUserId();
     if (userId != null) {
       Preferences prefs = M_ps.getPreferences(userId);
       ResourceProperties locProps = prefs.getProperties(ResourceLoader.APPLICATION_ID);
       String localeString = locProps.getProperty(ResourceLoader.LOCALE_KEY);
       // Parse user locale preference if set
       if (localeString != null) {
         String[] locValues = localeString.split("_");
         if (locValues.length > 1)
           // language, country
           loc = new Locale(locValues[0], locValues[1]);
         else if (locValues.length == 1)
           // language
           loc = new Locale(locValues[0]);
       }
       if (loc == null) loc = Locale.getDefault();
     } else {
       loc =
           (Locale)
               M_sm.getCurrentSession()
                   .getAttribute(ResourceLoader.LOCALE_KEY + M_sm.getCurrentSessionUserId());
     }
   } catch (NullPointerException e) {
     loc = Locale.getDefault();
   }
   return loc;
 }
  /* (non-Javadoc)
   * @see uk.ac.ox.oucs.oxam.logic.PaperFileService#deposit(uk.ac.ox.oucs.oxam.logic.PaperFile, uk.ac.ox.oucs.oxam.logic.Callback)
   */
  public void deposit(PaperFile paperFile, InputStream in) {
    PaperFileImpl impl = castToImpl(paperFile);
    String path = impl.getPath();
    ContentResourceEdit resource = null;
    try {

      try {
        contentHostingService.checkResource(path);
        resource = contentHostingService.editResource(path);
        // Ignore PermissionException, IdUnusedException, TypeException
        // As they are too serious to continue.
      } catch (IdUnusedException iue) {
        // Will attempt to create containing folders.

        resource = contentHostingService.addResource(path);
        // Like the basename function.
        String filename = StringUtils.substringAfterLast(path, "/");
        ResourceProperties props = resource.getPropertiesEdit();
        props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, filename);
        resource.setContentType(mimeTypes.getContentType(filename));
      }
      resource.setContent(in);
      contentHostingService.commitResource(resource, NotificationService.NOTI_NONE);
      LOG.debug("Sucessfully copied file to: " + path);
    } catch (OverQuotaException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ServerOverloadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (PermissionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InUseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TypeException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IdUsedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IdInvalidException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InconsistentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      // Close the stream here as this is where it's created.
      if (resource.isActiveEdit()) {
        contentHostingService.cancelResource(resource);
      }
    }
  }
  public boolean siteCanUseReviewService(Site site) {

    ResourceProperties properties = site.getProperties();

    String prop = (String) properties.get(siteProperty);
    if (prop != null) {
      return Boolean.valueOf(prop).booleanValue();
    }

    return false;
  }
Example #6
0
 /**
  * @param n
  * @return
  * @throws RepositoryException
  */
 private Map<String, Object> getProperties(ContentEntity n) {
   Map<String, Object> m = new HashMap<String, Object>();
   ResourceProperties rp = n.getProperties();
   for (Iterator<?> pi = rp.getPropertyNames(); pi.hasNext(); ) {
     String name = (String) pi.next();
     List<?> l = rp.getPropertyList(name);
     if (l.size() > 1) {
       String[] o = l.toArray(new String[0]);
       m.put(name, o);
     } else if (l.size() == 1) {
       m.put(name, l.get(0));
     }
   }
   return m;
 }
Example #7
0
  @WebMethod
  @Path("/undeleteAssignments")
  @Produces("text/plain")
  @GET
  public String undeleteAssignments(
      @WebParam(name = "sessionId", partName = "sessionId") @QueryParam("sessionId")
          String sessionId,
      @WebParam(name = "context", partName = "context") @QueryParam("context") String context) {
    try {
      // establish the session
      Session s = establishSession(sessionId);

      Iterator assingments = assignmentService.getAssignmentsForContext(context);
      while (assingments.hasNext()) {
        Assignment ass = (Assignment) assingments.next();
        ResourceProperties rp = ass.getProperties();

        try {
          String deleted = rp.getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);

          LOG.info("Assignment " + ass.getTitle() + " deleted status: " + deleted);
          if (deleted != null) {
            AssignmentEdit ae = assignmentService.editAssignment(ass.getId());
            ResourcePropertiesEdit rpe = ae.getPropertiesEdit();
            LOG.info("undeleting" + ass.getTitle() + " for site " + context);
            rpe.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);

            assignmentService.commitEdit(ae);
          }
        } catch (IdUnusedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (PermissionException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (InUseException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    } catch (Exception e) {
      LOG.error("WS undeleteAssignments(): " + e.getClass().getName() + " : " + e.getMessage());
      return e.getClass().getName() + " : " + e.getMessage();
    }

    return "success";
  }
Example #8
0
  @Override
  public String getDefaultPrivacyState(String userId) {
    String privacy = null;

    if (userId != null) {
      Preferences prefs = preferencesService.getPreferences(userId);
      ResourceProperties props = prefs.getProperties(PRIVACY_PREFS);
      privacy = props.getProperty(PrivacyManager.DEFAULT_PRIVACY_KEY);
    }

    if (privacy == null) {
      // default privacy is visible
      privacy = PrivacyManagerImpl.VISIBLE;
    }

    return privacy;
  }
 /** {@inheritDoc} */
 public List getResources(ContentCollection collection) {
   ContentHostingHandler chh = collection.getContentHandler();
   if (chh != null) {
     return chh.getResources(collection);
   } else {
     List l = storage.getResources(collection);
     for (java.util.Iterator i = l.iterator(); i.hasNext(); ) {
       ContentResource o = (ContentResource) i.next();
       ContentResource cr = getResource(o.getId());
       if (cr != null) {
         ResourceProperties p = cr.getProperties();
         if (p != null
             && p.getProperty(CHH_BEAN_NAME) != null
             && p.getProperty(CHH_BEAN_NAME).length() > 0)
           i.remove(); // this one is a virtual collection!
       }
     }
     return l;
   }
 }
  protected static User getUserProperty(ResourceProperties props, String name) {
    String id = props.getProperty(name);
    if (id != null) {
      try {
        return UserDirectoryService.getUser(id);
      } catch (UserNotDefinedException e) {
      }
    }

    return null;
  }
  /**
   * Gets the path of sites back to the root of the tree.
   *
   * @param s
   * @param ourParent
   * @return
   */
  private List<Site> getPwd(Site s, String ourParent) {
    if (ourParent == null) return null;

    // System.out.println("Getting Current Working Directory for
    // "+s.getId()+" "+s.getTitle());

    int depth = 0;
    Vector<Site> pwd = new Vector<Site>();
    Set<String> added = new HashSet<String>();

    // Add us to the list at the top (will become the end)
    pwd.add(s);
    added.add(s.getId());

    // Make sure we don't go on forever
    while (ourParent != null && depth < 8) {
      depth++;
      Site site = null;
      try {
        site = SiteService.getSiteVisit(ourParent);
      } catch (Exception e) {
        break;
      }
      // We have no patience with loops
      if (added.contains(site.getId())) break;

      // System.out.println("Adding Parent "+site.getId()+"
      // "+site.getTitle());
      pwd.insertElementAt(site, 0); // Push down stack
      added.add(site.getId());

      ResourceProperties rp = site.getProperties();
      ourParent = rp.getProperty(PROP_PARENT_ID);
    }

    // PWD is only defined for > 1 site
    if (pwd.size() < 2) return null;
    return pwd;
  }
  /**
   * Convert the ContentEntity into its virtual shadow via its ContentHostingHandler bean. If no
   * bean is defined for the ContentEntity, no resolution is performed. If the ContentEntity is
   * null, no resolution is performed.
   *
   * @param ce
   * @return a resolved ContentEntity where appropriate, otherwise the orginal
   */
  public ContentEntity getVirtualEntity(ContentEntity ce, String finalId) {
    if (ce == null) {
      return null;
    }
    ResourceProperties p = ce.getProperties();
    String chhbeanname = p.getProperty(CHH_BEAN_NAME);

    if (chhbeanname != null && chhbeanname.length() > 0) {
      try {
        ContentHostingHandler chh = (ContentHostingHandler) ComponentManager.get(chhbeanname);
        return chh.getVirtualContentEntity(ce, finalId);

      } catch (Exception e) {
        // log and return null
        log.warn(
            "Failed to find CHH Bean "
                + chhbeanname
                + " or bean failed to resolve virtual entity ID",
            e);
        return ce;
      }
    }
    return ce;
  }
Example #13
0
 /**
  * Get the current user preference value. First attempt Preferences, then defaults from
  * sakai.properties.
  *
  * @param name The property name.
  * @return The preference value or null if not set.
  */
 private static String getPreferenceString(String name) {
   Preferences prefs = M_ps.getPreferences(M_sm.getCurrentSessionUserId());
   ResourceProperties rp = prefs.getProperties(PREFS_KEY);
   String value = rp.getProperty(name);
   return value;
 }
  /** 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>");
    }
  }
Example #15
0
 /**
  * Get the current user preference list value. First attempt Preferences, then defaults from
  * sakai.properties.
  *
  * @param name The property name.
  * @return The preference list value or null if not set.
  */
 private static List getPreferenceList(String name) {
   Preferences prefs = M_ps.getPreferences(M_sm.getCurrentSessionUserId());
   ResourceProperties rp = prefs.getProperties(PREFS_KEY);
   List l = rp.getPropertyList(name);
   return l;
 }
  /**
   * Explode a site into a map suitable for use in the map
   *
   * @see
   *     org.sakaiproject.portal.api.PortalSiteHelper#convertSiteToMap(javax.servlet.http.HttpServletRequest,
   *     org.sakaiproject.site.api.Site, java.lang.String, java.lang.String, java.lang.String,
   *     boolean, boolean, boolean, boolean, java.lang.String, boolean)
   */
  public Map convertSiteToMap(
      HttpServletRequest req,
      Site s,
      String prefix,
      String currentSiteId,
      String myWorkspaceSiteId,
      boolean includeSummary,
      boolean expandSite,
      boolean resetTools,
      boolean doPages,
      String toolContextPath,
      boolean loggedIn) {
    if (s == null) return null;
    Map<String, Object> m = new HashMap<String, Object>();

    // In case the effective is different than the actual site
    String effectiveSite = getSiteEffectiveId(s);

    boolean isCurrentSite =
        currentSiteId != null
            && (s.getId().equals(currentSiteId) || effectiveSite.equals(currentSiteId));
    m.put("isCurrentSite", Boolean.valueOf(isCurrentSite));
    m.put(
        "isMyWorkspace",
        Boolean.valueOf(
            myWorkspaceSiteId != null
                && (s.getId().equals(myWorkspaceSiteId)
                    || effectiveSite.equals(myWorkspaceSiteId))));
    int siteTitleMaxLength = ServerConfigurationService.getInt("site.title.maxlength", 25);
    String titleStr = s.getTitle();
    String fullTitle = titleStr;
    if (titleStr != null) {
      titleStr = titleStr.trim();
      if (titleStr.length() > siteTitleMaxLength && siteTitleMaxLength >= 10) {
        titleStr = titleStr.substring(0, siteTitleMaxLength - 4) + " ...";
      } else if (titleStr.length() > siteTitleMaxLength) {
        titleStr = titleStr.substring(0, siteTitleMaxLength);
      }
      titleStr = titleStr.trim();
    }
    m.put("siteTitle", Web.escapeHtml(titleStr));
    m.put("fullTitle", Web.escapeHtml(fullTitle));
    m.put("siteDescription", Web.escapeHtml(s.getDescription()));
    m.put("shortDescription", Web.escapeHtml(s.getShortDescription()));
    String siteUrl = Web.serverUrl(req) + ServerConfigurationService.getString("portalPath") + "/";
    if (prefix != null) siteUrl = siteUrl + prefix + "/";
    // siteUrl = siteUrl + Web.escapeUrl(siteHelper.getSiteEffectiveId(s));
    m.put("siteUrl", siteUrl + Web.escapeUrl(getSiteEffectiveId(s)));
    m.put("siteType", s.getType());
    m.put("siteId", s.getId());

    // TODO: This should come from the site neighbourhood.
    ResourceProperties rp = s.getProperties();
    String ourParent = rp.getProperty(PROP_PARENT_ID);
    // We are not really a child unless the parent exists
    // And we have a valid pwd
    boolean isChild = false;

    // Get the current site hierarchy
    if (ourParent != null && isCurrentSite) {
      List<Site> pwd = getPwd(s, ourParent);
      if (pwd != null) {
        List<Map> l = new ArrayList<Map>();
        for (int i = 0; i < pwd.size(); i++) {
          Site site = pwd.get(i);
          // System.out.println("PWD["+i+"]="+site.getId()+"
          // "+site.getTitle());
          Map<String, Object> pm = new HashMap<String, Object>();
          pm.put("siteTitle", Web.escapeHtml(site.getTitle()));
          pm.put("siteUrl", siteUrl + Web.escapeUrl(getSiteEffectiveId(site)));
          l.add(pm);
          isChild = true;
        }
        if (l.size() > 0) m.put("pwd", l);
      }
    }

    // If we are a child and have a non-zero length, pwd
    // show breadcrumbs
    if (isChild) {
      m.put("isChild", Boolean.valueOf(isChild));
      m.put("parentSite", ourParent);
    }

    if (includeSummary) {
      summarizeTool(m, s, "sakai.announce");
    }
    if (expandSite) {
      Map pageMap =
          pageListToMap(
              req,
              loggedIn,
              s, /* SitePage */
              null,
              toolContextPath,
              prefix,
              doPages,
              resetTools,
              includeSummary);
      m.put("sitePages", pageMap);
    }

    return m;
  }
  /**
   * This method takes a list of sites and organizes it into a list of maps of properties. There is
   * an additional complication that the depth contains informaiton arround.
   *
   * @see
   *     org.sakaiproject.portal.api.PortalSiteHelper#convertSitesToMaps(javax.servlet.http.HttpServletRequest,
   *     java.util.List, java.lang.String, java.lang.String, java.lang.String, boolean, boolean,
   *     boolean, boolean, java.lang.String, boolean)
   */
  public List<Map> convertSitesToMaps(
      HttpServletRequest req,
      List mySites,
      String prefix,
      String currentSiteId,
      String myWorkspaceSiteId,
      boolean includeSummary,
      boolean expandSite,
      boolean resetTools,
      boolean doPages,
      String toolContextPath,
      boolean loggedIn) {
    List<Map> l = new ArrayList<Map>();
    Map<String, Integer> depthChart = new HashMap<String, Integer>();
    boolean motdDone = false;

    // We only compute the depths if there is no user chosen order
    boolean computeDepth = true;
    Session session = SessionManager.getCurrentSession();
    if (session != null) {
      Preferences prefs = PreferencesService.getPreferences(session.getUserId());
      ResourceProperties props = prefs.getProperties("sakai:portal:sitenav");

      List propList = props.getPropertyList("order");
      if (propList != null) {
        computeDepth = false;
      }
    }

    // Determine the depths of the child sites if needed
    for (Iterator i = mySites.iterator(); i.hasNext(); ) {
      Site s = (Site) i.next();

      // The first site is the current site
      if (currentSiteId == null) currentSiteId = s.getId();

      Integer cDepth = Integer.valueOf(0);
      if (computeDepth) {
        ResourceProperties rp = s.getProperties();
        String ourParent = rp.getProperty(PROP_PARENT_ID);
        // System.out.println("Depth Site:"+s.getTitle()+
        // "parent="+ourParent);
        if (ourParent != null) {
          Integer pDepth = depthChart.get(ourParent);
          if (pDepth != null) {
            cDepth = pDepth + 1;
          }
        }
        depthChart.put(s.getId(), cDepth);
        // System.out.println("Depth = "+cDepth);
      }

      Map m =
          convertSiteToMap(
              req,
              s,
              prefix,
              currentSiteId,
              myWorkspaceSiteId,
              includeSummary,
              expandSite,
              resetTools,
              doPages,
              toolContextPath,
              loggedIn);

      // Add the Depth of the site
      m.put("depth", cDepth);

      if (includeSummary && m.get("rssDescription") == null) {
        if (!motdDone) {
          summarizeTool(m, s, "sakai.motd");
          motdDone = true;
        } else {
          summarizeTool(m, s, "sakai.announcements");
        }
      }
      l.add(m);
    }
    return l;
  }
  /* (non-Javadoc)
   * @see org.sakaiproject.portal.charon.DefaultSiteViewImpl#processMySites(java.util.Map)
   */
  @Override
  protected void processMySites() {
    boolean useDHTMLMore =
        Boolean.valueOf(serverConfigurationService.getBoolean("portal.use.dhtml.more", false));
    if (useDHTMLMore) {
      List<Site> allSites = new ArrayList<Site>();
      allSites.addAll(mySites);
      allSites.addAll(moreSites);
      // get Sections
      Map<String, List> termsToSites = new HashMap<String, List>();
      Map<String, List> tabsMoreTerms = new HashMap<String, List>();
      for (int i = 0; i < allSites.size(); i++) {
        Site site = allSites.get(i);
        ResourceProperties siteProperties = site.getProperties();

        String type = site.getType();
        String term = null;

        if ("course".equals(type)) {
          term = siteProperties.getProperty("term");
          if (null == term) {
            term = rb.getString("moresite_unknown_term");
          }

        } else if ("project".equals(type)) {
          term = rb.getString("moresite_projects");
        } else if ("portfolio".equals(type)) {
          term = rb.getString("moresite_portfolios");
        } else if ("admin".equals(type)) {
          term = rb.getString("moresite_administration");
        } else {
          term = rb.getString("moresite_other");
        }

        List<Site> currentList = new ArrayList();
        if (termsToSites.containsKey(term)) {
          currentList = termsToSites.get(term);
          termsToSites.remove(term);
        }
        currentList.add(site);
        termsToSites.put(term, currentList);
      }

      class TitleSorter implements Comparator<Map> {

        public int compare(Map first, Map second) {

          if (first == null || second == null) return 0;

          String firstTitle = (String) first.get("siteTitle");
          String secondTitle = (String) second.get("siteTitle");

          if (firstTitle != null) return firstTitle.compareToIgnoreCase(secondTitle);

          return 0;
        }
      }

      Comparator<Map> titleSorter = new TitleSorter();

      // now loop through each section and convert the Lists to maps
      for (Map.Entry<String, List> entry : termsToSites.entrySet()) {
        List<Site> currentList = entry.getValue();
        List<Map> temp =
            siteHelper.convertSitesToMaps(
                request,
                currentList,
                prefix,
                currentSiteId,
                myWorkspaceSiteId,
                /* includeSummary */ false, /* expandSite */
                false,
                /* resetTools */ "true"
                    .equals(serverConfigurationService.getString(Portal.CONFIG_AUTO_RESET)),
                /* doPages */ true, /* toolContextPath */
                null,
                loggedIn);

        Collections.sort(temp, titleSorter);

        tabsMoreTerms.put(entry.getKey(), temp);
      }

      String[] termOrder = serverConfigurationService.getStrings("portal.term.order");
      List<String> tabsMoreSortedTermList = new ArrayList<String>();

      // Order term column headers according to order specified in
      // portal.term.order
      // Filter out terms for which user is not a member of any sites

      if (termOrder != null) {
        for (int i = 0; i < termOrder.length; i++) {

          if (tabsMoreTerms.containsKey(termOrder[i])) {

            tabsMoreSortedTermList.add(termOrder[i]);
          }
        }
      }

      Iterator i = tabsMoreTerms.keySet().iterator();
      while (i.hasNext()) {
        String term = (String) i.next();
        if (!tabsMoreSortedTermList.contains(term)) {
          tabsMoreSortedTermList.add(term);
        }
      }
      renderContextMap.put("tabsMoreTerms", tabsMoreTerms);
      renderContextMap.put("tabsMoreSortedTermList", tabsMoreSortedTermList);
    }
  }
Example #19
0
  /** From org.sakaiproject.entity.api.Entity */
  public ResourceProperties getProperties() {
    ResourceProperties rp = new BaseResourceProperties();

    rp.addProperty("id", getId());
    return rp;
  }
Example #20
0
  /*
   * (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();
  }