org.owasp.html.Sanitizers Java Examples

The following examples show how to use org.owasp.html.Sanitizers. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HtmlSanitizer.java    From cuba with Apache License 2.0 7 votes vote down vote up
/**
 * Init default policy factory that is used to produce HTML sanitizer policies that sanitize a sting of HTML.
 */
protected void initDefaultPolicyFactory() {
    policyFactory = new HtmlPolicyBuilder()
            .allowCommonInlineFormattingElements()
            .allowAttributes(FONT_COLOR_ATTRIBUTE_NAME).matching(FONT_COLOR_PATTERN).onElements(FONT)
            .allowAttributes(FONT_FACE_ATTRIBUTE_NAME).matching(FONT_FACE_PATTERN).onElements(FONT)
            .allowAttributes(FONT_SIZE_ATTRIBUTE_NAME).matching(FONT_SIZE_PATTERN).onElements(FONT)
            .allowAttributes(CLASS_ATTRIBUTE_NAME).matching(CLASS_PATTERN).globally()
            .allowStandardUrlProtocols().allowElements(A_ELEMENT_NAME)
            .allowAttributes(HREF_ATTRIBUTE_NAME).onElements(A_ELEMENT_NAME).requireRelNofollowOnLinks()
            .allowAttributes(TARGET_ATTRIBUTE_NAME).matching(true, TARGET_ATTRIBUTE_VALUES)
                .onElements(A_ELEMENT_NAME).requireRelsOnLinks(NOOPENNER_REL_VALUE, NOREFERRER_REL_VALUE)
            .allowStyling(CssSchema.withProperties(DEFAULT_WHITELIST))
            .allowStyling(CssSchema.withProperties(getAdditionalStylePolicies()))
            .toFactory()
            .and(Sanitizers.FORMATTING)
            .and(Sanitizers.BLOCKS)
            .and(Sanitizers.IMAGES)
            .and(Sanitizers.STYLES)
            .and(Sanitizers.TABLES);
}
 
Example #2
Source File: GetTestCaseList.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ITestCaseService testService = appContext.getBean(ITestCaseService.class);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    String test = policy.sanitize(httpServletRequest.getParameter("test"));
    JSONArray array = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    for (TestCase testcase : testService.findTestCaseByTest(test)) {
        array.put(testcase.getTestCase());
    }
    try {
        jsonObject.put("testcasesList", array);

        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().print(jsonObject.toString());
    } catch (JSONException exception) {
        LOG.warn(exception.toString());
    }
}
 
Example #3
Source File: findEnvironmentByCriteria.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws org.cerberus.exception.CerberusException
 * @throws org.json.JSONException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String system = policy.sanitize(request.getParameter("system"));
    String country = policy.sanitize(request.getParameter("country"));
    String application = policy.sanitize(request.getParameter("application"));
    
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ICountryEnvParamService ceService = appContext.getBean(ICountryEnvParamService.class);

    JSONArray array = new JSONArray();
    for (JSONObject ce : ceService.findActiveEnvironmentBySystemCountryApplication(system, country, application)) {
            array.put(ce);
    }
    response.setContentType("application/json");
    response.getWriter().print(array);
}
 
Example #4
Source File: MarkdownController.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@PostMapping("/")
public String markdownRenderer(@RequestBody String payload) {
  // Set up HTML renderer
  // https://github.com/atlassian/commonmark-java#extensions
  List<Extension> extensions =
      Arrays.asList(TablesExtension.create(), StrikethroughExtension.create());
  Parser parser = Parser.builder().extensions(extensions).build();
  Node document = parser.parse(payload);
  HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions).build();
  // Convert Markdown to HTML
  String converted = renderer.render(document);

  // Use prepackaged policies to sanitize HTML. Cusomized and tighter standards
  // are recommended.
  PolicyFactory policy =
      Sanitizers.FORMATTING
          .and(Sanitizers.BLOCKS)
          .and(Sanitizers.LINKS)
          .and(Sanitizers.IMAGES)
          .and(Sanitizers.TABLES);
  String safeHtml = policy.sanitize(converted);

  return safeHtml;
}
 
