private String getUrl(final String url) {
    StringBuffer content = new StringBuffer();
    try {
      // check to see if this URL failed before thia session
      if ((getSession() != null)
          && (getSession().getAttribute("pentaho-HtmlComponent-failed-url-" + url)
              != null)) { //$NON-NLS-1$
        return errorMessage;
      }
      if (BaseUIComponent.debug) {
        debug(Messages.getInstance().getString("Html.DEBUG_GETTING_CONTENT", url)); // $NON-NLS-1$
      }
      if (HttpUtil.getURLContent(url, content)) {
        return content.toString();
      } else {
        getSession()
            .setAttribute(
                "pentaho-HtmlComponent-failed-url-" + url, ""); // $NON-NLS-1$ //$NON-NLS-2$
        return errorMessage;
      }
    } catch (Exception e) {

      if (errorMessage != null) {
        return errorMessage;
      } else {
        error(
            Messages.getInstance()
                .getErrorString("Html.ERROR_0001_COULD_NOT_GET_CONTENT", url)); // $NON-NLS-1$
        return Messages.getInstance()
            .getErrorString("Html.ERROR_0001_COULD_NOT_GET_CONTENT", url); // $NON-NLS-1$
      }
    }
  }
 public boolean init() {
   if (filterPanel == null) {
     // load the XML document that defines the dial
     Document filterDocument = null;
     try {
       org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
       reader.setEntityResolver(new SolutionURIResolver());
       filterDocument =
           reader.read(
               ActionSequenceResource.getInputStream(definitionPath, LocaleHelper.getLocale()));
     } catch (Throwable t) {
       FilterPanelComponent.logger.error(
           Messages.getInstance().getString("FilterPanelComponent.ERROR_0002_CREATE_XML"),
           t); //$NON-NLS-1$
       return false;
     }
     try {
       filterPanel = getFilterPanel(filterDocument);
     } catch (FilterPanelException e) {
       // TODO sbarkdull localize
       FilterPanelComponent.logger.error(
           Messages.getInstance().getString("FilterPanelComponent.ERROR_0003_CREATE"),
           e); //$NON-NLS-1$
       return false;
     }
   }
   return true;
 }
  private void setDataByRow(final IPentahoResultSet data) {
    // TODO Make this routine MDX friendly
    if (data == null) {
      noDataMessage =
          Messages.getInstance().getString("CHART.USER_NO_DATA_AVAILABLE"); // $NON-NLS-1$
      return; // No data so we've got nothing to set
      // TODO come up with some sort of error strategy here.
    }
    Class timePeriodClass =
        TimeSeriesCollectionChartDefinition.getTimePeriodClass(getDomainPeriodType());
    Object[] rowData = data.next();
    while (rowData != null) {
      String seriesName = (String) rowData[0];
      TimeSeries wrkSeries = new TimeSeries(seriesName, timePeriodClass);
      for (int column = 1; column < rowData.length - 1; column = column + 2) {
        Date keyDate = getValidDate(rowData[column]);
        TimeSeriesDataItem timeSeriesDataItem =
            new TimeSeriesDataItem(
                RegularTimePeriod.createInstance(
                    timePeriodClass, keyDate, RegularTimePeriod.DEFAULT_TIME_ZONE),
                ((Number) rowData[column + 1]).doubleValue());
        wrkSeries.add(timeSeriesDataItem);
      }
      addSeries(wrkSeries);
      rowData = data.next();
    }

    if ((data.getRowCount() > 0) && (this.getSeriesCount() <= 0)) {
      noDataMessage =
          Messages.getInstance().getString("CHART.USER_INCORRECT_DATA_FORMAT"); // $NON-NLS-1$
    }
  }
 private String getFile(final String solutionPath) {
   IActionSequenceResource resource =
       new ActionSequenceResource(
           "",
           IActionSequenceResource.SOLUTION_FILE_RESOURCE,
           "text/html",
           solutionPath); //$NON-NLS-1$ //$NON-NLS-2$
   try {
     byte[] bytes =
         IOUtils.toByteArray(
             resource.getInputStream(
                 ISolutionRepository.ACTION_EXECUTE, LocaleHelper.getLocale()));
     return new String(bytes, LocaleHelper.getSystemEncoding());
   } catch (Exception e) {
     if (errorMessage != null) {
       return errorMessage;
     } else {
       error(
           Messages.getInstance()
               .getErrorString(
                   "Html.ERROR_0001_COULD_NOT_GET_CONTENT", solutionPath)); // $NON-NLS-1$
       return Messages.getInstance()
           .getErrorString("Html.ERROR_0001_COULD_NOT_GET_CONTENT", solutionPath); // $NON-NLS-1$
     }
   }
 }
  private Document listModels() {

    // Create a document that describes the result
    Document doc = DocumentHelper.createDocument();

    Element root = doc.addElement("metadata"); // $NON-NLS-1$

    Element modelsNode = root.addElement("models"); // $NON-NLS-1$
    if (domainName == null) {
      try {
        for (String domain : getMetadataRepository().getDomainIds()) {
          addThinDomainModels(domain, modelsNode, root);
        }
      } catch (Throwable t) {
        error(
            Messages.getInstance()
                .getString("PMDUIComponent.ERROR_0001_GET_MODEL_LIST")); // $NON-NLS-1$
        t.printStackTrace();
        root.addElement("message")
            .setText(
                Messages.getInstance()
                    .getString(
                        "PMDUIComponent.USER_NO_DOMAIN_SPECIFIED")); //$NON-NLS-1$ //$NON-NLS-2$
      }

    } else {
      addThinDomainModels(domainName, modelsNode, root);
    }
    return doc;
  }
  private Date getValidDate(Object raw) {

    if (raw instanceof String) {
      try {
        try {
          return formatter1.parse((String) raw);
        } catch (ParseException e) {
          // try w/o hours
        }
        return formatter2.parse((String) raw);
      } catch (ParseException e) {
        getLogger()
            .error(
                Messages.getInstance()
                    .getString(
                        "TimeSeriesCollectionChartDefinition.ERROR_0001_INVALID_DATE", //$NON-NLS-1$
                        (String) raw),
                e);
        return null;
      }
    } else {
      // This was the original code; if we have an unknown object
      // it will throw an exception, but would anyway.
      // It's a small atempt to make MDX queries work here
      return (Date) raw;
    }
  }
  /** @return String that represents the file path to a temporary file */
  protected String[] createTempFile() {
    // create temporary file names
    String solutionDir = "system/tmp/"; // $NON-NLS-1$
    String fileNamePrefix = "tmp_chart_"; // $NON-NLS-1$
    String extension = ".png"; // $NON-NLS-1$
    String fileName = null;
    String filePathWithoutExtension = null;
    try {
      File file =
          PentahoSystem.getApplicationContext()
              .createTempFile(getSession(), fileNamePrefix, extension, true);
      fileName = file.getName();
      filePathWithoutExtension = solutionDir + fileName.substring(0, fileName.indexOf('.'));
    } catch (IOException e) {
      getLogger()
          .error(
              Messages.getInstance()
                  .getErrorString("AbstractChartComponent.ERROR_0001_CANT_CREATE_TEMP_CHART"),
              e); //$NON-NLS-1$
    }
    String[] value = new String[2];
    value[AbstractChartComponent.FILENAME_INDEX] = fileName;
    value[AbstractChartComponent.FILENAME_WITHOUT_EXTENSION_INDEX] = filePathWithoutExtension;

    return value;
  }
 private void setDataByColumn(final IPentahoResultSet data) {
   // TODO Make this routine MDX friendly
   if (data == null) {
     noDataMessage =
         Messages.getInstance().getString("CHART.USER_NO_DATA_AVAILABLE"); // $NON-NLS-1$
     return; // No data so we've got nothing to set
     // TODO come up with some sort of error strategy here.
   }
   boolean firstPass = true;
   String lastSeries = ""; // $NON-NLS-1$
   String seriesName = ""; // $NON-NLS-1$
   Class timePeriodClass =
       TimeSeriesCollectionChartDefinition.getTimePeriodClass(getDomainPeriodType());
   Object[] rowData = data.next();
   TimeSeries wrkSeries = null;
   while (rowData != null) {
     seriesName = (String) rowData[0];
     if (firstPass || !seriesName.equalsIgnoreCase(lastSeries)) {
       if (!firstPass) {
         addSeries(wrkSeries);
       }
       wrkSeries = new TimeSeries(seriesName, timePeriodClass);
       lastSeries = seriesName;
       firstPass = false;
     }
     Date keyDate = getValidDate(rowData[1]);
     RegularTimePeriod regularTimePeriod =
         RegularTimePeriod.createInstance(
             timePeriodClass, keyDate, RegularTimePeriod.DEFAULT_TIME_ZONE);
     TimeSeriesDataItem timeSeriesDataItem =
         new TimeSeriesDataItem(regularTimePeriod, ((Number) rowData[2]).doubleValue());
     if (wrkSeries != null) {
       wrkSeries.add(timeSeriesDataItem);
     }
     rowData = data.next();
   }
   if (!firstPass) {
     addSeries(wrkSeries);
   }
   if ((data.getRowCount() > 0) && (this.getSeriesCount() <= 0)) {
     noDataMessage =
         Messages.getInstance().getString("CHART.USER_INCORRECT_DATA_FORMAT"); // $NON-NLS-1$
   }
 }
 public void setDateMinimum(final Node dateMinimumNode) {
   if (dateMinimumNode != null) {
     try {
       setDateMinimum(DateFormat.getDateInstance().parse(dateMinimumNode.getText()));
     } catch (ParseException e) {
       getLogger()
           .error(
               Messages.getInstance()
                   .getString(
                       "TimeSeriesCollectionChartDefinition.ERROR_0001_INVALID_DATE", //$NON-NLS-1$
                       dateMinimumNode.getText()),
               e);
     }
   }
 }
  protected void applyOuterURLTemplateParam() {
    if (outerParamNames == null) {
      return;
    }
    for (String outerParamName : outerParamNames) {
      Object value = null;
      if ((context != null) && context.getInputNames().contains(outerParamName)) {
        value = context.getInputParameterValue(outerParamName);
      }
      if (value == null) {
        return;
      }
      try {
        if (value.getClass().isArray()) {
          if (Array.getLength(value) > 0) {
            String[] encodedVals = new String[Array.getLength(value)];
            for (int i = 0; i < Array.getLength(value); ++i) // ESCA-JAVA0049:
            {
              encodedVals[i] =
                  URLEncoder.encode(
                      Array.get(value, i).toString(), LocaleHelper.getSystemEncoding());
            }
            // TODO Sleeze Alert!!! This is a temporary hack for making the
            // URLs generated support multiple selections.  A JIRA case PLATFORM-393
            // has been generated to address this issue.
            //
            // For now, applyTemplate looks for an "&" or "?" preceding and following the param,
            // uses all
            // the characters between them as the template and repeats it once for each param value
            // separating them with '&'
            urlTemplate = TemplateUtil.applyTemplate(urlTemplate, outerParamName, encodedVals);
          }
        } else {
          String encodedVal = URLEncoder.encode(value.toString(), LocaleHelper.getSystemEncoding());
          urlTemplate = TemplateUtil.applyTemplate(urlTemplate, outerParamName, encodedVal);
        }

        // encodedVal = URLEncoder.encode(stringVal, LocaleHelper.getSystemEncoding());
        // //$NON-NLS-1$
      } catch (UnsupportedEncodingException e) {
        getLogger()
            .error(
                Messages.getInstance()
                    .getErrorString("AbstractChartComponent.ERROR_0002_URL_ENCODE_FAILED"),
                e); //$NON-NLS-1$
      }
    }
  }
  @Override
  public Document getXmlContent() {

    if (action == PMDUIComponent.ACTION_LIST_MODELS) {
      return listModels();
    } else if (action == PMDUIComponent.ACTION_LOAD_MODEL) {
      return loadModel();
    } else if (action == PMDUIComponent.ACTION_LOOKUP) {
      return getLookup();
    } else {
      throw new RuntimeException(
          Messages.getInstance()
              .getErrorString(
                  "PMDUIComponent.ERROR_0002_ILLEGAL_ACTION",
                  String.valueOf(action))); // $NON-NLS-1$
    }
  }
 public boolean setDataAction(final String widgetGridDataDefinition) {
   try {
     Document dataActionDocument = null;
     try {
       org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
       reader.setEntityResolver(new SolutionURIResolver());
       dataActionDocument =
           reader.read(
               ActionSequenceResource.getInputStream(
                   widgetGridDataDefinition, LocaleHelper.getLocale()));
     } catch (Throwable t) {
       return false;
     }
     Node dataNode = dataActionDocument.selectSingleNode("widgetgrid/data"); // $NON-NLS-1$
     solution = XmlDom4JHelper.getNodeText("data-solution", dataNode); // $NON-NLS-1$
     actionPath = XmlDom4JHelper.getNodeText("data-path", dataNode); // $NON-NLS-1$
     actionName = XmlDom4JHelper.getNodeText("data-action", dataNode); // $NON-NLS-1$
     actionOutput = XmlDom4JHelper.getNodeText("data-output", dataNode); // $NON-NLS-1$
     valueItem = XmlDom4JHelper.getNodeText("data-value", dataNode); // $NON-NLS-1$
     nameItem = XmlDom4JHelper.getNodeText("data-name", dataNode); // $NON-NLS-1$
     widgetWidth =
         (int)
             XmlDom4JHelper.getNodeText(
                 "widgetgrid/width", dataActionDocument, 125); // $NON-NLS-1$
     widgetHeight =
         (int)
             XmlDom4JHelper.getNodeText(
                 "widgetgrid/height", dataActionDocument, 125); // $NON-NLS-1$
     columns =
         (int)
             XmlDom4JHelper.getNodeText(
                 "widgetgrid/columns", dataActionDocument, 2); // $NON-NLS-1$
     style = XmlDom4JHelper.getNodeText("widgetgrid/style", dataActionDocument); // $NON-NLS-1$
   } catch (Exception e) {
     error(
         Messages.getInstance()
             .getErrorString(
                 "WidgetGrid.ERROR_0003_DEFINITION_NOT_VALID", widgetGridDataDefinition),
         e); //$NON-NLS-1$
     return false;
   }
   return true;
 }
  @Override
  public Document getXmlContent() {
    //      assert null != urlFactory :
    // Messages.getInstance().getString("FilterPanelComponent.ERROR_0000_FACTORY_CANNOT_BE_NULL");
    // //$NON-NLS-1$

    boolean ok = filterPanel.populate(getParameterProviders(), defaultValues);

    if (!ok) {
      String msg =
          Messages.getInstance()
              .getString("FilterPanelComponent.ERROR_0001_POPULATE"); // $NON-NLS-1$
      FilterPanelComponent.log.error(msg);
      throw new UIException(msg);
    }

    String actionUrl = urlFactory.getActionUrlBuilder().getUrl();
    Document xForm = filterPanel.getXForm(actionUrl);

    setXsl("text/html", xslName); // $NON-NLS-1$

    return xForm;
  }
  protected Document createDials(
      final IPentahoResultSet resultSet, final WidgetDefinition widgetDefinition) {

    if (resultSet == null) {
      error(
          Messages.getInstance()
              .getErrorString("WidgetGrid.ERROR_0001_NO_RESULTS_FROM_ACTION")); // $NON-NLS-1$
      return null;
    }

    if (valueItem == null) {
      error(
          Messages.getInstance()
              .getErrorString("WidgetGrid.ERROR_0002_NO_VALUE_ITEM")); // $NON-NLS-1$
    }

    // Create a document that describes the result
    Document result = DocumentHelper.createDocument();
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    setXslProperty(
        "baseUrl", requestContext.getContextPath()); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty(
        "fullyQualifiedServerUrl",
        PentahoSystem.getApplicationContext()
            .getFullyQualifiedServerURL()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    Element root = result.addElement("widgets"); // $NON-NLS-1$

    IPentahoMetaData metaData = resultSet.getMetaData();
    // TODO support multiple column headers / row headers
    // TODO support an iteration across columns for a given row

    // find the column that we have been told to you
    Object[][] columnHeaders = metaData.getColumnHeaders();
    int nameColumnNo = -1;
    int valueColumnNo = -1;
    for (int idx = 0; idx < columnHeaders[0].length; idx++) {
      if (columnHeaders[0][idx].toString().equalsIgnoreCase(nameItem)) {
        nameColumnNo = idx;
      }
      if (columnHeaders[0][idx].toString().equalsIgnoreCase(valueItem)) {
        valueColumnNo = idx;
      }
    }

    if (nameColumnNo == -1) {
      // we did not find the specified name column
      error(
          Messages.getInstance()
              .getErrorString(
                  "WidgetGrid.ERROR_0004_NAME_COLUMN_MISSING", nameItem)); // $NON-NLS-1$
      return null;
    }

    if (valueColumnNo == -1) {
      // we did not find the specified name column
      error(
          Messages.getInstance()
              .getErrorString(
                  "WidgetGrid.ERROR_0005_VALUE_COLUMN_MISSING", valueItem)); // $NON-NLS-1$
      return null;
    }

    double value;
    String name;
    Object[] row = resultSet.next();
    while (row != null) {
      name = row[nameColumnNo].toString();
      try {
        value = Double.parseDouble(row[valueColumnNo].toString());
        createDial(value, name, root, widgetDefinition);
      } catch (Exception e) {
      }

      row = resultSet.next();
    }
    setXslProperty("urlTarget", "pentaho_popup"); // $NON-NLS-1$ //$NON-NLS-2$
    setXslProperty("columns", Integer.toString(columns)); // $NON-NLS-1$
    if (style != null) {
      setXslProperty("style", style); // $NON-NLS-1$
    }
    return result;
  }
  public Document getLookup() {
    // Create a document that describes the result
    Document doc = DocumentHelper.createDocument();

    Element root = doc.addElement("metadata"); // $NON-NLS-1$

    if (domainName == null) {
      // we can't do this without a model
      root.addElement("message")
          .setText(
              Messages.getInstance()
                  .getString(
                      "PMDUIComponent.USER_NO_DOMAIN_SPECIFIED")); //$NON-NLS-1$ //$NON-NLS-2$
      return doc;
    }

    if (modelId == null) {
      // we can't do this without a view
      root.addElement("message")
          .setText(
              Messages.getInstance()
                  .getString(
                      "PMDUIComponent.USER_NO_MODEL_SPECIFIED")); //$NON-NLS-1$ //$NON-NLS-2$
      return doc;
    }

    if (columnId == null) {
      // we can't do this without a view
      root.addElement("message")
          .setText(
              Messages.getInstance()
                  .getString(
                      "PMDUIComponent.USER_NO_COLUMN_SPECIFIED")); //$NON-NLS-1$ //$NON-NLS-2$
      return doc;
    }

    Domain domain = getMetadataRepository().getDomain(domainName);
    String locale =
        LocaleHelper.getClosestLocale(LocaleHelper.getLocale().toString(), domain.getLocaleCodes());
    LogicalModel model =
        domain.findLogicalModel(modelId); // This is the business view that was selected.
    if (model == null) {
      root.addElement("message")
          .setText(
              Messages.getInstance()
                  .getString(
                      "PMDUIComponent.USER_MODEL_LOADING_ERROR",
                      modelId)); //$NON-NLS-1$ //$NON-NLS-2$
      return doc;
    }

    LogicalColumn column = model.findLogicalColumn(columnId);
    if (column == null) {
      root.addElement("message")
          .setText(
              Messages.getInstance()
                  .getString("PMDUIComponent.USER_COLUMN_NOT_FOUND")); // $NON-NLS-1$ //$NON-NLS-2$
      return doc;
    }

    // Temporary hack to get the BusinessCategory. When fixed properly, you should be able to
    // interrogate the
    // business column thingie for it's containing BusinessCategory.
    Category view = null;
    for (Category category : model.getCategories()) {
      for (LogicalColumn col : category.getLogicalColumns()) {
        if (col.getId().equals(column.getId())) {
          view = category;
          break;
        }
      }
    }

    if (view == null) {
      root.addElement("message")
          .setText(
              Messages.getInstance()
                  .getString("PMDUIComponent.USER_VIEW_NOT_FOUND")); // $NON-NLS-1$ //$NON-NLS-2$
      return doc;
    }

    String mql =
        "<mql><domain_type>relational</domain_type><domain_id>"
            + domainName
            + "</domain_id><model_id>"
            + modelId
            + "</model_id>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    if (column.getProperty("lookup") == null) { // $NON-NLS-1$
      mql +=
          "<selection><view>"
              + view.getId()
              + "</view><column>"
              + column.getId()
              + "</column></selection>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      mql +=
          "<orders><order><direction>asc</direction><view_id>"
              + view.getId()
              + "</view_id><column_id>"
              + column.getId()
              + "</column_id></order></orders>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    } else {

      String lookup = (String) column.getProperty("lookup"); // $NON-NLS-1$
      // assume model and view are the same...
      StringTokenizer tokenizer1 = new StringTokenizer(lookup, ";"); // $NON-NLS-1$
      while (tokenizer1.hasMoreTokens()) {
        StringTokenizer tokenizer2 =
            new StringTokenizer(tokenizer1.nextToken(), "."); // $NON-NLS-1$
        if (tokenizer2.countTokens() == 2) {
          String lookupViewId = tokenizer2.nextToken();
          String lookupColumnId = tokenizer2.nextToken();
          mql +=
              "<selection><view>"
                  + lookupViewId
                  + "</view><column>"
                  + lookupColumnId
                  + "</column></selection>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }
      }
    }
    mql += "</mql>"; // $NON-NLS-1$
    ArrayList messages = new ArrayList();
    SimpleParameterProvider lookupParameters = new SimpleParameterProvider();
    lookupParameters.setParameter("mql", mql); // $NON-NLS-1$

    IRuntimeContext runtime =
        SolutionHelper.doAction(
            "/system/metadata/PickList.xaction",
            "lookup-list",
            lookupParameters,
            getSession(),
            messages,
            this); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
    IPentahoResultSet results = null;
    if (runtime != null) {
      if (runtime.getStatus() == IRuntimeContext.RUNTIME_STATUS_SUCCESS) {
        if (runtime.getOutputNames().contains("data")) { // $NON-NLS-1$
          results = runtime.getOutputParameter("data").getValueAsResultSet(); // $NON-NLS-1$
          Object[][] columnHeaders = results.getMetaData().getColumnHeaders();
          boolean hasColumnHeaders = columnHeaders != null;

          Element rowElement;
          Element dataElement = root.addElement("data"); // $NON-NLS-1$
          if (hasColumnHeaders) {
            for (int rowNo = 0; rowNo < columnHeaders.length; rowNo++) {
              rowElement = dataElement.addElement("COLUMN-HDR-ROW"); // $NON-NLS-1$
              for (int columnNo = 0; columnNo < columnHeaders[rowNo].length; columnNo++) {
                Object nameAttr =
                    results.getMetaData().getAttribute(rowNo, columnNo, "name"); // $NON-NLS-1$
                if ((nameAttr != null) && (nameAttr instanceof LocalizedString)) {
                  LocalizedString str = (LocalizedString) nameAttr;
                  String name = str.getLocalizedString(locale);
                  if (name != null) {
                    rowElement.addElement("COLUMN-HDR-ITEM").setText(name); // $NON-NLS-1$
                  } else {
                    rowElement
                        .addElement("COLUMN-HDR-ITEM")
                        .setText(columnHeaders[rowNo][columnNo].toString()); // $NON-NLS-1$
                  }
                } else {
                  rowElement
                      .addElement("COLUMN-HDR-ITEM")
                      .setText(columnHeaders[rowNo][columnNo].toString()); // $NON-NLS-1$
                }
              }
            }
          }
          Object[] row = results.next();
          while (row != null) {
            rowElement = dataElement.addElement("DATA-ROW"); // $NON-NLS-1$
            for (Object element : row) {
              if (element == null) {
                rowElement.addElement("DATA-ITEM").setText(""); // $NON-NLS-1$ //$NON-NLS-2$
              } else {
                rowElement.addElement("DATA-ITEM").setText(element.toString()); // $NON-NLS-1$
              }
            }
            row = results.next();
          }
        }
      }
    }

    return doc;
  }
  /**
   * Create a dial image.
   *
   * <ul>
   *   <li>Load the specified XML document describing the dial definition
   *   <li>Create a dial definition object from the XML definition
   *   <li>Use the JFreeChartEngine to create a dial image
   *   <li>Create an XML document describing the dial
   *   <li>Return the XML document
   * </ul>
   *
   * @return The XML document describing this dial
   */
  @Override
  public Document getXmlContent() {

    WidgetDefinition widget = null;
    if (type == DashboardWidgetComponent.TYPE_DIAL) {

      // load the XML document that defines the dial
      IActionSequenceResource resource =
          new ActionSequenceResource(
              title,
              IActionSequenceResource.SOLUTION_FILE_RESOURCE,
              "text/xml", //$NON-NLS-1$
              definitionPath);
      Document dialDefinition = null;
      try {
        org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
        reader.setEntityResolver(new SolutionURIResolver());
        dialDefinition =
            reader.read(
                resource.getInputStream(RepositoryFilePermission.READ, LocaleHelper.getLocale()));
      } catch (Throwable t) {
        // XML document can't be read. We'll just return a null document.
      }

      if (dialDefinition == null) {
        error(
            Messages.getInstance()
                .getErrorString(
                    "Widget.ERROR_0002_INVALID_RESOURCE", definitionPath)); // $NON-NLS-1$
        return null;
      }
      // create a dial definition from the XML definition
      widget = new DialWidgetDefinition(dialDefinition, 0, width, height, getSession());

      if (widget != null) {
        // set the value to be displayed on the dial
        widget.setValue(new Double(value));
      }
    }
    /*
     * else if( type == TYPE_THERMOMETER ) { // load the XML document that
     * defines the thermometer
     *
     * ActionResource resource = new ActionResource( title,
     * IActionResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$
     * PentahoSystem.getApplicationContext().getSolutionPath( definitionPath ) );
     * //$NON-NLS-1$ Document thermometerDefinition = null; try {
     * thermometerDefinition = PentahoSystem.getResourceAsDocument( resource ); }
     * catch (IOException e) {} // create a dial definition from the XML
     * definition widget = createThermometer( thermometerDefinition );
     *
     * if( widget != null ) { // set the value to be displayed on the dial
     * widget.setValue( new Double(value) ); // Set the XSL file to be used
     * to generate the HTML setXsl( "text/html", "DialWidget.xsl" );
     * //$NON-NLS-1$ //$NON-NLS-2$ } else { error(
     * Messages.getInstance().getString("Widget.ERROR_0001_COULD_NOT_CREATE") );
     * //$NON-NLS-1$ return null; } }
     */
    if (widget == null) {
      error(Messages.getInstance().getString("Widget.ERROR_0001_COULD_NOT_CREATE")); // $NON-NLS-1$
      return null;
    }
    // create an image for the dial using the JFreeChart engine
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    // create temporary file names
    String solutionDir = "system/tmp/"; // $NON-NLS-1$
    String fileNamePrefix = "tmp_pie_"; // $NON-NLS-1$
    String extension = ".png"; // $NON-NLS-1$
    String fileName = null;
    String filePathWithoutExtension = null;
    try {
      File file =
          PentahoSystem.getApplicationContext()
              .createTempFile(getSession(), fileNamePrefix, extension, true);
      fileName = file.getName();
      filePathWithoutExtension = solutionDir + fileName.substring(0, fileName.indexOf('.'));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    String dialTitle = ""; // $NON-NLS-1$
    JFreeChartEngine.saveChart(
        widget,
        dialTitle,
        units,
        filePathWithoutExtension,
        width,
        height,
        JFreeChartEngine.OUTPUT_PNG,
        printWriter,
        this);

    // Create a document that describes the result
    Document result = DocumentHelper.createDocument();
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    setXslProperty(
        "baseUrl", requestContext.getContextPath()); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty(
        "fullyQualifiedServerUrl",
        PentahoSystem.getApplicationContext()
            .getFullyQualifiedServerURL()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    Element root = result.addElement("widget"); // $NON-NLS-1$
    root.addElement("title").setText(title); // $NON-NLS-1$
    root.addElement("units").setText(units); // $NON-NLS-1$
    root.addElement("width").setText(Integer.toString(width)); // $NON-NLS-1$
    root.addElement("height").setText(Integer.toString(height)); // $NON-NLS-1$
    Element valueNode = root.addElement("value"); // $NON-NLS-1$
    valueNode.setText(Double.toString(value));
    valueNode.addAttribute(
        "in-image", Boolean.toString(widget.getValueFont() != null)); // $NON-NLS-1$
    root.addElement("image").setText(fileName); // $NON-NLS-1$
    return result;
  }
  @Override
  public Document getXmlContent() {

    // Create a document that describes the result
    Document result = DocumentHelper.createDocument();
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    setXslProperty(
        "baseUrl", requestContext.getContextPath()); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty(
        "fullyQualifiedServerUrl",
        PentahoSystem.getApplicationContext()
            .getFullyQualifiedServerURL()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    String mapName = "chart" + AbstractChartComponent.chartCount++; // $NON-NLS-1$
    Document chartDefinition =
        jcrHelper.getSolutionDocument(definitionPath, RepositoryFilePermission.READ);

    if (chartDefinition == null) {
      Element errorElement = result.addElement("error"); // $NON-NLS-1$
      errorElement
          .addElement("title")
          .setText(
              Messages.getInstance()
                  .getString(
                      "ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART")); //$NON-NLS-1$
                                                                                     // //$NON-NLS-2$
      String message =
          Messages.getInstance()
              .getString(
                  "CHARTS.ERROR_0001_CHART_DEFINIION_MISSING", definitionPath); // $NON-NLS-1$
      errorElement.addElement("message").setText(message); // $NON-NLS-1$
      error(message);
      return result;
    }
    // create a pie definition from the XML definition
    dataDefinition = createChart(chartDefinition);

    if (dataDefinition == null) {
      Element errorElement = result.addElement("error"); // $NON-NLS-1$
      errorElement
          .addElement("title")
          .setText(
              Messages.getInstance()
                  .getString(
                      "ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART")); //$NON-NLS-1$
                                                                                     // //$NON-NLS-2$
      String message =
          Messages.getInstance()
              .getString(
                  "CHARTS.ERROR_0002_CHART_DATA_MISSING",
                  actionPath); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      errorElement.addElement("message").setText(message); // $NON-NLS-1$
      // System .out.println( result.asXML() );
      return result;
    }

    // create an image for the dial using the JFreeChart engine
    PrintWriter printWriter = new PrintWriter(new StringWriter());
    // we'll dispay the title in HTML so that the dial image does not have
    // to
    // accommodate it
    String chartTitle = ""; // $NON-NLS-1$
    try {
      if (width == -1) {
        width =
            Integer.parseInt(
                chartDefinition.selectSingleNode("/chart/width").getText()); // $NON-NLS-1$
      }
      if (height == -1) {
        height =
            Integer.parseInt(
                chartDefinition.selectSingleNode("/chart/height").getText()); // $NON-NLS-1$
      }
    } catch (Exception e) {
      // go with the default
    }
    if (chartDefinition.selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME)
        != null) { //$NON-NLS-1$
      urlTemplate =
          chartDefinition
              .selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME)
              .getText(); //$NON-NLS-1$
    }

    if (chartDefinition.selectSingleNode("/chart/paramName") != null) { // $NON-NLS-1$
      paramName = chartDefinition.selectSingleNode("/chart/paramName").getText(); // $NON-NLS-1$
    }

    Element root = result.addElement("charts"); // $NON-NLS-1$
    TimeSeriesCollection chartDataDefinition = (TimeSeriesCollection) dataDefinition;
    if (chartDataDefinition.getSeriesCount() > 0) {
      // create temporary file names
      String[] tempFileInfo = createTempFile();
      String fileName = tempFileInfo[AbstractChartComponent.FILENAME_INDEX];
      String filePathWithoutExtension =
          tempFileInfo[AbstractChartComponent.FILENAME_WITHOUT_EXTENSION_INDEX];

      ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
      JFreeChartEngine.saveChart(
          chartDataDefinition,
          chartTitle,
          "",
          filePathWithoutExtension,
          width,
          height,
          JFreeChartEngine.OUTPUT_PNG,
          printWriter,
          info,
          this); //$NON-NLS-1$
      applyOuterURLTemplateParam();
      populateInfo(info);
      Element chartElement = root.addElement("chart"); // $NON-NLS-1$
      chartElement.addElement("mapName").setText(mapName); // $NON-NLS-1$
      chartElement.addElement("width").setText(Integer.toString(width)); // $NON-NLS-1$
      chartElement.addElement("height").setText(Integer.toString(height)); // $NON-NLS-1$
      for (int row = 0; row < chartDataDefinition.getSeriesCount(); row++) {
        for (int column = 0; column < chartDataDefinition.getItemCount(row); column++) {
          Number value = chartDataDefinition.getY(row, column);
          Comparable rowKey = chartDataDefinition.getSeriesKey(row);
          RegularTimePeriod columnKey = chartDataDefinition.getSeries(row).getTimePeriod(column);
          Element valueElement = chartElement.addElement("value2D"); // $NON-NLS-1$
          valueElement.addElement("value").setText(value.toString()); // $NON-NLS-1$
          valueElement.addElement("row-key").setText(rowKey.toString()); // $NON-NLS-1$
          valueElement.addElement("column-key").setText(columnKey.toString()); // $NON-NLS-1$
        }
      }
      String mapString = ImageMapUtilities.getImageMap(mapName, info);
      chartElement.addElement("imageMap").setText(mapString); // $NON-NLS-1$
      chartElement.addElement("image").setText(fileName); // $NON-NLS-1$
    }
    return result;
  }
  private void setChartAttributes(final Node chartAttributes) {
    if (chartAttributes == null) {
      return;
    }
    // get the chart type from the chart node -- this overrides the current
    // chart type
    setChartType(chartAttributes.selectSingleNode(ChartDefinition.TYPE_NODE_NAME));

    // set the chart background
    setChartBackground(
        chartAttributes.selectSingleNode(ChartDefinition.CHART_BACKGROUND_NODE_NAME));

    // set the plot background
    setPlotBackground(chartAttributes.selectSingleNode(ChartDefinition.PLOT_BACKGROUND_NODE_NAME));

    // set the orientation
    setOrientation(chartAttributes.selectSingleNode(XYChartDefinition.ORIENTATION_NODE_NAME));

    // do we want a legend
    setLegendIncluded(chartAttributes.selectSingleNode(ChartDefinition.INCLUDE_LEGEND_NODE_NAME));

    // get the chart title
    setTitle(chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME));

    // A list of <subtitle> nodes should not be allowed to exist as a child of the main XML element
    // (for XML schema to
    // be well constructed and validate the XML .
    // We have deprecated <subtitle> as a child of the main node , and now require a <subtitles>
    // parent node
    // under which <subtitle> can exist.

    List subtitles = chartAttributes.selectNodes(ChartDefinition.SUBTITLE_NODE_NAME);

    if ((subtitles == null) || (subtitles.isEmpty())) {
      Node subTitlesNode = chartAttributes.selectSingleNode(ChartDefinition.SUBTITLES_NODE_NAME);
      if (subTitlesNode != null) {
        subtitles = subTitlesNode.selectNodes(ChartDefinition.SUBTITLE_NODE_NAME);
      }
    } else {
      // log a deprecation warning for this property...
      getLogger()
          .warn(
              Messages.getInstance()
                  .getString(
                      "CHART.WARN_DEPRECATED_CHILD",
                      ChartDefinition.SUBTITLE_NODE_NAME,
                      ChartDefinition.SUBTITLES_NODE_NAME)); // $NON-NLS-1$
      getLogger()
          .warn(
              Messages.getInstance()
                  .getString(
                      "CHART.WARN_PROPERTY_WILL_NOT_VALIDATE",
                      ChartDefinition.SUBTITLE_NODE_NAME)); // $NON-NLS-1$
    }

    if (subtitles != null) {
      addSubTitles(subtitles);
    }

    // get the paint sequence
    setPaintSequence(chartAttributes.selectSingleNode(ChartDefinition.PALETTE_NODE_NAME));
    Node backgroundAlphaNode =
        chartAttributes.selectSingleNode(ChartDefinition.BACKGROUND_ALPHA_NODE_NAME);
    Node foregroundAlphaNode =
        chartAttributes.selectSingleNode(ChartDefinition.FOREGROUND_ALPHA_NODE_NAME);

    if (backgroundAlphaNode != null) {
      setBackgroundAlpha(
          chartAttributes.selectSingleNode(ChartDefinition.BACKGROUND_ALPHA_NODE_NAME));
    }
    if (foregroundAlphaNode != null) {
      setForegroundAlpha(
          chartAttributes.selectSingleNode(ChartDefinition.FOREGROUND_ALPHA_NODE_NAME));
    }
    // get the stacked value
    setStacked(chartAttributes.selectSingleNode(ChartDefinition.STACKED_NODE_NAME));

    // get the 3D value
    setThreeD(chartAttributes.selectSingleNode(ChartDefinition.THREED_NODE_NAME));

    // set the width
    setWidth(chartAttributes.selectSingleNode(ChartDefinition.WIDTH_NODE_NAME));

    // set the height
    setHeight(chartAttributes.selectSingleNode(ChartDefinition.HEIGHT_NODE_NAME));

    // set the dot width
    setDotWidth(chartAttributes.selectSingleNode(ChartDefinition.DOT_WIDTH_NODE_NAME));

    // set the dot height
    setDotHeight(chartAttributes.selectSingleNode(ChartDefinition.DOT_HEIGHT_NODE_NAME));

    // set vertical tick labels flag
    setDomainVerticalTickLabels(
        chartAttributes.selectSingleNode(XYChartDefinition.DOMAIN_VERTICAL_TICK_LABELS_NODE_NAME));

    // set the border on or off
    setBorderVisible(
        chartAttributes.selectSingleNode(ChartDefinition.CHART_BORDER_VISIBLE_NODE_NAME));

    // set the border Paint
    setBorderPaint(
        JFreeChartEngine.getPaint(
            chartAttributes.selectSingleNode(XYChartDefinition.CHART_BORDER_PAINT_NODE_NAME)));

    // set the title location
    setTitlePosition(chartAttributes.selectSingleNode(ChartDefinition.TITLE_POSITION_NODE_NAME));

    // set the legend location
    setLegendPosition(chartAttributes.selectSingleNode(ChartDefinition.LEGEND_POSITION_NODE_NAME));

    // set the title font
    setTitleFont(chartAttributes.selectSingleNode(ChartDefinition.TITLE_FONT_NODE_NAME));

    // set the domain title
    setDomainTitle(chartAttributes.selectSingleNode(XYChartDefinition.DOMAIN_TITLE_NODE_NAME));

    // set the domain font
    setDomainTitleFont(
        chartAttributes.selectSingleNode(XYChartDefinition.DOMAIN_TITLE_FONT_NODE_NAME));

    // set the range title
    setRangeTitle(chartAttributes.selectSingleNode(XYChartDefinition.RANGE_TITLE_NODE_NAME));

    // the the range font
    setRangeTitleFont(
        chartAttributes.selectSingleNode(XYChartDefinition.RANGE_TITLE_FONT_NODE_NAME));

    // set the range minimum
    setRangeMinimum(chartAttributes.selectSingleNode(XYChartDefinition.RANGE_MINIMUM_NODE_NAME));

    // set the range minimum
    setRangeMaximum(chartAttributes.selectSingleNode(XYChartDefinition.RANGE_MAXIMUM_NODE_NAME));

    // set the date minimum
    setDateMinimum(
        chartAttributes.selectSingleNode(
            TimeSeriesCollectionChartDefinition.DATE_MINIMUM_NODE_NAME));

    // set the date minimum
    setDateMaximum(
        chartAttributes.selectSingleNode(
            TimeSeriesCollectionChartDefinition.DATE_MAXIMUM_NODE_NAME));

    // set the Period type
    setDomainPeriodType(
        chartAttributes.selectSingleNode(XYChartDefinition.DOMAIN_PERIOD_TYPE_NODE_NAME));

    // set the line style
    setLineStyle(chartAttributes.selectSingleNode(ChartDefinition.LINE_STYLE_NODE_NAME));

    // set the line width
    setLineWidth(chartAttributes.selectSingleNode(ChartDefinition.LINE_WIDTH_NODE_NAME));

    // set the marker visibility
    setMarkersVisible(chartAttributes.selectSingleNode(ChartDefinition.MARKER_VISIBLE_NODE_NAME));

    // set legend font
    setLegendFont(chartAttributes.selectSingleNode(ChartDefinition.LEGEND_FONT_NODE_NAME));

    // set legend border visible
    setLegendBorderVisible(
        chartAttributes.selectSingleNode(ChartDefinition.DISPLAY_LEGEND_BORDER_NODE_NAME));

    setTooltipContent(
        chartAttributes.selectSingleNode(XYChartDefinition.TOOLTIP_CONTENT_NODE_NAME));

    setTooltipYFormat(
        chartAttributes.selectSingleNode(XYChartDefinition.TOOLTIP_Y_FORMAT_NODE_NAME));

    setTooltipXFormat(
        chartAttributes.selectSingleNode(XYChartDefinition.TOOLTIP_X_FORMAT_NODE_NAME));
  }
  private Document loadModel() {
    // Create a document that describes the result
    Document doc = DocumentHelper.createDocument();

    Element root = doc.addElement("metadata"); // $NON-NLS-1$

    if (domainName == null) {
      // we can't do this without a model
      root.addElement("message")
          .setText(
              Messages.getInstance()
                  .getString(
                      "PMDUIComponent.USER_NO_DOMAIN_SPECIFIED")); //$NON-NLS-1$ //$NON-NLS-2$
      return doc;
    }

    if (modelId == null) {
      // we can't do this without a model
      root.addElement("message")
          .setText(
              Messages.getInstance()
                  .getString(
                      "PMDUIComponent.USER_NO_MODEL_SPECIFIED")); //$NON-NLS-1$ //$NON-NLS-2$
      return doc;
    }

    Element modelNode = root.addElement("model"); // $NON-NLS-1$

    // because it's lighter weight, check the thin model
    Domain domain = getMetadataRepository().getDomain(domainName);
    if (domain == null) {
      root.addElement("message")
          .setText(
              Messages.getInstance()
                  .getString(
                      "PMDUIComponent.USER_DOMAIN_LOADING_ERROR",
                      domainName)); //$NON-NLS-1$ //$NON-NLS-2$
      return doc;
    }
    String locale =
        LocaleHelper.getClosestLocale(LocaleHelper.getLocale().toString(), domain.getLocaleCodes());
    LogicalModel model = domain.findLogicalModel(modelId);

    if (model == null) {
      root.addElement("message")
          .setText(
              Messages.getInstance()
                  .getString(
                      "PMDUIComponent.USER_MODEL_LOADING_ERROR",
                      modelId)); //$NON-NLS-1$ //$NON-NLS-2$
      error(
          Messages.getInstance()
              .getString("PMDUIComponent.USER_MODEL_LOADING_ERROR", modelId)); // $NON-NLS-1$
      return doc;
    }
    modelNode.addElement("domain_id").setText(domainName); // $NON-NLS-1$
    if (model.getId() != null) {
      modelNode.addElement("model_id").setText(model.getId()); // $NON-NLS-1$
    }
    if (model.getName(locale) != null) {
      modelNode.addElement("model_name").setText(model.getName(locale)); // $NON-NLS-1$
    }
    if (model.getDescription(locale) != null) {
      modelNode
          .addElement("model_description")
          .setText(model.getDescription(locale)); // $NON-NLS-1$
    }

    Element tableNode;

    for (Category category : model.getCategories()) {
      tableNode = modelNode.addElement("view"); // $NON-NLS-1$
      if (category.getId() != null) {
        tableNode.addElement("view_id").setText(category.getId()); // $NON-NLS-1$
      }
      if (category.getName(locale) != null) {
        tableNode.addElement("view_name").setText(category.getName(locale)); // $NON-NLS-1$
      }
      if (category.getDescription(locale) != null) {
        tableNode
            .addElement("view_description")
            .setText(category.getDescription(locale)); // $NON-NLS-1$
      }
      for (LogicalColumn column : category.getLogicalColumns()) {
        Boolean hidden = (Boolean) column.getProperty("hidden"); // $NON-NLS-1$
        if (hidden != null && hidden) {
          continue;
        }
        addColumn(column, tableNode, locale);
      }
    }

    return doc;
  }