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$
      }
    }
  }
 private void populateInfo(final ChartRenderingInfo info) {
   if (urlTemplate == null) {
     return;
   }
   Iterator iter = info.getEntityCollection().iterator();
   while (iter.hasNext()) {
     ChartEntity entity = (ChartEntity) iter.next();
     if (entity instanceof XYItemEntity) {
       if (urlTemplate != null) {
         XYItemEntity xyItemEntity = (XYItemEntity) entity;
         if (paramName == null) {
           xyItemEntity.setURLText(urlTemplate);
         } else {
           try {
             int seriesIndex = xyItemEntity.getSeriesIndex();
             int itemIndex = xyItemEntity.getItem();
             String xySeriesKey =
                 (String)
                     ((XYZSeriesCollectionChartDefinition) xyItemEntity.getDataset())
                         .getSeriesKey(seriesIndex);
             String encodedVal = URLEncoder.encode(xySeriesKey, LocaleHelper.getSystemEncoding());
             String drillURL = TemplateUtil.applyTemplate(urlTemplate, paramName, encodedVal);
             String itemValueStr =
                 ((XYZSeriesCollectionChartDefinition) xyItemEntity.getDataset())
                     .getX(seriesIndex, itemIndex)
                     .toString();
             encodedVal = URLEncoder.encode(itemValueStr, LocaleHelper.getSystemEncoding());
             if (seriesName == null) {
               drillURL =
                   TemplateUtil.applyTemplate(drillURL, "SERIES", encodedVal); // $NON-NLS-1$
             } else {
               drillURL = TemplateUtil.applyTemplate(drillURL, seriesName, encodedVal);
             }
             xyItemEntity.setURLText(drillURL);
           } catch (UnsupportedEncodingException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
           }
         }
       }
     }
   }
 }
  protected void createDial(
      final double value,
      final String name,
      final Element root,
      final WidgetDefinition widgetDefinition) {

    widgetDefinition.setValue(new Double(value));

    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);

    // TODO get units from somewhere
    String units = ""; // $NON-NLS-1$
    String dialName = ""; // $NON-NLS-1$
    // 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();
    }
    JFreeChartEngine.saveChart(
        widgetDefinition,
        dialName,
        units,
        filePathWithoutExtension,
        widgetWidth,
        widgetHeight,
        JFreeChartEngine.OUTPUT_PNG,
        printWriter,
        this);

    Element widgetNode = root.addElement("widget"); // $NON-NLS-1$

    widgetNode.addElement("title").setText(name); // $NON-NLS-1$
    widgetNode.addElement("units").setText(units); // $NON-NLS-1$
    widgetNode.addElement("width").setText(Integer.toString(widgetWidth)); // $NON-NLS-1$
    widgetNode.addElement("height").setText(Integer.toString(widgetHeight)); // $NON-NLS-1$
    Element valueNode = widgetNode.addElement("value"); // $NON-NLS-1$
    valueNode.setText(Double.toString(value));
    valueNode.addAttribute(
        "in-image", Boolean.toString(widgetDefinition.getValueFont() != null)); // $NON-NLS-1$
    root.addElement("image").setText(fileName); // $NON-NLS-1$
    widgetNode.addElement("image").setText(fileName); // $NON-NLS-1$

    // apply the current data item name to the URL template
    String drillUrl = TemplateUtil.applyTemplate(urlTemplate, nameItem, name);

    // now apply any parameters to the URL template
    drillUrl = TemplateUtil.applyTemplate(drillUrl, context);

    widgetNode.addElement("urlDrill").setText(drillUrl); // $NON-NLS-1$
  }
  /**
   * This method is called when TemplateUtil.applyTemplate() encounters a parameter.
   * TemplateUtil.applyTemplate is called when someone makes a call to applyInputsToFormat() In this
   * class it is called in the above "runQuery()" method.
   *
   * @param template the source string
   * @param parameter the parameter value
   * @param parameterMatcher the regex parameter matcher
   * @param copyStart the start of the copy
   * @param results the output result
   * @return the next copystart
   */
  @Override
  public int resolveParameter(
      final String template,
      final String parameter,
      final Matcher parameterMatcher,
      int copyStart,
      final StringBuffer results) {

    StringTokenizer tokenizer = new StringTokenizer(parameter, ":"); // $NON-NLS-1$
    if (tokenizer.countTokens() == 2) { // Currently, the component only handles one bit of metadata
      String parameterPrefix = tokenizer.nextToken();
      String inputName = tokenizer.nextToken();

      // if the template contains a prepare later prefix,
      // mark a spot in the preparedParameters list and move on.
      if (parameterPrefix.equals(IPreparedComponent.PREPARE_LATER_PREFIX)) {
        if (!isDefinedOutput(IPreparedComponent.PREPARED_COMPONENT_NAME)) {
          error(
              Messages.getInstance()
                  .getErrorString(
                      "IPreparedComponent.ERROR_0003_INVALID_PARAMETER_STATE")); //$NON-NLS-1$
          return -1;
        }
        preparedParameters.add(IPreparedComponent.PREPARE_LATER_PLACEHOLDER);
        int start = parameterMatcher.start();
        int end = parameterMatcher.end();
        results.append(template.substring(copyStart, start));
        results.append(
            "{"
                + IPreparedComponent.PREPARE_LATER_INTER_PREFIX
                + ":"
                + inputName
                + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        return end;
      }

      if (parameterPrefix.equals(SQLBaseComponent.PREPARE_PARAMETER_PREFIX)) {
        // We know this parameter is for us.
        // First, is this a special input
        Object parameterValue = TemplateUtil.getSystemInput(inputName, getRuntimeContext());
        if ((parameterValue == null) && isDefinedInput(inputName)) {
          parameterValue = this.getInputValue(inputName);
        }
        if (parameterValue != null) {
          // We have a parameter value - now, it's time to create a parameter and build up the
          // parameter string
          int start = parameterMatcher.start();
          int end = parameterMatcher.end();
          // First, find out if the parameter was quoted...
          if ((start > 0) && (end < template.length())) {
            if ((template.charAt(start - 1) == '\'') && (template.charAt(end) == '\'')) {
              // Ok, the parameter was quoted as near as we can tell. So, we need
              // to increase the size of the amount we overwrite by one in each
              // direction. This is for backward compatibility.
              start--;
              end++;
            }
          }
          // We now have a valid start and end. It's time to see whether we're dealing
          // with an array, a result set, or a scalar.
          StringBuffer parameterBuffer = new StringBuffer();
          if (parameterValue instanceof String) {
            preparedParameters.add(parameterValue);
            parameterBuffer.append('?');
          } else if (parameterValue instanceof Object[]) {
            Object[] pObj = (Object[]) parameterValue;
            for (Object element : pObj) {
              preparedParameters.add(element);
              parameterBuffer.append(
                  (parameterBuffer.length() == 0) ? "?" : ",?"); // $NON-NLS-1$ //$NON-NLS-2$
            }
          } else if (parameterValue instanceof IPentahoResultSet) {
            IPentahoResultSet rs = (IPentahoResultSet) parameterValue;
            // See if we can find a column in the metadata with the same
            // name as the input
            IPentahoMetaData md = rs.getMetaData();
            int columnIdx = -1;
            if (md.getColumnCount() == 1) {
              columnIdx = 0;
            } else {
              columnIdx = md.getColumnIndex(new String[] {parameter});
            }
            if (columnIdx < 0) {
              error(
                  Messages.getInstance()
                      .getErrorString(
                          "Template.ERROR_0005_COULD_NOT_DETERMINE_COLUMN")); //$NON-NLS-1$
              return -1;
            }
            int rowCount = rs.getRowCount();
            Object valueCell = null;
            // TODO support non-string columns
            for (int i = 0; i < rowCount; i++) {
              valueCell = rs.getValueAt(i, columnIdx);
              preparedParameters.add(valueCell);
              parameterBuffer.append(
                  (parameterBuffer.length() == 0) ? "?" : ",?"); // $NON-NLS-1$ //$NON-NLS-2$
            }
          } else if (parameterValue instanceof List) {
            List pObj = (List) parameterValue;
            for (int i = 0; i < pObj.size(); i++) {
              preparedParameters.add(pObj.get(i));
              parameterBuffer.append(
                  (parameterBuffer.length() == 0) ? "?" : ",?"); // $NON-NLS-1$ //$NON-NLS-2$
            }
          } else {
            // If we're here, we know parameterValue is not null and not a string
            this.preparedParameters.add(parameterValue);
            parameterBuffer.append('?');
          }

          // OK - We have a parameterBuffer and have filled out the preparedParameters
          // list. It's time to change the SQL to insert our parameter marker and tell
          // the caller we've done our job.
          results.append(template.substring(copyStart, start));
          copyStart = end;
          results.append(parameterBuffer);
          return copyStart;
        }
      }
    }

    return -1; // Nothing here for us - let default behavior through
  }
  /**
   * executes a prepared method that returns a result set executePrepared looks up any
   * "PREPARELATER" params in the preparedParams map.
   *
   * @param preparedParams a map of possible parameters.
   * @return result set
   */
  public IPentahoResultSet executePrepared(final Map preparedParams) {
    try {
      if (connection == null) {
        error(
            Messages.getInstance()
                .getErrorString("SQLBaseComponent.ERROR_0007_NO_CONNECTION")); // $NON-NLS-1$
        return null;
      }
      if (!connection.initialized()) {
        error(
            Messages.getInstance()
                .getErrorString("SQLBaseComponent.ERROR_0007_NO_CONNECTION")); // $NON-NLS-1$
        return null;
      }

      if (preparedQuery == null) {
        error(
            Messages.getInstance()
                .getErrorString(
                    "SQLBaseComponent.ERROR_0001_QUERY_NOT_SPECIFIED",
                    getActionName())); //$NON-NLS-1$
        return null;
      }

      // copy the preparedParams list, so it can be used multiple times.
      ArrayList copyOfPreparedParameters = new ArrayList(preparedParameters);

      // parse preparedQuery, replacing any {PREPARELATER:NAME} with appropriate values
      String query =
          TemplateUtil.applyTemplate(
              preparedQuery,
              getRuntimeContext(),
              new ParamResolver(copyOfPreparedParameters, preparedParams));

      if (ComponentBase.debug) {
        dumpQuery(query);
      }

      // evaluate
      IPentahoResultSet resultSet = null;
      if (preparedParameters.size() > 0) {
        resultSet = connection.prepareAndExecuteQuery(query, copyOfPreparedParameters);
      } else {
        resultSet = connection.executeQuery(query);
      }

      if (connection instanceof SQLConnection) {
        if (((SQLConnection) connection).isForcedForwardOnly()) {
          warn(
              Messages.getInstance()
                  .getString("SQLBaseComponent.WARN_FALL_BACK_TO_NONSCROLLABLE")); // $NON-NLS-1$
        }
      }

      boolean live = true;
      IActionDefinition actionDefinition = getActionDefinition();
      if (actionDefinition instanceof AbstractRelationalDbAction) {
        AbstractRelationalDbAction relationalDbAction =
            (AbstractRelationalDbAction) actionDefinition;
        live = relationalDbAction.getLive().getBooleanValue(false);
      }

      IPentahoResultSet rs = resultSet;

      // BISERVER-5915, BISERVER-5875 - if the live setting is false, return an in memory resultset.
      if (!live) {
        rs = resultSet.memoryCopy();
      }

      rSet = rs;
      return rs;

    } catch (Exception e) {
      error(
          Messages.getInstance()
              .getErrorString("SQLBaseComponent.ERROR_0006_EXECUTE_FAILED", getActionName()),
          e); //$NON-NLS-1$
    }
    return null;
  }