Example #5
Source File: Utils.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public static PolicyFactory sanitizer() {
	if (sanitizer == null) {
		sanitizer = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS).and(Sanitizers.IMAGES).and(Sanitizers.STYLES);
		PolicyFactory html = new HtmlPolicyBuilder()
			.allowElements("table", "tr", "td", "thead", "tbody", "th", "hr", "font", "button", "input", "select", "option", "video", "audio")
			.allowAttributes("class").globally()
			.allowAttributes("color").globally()
			.allowAttributes("bgcolor").globally()
			.allowAttributes("align").globally()
			.allowAttributes("target").globally()
			.allowAttributes("value").globally()
			.allowAttributes("name").globally()
			.allowAttributes("controls").globally()
			.allowAttributes("src").globally()
			.allowAttributes("autoplay").globally()
			.allowAttributes("muted").globally()
			.allowAttributes("loop").globally()
			.allowAttributes("poster").globally()
			.allowElements("a").requireRelNofollowOnLinks()
			.allowAttributes("href").onElements("a")
			.allowUrlProtocols("http", "https", "mailto", "chat")
			.toFactory();
		sanitizer = sanitizer.and(html);
	}
	return sanitizer;
}
 
Example #6
Source File: TestCaseActionExecutionDetail.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {

    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ITestCaseStepActionExecutionService testCaseExecutionDetailService = appContext.getBean(ITestCaseStepActionExecutionService.class);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    String test = policy.sanitize(httpServletRequest.getParameter("test"));
    String testcase = policy.sanitize(httpServletRequest.getParameter("testcase"));
    String country = policy.sanitize(httpServletRequest.getParameter("country"));


    JSONArray data = testCaseExecutionDetailService.lastActionExecutionDuration(test, testcase, country);

    try {


        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().print(data.toString());
    } catch (Exception e) {
        httpServletResponse.setContentType("text/html");
        httpServletResponse.getWriter().print(e.getMessage());
    }
}
 
Example #7
Source File: GetCountryForTestCase.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String testName = policy.sanitize(httpServletRequest.getParameter("test"));
    String testCaseName = policy.sanitize(httpServletRequest.getParameter("testCase"));

    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ITestCaseCountryService testCaseCountryService = appContext.getBean(ITestCaseCountryService.class);

    JSONArray array = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    for (String country : testCaseCountryService.findListOfCountryByTestTestCase(testName, testCaseName)) {
        array.put(country);
    }
    try {
        jsonObject.put("countriesList", array);

        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().print(jsonObject.toString());
    } catch (JSONException exception) {
        LOG.warn(exception.toString());
    }
}
 
Example #8
Source File: GetTestBySystem.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String system = policy.sanitize(request.getParameter("system"));
    
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ITestCaseService testService = appContext.getBean(ITestCaseService.class);

    JSONArray array = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    for (String test : testService.findTestWithTestCaseActiveAutomatedBySystem(system)) {
        array.put(test);
    }
    try {
        jsonObject.put("testsList", array);

        response.setContentType("application/json");
        response.getWriter().print(jsonObject.toString());
    } catch (JSONException exception) {
        LOG.warn(exception.toString());
    }
}
 
Example #9
Source File: ReadDocumentation.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse response) throws ServletException, IOException {
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IDocumentationService docService = appContext.getBean(IDocumentationService.class);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    JSONObject jsonResponse = new JSONObject();
    List<Documentation> result = new ArrayList<Documentation>();
    JSONObject format = new JSONObject();

    response.setContentType("application/json");
    response.setCharacterEncoding("utf8");

    String lang = ParameterParserUtil.parseStringParamAndSanitize(httpServletRequest.getParameter("lang"), "en");

    result = docService.findAllWithEmptyDocLabel(lang);
    format = docService.formatGroupByDocTable(result);
    try {
        jsonResponse.put("labelTable", format);
    } catch (JSONException ex) {
        LOG.warn(ex);
    }
    response.getWriter().print(jsonResponse.toString());
}
 
