Package com.mockey.model

Examples of com.mockey.model.Service


        try {
            Long serviceId = new Long(req.getParameter("serviceId"));
            int hangTime = Integer.parseInt(req.getParameter("hangTime"));
            int serviceResponseType = Integer.parseInt(req.getParameter("serviceResponseType"));
            Long defaultScenarioId = Long.parseLong(req.getParameter("scenario"));
            Service service = store.getServiceById(serviceId);
            service.setServiceResponseType(serviceResponseType);
            service.setHangTime(hangTime);
            service.setDefaultScenarioId(defaultScenarioId);
            store.saveOrUpdateService(service);
            String filter = req.getParameter("filter");
            if(filter!=null && "yes".equals(filter)){
                req.setAttribute("filter", "yes");
                List<Service> list = new ArrayList<Service>();
View Full Code Here


    JSONObject jsonObject = new JSONObject();
    try {
      if ("clear_last_visit".equalsIgnoreCase(action)) {
        if (serviceId != null && scenarioId != null) {
          Service service = store.getServiceById(new Long(serviceId));
          Scenario scenario = service
              .getScenario(new Long(scenarioId));
          scenario.setLastVisit(null);
          service.saveOrUpdateScenario(scenario);
          store.saveOrUpdateService(service);

        } else if (serviceId != null) {
          Service service = store.getServiceById(new Long(serviceId));
          service.setLastVisit(null);
          store.saveOrUpdateService(service);
        } else if (servicePlanId != null) {
          ServicePlan servicePlan = store
              .getServicePlanById(new Long(servicePlanId));
          servicePlan.setLastVisit(null);
View Full Code Here

    try {
      Long serviceId = new Long(req.getParameter("serviceId"));
      Long scenarioId = null;
      scenarioId = new Long(req.getParameter("scenarioId"));
      Service service = store.getServiceById(serviceId);
      Scenario scenario = service.getScenario(scenarioId);
      req.setAttribute("service", service);
      req.setAttribute("scenario", scenario);
    } catch (Exception e) {
      logger.debug("Unable to retrieve a Service of ID: "
          + req.getParameter("serviceId"));
View Full Code Here

      // then we'll create a new Scenario
      // for this service.
    }

    // Get the service.
    Service service = store.getServiceById(serviceId);

    // DELETE scenario logic
    if (req.getParameter("deleteScenario") != null && serviceId != null
        && scenarioId != null) {
      try {

        service.deleteScenario(scenarioId);
        store.saveOrUpdateService(service);
      } catch (Exception e) {
        // Just in case an invalid service ID
        // or scenario ID were past in.
      }
      resp.setContentType("application/json");
      PrintWriter out = resp.getWriter();
      JSONObject result = new JSONObject();
      JSONObject message = new JSONObject();
      try {
        result.put("result", message);
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      out.println(result.toString());
      out.flush();
      out.close();
      return;
    }

    Scenario scenario = null;

    // ************************************************
    // HACK A: if renaming an existing Scenario Name, then
    // we need to update this Service's Scenario Name in a
    // Service Plan. NOTE:
    // * we can't ask the Service to update the Plan because it doesn't
    // know about it.
    // * we can't ask the Store to update the Plan because it doesn't
    // know about the Scenario's 'old' name, only this Servlet does!
    // Hence, we do it here via 'newName' and 'oldName'.
    // ************************************************
    String oldName = null;
    String newName = null;
    try {
      scenario = service.getScenario(new Long(req
          .getParameter("scenarioId")));
      // ***************** HACK A ****************
      oldName = scenario.getScenarioName();
      // *****************************************
    } catch (Exception e) {
      //
    }

    // CREATE OR UPDATE OF SCENARIO
    // If scenario is null, that means we're creating,
    // not updating
    if (scenario == null) {
      scenario = new Scenario();
    }

    String scenarioName = req.getParameter("scenarioName");
    if (scenarioName == null || scenarioName.trim().length() == 0) {
      // Let's be nice and make up a name.
      scenarioName = "Scenario for " + service.getServiceName()
          + "(name auto-generated)";
    }
    // ***************** HACK A ****************
    newName = scenarioName;
    // *****************************************

    scenario.setScenarioName(scenarioName);

    if (req.getParameter("tag") != null) {
      scenario.setTag(req.getParameter("tag"));
    }

    if (req.getParameter("httpResponseStatusCode") != null) {
      try {
        String v = req.getParameter("httpResponseStatusCode");
        int statusCodeVal = Integer.parseInt(v);
        scenario.setHttpResponseStatusCode(statusCodeVal);
      } catch (Exception e) {

      }
    }
   
    if (req.getParameter("httpMethodType") != null) {
      try {
        String v = req.getParameter("httpMethodType");
        scenario.setHttpMethodType(v);
      } catch (Exception e) {

      }
    }

    if (req.getParameter("responseHeader") != null) {
      String responseHeader = req.getParameter("responseHeader");
      if (responseHeader != null) {
        scenario.setResponseHeader(responseHeader);
      }

    }

    if (req.getParameter("responseMessage") != null) {
      scenario.setResponseMessage(req.getParameter("responseMessage"));
    }
    if (req.getParameter("matchStringArg") != null) {
      scenario.setMatchStringArg(req.getParameter("matchStringArg"));
    }

    String matchArgAsRegexBoolVal = req
        .getParameter("matchStringArgEvaluationRulesFlag");
    if (matchArgAsRegexBoolVal != null) {
      try {
        scenario.setMatchStringArgEvaluationRulesFlag(Boolean
            .parseBoolean(matchArgAsRegexBoolVal));
      } catch (Exception t) {
        logger.error(
            "Unable to parse the Scenario match-to-be-used-as-a-regex flag, which should be 'true' or 'false' but was  "
                + matchArgAsRegexBoolVal, t);
      }
    }

    // VALIDATION
    Map<String, String> errorMap = ScenarioValidator.validate(scenario);

    if ((errorMap != null) && (errorMap.size() == 0)) {

      // If creating a Scenario, then the returned scenario
      // will now have an id. If updating scenario, then
      // scenario ID remains the same.
      scenario = service.saveOrUpdateScenario(scenario);

      // Make this the default 'error response' scenario
      // for the service
      String v = req.getParameter("errorScenario");
      if (v != null && "true".equalsIgnoreCase(v.trim())) {
        service.setErrorScenarioId(scenario.getId());
      } else if (service.getErrorScenarioId() == scenario.getId()) {
        service.setErrorScenarioId(null);
      }

      // Make this the default universal 'error response',
      // for all services defined in Mockey.
      v = req.getParameter("universalErrorScenario");
      if (v != null && "true".equalsIgnoreCase(v.trim())) {
        ScenarioRef scenarioRef = new ScenarioRef(scenario.getId(),
            scenario.getServiceId());
        store.setUniversalErrorScenarioRef(scenarioRef);

      } else if (store.getUniversalErrorScenario() != null) {
        store.setUniversalErrorScenarioRef(null);
      }

      store.saveOrUpdateService(service);

      // ***************** HACK A ****************
      if (newName != null && oldName != null
          && !oldName.trim().equals(newName.trim())) {
        // OK, we had an existing Service Scenario with a name change.
        // Let's update the appropriate Service Plan.
        store.updateServicePlansWithNewScenarioName(serviceId, oldName, newName);
       
      }
      // *****************************************
      resp.setContentType("application/json");
      PrintWriter out = resp.getWriter();

      JSONObject object = new JSONObject();
      JSONObject resultObject = new JSONObject();
      try {

        object.put("success", "Scenario updated");
        object.put("scenarioId", scenario.getId().toString());
        object.put("serviceId", service.getId().toString());
        resultObject.put("result", object);
      } catch (JSONException e1) {
        e1.printStackTrace();
      }
      out.println(resultObject);
View Full Code Here

      } else if ("delete_tag_from_store".equals(action)) {
        store.deleteTagFromStore(tag);
        jsonObject.put("success", "Deleted tag from all things.");

      } else if ("delete_tag_from_service".equals(action)) {
        Service service = store.getServiceById(new Long(serviceId));

        service.removeTagFromList(tag);
        store.saveOrUpdateService(service);
        jsonObject.put("success", "Deleted tag from Service.");

      } else if ("delete_tag_from_service_plan".equals(action)) {
        ServicePlan servicePlan = store.getServicePlanById(new Long(
            servicePlanId));

        servicePlan.removeTagFromList(tag);
        store.saveOrUpdateServicePlan(servicePlan);

        jsonObject.put("success", "Deleted tag from Service Plan.");

      } else if ("delete_tag_from_scenario".equals(action)) {
        Service service = store.getServiceById(new Long(serviceId));

        Scenario scenario = service.getScenario(new Long(scenarioId));
        scenario.removeTagFromList(tag);
        service.saveOrUpdateScenario(scenario);
        store.saveOrUpdateService(service);
        jsonObject.put("success", "Deleted tag from Scenario.");

      } else if ("update_service_tag".equals(action)) {
        Service service = store.getServiceById(new Long(serviceId));

        service.clearTagList();
        service.addTagToList(tag);
        store.saveOrUpdateService(service);
        jsonObject.put("success", "Updated tag(s) for this Service.");

      } else if ("update_scenario_tag".equals(action)) {
        Service service = store.getServiceById(new Long(serviceId));

        Scenario scenario = service.getScenario(new Long(scenarioId));
        scenario.clearTagList();
        scenario.addTagToList(tag);
        service.saveOrUpdateScenario(scenario);
        store.saveOrUpdateService(service);
        jsonObject.put("success", "Updated tag(s) for this Scenario.");

      }

      // PRESENT STATE
      //
      // OK, now that things are up to date (if any action occurred),
      // let's present the state in the JSON
      // Why get the Service again? Because, we could have removed/edited
      // the tag information from one of the steps above.
      if (serviceId != null) {
        Service service = store.getServiceById(new Long(serviceId));
        jsonObject.put("serviceId", "" + serviceId);

        if (scenarioId != null) {
          Scenario scenario = service
              .getScenario(new Long(scenarioId));
          jsonObject.put("scenarioId", "" + scenario.getId());
          jsonObject.put("tag", "" + scenario.getTag());
        } else {
          jsonObject.put("tag", "" + service.getTag());
        }
      }

    } catch (Exception e) {
      logger.debug("Unable to manage tag '" + tag + "' with action '"
View Full Code Here

   */
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    Long serviceId = new Long(req.getParameter("serviceId"));
    Service service = store.getServiceById(serviceId);
    req.setAttribute("service", service);
    RequestDispatcher dispatch = req
        .getRequestDispatcher("/service_scenario_list.jsp");
    dispatch.forward(req, resp);
  }
View Full Code Here

  private ServicePlan createOrUpdatePlan(ServicePlan servicePlan, String[] serviceIdArray) {
    List<PlanItem> planItemList = new ArrayList<PlanItem>();
    if (serviceIdArray != null) {
      for (String serviceId : serviceIdArray) {

        Service service = store.getServiceById(new Long(serviceId));

        PlanItem planItem = new PlanItem();
        planItem.setHangTime(service.getHangTime());
        planItem.setServiceName(service.getServiceName());

        planItem.setScenarioName(service.getDefaultScenarioName());
        planItem.setServiceResponseType(service.getServiceResponseType());
        planItemList.add(planItem);

      }
    }
    servicePlan.setPlanItemList(planItemList);
View Full Code Here

    String[] replacementArray = req.getParameterValues("replacement[]");
    JSONObject successOrFail = new JSONObject();
    if (matchPattern != null && replacementArray != null) {

      for (Long serviceId : store.getServiceIds()) {
        Service service = store.getServiceById(serviceId);
        List<Url> newUrlList = new ArrayList<Url>();
        // Build a list of real Url objects.
        for (Url realUrl : service.getRealServiceUrls()) {
          for (String replacement : replacementArray) {
            // We don't want to inject empty string match
            if (replacement.trim().length() > 0) {
              Url newUrl = new Url(realUrl.getFullUrl()
                  .replaceAll(matchPattern, replacement));
              if (!service.hasRealServiceUrl(newUrl)) {
                newUrlList.add(newUrl);
                // Note: you should not save or update
                // the realServiceUrl or service while
                // iterating through the list itself, or you'll
                // get
                // a java.util.ConcurrentModificationException
                // Wait until 'after'
              }
            }
          }
        }
        // Save/update this new Url object list.
        for (Url newUrl : newUrlList) {
          service.saveOrUpdateRealServiceUrl(newUrl);
        }

        // Now update the service.
        store.saveOrUpdateService(service);
      }
View Full Code Here

   */
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String[] realSrvUrl = req.getParameterValues("realServiceUrl[]");

    Service service = new Service();

    Long serviceId = null;
    // ************************************************
    // HACK A: if renaming an existing Service Name, then
    // we need to update this Service's Name in a
    // Service Plan.
    // ************************************************
    String oldName = null;
    String newName = null;
    try {
      serviceId = new Long(req.getParameter("serviceId"));
      service = store.getServiceById(serviceId);
      oldName = service.getServiceName();
    } catch (Exception e) {
      // Do nothing
    }
    if (service == null) {
      service = new Service();
    }
    // NEW REAL URL LIST
    // 1. Overwrite list of predefined URLs
    // 2. Ensure non-empty trim String for new Url objects.
    if (realSrvUrl != null) {
      List<Url> newUrlList = new ArrayList<Url>();
      for (int i = 0; i < realSrvUrl.length; i++) {
        String url = realSrvUrl[i];
        if (url.trim().length() > 0) {

          newUrlList.add(new Url(realSrvUrl[i].trim()));
        }

      }
      // Before we ADD new URLS, let's start with a clean list.
      // Why? In case the user removes the URL within the form,
      // then it will be an 'empty' value.
      service.clearRealServiceUrls();

      // Now we add.
      for (Url urlItem : newUrlList) {
        service.saveOrUpdateRealServiceUrl(urlItem);
      }
    }

    // UPDATE HANGTIME - optional
    try {
      service.setHangTime(Integer.parseInt(req.getParameter("hangTime")));

    } catch (Exception e) {
      // DO NOTHING
    }

    // NAME - optional
    if (req.getParameter("serviceName") != null) {
      service.setServiceName(req.getParameter("serviceName"));
      newName = service.getServiceName();
    }

    // TAG - optional
    if (req.getParameter("tag") != null) {
      service.setTag(req.getParameter("tag"));
    }

    // REQUEST INSPECTION rules in JSON format. - optional
    if (req.getParameter("requestInspectorJsonRules") != null) {
      service.setRequestInspectorJsonRules(req.getParameter(
          "requestInspectorJsonRules").trim());
    }
    // REQUEST INSPECTION enable flag - optional
    if (req.getParameter("requestInspectorJsonRulesEnableFlag") != null) {
      try {
        service.setRequestInspectorJsonRulesEnableFlag(new Boolean(req
            .getParameter("requestInspectorJsonRulesEnableFlag"))
            .booleanValue());
      } catch (Exception e) {
        logger.error("Json Rule Enable flag has an invalid format.", e);
      }
    }

    // REQUEST SCHEMA rules in JSON format. - optional
    if (req.getParameter("responseSchema") != null) {
      service.setResponseSchema(req.getParameter("responseSchema").trim());
    }
    // RESPONSE SCHEMA enable flag - optional
    if (req.getParameter("responseSchemaEnableFlag") != null) {
      try {
        service.setResponseSchemaFlag(new Boolean(req
            .getParameter("responseSchemaEnableFlag"))
            .booleanValue());
      } catch (Exception e) {
        logger.error("Json Rule Enable flag has an invalid format.", e);
      }
    }
    // Last visit
    if (req.getParameter("lastVisit") != null) {
      try {
        String lastvisit = req.getParameter("lastVisit");
        if (lastvisit.trim().length() > 0
            && !"mm/dd/yyyy".equals(lastvisit.trim().toLowerCase())) {
          Date f = formatter.parse(lastvisit);
          service.setLastVisit(f.getTime());
        } else {
          service.setLastVisit(null);
        }
      } catch (Exception e) {
        logger.error("Last visit has an invalid format. Should be "
            + DATE_FORMAT, e);
      }

    }
    String classNameForRequestInspector = req
        .getParameter("requestInspectorName");
    if (classNameForRequestInspector != null
        && classNameForRequestInspector.trim().length() > 0) {
      /**
       * OPTIONAL See if we can create an instance of a request inspector.
       * If yes, then set the service to the name.
       */
      try {
        Class<?> clazz = Class.forName(classNameForRequestInspector);
        if (!clazz.isInterface()
            && IRequestInspector.class.isAssignableFrom(clazz)) {
          service.setRequestInspectorName(classNameForRequestInspector);
        } else {
          service.setRequestInspectorName("");
        }

      } catch (ClassNotFoundException t) {
        logger.error("Service setup: unable to find class '"
            + classNameForRequestInspector + "'", t);
      }

    }

    // DESCRIPTION - optional
    if (req.getParameter("description") != null) {
      service.setDescription(req.getParameter("description"));
    }

    // MOCK URL - optional
    if (req.getParameter("url") != null) {
      service.setUrl(req.getParameter("url"));
    }

    Map<String, String> errorMap = ServiceValidator.validate(service);

    if ((errorMap != null) && (errorMap.size() == 0)) {
      // no errors, so create service.

      Service updatedService = store.saveOrUpdateService(service);
      Util.saveSuccessMessage("Service updated.", req);
      // ***************** HACK A ****************
      if (newName != null && oldName != null
          && !oldName.trim().equals(newName.trim())) {
        // OK, we had an existing Service Scenario with a name change.
        // Let's update the appropriate Service Plan.
        store.updateServicePlansWithNewServiceName(oldName, newName);
      }
      // *****************************************
      String redirectUrl = Url.getContextAwarePath("/setup?serviceId="
          + updatedService.getId(), req.getContextPath());
      resp.setContentType("application/json");
      PrintWriter out = resp.getWriter();
      String resultingJSON = "{ \"result\": { \"redirect\": \""
          + redirectUrl + "\"}}";
      out.println(resultingJSON);
View Full Code Here

    String serviceResponseType = req
        .getParameter(ServiceConfigurationAPI.API_SERVICE_RESPONSE_TYPE);
    String defaultUrlIndex = req.getParameter("defaultUrlIndex");
    String transientState = req
        .getParameter(ServiceConfigurationAPI.API_TRANSIENT_STATE);
    Service service = null;
    JSONObject jsonResultObject = new JSONObject();

    if (serviceId != null) {
      service = store.getServiceById(new Long(serviceId));
    } else {
      service = store.getServiceByName(serviceName);
    }

    try {
      service.setServiceResponseTypeByString(serviceResponseType);

    } catch (Exception e) {
      log.debug("Updating service without a 'service response type' value");
    }

    try {
      int index = Integer.parseInt(defaultUrlIndex);

      service.setDefaultRealUrlIndex(index - 1);
    } catch (Exception e) {

    }

    try {
      if (requestInspectorName != null) {
        service.setRequestInspectorName(requestInspectorName);
      }
    } catch (Exception e) {
      log.debug("Updating service without a 'request Inspector Name' value although, one was given:"
          + requestInspectorName);
    }

    // SCHEMA
    try {
      if (serviceResponseSchemaEnableFlag != null) {
        service.setResponseSchemaFlag(Boolean
            .valueOf(serviceResponseSchemaEnableFlag));
      }
    } catch (Exception e) {
      log.debug("Unable to set the Service JSON Schema enable flag. Non-null value given: "
          + serviceResponseSchemaEnableFlag);
    }

    try {
      if (serviceResponseSchema != null) {
        service.setResponseSchema(serviceResponseSchema);
      }
    } catch (Exception e) {
      // Do nothing.
    }
   
    // ******************************
    // REQUEST Evaluation Rules
    // ******************************
    try {
      if (reqInspectorRulesEnableFlag != null) {
        service.setRequestInspectorJsonRulesEnableFlag(Boolean
            .valueOf(reqInspectorRulesEnableFlag));
      }
    } catch (Exception e) {
      log.debug("Unable to set the Service JSON Schema enable flag. Non-null value given: "
          + serviceResponseSchemaEnableFlag);
    }
    try {
      if (reqInspectorRules != null) {
        service.setRequestInspectorJsonRules(reqInspectorRules);
      }
    } catch (Exception e) {
      // TODO: we should add JSON Schema to evaluate the rules. Right?
    }

    try {
      if (hangTime != null) {
        service.setHangTime((new Integer(hangTime).intValue()));
      }
    } catch (Exception e) {
      log.debug("Updating service without a 'hang time' value");
    }

    try {
      if (transientState != null) {
        service.setTransientState((new Boolean(transientState)));
      }
    } catch (Exception e) {
      log.debug("Updating service without a 'transient state' value");
    }

    try {
      if (scenarioId != null) {
        service.setDefaultScenarioId(new Long(scenarioId));
      } else {
        service.setDefaultScenarioByName(scenarioName);
      }
    } catch (Exception e) {
      // Do nothing.
      log.debug("Updating service without a 'default scenario ID' value");
    }
    service = store.saveOrUpdateService(service);

    resp.setContentType("application/json");
    PrintWriter out = resp.getWriter();

    JSONObject jsonResponseObject = new JSONObject();
    try {

      if (service != null) {

        jsonResultObject.put("success", "updated");
        jsonResultObject.put(ServiceConfigurationAPI.API_SERVICE_NAME,
            service.getServiceName());
        jsonResultObject.put(ServiceConfigurationAPI.API_SERVICE_ID,
            service.getId());
        jsonResultObject.put(
            ServiceConfigurationAPI.API_SERVICE_SCENARIO_ID,
            service.getDefaultScenarioId());
       
        jsonResultObject.put(
            ServiceConfigurationAPI.API_SERVICE_SCHEMA_ENABLE_FLAG,
            service.isResponseSchemaFlag());
       
        jsonResultObject.put(
            ServiceConfigurationAPI.API_SERVICE_REQUEST_INSPECTOR_RULES_ENABLE_FLAG,
            service.isRequestInspectorJsonRulesEnableFlag());
       
        jsonResultObject.put(
            ServiceConfigurationAPI.API_SERVICE_SCENARIO_NAME,
            service.getDefaultScenarioName());
        jsonResultObject.put(
            ServiceConfigurationAPI.API_SERVICE_RESPONSE_TYPE,
            service.getServiceResponseTypeAsString());
        jsonResultObject.put(
            ServiceConfigurationAPI.API_SERVICE_HANGTIME,
            service.getHangTime());
        jsonResultObject
            .put(ServiceConfigurationAPI.API_SERVICE_REQUEST_INSPECTOR_NAME,
                service.getRequestInspectorName());
        jsonResponseObject.put("result", jsonResultObject);
      } else {

        StringBuffer outputInfo = new StringBuffer();
        outputInfo.append(ServiceConfigurationAPI.API_SERVICE_ID + ":"
View Full Code Here

TOP

Related Classes of com.mockey.model.Service

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.