@Test
  @PrepareForTest({Encode.class})
  public void testStartExecutionTransServletEscapesHtmlWhenTransFound()
      throws ServletException, IOException {
    KettleLogStore.init();
    HttpServletRequest mockHttpServletRequest = mock(HttpServletRequest.class);
    HttpServletResponse mockHttpServletResponse = mock(HttpServletResponse.class);
    Trans mockTrans = mock(Trans.class);
    TransMeta mockTransMeta = mock(TransMeta.class);
    LogChannelInterface mockChannelInterface = mock(LogChannelInterface.class);
    StringWriter out = new StringWriter();
    PrintWriter printWriter = new PrintWriter(out);

    PowerMockito.spy(Encode.class);
    when(mockHttpServletRequest.getContextPath())
        .thenReturn(StartExecutionTransServlet.CONTEXT_PATH);
    when(mockHttpServletRequest.getParameter(anyString()))
        .thenReturn(ServletTestUtils.BAD_STRING_TO_TEST);
    when(mockHttpServletResponse.getWriter()).thenReturn(printWriter);
    when(mockTransformationMap.getTransformation(any(CarteObjectEntry.class)))
        .thenReturn(mockTrans);
    when(mockTrans.getLogChannel()).thenReturn(mockChannelInterface);
    when(mockTrans.isReadyToStart()).thenReturn(true);
    when(mockTrans.getLogChannelId()).thenReturn("test");
    when(mockTrans.getTransMeta()).thenReturn(mockTransMeta);
    when(mockTransMeta.getMaximum()).thenReturn(new Point(10, 10));

    startExecutionTransServlet.doGet(mockHttpServletRequest, mockHttpServletResponse);
    assertFalse(ServletTestUtils.hasBadText(ServletTestUtils.getInsideOfTag("H1", out.toString())));

    PowerMockito.verifyStatic(atLeastOnce());
    Encode.forHtml(anyString());
  }
 private NodeAttrEntity(final NodeDetail node, URI uri, String lang) {
   this.componentId = node.getNodePK().getInstanceId();
   this.id = node.getNodePK().getId();
   this.uri = uri;
   if (node.getNbObjects() != -1) {
     this.nbItems = String.valueOf(node.getNbObjects());
   }
   this.status = node.getStatus();
   this.role = node.getUserRole();
   this.creatorId = node.getCreatorId();
   this.description = Encode.forHtml(node.getDescription(lang));
   UserDetail user = UserDetail.getById(node.getCreatorId());
   if (user != null) {
     this.creator = UserProfileEntity.fromUser(user);
   }
   try {
     this.creationDate = DateUtil.parse(node.getCreationDate());
   } catch (ParseException e) {
   }
 }
  @Test
  @PrepareForTest({Encode.class})
  public void testStartExecutionTransServletEscapesHtmlWhenTransNotFound()
      throws ServletException, IOException {
    HttpServletRequest mockHttpServletRequest = mock(HttpServletRequest.class);
    HttpServletResponse mockHttpServletResponse = mock(HttpServletResponse.class);

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

    PowerMockito.spy(Encode.class);
    when(mockHttpServletRequest.getContextPath())
        .thenReturn(StartExecutionTransServlet.CONTEXT_PATH);
    when(mockHttpServletRequest.getParameter(anyString()))
        .thenReturn(ServletTestUtils.BAD_STRING_TO_TEST);
    when(mockHttpServletResponse.getWriter()).thenReturn(printWriter);

    startExecutionTransServlet.doGet(mockHttpServletRequest, mockHttpServletResponse);
    assertFalse(ServletTestUtils.hasBadText(ServletTestUtils.getInsideOfTag("H1", out.toString())));

    PowerMockito.verifyStatic(atLeastOnce());
    Encode.forHtml(anyString());
  }
  private String printBreadCrumb() {
    StringBuilder result = new StringBuilder();
    String information = getExtraInformation();
    String path = getPath();
    // print javascript to go to spaces in displayed path
    result.append(printScript());
    if (!StringUtil.isDefined(getSpaceJavascriptCallback())) {
      setSpaceJavascriptCallback("goSpace");
    }
    result.append("<div id=\"breadCrumb\">");

    boolean emptyBreadCrumb = true;

    // Display spaces path from root to component
    String language =
        (getMainSessionController() == null)
            ? ""
            : getMainSessionController().getFavoriteLanguage();
    if (StringUtil.isDefined(getComponentId()) || StringUtil.isDefined(getSpaceId())) {
      List<SpaceInst> spaces;

      OrganizationController organizationController =
          OrganizationControllerProvider.getOrganisationController();
      if (StringUtil.isDefined(getComponentId())) {
        spaces = organizationController.getSpacePathToComponent(getComponentId());
      } else {
        spaces = organizationController.getSpacePath(getSpaceId());
      }
      boolean firstSpace = true;
      for (SpaceInst spaceInst : spaces) {
        String spaceId = spaceInst.getId();
        if (!spaceId.startsWith("WA")) {
          spaceId = "WA" + spaceId;
        }
        String href = "javascript:" + getSpaceJavascriptCallback() + "('" + spaceId + "')";
        if (!isClickable()) {
          href = "#";
        }

        if (!firstSpace) {
          result.append(CONNECTOR);
        }
        result.append("<a href=\"").append(href).append("\"");
        result.append(" class=\"space\"");
        result.append(" id=\"space").append(spaceId).append("\"");
        result.append(">");
        result.append(Encode.forHtml(spaceInst.getName(language)));
        result.append("</a>");

        firstSpace = false;
        emptyBreadCrumb = false;
      }

      if (StringUtil.isDefined(getComponentId())) {
        // Display component's label
        ComponentInstLight componentInstLight =
            organizationController.getComponentInstLight(getComponentId());
        if (componentInstLight != null) {
          result.append(CONNECTOR);
          result.append("<a href=\"");
          if (!isClickable()) {
            result.append("#");
          } else if (StringUtil.isDefined(getComponentJavascriptCallback())) {
            result
                .append("javascript:")
                .append(getComponentJavascriptCallback())
                .append("('")
                .append(getComponentId())
                .append("')");
          } else {
            result
                .append(URLUtil.getApplicationURL())
                .append(URLUtil.getURL(getSpaceId(), getComponentId()));
            if (ignoreComponentLink()) {
              result.append("Main");
            } else {
              result.append(getComponentLink());
            }
          }
          result.append("\"");
          result.append(" class=\"component\"");
          result.append(" id=\"bc_").append(componentInstLight.getId()).append("\"");
          result.append(">");
          result.append(Encode.forHtml(componentInstLight.getLabel(language)));
          result.append("</a>");
          emptyBreadCrumb = false;
        }
      }
    } else {
      if (getDomainName() != null) {
        result.append(getDomainName());
        emptyBreadCrumb = false;
      }
      if (getComponentName() != null) {
        if (getDomainName() != null) {
          result.append(CONNECTOR);
        }
        if (getComponentLink() != null) {
          result
              .append("<a href=\"")
              .append(getComponentLink())
              .append("\">")
              .append(getComponentName())
              .append("</a>");
        } else {
          result.append(getComponentName());
        }
        emptyBreadCrumb = false;
      }
    }

    // Display path
    List<BrowseBarElement> elements = getElements();
    if (!elements.isEmpty()) {
      for (BrowseBarElement element : elements) {
        if (!emptyBreadCrumb) {
          result.append(CONNECTOR);
        }
        result.append("<a href=\"").append(element.getLink()).append("\"");
        result.append(" class=\"element\"");
        if (StringUtil.isDefined(element.getId())) {
          result.append(" id=\"").append(element.getId()).append("\"");
        }
        result.append(">");
        result.append(EncodeHelper.javaStringToHtmlString(element.getLabel()));
        result.append("</a>");
        emptyBreadCrumb = false;
      }
    } else if (StringUtil.isDefined(path)) {
      if (!emptyBreadCrumb) {
        result.append(CONNECTOR);
      }
      result.append("<span class=\"path\">");
      result.append(path);
      result.append("</span>");
    }

    // Display extra information
    if (StringUtil.isDefined(information)) {
      if (!emptyBreadCrumb) {
        result.append(CONNECTOR);
      }
      result.append("<span class=\"information\">");
      result.append(information);
      result.append("</span>");
    }

    result.append("</div>");

    return result.toString();
  }
  /**
   * <div id="mindtouch">
   *
   * <h1>/kettle/prepareExec</h1>
   *
   * <a name="GET"></a>
   *
   * <h2>GET</h2>
   *
   * <p>Prepares previously loaded transformation for execution. Method is used for preparing
   * previously uploaded transformation for execution by its name.
   *
   * <p><b>Example Request:</b><br>
   *
   * <pre function="syntax.xml">
   * GET /kettle/prepareExec/?name=dummy-trans2&xml=Y
   * </pre>
   *
   * <h3>Parameters</h3>
   *
   * <table class="pentaho-table">
   * <tbody>
   * <tr>
   * <th>name</th>
   * <th>description</th>
   * <th>type</th>
   * </tr>
   * <tr>
   * <td>name</td>
   * <td>Name of the transformation to be prepared for execution.</td>
   * <td>query</td>
   * </tr>
   * <tr>
   * <td>xml</td>
   * <td>Boolean flag which sets the output format required. Use <code>Y</code> to receive XML response.</td>
   * <td>boolean</td>
   * </tr>
   * <tr>
   * <td>id</td>
   * <td>Carte transformation ID of the transformation to be prepared for execution.</td>
   * <td>query, optional</td>
   * </tr>
   * </tbody>
   * </table>
   *
   * <h3>Response Body</h3>
   *
   * <table class="pentaho-table">
   * <tbody>
   * <tr>
   * <td align="right">text:</td>
   * <td>HTML</td>
   * </tr>
   * <tr>
   * <td align="right">media types:</td>
   * <td>text/xml, text/html</td>
   * </tr>
   * </tbody>
   * </table>
   *
   * <p>Response XML or HTML containing operation result. When using xml=Y <code>result</code> field
   * indicates whether operation was successful (<code>OK</code>) or not (<code>ERROR</code>).
   *
   * <p><b>Example Response:</b>
   *
   * <pre function="syntax.xml">
   * <?xml version="1.0" encoding="UTF-8"?>
   * <webresult>
   * <result>OK</result>
   * <message/>
   * <id/>
   * </webresult>
   * </pre>
   *
   * <h3>Status Codes</h3>
   *
   * <table class="pentaho-table">
   * <tbody>
   * <tr>
   * <th>code</th>
   * <th>description</th>
   * </tr>
   * <tr>
   * <td>200</td>
   * <td>Request was processed.</td>
   * </tr>
   * <tr>
   * <td>500</td>
   * <td>Internal server error occurs during request processing.</td>
   * </tr>
   * </tbody>
   * </table>
   *
   * </div>
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (isJettyMode() && !request.getContextPath().startsWith(CONTEXT_PATH)) {
      return;
    }

    if (log.isDebug()) {
      logDebug(
          BaseMessages.getString(
              PKG, "PrepareExecutionTransServlet.TransPrepareExecutionRequested"));
    }

    String transName = request.getParameter("name");
    String id = request.getParameter("id");
    boolean useXML = "Y".equalsIgnoreCase(request.getParameter("xml"));

    response.setStatus(HttpServletResponse.SC_OK);

    PrintWriter out = response.getWriter();
    if (useXML) {
      response.setContentType("text/xml");
      out.print(XMLHandler.getXMLHeader(Const.XML_ENCODING));
    } else {

      response.setCharacterEncoding("UTF-8");
      response.setContentType("text/html;charset=UTF-8");

      out.println("<HTML>");
      out.println("<HEAD>");
      out.println(
          "<TITLE>"
              + BaseMessages.getString(PKG, "PrepareExecutionTransServlet.TransPrepareExecution")
              + "</TITLE>");
      out.println(
          "<META http-equiv=\"Refresh\" content=\"2;url="
              + convertContextPath(GetTransStatusServlet.CONTEXT_PATH)
              + "?name="
              + URLEncoder.encode(transName, "UTF-8")
              + "\">");
      out.println("<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
      out.println("</HEAD>");
      out.println("<BODY>");
    }

    try {
      // ID is optional...
      //
      Trans trans;
      CarteObjectEntry entry;
      if (Utils.isEmpty(id)) {
        // get the first transformation that matches...
        //
        entry = getTransformationMap().getFirstCarteObjectEntry(transName);
        if (entry == null) {
          trans = null;
        } else {
          id = entry.getId();
          trans = getTransformationMap().getTransformation(entry);
        }
      } else {
        // Take the ID into account!
        //
        entry = new CarteObjectEntry(transName, id);
        trans = getTransformationMap().getTransformation(entry);
      }

      TransConfiguration transConfiguration = getTransformationMap().getConfiguration(entry);

      if (trans != null && transConfiguration != null) {
        TransExecutionConfiguration executionConfiguration =
            transConfiguration.getTransExecutionConfiguration();
        // Set the appropriate logging, variables, arguments, replay date, ...
        // etc.
        trans.setArguments(executionConfiguration.getArgumentStrings());
        trans.setReplayDate(executionConfiguration.getReplayDate());
        trans.setSafeModeEnabled(executionConfiguration.isSafeModeEnabled());
        trans.setGatheringMetrics(executionConfiguration.isGatheringMetrics());
        trans.injectVariables(executionConfiguration.getVariables());
        trans.setPreviousResult(executionConfiguration.getPreviousResult());

        try {
          trans.prepareExecution(null);

          if (useXML) {
            out.println(WebResult.OK.getXML());
          } else {

            out.println(
                "<H1>"
                    + Encode.forHtml(
                        BaseMessages.getString(
                            PKG, "PrepareExecutionTransServlet.TransPrepared", transName))
                    + "</H1>");
            out.println(
                "<a href=\""
                    + convertContextPath(GetTransStatusServlet.CONTEXT_PATH)
                    + "?name="
                    + URLEncoder.encode(transName, "UTF-8")
                    + "&id="
                    + URLEncoder.encode(id, "UTF-8")
                    + "\">"
                    + BaseMessages.getString(PKG, "TransStatusServlet.BackToTransStatusPage")
                    + "</a><p>");
          }
        } catch (Exception e) {

          String logText =
              KettleLogStore.getAppender()
                  .getBuffer(trans.getLogChannel().getLogChannelId(), true)
                  .toString();
          if (useXML) {
            out.println(
                new WebResult(
                    WebResult.STRING_ERROR,
                    BaseMessages.getString(
                        PKG,
                        "PrepareExecutionTransServlet.Error.TransInitFailed",
                        Const.CR + logText + Const.CR + Const.getStackTracker(e))));
          } else {
            out.println(
                "<H1>"
                    + Encode.forHtml(
                        BaseMessages.getString(
                            PKG, "PrepareExecutionTransServlet.Log.TransNotInit", transName))
                    + "</H1>");

            out.println("<pre>");
            out.println(Encode.forHtml(logText));
            out.println(Encode.forHtml(Const.getStackTracker(e)));
            out.println("</pre>");
            out.println(
                "<a href=\""
                    + convertContextPath(GetTransStatusServlet.CONTEXT_PATH)
                    + "?name="
                    + URLEncoder.encode(transName, "UTF-8")
                    + "&id="
                    + id
                    + "\">"
                    + BaseMessages.getString(PKG, "TransStatusServlet.BackToTransStatusPage")
                    + "</a><p>");
          }
        }
      } else {
        if (useXML) {
          out.println(
              new WebResult(
                  WebResult.STRING_ERROR,
                  BaseMessages.getString(
                      PKG, "TransStatusServlet.Log.CoundNotFindSpecTrans", transName)));
        } else {
          out.println(
              "<H1>"
                  + Encode.forHtml(
                      BaseMessages.getString(
                          PKG, "TransStatusServlet.Log.CoundNotFindTrans", transName))
                  + "</H1>");
          out.println(
              "<a href=\""
                  + convertContextPath(GetStatusServlet.CONTEXT_PATH)
                  + "\">"
                  + BaseMessages.getString(PKG, "TransStatusServlet.BackToStatusPage")
                  + "</a><p>");
        }
      }
    } catch (Exception ex) {
      if (useXML) {
        out.println(
            new WebResult(
                WebResult.STRING_ERROR,
                BaseMessages.getString(
                    PKG,
                    "PrepareExecutionTransServlet.Error.UnexpectedError",
                    Const.CR + Const.getStackTracker(ex))));

      } else {
        out.println("<p>");
        out.println("<pre>");
        out.println(Encode.forHtml(Const.getStackTracker(ex)));
        out.println("</pre>");
      }
    }

    if (!useXML) {
      out.println("<p>");
      out.println("</BODY>");
      out.println("</HTML>");
    }
  }
 @Override
 public void setStringValue(String value) {
   this.value = Encode.forHtml(value);
 }
  private String buildNotificationGroupsHtml() {

    StringBuilder html = new StringBuilder();

    StatsAggHtmlFramework statsAggHtmlFramework = new StatsAggHtmlFramework();
    String htmlHeader = statsAggHtmlFramework.createHtmlHeader("StatsAgg - " + PAGE_NAME, "");

    StringBuilder htmlBodyStringBuilder = new StringBuilder();
    htmlBodyStringBuilder.append(
        "<div id=\"page-content-wrapper\">\n"
            + "<!-- Keep all page content within the page-content inset div! -->\n"
            + "<div class=\"page-content inset statsagg_page_content_font\">\n"
            + "  <div class=\"content-header\"> \n"
            + "    <div class=\"pull-left content-header-h2-min-width-statsagg\"> <h2> "
            + PAGE_NAME
            + " </h2> </div>\n"
            + "    <div class=\"pull-right \">\n"
            + "     <a href=\"CreateNotificationGroup\" class=\"btn btn-primary statsagg_page_content_font\">Create New Notification Group <i class=\"fa fa-long-arrow-right\"></i></a> \n"
            + "    </div>"
            + "  </div>"
            + "  <table id=\"NotificationGroupsTable\" style=\"display:none\" class=\"table table-bordered table-hover \">\n"
            + "    <thead>\n"
            + "      <tr>\n"
            + "        <th>Notification Group Name</th>\n"
            + "        <th>Email addresses</th>\n"
            + "        <th>Operations</th>\n"
            + "      </tr>\n"
            + "    </thead>\n"
            + "    <tbody>\n");

    AlertsDao alertsDao = new AlertsDao();
    Set<Integer> notificationGroupIdsAssociatedWithAlerts =
        alertsDao.getAllDistinctNotificationGroupIds();
    NotificationGroupsDao notificationGroupsDao = new NotificationGroupsDao();
    List<NotificationGroup> notificationGroups =
        notificationGroupsDao.getAllDatabaseObjectsInTable();

    for (NotificationGroup notificationGroup : notificationGroups) {

      String notificationGroupDetails =
          "<a href=\"NotificationGroupDetails?Name="
              + StatsAggHtmlFramework.urlEncode(notificationGroup.getName())
              + "\">"
              + StatsAggHtmlFramework.htmlEncode(notificationGroup.getName())
              + "</a>";

      StringBuilder emailAddressesOutput = new StringBuilder();
      String[] emailAddresses = StringUtils.split(notificationGroup.getEmailAddresses(), ",");
      if ((emailAddresses != null) && (emailAddresses.length != 0)) {
        for (int i = 0; i < emailAddresses.length; i++) {
          String trimmedEmailAddress = emailAddresses[i].trim();
          emailAddressesOutput.append(trimmedEmailAddress);
          if ((i + 1) != emailAddresses.length) emailAddressesOutput.append(", ");
        }
      }

      String alter =
          "<a href=\"CreateNotificationGroup?Operation=Alter&amp;Name="
              + StatsAggHtmlFramework.urlEncode(notificationGroup.getName())
              + "\">alter</a>";

      List<KeyValue> cloneKeysAndValues = new ArrayList<>();
      cloneKeysAndValues.add(new KeyValue("Operation", "Clone"));
      cloneKeysAndValues.add(
          new KeyValue("Name", Encode.forHtmlAttribute(notificationGroup.getName())));
      String clone =
          StatsAggHtmlFramework.buildJavaScriptPostLink(
              "Clone_" + notificationGroup.getName(),
              "NotificationGroups",
              "clone",
              cloneKeysAndValues);

      List<KeyValue> testKeysAndValues = new ArrayList<>();
      testKeysAndValues.add(new KeyValue("Operation", "Test"));
      testKeysAndValues.add(
          new KeyValue("Name", Encode.forHtmlAttribute(notificationGroup.getName())));
      String test =
          StatsAggHtmlFramework.buildJavaScriptPostLink(
              "Test_" + notificationGroup.getName(),
              "NotificationGroups",
              "test",
              testKeysAndValues,
              true,
              "Are you sure you want to send a test email alert to \\'"
                  + Encode.forJavaScript(notificationGroup.getName())
                  + "\\'?");

      List<KeyValue> removeKeysAndValues = new ArrayList<>();
      removeKeysAndValues.add(new KeyValue("Operation", "Remove"));
      removeKeysAndValues.add(
          new KeyValue("Name", Encode.forHtmlAttribute(notificationGroup.getName())));
      String remove =
          StatsAggHtmlFramework.buildJavaScriptPostLink(
              "Remove_" + notificationGroup.getName(),
              "NotificationGroups",
              "remove",
              removeKeysAndValues,
              true,
              "Are you sure you want to remove this notification group?");

      htmlBodyStringBuilder
          .append("<tr>\n")
          .append("<td class=\"statsagg_force_word_break\">")
          .append(notificationGroupDetails)
          .append("</td>\n")
          .append("<td class=\"statsagg_force_word_break\">")
          .append(StatsAggHtmlFramework.htmlEncode(emailAddressesOutput.toString()))
          .append("</td>\n")
          .append("<td>")
          .append(alter)
          .append(", ")
          .append(clone)
          .append(", ")
          .append(test);

      if (notificationGroupIdsAssociatedWithAlerts == null)
        htmlBodyStringBuilder.append(", ").append(remove);
      else if (!notificationGroupIdsAssociatedWithAlerts.contains(notificationGroup.getId()))
        htmlBodyStringBuilder.append(", ").append(remove);

      htmlBodyStringBuilder.append("</td>\n").append("</tr>\n");
    }

    htmlBodyStringBuilder.append(
        ""
            + "</tbody>\n"
            + "<tfoot> \n"
            + "  <tr>\n"
            + "    <th></th>\n"
            + "    <th></th>\n"
            + "    <th></th>\n"
            + "  </tr>\n"
            + "</tfoot>"
            + "</table>\n"
            + "</div>\n"
            + "</div>\n");

    String htmlBody = (statsAggHtmlFramework.createHtmlBody(htmlBodyStringBuilder.toString()));

    html.append("" + "<!DOCTYPE html>\n" + "<html>\n")
        .append(htmlHeader)
        .append(htmlBody)
        .append("</html>");

    return html.toString();
  }
 public OWSException(int httpCode, String exceptionCode, String locator, String exceptionText) {
   this.httpCode = httpCode;
   this.exceptionCode = Encode.forXml(exceptionCode);
   this.locator = Encode.forXml(locator);
   this.exceptionText = Encode.forXml(exceptionText);
 }