Example #10
Source File: DeleteTestCaseFromTestPage.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String[] tcToDelete = request.getParameterValues("test_testcase_delete");
    String testToDelete = policy.sanitize(request.getParameter("test_of_page"));

    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ITestCaseService tcService = appContext.getBean(ITestCaseService.class);
    ITestCaseStepService tcsService = appContext.getBean(ITestCaseStepService.class);
    try {
        for (String ttd : tcToDelete) {
            TestCase testCase = tcService.findTestCaseByKey(testToDelete, ttd);
            if (testCase != null) {
                List<TestCaseStep> tcsList = tcsService.getTestCaseStepUsingTestCaseInParamter(testCase.getTest(), testCase.getTestCase());
                if (tcsList != null && !tcsList.isEmpty()){
                    response.sendError(403, MessageGeneralEnum.GUI_TESTCASE_DELETE_USED_STEP.getDescription());
                    return;
                }
                tcService.deleteTestCase(testCase);
        
            } else {
                throw new CerberusException(new MessageGeneral(MessageGeneralEnum.NO_DATA_FOUND));
            }
        }
    } catch (CerberusException ex) {
        LOG.warn(ex);
    }

    response.sendRedirect("Test.jsp?stestbox="+testToDelete);
}
 
Example #11
Source File: SetTagToExecution.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ITestCaseExecutionService executionService = appContext.getBean(ITestCaseExecutionService.class);

    try {
        String id = policy.sanitize(request.getParameter("executionId"));
        String tag = policy.sanitize(request.getParameter("newTag"));
        executionService.setTagToExecution(Long.valueOf(id), tag);

        // Create Tag when exist.
        if (!StringUtil.isNullOrEmpty(tag)) {
            // We create or update it.
            ITagService tagService = appContext.getBean(ITagService.class);
            tagService.createAuto(tag, "", request.getRemoteUser(), null, null);
        }

        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet SetTagToExecution</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet SetTagToExecution at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    } catch (CerberusException ex) {
        LOG.warn(ex);
    } finally {
        out.close();
    }
}
 
Example #12
Source File: UpdateCampaign.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
private List<ScheduleEntry> getScheduleEntryListFromParameter(HttpServletRequest request, ApplicationContext appContext, String campaign, JSONArray json) throws JSONException {
    List<ScheduleEntry> scheList = new ArrayList<>();
    IScheduleEntryService scheService = appContext.getBean(IScheduleEntryService.class);
    IFactoryScheduleEntry scheFactory = appContext.getBean(IFactoryScheduleEntry.class);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding() == null ? "UTF-8" : request.getCharacterEncoding();
    for (int i = 0; i < json.length(); i++) {
        JSONObject tcsaJson = json.getJSONObject(i);
        // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
        boolean delete = tcsaJson.getBoolean("toDelete");
        String cronExpression = policy.sanitize(tcsaJson.getString("cronDefinition"));
        String active = policy.sanitize(tcsaJson.getString("active"));
        String strId = tcsaJson.getString("ID");
        String desc = tcsaJson.getString("description");
        String type = "CAMPAIGN";
        String name = campaign;

        int id;
        if (strId.isEmpty()) {
            id = 0;
        } else {
            try {
                id = Integer.parseInt(strId);
            } catch (NumberFormatException e) {
                LOG.warn("Unable to parse pool size: " + strId + ". Applying default value");
                id = 0;
            }
        }

        Timestamp timestampfactice = new Timestamp(System.currentTimeMillis());

        if (!delete) {
            ScheduleEntry sch = scheFactory.create(id, type, name, cronExpression, timestampfactice, active, desc, request.getRemoteUser(), timestampfactice, request.getRemoteUser(), timestampfactice);
            scheList.add(sch);
        }
    }
    return scheList;
}
 
Example #13
Source File: CreateTestDataLib.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
private List<TestDataLibData> getSubDataFromParameter(HttpServletRequest request, ApplicationContext appContext, int testDataLibId, JSONArray json) throws JSONException {
    List<TestDataLibData> tdldList = new ArrayList<>();
    IFactoryTestDataLibData tdldFactory = appContext.getBean(IFactoryTestDataLibData.class);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding() == null ? "UTF-8" : request.getCharacterEncoding();

    for (int i = 0; i < json.length(); i++) {
        JSONObject objectJson = json.getJSONObject(i);

        // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
        boolean delete = objectJson.getBoolean("toDelete");
        Integer testDataLibDataId = objectJson.getInt("testDataLibDataID");
        // Parameter that needs to be secured --> We SECURE+DECODE them
        // NONE
        // Parameter that we cannot secure as we need the html --> We DECODE them
        String subdata = ParameterParserUtil.parseStringParam(objectJson.getString("subData"), "");
        String encrypt = objectJson.getBoolean("encrypt") ? "Y" : "N";
        String value = ParameterParserUtil.parseStringParam(objectJson.getString("value"), "");
        String column = ParameterParserUtil.parseStringParam(objectJson.getString("column"), "");
        String parsingAnswer = ParameterParserUtil.parseStringParam(objectJson.getString("parsingAnswer"), "");
        String columnPosition = ParameterParserUtil.parseStringParam(objectJson.getString("columnPosition"), "");
        String description = ParameterParserUtil.parseStringParam(objectJson.getString("description"), "");

        if (!delete) {
            TestDataLibData tdld = tdldFactory.create(testDataLibDataId, testDataLibId, subdata, encrypt, value, column, parsingAnswer, columnPosition, description);
            tdldList.add(tdld);
        }
    }
    return tdldList;
}
 
