public List<DashboardFilterProperty> getVisibleProperties() {
   List<DashboardFilterProperty> results = new ArrayList<DashboardFilterProperty>();
   Iterator it = properties.iterator();
   while (it.hasNext()) {
     DashboardFilterProperty dashboardFilterProperty = (DashboardFilterProperty) it.next();
     if (dashboardFilterProperty.isVisible()) results.add(dashboardFilterProperty);
   }
   return results;
 }
 public DashboardFilterProperty getDashboardFilterProperty(String propertyId) {
   Iterator it = properties.iterator();
   while (it.hasNext()) {
     DashboardFilterProperty dashboardFilterProperty = (DashboardFilterProperty) it.next();
     if (propertyId.equals(dashboardFilterProperty.getPropertyId()))
       return dashboardFilterProperty;
   }
   return null;
 }
  public DashboardFilterProperty[] getBeingFilteredProperties() {
    List results = new ArrayList();
    Iterator it = properties.iterator();
    while (it.hasNext()) {
      DashboardFilterProperty dashboardFilterProperty = (DashboardFilterProperty) it.next();
      if (dashboardFilterProperty.isBeingFiltered()) results.add(dashboardFilterProperty);
    }

    return (DashboardFilterProperty[]) results.toArray(new DashboardFilterProperty[results.size()]);
  }
 public DashboardFilterProperty getDashboardFilterPropertyForCurrentFilter(
     String dataProviderCode, String propertyId) {
   Iterator it = properties.iterator();
   while (it.hasNext()) {
     DashboardFilterProperty dashboardFilterProperty = (DashboardFilterProperty) it.next();
     if (dataProviderCode.equals(dashboardFilterProperty.getDataProviderCode())
         && propertyId.equals(dashboardFilterProperty.getPropertyId()))
       return dashboardFilterProperty;
   }
   return null;
 }
 // Calls dashboard filter to get static  properties but keep properties instance configuration. Is
 // propety is found on this instance properties List thsi instance is returned.
 public DashboardFilterProperty[] getStaticPropertiesForCurrentFilter() {
   DashboardFilterProperty[] staticProperties = getFilter().getStaticProperties();
   if (staticProperties == null) return null;
   DashboardFilterProperty[] results = new DashboardFilterProperty[staticProperties.length];
   for (int i = 0; i < staticProperties.length; i++) {
     DashboardFilterProperty staticProperty = staticProperties[i];
     DashboardFilterProperty property =
         getDashboardFilterPropertyForCurrentFilter(
             staticProperty.getDataProviderCode(), staticProperty.getPropertyId());
     if (property != null) results[i] = property;
     else results[i] = staticProperty;
   }
   return results;
 }
  public void beforeRenderComponent() {
    super.beforeRenderComponent();

    // Initialize the dashboard (loads all its kpi panels)
    DashboardHandler.lookup().getCurrentDashboard();

    // Get the filter.
    DashboardFilter filter = getFilter();

    // Check all visible properties exist.
    Iterator props = properties.iterator();
    while (props.hasNext()) {
      DashboardFilterProperty dashboardFilterProperty = (DashboardFilterProperty) props.next();
      if (!dashboardFilterProperty.isPropertyAlive()) props.remove();
    }

    // Check if filtered properties for this filter component are already in dashboard filter.
    DashboardFilterProperty[] beingFilteredProps = getBeingFilteredProperties();
    for (int i = 0; i < beingFilteredProps.length; i++) {
      List dfProperties = Arrays.asList(filter.getPropertyIds());
      DashboardFilterProperty beignFilteredProp = beingFilteredProps[i];
      if (!dfProperties.contains(beignFilteredProp.getPropertyId()))
        beignFilteredProp.setBeignFiltered(false);
    }

    // Check filtered properties and hide from available filter properties (set property not
    // visible)
    String[] propIds = filter.getPropertyIds();
    for (int i = 0; i < propIds.length; i++) {
      String propId = propIds[i];
      DashboardFilterProperty prop = getDashboardFilterProperty(propId);
      if (prop == null) {
        DashboardFilterProperty parentProperty = filter.getPropertyInParentDashboards(propId);
        if (parentProperty != null) {
          prop =
              new DashboardFilterProperty(
                  parentProperty.getDataProviderCode(), propId, getFilter(), null, true);
          properties.add(prop);
        }
      } else {
        prop.setBeignFiltered(true);
      }
    }
  }
  public String serializeComponentData() throws Exception {
    // Serialize visible properties and options.
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    int indent = 0;
    printIndent(out, indent);
    out.println("<dashboard_filter>");
    Iterator it = properties.iterator();
    while (it.hasNext()) {
      DashboardFilterProperty dashboardFilterProperty = (DashboardFilterProperty) it.next();
      printIndent(out, indent + 1);
      out.println(
          "<property id=\""
              + StringEscapeUtils.escapeXml(dashboardFilterProperty.getPropertyId())
              + "\" providerCode =\""
              + StringEscapeUtils.escapeXml(dashboardFilterProperty.getDataProviderCode())
              + "\">");
      printIndent(out, indent + 2);
      out.println("<visible>" + dashboardFilterProperty.isVisible() + "</visible>");
      if (dashboardFilterProperty.getSectionId() != null) {
        printIndent(out, indent + 2);
        out.println("<section>" + dashboardFilterProperty.getSectionId() + "</section>");
      }
      printIndent(out, indent + 1);
      out.println("</property>");
    }

    // Serialize options.
    printIndent(out, indent + 1);
    out.println("<options>");
    printIndent(out, indent + 2);
    out.println("<shortViewMode>" + isShortMode + "</shortViewMode>");
    printIndent(out, indent + 2);
    out.println("<showLegend>" + showLegend + "</showLegend>");
    printIndent(out, indent + 2);
    out.println("<showRefreshButton>" + showRefreshButton + "</showRefreshButton>");
    printIndent(out, indent + 2);
    out.println("<showApplyhButton>" + showApplyButton + "</showApplyhButton>");
    printIndent(out, indent + 2);
    out.println("<showClearButton>" + showClearButton + "</showClearButton>");
    printIndent(out, indent + 2);
    out.println("<showPropertyNames>" + showPropertyNames + "</showPropertyNames>");
    printIndent(out, indent + 2);
    out.println("<showSubmitOnChange>" + showSubmitOnChange + "</showSubmitOnChange>");
    printIndent(out, indent + 1);
    out.println("<showAutoRefresh>" + showAutoRefresh + "</showAutoRefresh>");
    printIndent(out, indent + 1);
    out.println("</options>");
    printIndent(out, indent);

    out.println("</dashboard_filter>");
    serializedProperties = sw.toString();
    return sw.toString();
  }
  // Return if is needed to serialize and save properties after this call because properties that
  // does not exist on current filter or data providers must be deleted from persistence.
  // return: must clear serialized trash properties after deserialize process saving this data.
  public boolean deserializeComponentData(String serializedData) throws Exception {
    // Load options and visible properties
    if (serializedData == null || serializedData.trim().length() == 0) {
      log.info("No data to deserialize.");
      return false;
    }

    DOMParser parser = new DOMParser();
    parser.parse(new InputSource(new StringReader(serializedData)));
    Document doc = parser.getDocument();
    NodeList nodes = doc.getElementsByTagName("dashboard_filter");
    if (nodes.getLength() > 1) {
      log.error("Each dashboard filter component just can parse one <dashboard_filter>");
      return false;
    }
    if (nodes.getLength() == 0) {
      log.info("No data to deserialize.");
      return false;
    }

    boolean needsToSerializeAfter = false;
    serializedProperties = serializedData;
    Node rootNode = nodes.item(0);
    nodes = rootNode.getChildNodes();
    for (int x = 0; x < nodes.getLength(); x++) {
      Node node = nodes.item(x);
      if (node.getNodeName().equals("property")) {
        // Parse visible properties.
        String dataProviderCode = node.getAttributes().getNamedItem("providerCode").getNodeValue();
        String propertyId = node.getAttributes().getNamedItem("id").getNodeValue();
        String sectionId = null;
        boolean visible = false;
        NodeList subnodes = node.getChildNodes();
        for (int i = 0; i < subnodes.getLength(); i++) {
          Node subnode = subnodes.item(i);
          if (subnode.getNodeName().equals("section")) {
            sectionId = subnode.getFirstChild().getNodeValue();
          }
          if (subnode.getNodeName().equals("visible")) {
            visible = Boolean.valueOf(subnode.getFirstChild().getNodeValue()).booleanValue();
          }
        }
        Long lSectionId = sectionId != null ? Long.decode(sectionId) : null;
        DashboardFilterProperty filterProp =
            new DashboardFilterProperty(
                dataProviderCode, propertyId, getFilter(), lSectionId, true);
        filterProp.setVisible(visible);
        if (filterProp.isPropertyAlive()) properties.add(filterProp);
        else needsToSerializeAfter = true;
      } else if (node.getNodeName().equals("options")) {
        // Parse component options.
        NodeList options = node.getChildNodes();
        String showRefreshButton = null;
        String showPropertyNames = null;
        String showClearButton = null;
        String showApplyButton = null;
        String showSubmitOnChange = null;
        String showShortViewMode = null;
        String showLegend = null;
        String showAutoRefresh = null;
        for (int i = 0; i < options.getLength(); i++) {
          Node option = options.item(i);
          if (option.getNodeName().equals("showRefreshButton"))
            showRefreshButton = option.getFirstChild().getNodeValue();
          if (option.getNodeName().equals("showPropertyNames"))
            showPropertyNames = option.getFirstChild().getNodeValue();
          if (option.getNodeName().equals("showClearButton"))
            showClearButton = option.getFirstChild().getNodeValue();
          if (option.getNodeName().equals("showApplyhButton"))
            showApplyButton = option.getFirstChild().getNodeValue();
          if (option.getNodeName().equals("showSubmitOnChange"))
            showSubmitOnChange = option.getFirstChild().getNodeValue();
          if (option.getNodeName().equals("shortViewMode"))
            showShortViewMode = option.getFirstChild().getNodeValue();
          if (option.getNodeName().equals("showLegend"))
            showLegend = option.getFirstChild().getNodeValue();
          if (option.getNodeName().equals("showAutoRefresh"))
            showAutoRefresh = option.getFirstChild().getNodeValue();
        }
        this.showPropertyNames = Boolean.valueOf(showPropertyNames).booleanValue();
        this.showRefreshButton = Boolean.valueOf(showRefreshButton).booleanValue();
        this.showApplyButton = Boolean.valueOf(showApplyButton).booleanValue();
        this.showClearButton = Boolean.valueOf(showClearButton).booleanValue();
        this.showSubmitOnChange = Boolean.valueOf(showSubmitOnChange).booleanValue();
        this.isShortMode = Boolean.valueOf(showShortViewMode).booleanValue();
        this.showLegend = Boolean.valueOf(showLegend).booleanValue();
        this.showAutoRefresh = Boolean.valueOf(showAutoRefresh).booleanValue();

        // Enable auto-refresh if necessary on start.
        if (this.showAutoRefresh) setRefreshEnabled(true);
      }
    }
    return needsToSerializeAfter;
  }
  public CommandResponse actionFilter(CommandRequest request) {
    try {
      // Init attributes for start applying the filter.
      filterPropertyErrors.clear();

      // Parse parameters and set the filter.
      Iterator visiblePropertiesIt = properties.iterator();
      while (visiblePropertiesIt.hasNext()) {
        DashboardFilterProperty dashboardFilterProperty =
            (DashboardFilterProperty) visiblePropertiesIt.next();

        // Is property already in the dashboard filter?. Then is not possible to filter by this
        // property, it's already added to dashboard filter.
        if (dashboardFilterProperty.isBeingFiltered()) continue;
        if (!dashboardFilterProperty.isPropertyAlive()) {
          log.warn(
              "Trying to filter by "
                  + dashboardFilterProperty.getPropertyId()
                  + ". This property is not in any dataset.");
          continue;
        }
        if (!dashboardFilterProperty.isVisible()) continue;

        Object[] result;
        try {
          result =
              requestProcessor.parseDashboardProperty(
                  request.getRequestObject(), dashboardFilterProperty);
        } catch (Exception e) {
          log.error("Error parsing property " + dashboardFilterProperty.getPropertyId() + ".", e);
          continue;
        }

        if (result.length != 3) {
          log.error(
              "Error parsing property: '"
                  + dashboardFilterProperty.getPropertyId()
                  + "' for dataProvider: '"
                  + dashboardFilterProperty.getDataProviderCode()
                  + "'");
          continue;
        }

        Collection allowedValues = (Collection) result[0];
        Object minValue = result[1];
        Object maxValue = result[2];
        if (allowedValues == null && minValue == null && maxValue == null) continue;

        // Set the filter with this property.
        Dashboard currentDashboard = DashboardHandler.lookup().getCurrentDashboard();
        if (currentDashboard.filter(
            dashboardFilterProperty.getPropertyId(),
            minValue,
            true,
            maxValue,
            true,
            allowedValues,
            FilterByCriteria.ALLOW_ANY)) {
          return new ShowCurrentScreenResponse();
        }
      }
    } catch (Exception e) {
      log.error("Error trying to filter properties for dashboard", e);
    }
    return null;
  }
  public void actionStore(CommandRequest request) {
    Map parameters = request.getRequestObject().getParameterMap();

    // Initialize parameters and properties to default.
    showPropertyNames = false;
    showRefreshButton = false;
    showApplyButton = false;
    showClearButton = false;
    showSubmitOnChange = false;
    isShortMode = false;
    showLegend = false;
    showAutoRefresh = false;
    properties.clear();
    notAllowedProperties.clear();

    // Component options.
    if (parameters.containsKey(PARAM_SHOW_REFRESH_BUTTON)) showRefreshButton = true;
    if (parameters.containsKey(PARAM_SHOW_PROPERTY_NAMES)) showPropertyNames = true;
    if (parameters.containsKey(PARAM_SHOW_CLEAR_BUTTON)) showClearButton = true;
    if (parameters.containsKey(PARAM_SHOW_APPLY_BUTTON)) showApplyButton = true;
    if (parameters.containsKey(PARAM_SHOW_SUBMIT_ON_CHANGE)) showSubmitOnChange = true;
    if (parameters.containsKey(PARAM_SHORT_MODE)) isShortMode = true;
    if (parameters.containsKey(PARAM_SHOW_LEGEND)) showLegend = true;
    if (parameters.containsKey(PARAM_SHOW_AUTO_REFRESH)) showAutoRefresh = true;

    // Component properties.
    DashboardFilterProperty[] allProperties = getAllPropertiesForCurrentFilter();
    for (int i = 0; i < allProperties.length; i++) {
      DashboardFilterProperty property = allProperties[i];
      String dataProviderCode = property.getDataProviderCode();
      String propertyId = property.getPropertyId();

      String visibleParamKey =
          new StringBuffer()
              .append(PARAM_VISIBLE)
              .append("/")
              .append(dataProviderCode)
              .append("/")
              .append(propertyId)
              .toString();
      String drillDownParamKey =
          new StringBuffer()
              .append(PARAM_SECTION)
              .append("/")
              .append(dataProviderCode)
              .append("/")
              .append(propertyId)
              .toString();
      boolean isVisible = parameters.containsKey(visibleParamKey);
      Long sectionId = null;
      if (parameters.containsKey(drillDownParamKey)) {
        String sectionIdStr = ((String[]) parameters.get(drillDownParamKey))[0];
        if (!PARAM_DRILLDOWN_DISABLED.equals(sectionIdStr)) sectionId = Long.decode(sectionIdStr);
      }

      if (!isVisible && sectionId == null) continue;

      // Property must be added?
      DashboardFilterProperty prop =
          getDashboardFilterPropertyForCurrentFilter(dataProviderCode, propertyId);
      if (prop == null)
        prop = new DashboardFilterProperty(dataProviderCode, propertyId, getFilter(), null, false);

      // Check if another property with same identifier.
      if (getDashboardFilterProperty(propertyId) != null) {
        // Another property with same id is already set to the filter.
        // Filter cannot use two properties with same property id., so show warning.
        notAllowedProperties.add(prop);
        continue;
      }

      // Add property to this component.
      properties.add(prop);

      // Set property parameters
      prop.setBeignFiltered(false);
      prop.setVisible(isVisible);
      prop.setSectionId(sectionId);
    }
  }