/**
     * Get the fields for the database from the edit for this id, and the id again at the end if
     * needed
     *
     * @param id The resource id
     * @param edit The edit (may be null in a new)
     * @param idAgain If true, include the id field again at the end, else don't.
     * @return The fields for the database.
     */
    protected Object[] fields(String id, AliasEdit edit, boolean idAgain) {
      Object[] rv = new Object[idAgain ? 7 : 6];
      rv[0] = caseId(id);
      if (idAgain) {
        rv[6] = rv[0];
      }

      if (edit == null) {
        String current = sessionManager().getCurrentSessionUserId();
        if (current == null) current = "";

        Time now = timeService().newTime();
        rv[1] = "";
        rv[2] = current;
        rv[3] = current;
        rv[4] = now;
        rv[5] = now;
      } else {
        rv[1] = edit.getTarget();
        ResourceProperties props = edit.getProperties();
        rv[2] = StringUtil.trimToZero(((BaseAliasEdit) edit).m_createdUserId);
        rv[3] = StringUtil.trimToZero(((BaseAliasEdit) edit).m_lastModifiedUserId);
        rv[4] = edit.getCreatedTime();
        rv[5] = edit.getModifiedTime();
      }

      return rv;
    }
    public List search(String criteria, int first, int last) {
      // if we have to be concerned with old stuff, we cannot let the db do the search
      if (m_checkOld) {
        List all = getAll();
        List rv = new Vector();

        for (Iterator i = all.iterator(); i.hasNext(); ) {
          Alias a = (Alias) i.next();
          if (StringUtil.containsIgnoreCase(a.getId(), criteria)
              || StringUtil.containsIgnoreCase(a.getTarget(), criteria)) {
            rv.add(a);
          }
        }

        Collections.sort(rv);

        // subset by position
        if (first < 1) first = 1;
        if (last >= rv.size()) last = rv.size();

        rv = rv.subList(first - 1, last);

        return rv;
      }

      Object[] fields = new Object[2];
      fields[0] = "%" + criteria.toUpperCase() + "%";
      fields[1] = fields[0];
      List all =
          super.getSelectedResources(
              "UPPER(ALIAS_ID) LIKE ? OR UPPER(TARGET) LIKE ?", fields, first, last);

      return all;
    }
    public int countSearch(String criteria) {
      // if we have to be concerned with old stuff, we cannot let the db do the search and count
      if (m_checkOld) {
        List all = getAll();
        List rv = new Vector();

        for (Iterator i = all.iterator(); i.hasNext(); ) {
          Alias a = (Alias) i.next();
          if (StringUtil.containsIgnoreCase(a.getId(), criteria)
              || StringUtil.containsIgnoreCase(a.getTarget(), criteria)) {
            rv.add(a);
          }
        }

        return rv.size();
      }

      Object[] fields = new Object[2];
      fields[0] = "%" + criteria.toUpperCase() + "%";
      fields[1] = fields[0];
      int rv =
          super.countSelectedResources("UPPER(ALIAS_ID) LIKE ? OR UPPER(TARGET) LIKE ?", fields);

      return rv;
    }