Example #14
Source File: UpdateTestDataLib.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
private List<TestDataLibData> getSubDataFromParameter(HttpServletRequest request, ApplicationContext appContext, int testDataLibId, JSONArray json) throws JSONException {
    List<TestDataLibData> tdldList = new ArrayList<>();
    IFactoryTestDataLibData tdldFactory = appContext.getBean(IFactoryTestDataLibData.class);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding() == null ? "UTF-8" : request.getCharacterEncoding();

    for (int i = 0; i < json.length(); i++) {
        JSONObject objectJson = json.getJSONObject(i);

        // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
        boolean delete = objectJson.getBoolean("toDelete");
        Integer testDataLibDataId = objectJson.getInt("testDataLibDataID");
        String encrypt = objectJson.getBoolean("encrypt") ? "Y" : "N";
        // Parameter that needs to be secured --> We SECURE+DECODE them
        // NONE
        // Parameter that we cannot secure as we need the html --> We DECODE them
        String subdata = ParameterParserUtil.parseStringParam(objectJson.getString("subData"), "");
        String value = ParameterParserUtil.parseStringParam(objectJson.getString("value"), "");
        String column = ParameterParserUtil.parseStringParam(objectJson.getString("column"), "");
        String parsingAnswer = ParameterParserUtil.parseStringParam(objectJson.getString("parsingAnswer"), "");
        String columnPosition = ParameterParserUtil.parseStringParam(objectJson.getString("columnPosition"), "");
        String description = ParameterParserUtil.parseStringParam(objectJson.getString("description"), "");

        if (!delete) {
            TestDataLibData tdld = tdldFactory.create(testDataLibDataId, testDataLibId, subdata, encrypt, value, column, parsingAnswer, columnPosition, description);
            tdldList.add(tdld);
        }
    }
    return tdldList;
}
 
Example #15
Source File: FindInvariantByID.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String idName = policy.sanitize(request.getParameter("idName"));

    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    response.setContentType("application/json");
    response.setCharacterEncoding("utf8");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);

    IInvariantService invariantService = appContext.getBean(InvariantService.class);

    JSONArray array = new JSONArray();
    List<Invariant> lstInvariant = invariantService.readByIdName(idName);
    for (Invariant myInvariant : lstInvariant) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("value", myInvariant.getValue());
        jsonObject.put("description", myInvariant.getDescription());
        jsonObject.put("gp1", myInvariant.getGp1());
        jsonObject.put("gp2", myInvariant.getGp2());
        jsonObject.put("gp3", myInvariant.getGp3());
        array.put(jsonObject);
    }

    response.getWriter().print(array.toString());

}
 
Example #16
Source File: GetEnvironmentAvailable.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String testName = policy.sanitize(httpServletRequest.getParameter("test"));
    String testCaseName = policy.sanitize(httpServletRequest.getParameter("testCase"));
    String country = policy.sanitize(httpServletRequest.getParameter("country"));

    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ICountryEnvironmentService countryEnvironmentService = appContext.getBean(CountryEnvironmentService.class);

    JSONArray array = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    try {
        for (String[] strings : countryEnvironmentService.getEnvironmentAvailable(testName, testCaseName, country)) {
            JSONObject env = new JSONObject();
            env.put("environment", strings[0]);
            env.put("description", strings[0].concat(" With Build: ").concat(strings[1]).concat(" And Revision: ").concat(strings[2]));
            array.put(env);
        }

        jsonObject.put("envList", array);

        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().print(jsonObject.toString());
    } catch (JSONException exception) {
        LOG.warn(exception.toString());
    }
}
 
Example #17
Source File: GetTestCaseForTest.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String testName = policy.sanitize(httpServletRequest.getParameter("test"));
    String system = policy.sanitize(httpServletRequest.getParameter("system"));

    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ITestCaseService testService = appContext.getBean(ITestCaseService.class);

    JSONArray array = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    try {
        List<TestCase> tcaseList;
        if (system == null){
            tcaseList = testService.findTestCaseByTest(testName);
        } else{
            tcaseList = testService.findTestCaseActiveAutomatedBySystem(testName, system);
        }
        
        for (TestCase list : tcaseList) {
            JSONObject testCase = new JSONObject();
            testCase.put("testCase", list.getTestCase());
            testCase.put("description", list.getTestCase().concat(" [").concat(list.getApplication()).concat("] : ").concat(list.getDescription()));
            testCase.put("application", list.getApplication());
            array.put(testCase);
        }
        jsonObject.put("testCaseList", array);

        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().print(jsonObject.toString());
    } catch (JSONException exception) {
        LOG.warn(exception.toString());
    }
}
 
Example #18
Source File: ExportTestCase.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param httpServletRequest servlet request
 * @param httpServletResponse servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {
    try {
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        ITestCaseService testService = appContext.getBean(ITestCaseService.class);

        PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
        String test = policy.sanitize(httpServletRequest.getParameter("test"));
        String testcase = policy.sanitize(httpServletRequest.getParameter("testcase"));

        TestCase tcInfo = testService.findTestCaseByKeyWithDependency(test, testcase);

        // Java object to JSON string
        ObjectMapper mapper = new ObjectMapper();
        JSONObject jo = new JSONObject(mapper.writeValueAsString(tcInfo));
        jo.put("bugs", tcInfo.getBugs());

        JSONObject export = new JSONObject();
        export.put("version", Infos.getInstance().getProjectVersion());
        export.put("user", httpServletRequest.getUserPrincipal());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        export.put("date", formatter.format(new Date()));
        export.put("testCase", jo);

        httpServletResponse.setContentType("application/json");
        httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + test + "-" + testcase + ".json");
        // Nice formating the json result by putting indent 4 parameter.
        httpServletResponse.getOutputStream().print(export.toString(4));

    } catch (CerberusException | JSONException ex) {
        LOG.warn(ex);
    }
}
 
Example #19
Source File: Telegram.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public String sanitize(String text) {
	// Telegram does not support <br> but does support new lines.
	text = text.replace("<br/>", "\n");
	text = text.replace("<br>", "\n");
	text = text.replace("</br>", "");
	text = text.replace("<p/>", "\n");
	text = text.replace("<p>", "\n");
	text = text.replace("</p>", "");
	text = text.replace("<li>", "\n");
	text = text.replace("</li>", "");
	text = text.replace("<ul>", "");
	text = text.replace("</ul>", "\n");
	text = text.replace("<ol>", "");
	text = text.replace("</ol>", "\n");
	if (sanitizer == null) {
		sanitizer = new HtmlPolicyBuilder().allowElements(
				"b", "i", "strong", "code", "em", "pre").toFactory().and(Sanitizers.LINKS);
	}
	String result = sanitizer.sanitize(text);
	if (result.contains("&")) {
		// The sanitizer is too aggressive and escaping some chars.
		//result = result.replace("&#34;", "\"");
		result = result.replace("&#96;", "`");
		//result = result.replace("&#39;", "'");
		result = result.replace("&#64;", "@");
		result = result.replace("&#61;", "=");
		result = result.replace("&#43;", "+");
		result = result.replace("&amp;", "&");
	}
	return result;
}
 
Example #20
Source File: Example.java    From safe-html-types with Apache License 2.0 5 votes vote down vote up
public static void main(String[] argv) {
  SafeHtmlMint mint = SafeHtmlMint.fromPolicyFactory(
      Sanitizers.FORMATTING.and(Sanitizers.BLOCKS));
  for (String arg : argv) {
    SafeHtml html = mint.sanitize(arg);
    System.out.println(html.getSafeHtmlString());
  }
}
 