Exemple #4
0
  /* get any site ids that are in the tool property and normalize the string.
   *
   */
  protected String[] extractSiteIdsFromProperties(Properties props) {
    //	Properties props = extractPropertiesFromTool();

    String targetSiteId = StringUtil.trimToNull(props.getProperty(SEARCH_SITE_IDS));
    if (targetSiteId == null) return new String[] {""};
    String[] searchSiteIds = StringUtil.split(targetSiteId, ",");
    for (int i = 0; i < searchSiteIds.length; i++) {
      searchSiteIds[i] = StringUtil.trimToZero(searchSiteIds[i]);
    }
    return searchSiteIds;
  }
    /**
     * Count all the aliases with id or target matching criteria.
     *
     * @param criteria The search criteria.
     * @return The count of all aliases with id or target matching criteria.
     */
    public int countSearch(String criteria) {
      List all = super.getAllResources();

      Vector rv = new Vector();
      for (Iterator i = all.iterator(); i.hasNext(); ) {
        Alias a = (Alias) i.next();
        if (StringUtil.containsIgnoreCase(a.getId(), criteria)
            || StringUtil.containsIgnoreCase(a.getTarget(), criteria)) {
          rv.add(a);
        }
      }

      return rv.size();
    }
  /** Final initialization, once all dependencies are set. */
  public void init() {
    if (m_enabled) {
      // slip in our appender
      Appender a = Logger.getRootLogger().getAppender("Sakai");
      if (a != null) {
        Logger.getRootLogger().removeAppender(a);
        Logger.getRootLogger().addAppender(new SakaiAppender(a));
      }

      // set the log4j logging system with some overrides from sakai.properties
      // each in the form LEVEL.NAME where LEVEL is OFF | TRACE | DEBUG | INFO | WARN | ERROR |
      // FATAL | ALL, name is the logger name (such as org.sakaiproject)
      // example:
      // log.config.count=3
      // log.config.1 = ALL.org.sakaiproject.log.impl
      // log.config.2 = OFF.org.sakaiproject
      // log.config.3 = DEBUG.org.sakaiproject.db.impl
      String configs[] = serverConfigurationService().getStrings("log.config");
      if (configs != null) {
        for (int i = 0; i < configs.length; i++) {
          String parts[] = StringUtil.splitFirst(configs[i], ".");
          if ((parts != null) && (parts.length == 2)) {
            doSetLogLevel(parts[0], parts[1]);
          } else {
            M_log.warn("invalid log.config entry: ignoring: " + configs[i]);
          }
        }
      }
    }

    M_log.info("init(): enabled: " + m_enabled);
  }
  /** Handle a Search request. */
  public void doSearch(RunData runData, Context context) {
    // access the portlet element id to find our state
    String peid = ((JetspeedRunData) runData).getJs_peid();
    SessionState state = ((JetspeedRunData) runData).getPortletSessionState(peid);

    // read the search form field into the state object
    String search = StringUtil.trimToNull(runData.getParameters().getString(FORM_SEARCH));

    // set the flag to go to the prev page on the next list
    if (search == null) {
      state.removeAttribute(STATE_SEARCH);
    } else {
      state.setAttribute(STATE_SEARCH, search);
    }

    // start paging again from the top of the list
    resetPaging(state);

    // if we are searching, turn off auto refresh
    if (search != null) {
      ObservingCourier observer = (ObservingCourier) state.getAttribute(STATE_OBSERVER);
      if (observer != null) {
        observer.disable();
      }
    }

    // else turn it back on
    else {
      enableObserver(state);
    }
  } // doSearch
  private String processTool(Element element, List order, List required, List defaultTools) {
    String id = StringUtil.trimToNull(element.getAttribute("id"));
    if (id != null) {
      order.add(id);
    }

    String req = StringUtil.trimToNull(element.getAttribute("required"));
    if ((req != null) && (Boolean.TRUE.toString().equalsIgnoreCase(req))) {
      required.add(id);
    }

    String sel = StringUtil.trimToNull(element.getAttribute("selected"));
    if ((sel != null) && (Boolean.TRUE.toString().equalsIgnoreCase(sel))) {
      defaultTools.add(id);
    }
    return id;
  }
    /**
     * Search for aliases with id or target matching criteria, in range.
     *
     * @param criteria The search criteria.
     * @param first The first record position to return.
     * @param last The last record position to return.
     * @return The List (BaseAliasEdit) of all alias.
     */
    public List search(String criteria, int first, int last) {
      List all = super.getAllResources();

      List rv = new Vector();
      for (Iterator i = all.iterator(); i.hasNext(); ) {
        Alias a = (Alias) i.next();
        if (StringUtil.containsIgnoreCase(a.getId(), criteria)
            || StringUtil.containsIgnoreCase(a.getTarget(), criteria)) {
          rv.add(a);
        }
      }

      Collections.sort(rv);

      // subset by position
      if (first < 1) first = 1;
      if (last >= rv.size()) last = rv.size();

      rv = rv.subList(first - 1, last);

      return rv;
    }
  /**
   * Respond to navigation / access requests.
   *
   * @param req The servlet request.
   * @param res The servlet response.
   * @throws ServletException.
   * @throws IOException.
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      // this is either going to be editor.js or editor-launch.js
      String path = URLUtils.getSafePathInfo(req);
      if ((path == null) || (path.length() <= 1)) throw new Exception("no path");

      // get the requested file, ignoring the first "/"
      String[] parts = StringUtil.splitFirst(path.substring(1), "/");
      String name = parts[0];

      String placementId = req.getParameter("placement");
      ToolConfiguration tool = SiteService.findTool(placementId);

      Editor editor = portalService.getActiveEditor(tool);

      if (EDITOR_JS.equals(name)) {
        res.sendRedirect(editor.getEditorUrl());
        // res.sendRedirect("/library/editor/FCKeditor/fckeditor.js");
        // res.sendRedirect("/library/editor/ckeditor/ckeditor.js");
      } else if (EDITOR_LAUNCH_JS.equals(name)) {
        res.sendRedirect(editor.getLaunchUrl());
        // res.sendRedirect("/library/editor/launchfck.js");
        // res.sendRedirect("/library/editor/ckeditor.launch.js");
      } else if (EDITOR_BOOTSTRAP_JS.equals(name)) {
        res.addHeader("Pragma", "no-cache");
        res.addHeader("Cache-Control", "no-cache");
        res.addHeader("Content-Type", "text/javascript");

        // Note that this is the same stuff as in SkinnableCharonPortal. We should probably do a bit
        // of refactoring.
        PrintWriter out = res.getWriter();
        out.print("var sakai = sakai || {}; sakai.editor = sakai.editor || {}; \n");
        out.print(
            "sakai.editor.collectionId = '" + portalService.getBrowserCollectionId(tool) + "';\n");
        out.print(
            "sakai.editor.enableResourceSearch = '"
                + EditorConfiguration.enableResourceSearch()
                + "';\n");
        out.print(editor.getPreloadScript());
      } else {
        throw new Exception("unrecognized request");
      }

    } catch (Throwable t) {
      doError(req, res, t);
    }
  }
  /**
   * Respond to navigation / access requests.
   *
   * @param req The servlet request.
   * @param res The servlet response.
   * @throws ServletException.
   * @throws IOException.
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      // get the Sakai session
      Session session = SessionManager.getCurrentSession();

      // our path is /placement-id/tool-destination, but we want to
      // include anchors and parameters in the destination...
      String path = URLUtils.getSafePathInfo(req);
      if ((path == null) || (path.length() <= 1)) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }

      // get the placement id, ignoring the first "/"
      String[] parts = StringUtil.splitFirst(path.substring(1), "/");
      String placementId = parts[0];

      // get the toolPath if specified
      String toolPath = null;
      if (parts.length == 2) toolPath = "/" + parts[1];

      boolean success =
          doTool(
              req,
              res,
              session,
              placementId,
              req.getContextPath() + req.getServletPath() + "/" + placementId,
              toolPath);

    } catch (Exception t) {
      doError(req, res, t);
    }
  }
  /**
   * Load this single file as a registration file, loading tools and locks.
   *
   * @param in The Stream to load
   */
  private void loadToolOrder(InputStream in) {
    Document doc = Xml.readDocumentFromStream(in);
    Element root = doc.getDocumentElement();
    if (!root.getTagName().equals("toolOrder")) {
      M_log.info(
          "loadToolOrder: invalid root element (expecting \"toolOrder\"): " + root.getTagName());
      return;
    }

    // read the children nodes
    NodeList rootNodes = root.getChildNodes();
    final int rootNodesLength = rootNodes.getLength();
    for (int i = 0; i < rootNodesLength; i++) {
      Node rootNode = rootNodes.item(i);
      if (rootNode.getNodeType() != Node.ELEMENT_NODE) continue;
      Element rootElement = (Element) rootNode;

      // look for "category" elements
      if (rootElement.getTagName().equals("category")) {
        String name = StringUtil.trimToNull(rootElement.getAttribute("name"));
        if (name != null) {
          // form a list for this category
          List order = (List) m_toolOrders.get(name);
          if (order == null) {
            order = new Vector();
            m_toolOrders.put(name, order);

            List required = new Vector();
            m_toolsRequired.put(name, required);
            List defaultTools = new Vector();
            m_defaultTools.put(name, defaultTools);

            List<String> toolCategories = new Vector();
            m_toolCategoriesList.put(name, toolCategories);

            Map<String, List<String>> toolCategoryMappings = new HashMap();
            m_toolCategoriesMap.put(name, toolCategoryMappings);

            Map<String, String> toolToCategoryMap = new HashMap();
            m_toolToToolCategoriesMap.put(name, toolToCategoryMap);

            // get the kids
            NodeList nodes = rootElement.getChildNodes();
            final int nodesLength = nodes.getLength();
            for (int c = 0; c < nodesLength; c++) {
              Node node = nodes.item(c);
              if (node.getNodeType() != Node.ELEMENT_NODE) continue;
              Element element = (Element) node;

              if (element.getTagName().equals("tool")) {
                processTool(element, order, required, defaultTools);
              } else if (element.getTagName().equals("toolCategory")) {
                processCategory(
                    element,
                    order,
                    required,
                    defaultTools,
                    toolCategories,
                    toolCategoryMappings,
                    toolToCategoryMap);
              }
            }
          }
        }
      }
    }
  }
  /** {@inheritDoc} */
  public String getString(String name, String dflt) {
    String rv = StringUtil.trimToNull((String) properties.get(name));
    if (rv == null) rv = dflt;

    return rv;
  }
  /**
   * Construct from a dom element.
   *
   * @param service the UiService.
   * @param xml The dom element.
   */
  protected UiSelection(UiServiceImpl service, Element xml) {
    // component stuff
    super(service, xml);

    // short form for title - attribute "title" as the selector
    String title = StringUtil.trimToNull(xml.getAttribute("title"));
    if (title != null) {
      setTitle(title);
    }

    // short for model
    String model = StringUtil.trimToNull(xml.getAttribute("model"));
    if (model != null) {
      PropertyReference pRef = service.newPropertyReference().setReference(model);
      setProperty(pRef);
    }

    // short for correct
    String correct = StringUtil.trimToNull(xml.getAttribute("correct"));
    if (model != null) {
      PropertyReference pRef = service.newPropertyReference().setReference(correct);
      setCorrect(pRef);
    }

    // short form for destination - attribute "destination" as the destination
    String destination = StringUtil.trimToNull(xml.getAttribute("destination"));
    if (destination != null) {
      setDestination(service.newDestination().setDestination(destination));
    }

    // selected value
    String value = StringUtil.trimToNull(xml.getAttribute("value"));
    if (value != null) this.selectedValue = value;

    // select all
    String selectAll = StringUtil.trimToNull(xml.getAttribute("selectAll"));
    if ((selectAll != null) && ("FALSE".equals(selectAll))) setSelectAll(false);

    // orientation
    String orientation = StringUtil.trimToNull(xml.getAttribute("orientation"));
    if (orientation != null) {
      if (orientation.equals("HORIZONTAL")) {
        setOrientation(Orientation.horizontal);
      } else if (orientation.equals("DROPDOWN")) {
        setOrientation(Orientation.dropdown);
      }
    }

    if (xml.getAttribute("noprint") != null) {
      String noprintflag = StringUtil.trimToNull(xml.getAttribute("noprint"));
      if (noprintflag != null) {
        this.noprintflag = Boolean.parseBoolean(noprintflag);
      }
    }

    // title
    Element settingsXml = XmlHelper.getChildElementNamed(xml, "title");
    if (settingsXml != null) {
      // let Message parse this
      this.titleMessage = new UiMessage(service, settingsXml);
    }

    // model
    settingsXml = XmlHelper.getChildElementNamed(xml, "model");
    if (settingsXml != null) {
      PropertyReference pRef = service.parsePropertyReference(settingsXml);
      if (pRef != null) setProperty(pRef);
    }

    // correct
    settingsXml = XmlHelper.getChildElementNamed(xml, "correct");
    if (settingsXml != null) {
      Element innerXml = XmlHelper.getChildElementNamed(settingsXml, "model");
      if (innerXml != null) {
        PropertyReference pRef = service.parsePropertyReference(innerXml);
        if (pRef != null) setCorrect(pRef);
      }
    }

    // correct decision
    settingsXml = XmlHelper.getChildElementNamed(xml, "correctDecision");
    if (settingsXml != null) {
      setCorrectDecision(service.parseDecisions(settingsXml));
    }

    // selection choices
    settingsXml = XmlHelper.getChildElementNamed(xml, "selectionChoices");
    if (settingsXml != null) {
      NodeList contained = settingsXml.getChildNodes();
      for (int i = 0; i < contained.getLength(); i++) {
        Node node = contained.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
          Element innerXml = (Element) node;
          if ("selectionChoice".equals(innerXml.getTagName())) {
            Message displayMsg = null;
            Message valueMsg = null;
            Element wayInnerXml = XmlHelper.getChildElementNamed(innerXml, "displayMessage");
            if (wayInnerXml != null) {
              displayMsg = new UiMessage(service, wayInnerXml);
            }
            wayInnerXml = XmlHelper.getChildElementNamed(innerXml, "valueMessage");
            if (wayInnerXml != null) {
              valueMsg = new UiMessage(service, wayInnerXml);
            }
            this.selectionMessages.add(displayMsg);
            this.selectionValues.add(valueMsg);

            // is there a container?
            Container container = null;
            boolean separate = false;
            boolean reversed = false;
            boolean indented = false;
            Element containerXml = XmlHelper.getChildElementNamed(innerXml, "container");
            if (containerXml != null) {
              String separateCode = StringUtil.trimToNull(containerXml.getAttribute("separate"));
              separate = "TRUE".equals(separateCode);

              String reversedCode = StringUtil.trimToNull(containerXml.getAttribute("reversed"));
              reversed = "TRUE".equals(reversedCode);

              String indentedCode = StringUtil.trimToNull(containerXml.getAttribute("indented"));
              indented = "TRUE".equals(indentedCode);

              container = new UiContainer(service, innerXml);
            }
            this.selectionContainers.add(new ContainerRef(container, separate, reversed, indented));
          }
        }
      }
    }

    // selection choices from model
    settingsXml = XmlHelper.getChildElementNamed(xml, "selectionModel");
    if (settingsXml != null) {
      String name = StringUtil.trimToNull(settingsXml.getAttribute("name"));
      if (name != null) this.iteratorName = name;

      // short for model
      model = StringUtil.trimToNull(settingsXml.getAttribute("model"));
      if (model != null) {
        this.selectionReference = service.newPropertyReference().setReference(model);
      }

      Element innerXml = XmlHelper.getChildElementNamed(settingsXml, "model");
      if (innerXml != null) {
        this.selectionReference = service.parsePropertyReference(innerXml);
      }

      // value message
      innerXml = XmlHelper.getChildElementNamed(settingsXml, "valueMessage");
      if (innerXml != null) {
        this.selectionValueMessage = new UiMessage(service, innerXml);
      }

      // display model
      innerXml = XmlHelper.getChildElementNamed(settingsXml, "displayMessage");
      if (innerXml != null) {
        this.selectionDisplayMessage = new UiMessage(service, innerXml);
      }
    }

    // read only shortcut
    String readOnly = StringUtil.trimToNull(xml.getAttribute("readOnly"));
    if ((readOnly != null) && ("TRUE".equals(readOnly))) {
      this.readOnly =
          new UiDecision().setProperty(new UiConstantPropertyReference().setValue("true"));
    }

    // read only collapsed shortcut
    String readOnlyCollapsed = StringUtil.trimToNull(xml.getAttribute("readOnlyCollapsed"));
    if ((readOnlyCollapsed != null) && ("TRUE".equals(readOnlyCollapsed))) {
      this.readOnlyCollapsed =
          new UiDecision().setProperty(new UiConstantPropertyReference().setValue("true"));
    }

    // read only
    settingsXml = XmlHelper.getChildElementNamed(xml, "readOnly");
    if (settingsXml != null) {
      this.readOnly = service.parseDecisions(settingsXml);
    }

    // read only collapsed
    settingsXml = XmlHelper.getChildElementNamed(xml, "readOnlyCollapsed");
    if (settingsXml != null) {
      this.readOnlyCollapsed = service.parseDecisions(settingsXml);
    }

    // single select
    settingsXml = XmlHelper.getChildElementNamed(xml, "singleSelect");
    if (settingsXml != null) {
      this.singleSelectDecision = service.parseDecisions(settingsXml);
    }

    // short for height
    String height = StringUtil.trimToNull(xml.getAttribute("height"));
    if (height != null) {
      this.setHeight(Integer.parseInt(height));
    }

    // submit value
    String submitValue = StringUtil.trimToNull(xml.getAttribute("submitValue"));
    if ((submitValue != null) && ("TRUE".equals(submitValue))) {
      this.submitValue = true;
    }

    // submitDestination
    settingsXml = XmlHelper.getChildElementNamed(xml, "destination");
    if (settingsXml != null) {
      // let Destination parse this
      this.submitDestination = new UiDestination(service, settingsXml);
    }

    // onEmptyAlert
    settingsXml = XmlHelper.getChildElementNamed(xml, "onEmptyAlert");
    if (settingsXml != null) {
      Element innerXml = XmlHelper.getChildElementNamed(settingsXml, "message");
      if (innerXml != null) {
        this.onEmptyAlertMsg = new UiMessage(service, innerXml);
      }

      this.onEmptyAlertDecision = service.parseDecisions(settingsXml);
    }
  }