Example #21
Source File: UtilCodec.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public String sanitize(String original) {
    if (original == null) {
        return null;
    }
    PolicyFactory sanitizer = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS).and(Sanitizers.IMAGES).and(Sanitizers.LINKS).and(Sanitizers.STYLES);
    if (UtilProperties.getPropertyAsBoolean("owasp", "sanitizer.permissive.policy", false)) {
        sanitizer = sanitizer.and(PERMISSIVE_POLICY);
    }
    return sanitizer.sanitize(original);
}
 
Example #22
Source File: CreateBuildRevisionParameters.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws org.cerberus.exception.CerberusException
 * @throws org.json.JSONException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding() == null ? "UTF-8" : request.getCharacterEncoding();

    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    
    /**
     * Parsing and securing all required parameters.
     */
    // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
    // Parameter that needs to be secured --> We SECURE+DECODE them
    String build = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("build"), "", charset);
    String revision = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("revision"), "", charset);
    String release = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("release"), "", charset);
    String application = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("application"), "", charset);
    String project = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("project"), "", charset);
    String ticketidfixed = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("ticketidfixed"), "", charset);
    String bugidfixed = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("bugidfixed"), "", charset);
    String releaseowner = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("releaseowner"), "", charset);
    String subject = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("subject"), "", charset);
    String jenkinsbuildid = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("jenkinsbuildid"), "", charset);
    String mavenGroupID = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("mavengroupid"), "", charset);
    String mavenArtifactID = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("mavenartifactid"), "", charset);
    String mavenVersion = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("mavenversion"), "", charset);
    // Parameter that we cannot secure as we need the html --> We DECODE them
    String link = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("link"), "", charset);
    String repositoryUrl = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("repositoryurl"), "", charset);

    /**
     * Checking all constrains before calling the services.
     */
    if (false) {
        // No constrain on that Create operation.
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IBuildRevisionParametersService buildRevisionParametersService = appContext.getBean(IBuildRevisionParametersService.class);
        IFactoryBuildRevisionParameters buildRevisionParametersFactory = appContext.getBean(IFactoryBuildRevisionParameters.class);

        BuildRevisionParameters brpData = buildRevisionParametersFactory.create(0, build, revision, release, application, project, ticketidfixed, bugidfixed, link, releaseowner, subject, null, jenkinsbuildid, mavenGroupID, mavenArtifactID, mavenVersion, repositoryUrl);
        ans = buildRevisionParametersService.create(brpData);

        if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            /**
             * Object created. Adding Log entry.
             */
            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            logEventService.createForPrivateCalls("/CreateBuildRevisionParameters", "CREATE", "Create BuildRevisionParameters : ['" + application + "'|'" + build + "'|'" + revision + "']", request);
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();

}
 
Example #23
Source File: CreateTest.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws org.json.JSONException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);

    /**
     * Parsing and securing all required parameters.
     */
    String test = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("test"), "");
    String active = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Active"), "");
    String parentTest = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("ParentTest"), null);
    String description = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Description"), "");

    /**
     * Checking all constrains before calling the services.
     */
    if (test.isEmpty()) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Test")
                .replace("%OPERATION%", "Create")
                .replace("%REASON%", "Test name is missing!"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        ITestService testService = appContext.getBean(ITestService.class);
        IFactoryTest factoryTest = appContext.getBean(IFactoryTest.class);

        Test testData = factoryTest.create(test, description, active, parentTest, request.getUserPrincipal().getName(), null, null, null);
        ans = testService.create(testData);

        if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            /**
             * Object created. Adding Log entry.
             */
            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            IFactoryLogEvent factoryLogEvent = appContext.getBean(FactoryLogEvent.class);

            logEventService.createForPrivateCalls("/CreateTest", "CREATE", "Create Test : ['" + test + "']", request);
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
 
Example #24
Source File: GetStepInLibrary.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, CerberusException {
        PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
//        String system = policy.sanitize(request.getParameter("system"));
        String system = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("system"), null);
        String test = policy.sanitize(request.getParameter("test"));
        String testCase = policy.sanitize(request.getParameter("testCase"));
        String withTestCase = policy.sanitize(request.getParameter("withTestCase"));

        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        ITestCaseStepService testCaseStepService = appContext.getBean(ITestCaseStepService.class);
        ITestCaseService testCaseService = appContext.getBean(ITestCaseService.class);

        JSONArray array = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        try {
            List<TestCaseStep> tcsList;
            if (test.equals("") && testCase.equals("")) {
                tcsList = testCaseStepService.getStepLibraryBySystem(system);
            } else if (testCase.equals("")) {
                tcsList = testCaseStepService.getStepLibraryBySystemTest(system, test);
            } else {
                tcsList = testCaseStepService.getStepLibraryBySystemTestTestCase(system, test, testCase);
            }
            for (TestCaseStep list : tcsList) {
                JSONObject tcs = new JSONObject();
                tcs.put("test", list.getTest());
                tcs.put("testCase", list.getTestCase());
                tcs.put("step", list.getStep());
                tcs.put("sort", list.getSort());
                tcs.put("description", list.getDescription());
                if (list.getTestCaseObj() != null) {
                    tcs.put("tcdesc", list.getTestCaseObj().getDescription());
                    tcs.put("tcapp", list.getTestCaseObj().getApplication());
                }
                array.put(tcs);
            }
            jsonObject.put("testCaseSteps", array);

            response.setContentType("application/json");
            response.getWriter().print(jsonObject.toString());
        } catch (JSONException exception) {
            LOG.warn(exception.toString());
        }
    }
 
Example #25
Source File: UpdateTest.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws org.json.JSONException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    
    /**
     * Parsing and securing all required parameters.
     */
    String originalTest = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("originalTest"), "");
    String test = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("test"), "");
    String description = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Description"), "");
    String active = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Active"), "");
    String automated = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Automated"), "");

    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(test)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Test")
                .replace("%OPERATION%", "Update")
                .replace("%REASON%", "Test name (test) is missing"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        ITestService testService = appContext.getBean(ITestService.class);

        AnswerItem resp = testService.readByKey(originalTest);

        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem()!=null)) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Application")
                    .replace("%OPERATION%", "Update")
                    .replace("%REASON%", "Test does not exist."));
            ans.setResultMessage(msg);

        } else {
            /**
             * The service was able to perform the query and confirm the
             * object exist, then we can update it.
             */
            Test testData = (Test) resp.getItem();
            testData.setTest(test);
            testData.setDescription(description);
            testData.setActive(active);
            ans = testService.update(originalTest, testData);
            
              if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Update was successful. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/UpdateTest", "UPDATE", "Updated Test : ['" + originalTest + "']", request);
            }
        }

    }
     /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
 
Example #26
Source File: ReadScheduleEntry.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    AnswerList<ScheduleEntry> ans = new AnswerList<>();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);

    /**
     * Parsing and securing all required parameters.
     */
    String name = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("name"), "");
    /**
     * Checking all constrains before calling the services.
     */
    if (name.isEmpty()) {
        msg = new MessageEvent(MessageEventEnum.SCHEDULER_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "campaign")
                .replace("%OPERATION%", "Create")
                .replace("%REASON%", "Some mendatory fields are missing or iregular!"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IFactoryScheduleEntry factoryScheduleEntry = appContext.getBean(IFactoryScheduleEntry.class);
        IScheduleEntryService scheduleEntryService = appContext.getBean(IScheduleEntryService.class);
        ans = scheduleEntryService.readByName(name);
        if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {//the service was able to perform the query, then we should get all values
            for (ScheduleEntry sched : (List<ScheduleEntry>) ans.getDataList()) {
                jsonArray.put(convertScheduleEntrytoJSONObject(sched));
            }
        }

        if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            /**
             * Object created. Adding Log entry.
             */
            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            IFactoryLogEvent factoryLogEvent = appContext.getBean(FactoryLogEvent.class);
            IMyVersionService myVersionService = appContext.getBean(IMyVersionService.class);
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());
    jsonResponse.put("contentTable", jsonArray);

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();

}
 
Example #27
Source File: DeleteCountryEnvParam.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    
    /**
     * Parsing and securing all required parameters.
     */
    String system = policy.sanitize(request.getParameter("system"));
    String country = policy.sanitize(request.getParameter("country"));
    String environment = policy.sanitize(request.getParameter("environment"));

    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(system)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME)
                .replace("%OPERATION%", "Delete")
                .replace("%REASON%", "System is missing!"));
        ans.setResultMessage(msg);
    } else if (StringUtil.isNullOrEmpty(country)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME)
                .replace("%OPERATION%", "Delete")
                .replace("%REASON%", "Country is missing!"));
        ans.setResultMessage(msg);
    } else if (StringUtil.isNullOrEmpty(environment)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME)
                .replace("%OPERATION%", "Delete")
                .replace("%REASON%", "Environment is missing!"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        ICountryEnvParamService countryEnvParamService = appContext.getBean(ICountryEnvParamService.class);

        AnswerItem resp = countryEnvParamService.readByKey(system, country, environment);
        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem()!=null)) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME)
                    .replace("%OPERATION%", "Delete")
                    .replace("%REASON%", OBJECT_NAME + " does not exist."));
            ans.setResultMessage(msg);

        } else {
            /**
             * The service was able to perform the query and confirm the
             * object exist, then we can delete it.
             */
            CountryEnvParam cepData = (CountryEnvParam) resp.getItem();
            ans = countryEnvParamService.delete(cepData);

            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Delete was successful. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/DeleteCountryEnvParam", "DELETE", "Delete CountryEnvParam : ['" + system + "'|'" + country + "'|'" + environment + "']", request);
            }
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse.toString());
    response.getWriter().flush();

}
 
Example #28
Source File: CreateDeployType.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws org.cerberus.exception.CerberusException
 * @throws org.json.JSONException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    
    /**
     * Parsing and securing all required parameters.
     */
    String deploytype = policy.sanitize(request.getParameter("deploytype"));
    String description = policy.sanitize(request.getParameter("description"));

    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(deploytype)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Deploy Type")
                .replace("%OPERATION%", "Create")
                .replace("%REASON%", "Deploy Type name is missing!"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IDeployTypeService deployTypeService = appContext.getBean(IDeployTypeService.class);
        IFactoryDeployType factoryDeployType = appContext.getBean(IFactoryDeployType.class);

        DeployType deployTypeData = factoryDeployType.create(deploytype, description);
        ans = deployTypeService.create(deployTypeData);

        if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            /**
             * Object created. Adding Log entry.
             */
            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            logEventService.createForPrivateCalls("/CreateDeployType", "CREATE", "Create DeployType : ['" + deploytype + "']", request);
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();

}
 
Example #29
Source File: DeleteApplication.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    
    /**
     * Parsing and securing all required parameters.
     */
    String key = policy.sanitize(request.getParameter("application"));

    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(key)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Application")
                .replace("%OPERATION%", "Delete")
                .replace("%REASON%", "Application ID (application) is missing!"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IApplicationService applicationService = appContext.getBean(IApplicationService.class);

        AnswerItem resp = applicationService.readByKey(key);
        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem()!=null)) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Application")
                    .replace("%OPERATION%", "Delete")
                    .replace("%REASON%", "Application does not exist."));
            ans.setResultMessage(msg);

        } else {
            /**
             * The service was able to perform the query and confirm the
             * object exist, then we can delete it.
             */
            Application applicationData = (Application) resp.getItem();
            ans = applicationService.delete(applicationData);

            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Delete was successful. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/DeleteApplication", "DELETE", "Delete Application : ['" + key + "']", request);
            }
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse.toString());
    response.getWriter().flush();

}
 
Example #30
Source File: DeleteDeployType.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    
    /**
     * Parsing and securing all required parameters.
     */
    String key = policy.sanitize(request.getParameter("deploytype"));

    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(key)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Deploy Type")
                .replace("%OPERATION%", "Delete")
                .replace("%REASON%", "Deployement Type ID (deploytype) is missing."));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IDeployTypeService deployTypeService = appContext.getBean(IDeployTypeService.class);

        AnswerItem resp = deployTypeService.readByKey(key);
        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem()!=null)) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Deploy Type")
                    .replace("%OPERATION%", "Delete")
                    .replace("%REASON%", "Deploy Type does not exist."));
            ans.setResultMessage(msg);

        } else {
            /**
             * The service was able to perform the query and confirm the
             * object exist, then we can delete it.
             */
            DeployType deployTypeData = (DeployType) resp.getItem();
            ans = deployTypeService.delete(deployTypeData);

            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Delete was successful. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/DeleteDeployType", "DELETE", "Delete Deploy Type : ['" + key + "']", request);
            }
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse.toString());
    response.getWriter().flush();

}