@Test
  public final void testProcessSave() {
    try {

      MockHttpServletRequest request = new MockHttpServletRequest();
      MockHttpServletResponse response = new MockHttpServletResponse();

      // TargetInstance target = manager.getTargetInstance(5000L);

      request.getSession().setAttribute(TargetInstanceCommand.SESSION_MODE, true);
      request.getSession().setAttribute(Constants.GBL_SESS_EDIT_MODE, true);

      TargetInstanceCommand comm = new TargetInstanceCommand();
      comm.setCmd(TargetInstanceCommand.ACTION_EDIT);
      comm.setTargetInstanceId(5000L);

      Tab currTab = testInstance.getTabConfig().getTabs().get(0);
      assertTrue(currTab != null);
      BindException aError = new BindException(new TargetDefaultCommand(), null);
      testInstance.showForm(request, response, comm, aError);
      // context = testInstance.getEditorContext(request);
      // context.getTarget().setName("Test Target");
      // context.setParents(new ArrayList<GroupMemberDTO>());
      ModelAndView mav = testInstance.processSave(currTab, request, response, comm, aError);
      assertTrue(mav != null);
      assertTrue(mav.getViewName().equals("TargetInstanceQueue"));
      assertTrue(mav.getModel().get("page_message") != null);
      assertTrue(((String) mav.getModel().get("page_message")).startsWith("targetInstance.saved"));
    } catch (Exception e) {
      String message = e.getClass().toString() + " - " + e.getMessage();
      log.debug(message);
      fail(message);
    }
  }
Beispiel #2
0
  @Test
  public void editDocumentWithParams2() throws DocumentNotFoundException {

    final DocumentReference documentReference =
        newDocumentReference("hello.txt")
            .withDocumentClass("test")
            .withIndex("name", "Wangler")
            .build();

    when(documentService.findDocumentReference(1L)).thenReturn(documentReference);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("firstname", "Silvio");
    final ModelAndView modelAndView = controller.editDocument(1L, request);

    assertThat(modelAndView.getViewName(), is("import.successful"));
    assertThat(modelAndView.getModel().size(), is(1));
    assertThat(modelAndView.getModel().containsKey("doc"), is(true));
    final DocumentReference doc = (DocumentReference) modelAndView.getModel().get("doc");
    assertThat(doc, is(documentReference));
    assertThat(
        doc.getIndices().get(new TranslatableKey("name")).getValue().toString(), is("Wangler"));

    InOrder order = inOrder(documentService);

    order.verify(documentService).findDocumentReference(1L);
    order.verify(documentService, never()).updateIndices(documentReference);
    order.verifyNoMoreInteractions();
  }
  @Override
  public void beforeView(
      final HttpServletRequest request,
      final HttpServletResponse response,
      final ModelAndView modelAndView)
      throws Exception {

    if (modelAndView != null && modelAndView.getModel().containsKey("metatags")) {

      final List<MetaElementData> metaelements =
          ((List<MetaElementData>) modelAndView.getModel().get("metatags"));
      final UiExperienceLevel currentUiExperienceLevel = uiExperienceService.getUiExperienceLevel();
      if (UiExperienceLevel.DESKTOP.equals(currentUiExperienceLevel)) {
        if (!ResponsiveUtils.isResponsive()) {
          // Provide some hints to mobile browser even though this is not the mobile site -->
          metaelements.add(createMetaElement("HandheldFriendly", "True"));
          metaelements.add(createMetaElement("MobileOptimized", "970"));
          metaelements.add(
              createMetaElement("viewport", "width=970, target-densitydpi=160, maximum-scale=1.0"));
        }
      } else if (UiExperienceLevel.MOBILE.equals(currentUiExperienceLevel)) {
        // Provide some hints to mobile browser even though this is not the mobile site -->
        metaelements.add(createMetaElement("HandheldFriendly", "True"));
        metaelements.add(createMetaElement("MobileOptimized", "320"));
        metaelements.add(
            createMetaElement(
                "viewport",
                "width=device-width, target-densitydpi=160, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"));
        metaelements.add(createMetaElement("format-detection", "telephone=no"));
      }
    }
  }
  @Test
  public void testHandleHttpServletRequestHttpServletResponseObjectBindException() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    ArchiveCommand comm = new ArchiveCommand();
    comm.setHarvestResultNumber(1);
    comm.setTargetInstanceID(5001);
    BindException errors = new BindException(comm, "ArchiveCommand");

    ModelAndView mav = null;
    ;
    try {
      mav = testInstance.handle(request, response, comm, errors);
    } catch (Exception e) {
      fail(e.getMessage());
      return;
    }
    assertNotNull(mav);
    assertEquals("deposit-form-envelope", mav.getViewName());
    assertNotNull(mav.getModel().get(Constants.GBL_CMD_DATA));
    assertEquals(
        1, ((ArchiveCommand) mav.getModel().get(Constants.GBL_CMD_DATA)).getHarvestResultNumber());
    assertEquals(
        5001, ((ArchiveCommand) mav.getModel().get(Constants.GBL_CMD_DATA)).getTargetInstanceID());
    assertNull(mav.getModel().get("hasErrors"));
  }
  public void testProcess() throws Exception {

    Controller c = (Controller) applicationContext.getBean("peopleController");
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    HttpServletResponse response = new MockHttpServletResponse();

    request.addParameter("importStudents", "Import Students");

    ModelAndView mav =
        c.handleRequest((HttpServletRequest) request, (HttpServletResponse) response);
    Map m = mav.getModel();
    PeopleBacking p = (PeopleBacking) m.get("peopleBacking");

    MockPageContext ctx = new MockPageContext();
    ctx.setAttribute("peopleBacking", mav.getModel().get("peopleBacking"));
    request.setAttribute("peopleBacking", mav.getModel().get("peopleBacking"));

    List<ProcessErrors> errors =
        (List<ProcessErrors>)
            ExpressionEvaluationUtils.evaluate(
                "test", "${peopleBacking.processStudentsErrors}", List.class, ctx);

    for (ProcessErrors e : errors) {
      ctx.setAttribute("processErrors", e);
      log.debug(
          ExpressionEvaluationUtils.evaluate(
              "test", "${processErrors.message}", String.class, ctx));
    }
  }
Beispiel #6
0
  @Test
  @SuppressWarnings("unchecked")
  public void edit() throws Exception {

    final DocumentClass documentClass = new DocumentClass("hello");
    final DocumentReference documentReference =
        newDocumentReference("hello.txt").withDocumentClass(documentClass).build();

    when(documentService.findDocumentReference(1L)).thenReturn(documentReference);
    SortedSet<Attribute> attributes = new TreeSet<>();
    attributes.add(new Attribute("a", false, AttributeDataType.CURRENCY));
    attributes.add(new Attribute("b", false, AttributeDataType.STRING));
    when(documentService.findAttributes(documentClass)).thenReturn(attributes);

    final ModelAndView modelAndView = controller.editDocument(1L);

    assertThat(modelAndView.getViewName(), is("edit.doc"));
    assertThat(modelAndView.getModel().size(), is(2));
    assertThat(modelAndView.getModel().containsKey("doc"), is(true));
    assertThat((DocumentReference) modelAndView.getModel().get("doc"), is(documentReference));
    assertThat(modelAndView.getModel().containsKey("attributes"), is(true));
    assertThat(((SortedSet<Attribute>) modelAndView.getModel().get("attributes")).size(), is(2));

    InOrder order = inOrder(documentService);
    order.verify(documentService).findDocumentReference(1L);
    order.verify(documentService).findAttributes(documentReference.getDocumentClass());
    order.verifyNoMoreInteractions();
  }
  @Test
  public void testSpeciesAttributeValueByName() throws Exception {

    login("admin", "password", new String[] {Role.ADMIN});

    request.setMethod("POST");
    request.setRequestURI(request.getContextPath() + TrackerController.EDIT_URL);
    request.setParameter(BdrsWebConstants.PARAM_SURVEY_ID, survey.getId().toString());
    request.setParameter(
        WebFormAttributeParser.getParamKey("", attr), this.dropBear.getScientificName());

    ModelAndView mav = handle(request, response);

    Map<String, String> errorMap =
        (Map<String, String>) mav.getModel().get(TrackerController.MV_ERROR_MAP);
    Assert.assertNull("error map should be null", errorMap);

    Integer recId = (Integer) mav.getModel().get(RecordWebFormContext.MODEL_RECORD_ID);
    Assert.assertNotNull("rec id should not be null", recId);

    Record record = recordDAO.getRecord(recId);
    Assert.assertNotNull("record should not be null", record);

    Assert.assertEquals("wrong attribute value count", 1, record.getAttributes().size());

    AttributeValue av = (AttributeValue) record.getAttributes().toArray()[0];

    Assert.assertNotNull("species should not be null", av.getSpecies());

    Assert.assertEquals("wrong species id", av.getSpecies().getId(), this.dropBear.getId());
  }
  @Test
  public void testHandleRequestView() throws Exception {
    HelloController controller = new HelloController();
    ModelAndView modelAndView = controller.handleRequest(null, null);

    Assert.assertEquals("hello.jsp", modelAndView.getViewName());
    Assert.assertNotNull(modelAndView.getModel());
    String nowValue = (String) modelAndView.getModel().get("now");
    Assert.assertNotNull(nowValue);
  }
 @Test
 public void testGetCountryAll() throws Exception {
   ModelAndView modelAndView =
       mockMvc
           .perform(get("/countries_wfc.do"))
           .andExpect(status().isOk())
           .andReturn()
           .getModelAndView();
   assertNotNull(modelAndView.getModel().get("countries"));
   assertEquals(4, ((List) modelAndView.getModel().get("countries")).size());
 }
  @RequestMapping("/server.jsp")
  public ModelAndView serverInfo() {
    List<User> moderators = userDao.getModerators();

    ModelAndView mv = new ModelAndView("server");
    mv.getModel().put("moderators", moderators);

    List<User> correctors = userDao.getCorrectors();

    mv.getModel().put("correctors", correctors);

    return mv;
  }
Beispiel #11
0
  /**
   * Handles the request.
   *
   * @param httpServletRequest the http servlet request
   * @param httpServletResponse the http servlet response
   * @return the model and view
   * @throws Exception the exception
   */
  @RequestMapping(method = RequestMethod.GET)
  protected ModelAndView handleRequestInternal(
      final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse)
      throws Exception {
    final ModelAndView modelAndView = new ModelAndView(MONITORING_VIEW_STATISTICS);
    modelAndView.addObject("pageTitle", modelAndView.getViewName());
    modelAndView.addObject("availableProcessors", Runtime.getRuntime().availableProcessors());
    modelAndView.addObject("casTicketSuffix", casProperties.getHost().getName());
    modelAndView.getModel().putAll(getAvailability(httpServletRequest, httpServletResponse));
    modelAndView.addObject("startTime", this.upTimeStartDate.toLocalDateTime());

    modelAndView.getModel().putAll(getMemoryStats(httpServletRequest, httpServletResponse));
    return modelAndView;
  }
 @Test
 public void testHandleRequest() throws Exception {
   ModelAndView mav = c.handleRequest(null);
   Map m = mav.getModel();
   assertNotNull(m.get(Constants.USER_LIST));
   assertEquals("admin/userList", mav.getViewName());
 }
Beispiel #13
0
  @Test
  public void shouldFindTheLatestJobWhenJobStatusIsRequested() throws Exception {
    JobInstance job =
        JobInstanceMother.buildEndingWithState(JobState.Rescheduled, JobResult.Unknown, "config");
    job.assign("agent", new Date());

    JobInstance newJob =
        JobInstanceMother.buildEndingWithState(
            JobState.Building, JobResult.Unknown, "another_config");
    newJob.setId(2);
    newJob.assign("another_agent", new Date());

    String pipelineName = job.getPipelineName();
    String stageName = job.getStageName();

    when(jobInstanceService.buildByIdWithTransitions(job.getId())).thenReturn(job);
    when(jobDetailService.findMostRecentBuild(job.getIdentifier())).thenReturn(newJob);
    when(stageService.getBuildDuration(pipelineName, stageName, newJob))
        .thenReturn(new DurationBean(newJob.getId(), 5l));

    ModelAndView modelAndView =
        jobController.handleRequest(pipelineName, stageName, job.getId(), response);

    verify(jobInstanceService).buildByIdWithTransitions(job.getId());
    verify(jobDetailService).findMostRecentBuild(job.getIdentifier());
    verify(stageService).getBuildDuration(pipelineName, stageName, newJob);

    JsonValue json = from(((JsonList) modelAndView.getModel().get("json")).getJsonMap(0));

    JsonValue buildingInfo = json.getObject("building_info");

    assertThat(buildingInfo.getString("id"), is("2"));
    assertThat(buildingInfo.getString("last_build_duration"), is("5"));
  }
  @Test
  public void verifyOKWithState() throws Exception {
    final MockHttpServletRequest mockRequest =
        new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL);
    mockRequest.addParameter(OAuthConstants.TICKET, SERVICE_TICKET);
    final MockHttpSession mockSession = new MockHttpSession();
    mockSession.putValue(OAuthConstants.OAUTH20_CALLBACKURL, REDIRECT_URI);
    mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME);
    mockSession.putValue(OAuthConstants.OAUTH20_STATE, STATE);
    mockRequest.setSession(mockSession);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final ModelAndView modelAndView =
        oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(OAuthConstants.CONFIRM_VIEW, modelAndView.getViewName());
    final Map<String, Object> map = modelAndView.getModel();
    assertEquals(SERVICE_NAME, map.get("serviceName"));
    assertEquals(
        REDIRECT_URI
            + "?"
            + OAuthConstants.CODE
            + "="
            + SERVICE_TICKET
            + "&"
            + OAuthConstants.STATE
            + "="
            + STATE,
        map.get("callbackUrl"));
  }
 @Override
 public void postHandle(
     HttpServletRequest request,
     HttpServletResponse response,
     Object handler,
     ModelAndView modelAndView)
     throws Exception {
   if (modelAndView != null && !modelAndView.getViewName().startsWith("redirect:")) {
     FilterInvocation filterInvocation =
         new FilterInvocation(
             request,
             response,
             new FilterChain() {
               public void doFilter(ServletRequest request, ServletResponse response)
                   throws IOException, ServletException {
                 throw new UnsupportedOperationException();
               }
             });
     Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
     WebSecurityExpressionRoot sec =
         new WebSecurityExpressionRoot(authentication, filterInvocation);
     sec.setTrustResolver(new AuthenticationTrustResolverImpl());
     modelAndView.getModel().put("sec", sec);
   }
 }
  @Test
  public void verifyValidServiceTicketWithValidPgtAndProxyHandlerFailing() throws Exception {
    final TicketGrantingTicket tId =
        getCentralAuthenticationService()
            .createTicketGrantingTicket(TestUtils.getCredentialsWithSameUsernameAndPassword());
    final ServiceTicket sId =
        getCentralAuthenticationService().grantServiceTicket(tId.getId(), TestUtils.getService());

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", TestUtils.getService().getId());
    request.addParameter("ticket", sId.getId());
    request.addParameter("pgtUrl", "https://www.github.com");

    this.serviceValidateController.setProxyHandler(
        new ProxyHandler() {
          @Override
          public String handle(
              final Credential credential, final TicketGrantingTicket proxyGrantingTicketId) {
            return null;
          }

          @Override
          public boolean canHandle(final Credential credential) {
            return true;
          }
        });

    final ModelAndView modelAndView =
        this.serviceValidateController.handleRequestInternal(
            request, new MockHttpServletResponse());
    assertEquals(
        ServiceValidateController.DEFAULT_SERVICE_FAILURE_VIEW_NAME, modelAndView.getViewName());
    assertNull(modelAndView.getModel().get("pgtIou"));
  }
Beispiel #17
0
  public void postHandle(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      Object o,
      ModelAndView modelAndView)
      throws Exception {
    if (modelAndView == null) {
      // skip  resource requests
      return;
    }

    if (isDebugEnabled) {
      if (o instanceof HandlerMethod) {
        modelAndView.addObject("method", ((HandlerMethod) o).getMethod().toString());
      }
    }
    Map<String, Object> model = modelAndView.getModel();

    String view = getViewName(modelAndView);
    // making insertion inside of jsp
    model.put("TEMPLATE_BODY", prefix + view + suffix);

    modelAndView.setViewName("template/default");

    setTitle(model);
    model.put("js", jsInclude);
    model.put("css", cssInclude);
    model.put("status", parser.getConfig().isActive());
  }
  /**
   * Test located specimen feature can handle the underlying service returning null (indicating no
   * results)
   *
   * @throws Exception the exception
   */
  @Test
  public void testLocatedSpecimenFeature_NoResults() throws Exception {

    final String serviceUrl = "http://fake.com/wfs";
    final String featureId = "feature_id_thatdne";
    final String materialClass = "matclass";
    final YilgarnObservationRecord[] mockObservations = new YilgarnObservationRecord[] {};
    final YilgarnLocatedSpecimenRecord mockLocSpecRecord =
        context.mock(YilgarnLocatedSpecimenRecord.class);

    context.checking(
        new Expectations() {
          {
            oneOf(mockGeochemService).getLocatedSpecimens(serviceUrl, featureId);
            will(returnValue(null));

            allowing(mockLocSpecRecord).getMaterialClass();
            will(returnValue(materialClass));
            allowing(mockLocSpecRecord).getRelatedObservations();
            will(returnValue(mockObservations));
          }
        });

    ModelAndView modelAndView = controller.doLocatedSpecimenFeature(serviceUrl, featureId);
    Map<String, Object> model = modelAndView.getModel();
    Assert.assertNotNull(modelAndView);
    Assert.assertFalse((Boolean) model.get("success"));
  }
Beispiel #19
0
 @ExceptionHandler(value = NoSuchResourceException.class)
 public ModelAndView handle(Exception e) {
   ModelAndView mv = new ModelAndView();
   mv.getModel().put("e", e);
   mv.setViewName("noSuchResource");
   return mv;
 }
  /**
   * Get a Spring {@link ModelAndView} prepopulated with useful objects.
   *
   * @return
   */
  public ModelAndView getModelAndView() {
    ModelAndView mav = new ModelAndView();

    addGlobalModelItems(mav.getModel());

    return mav;
  }
 @Test
 public void shouldReturnXmlAndErrorMessageWhenPostOfPipelineAsInvalidPartialXml()
     throws Exception {
   groupName = BasicPipelineConfigs.DEFAULT_GROUP;
   configHelper.addPipeline("pipeline", "stage", "build1", "build2");
   String badXml =
       "<pipeline name=\"cruise\" labeltemplate=\"invalid\">\n"
           + "  <materials>\n"
           + "    <svn url=\"file:///tmp/foo\" checkexternals=\"true\" />\n"
           + "  </materials>\n"
           + "  <stage name=\"dev\">\n"
           + "    <jobs>\n"
           + "      <job name=\"linux\" />\n"
           + "      <job name=\"windows\" />\n"
           + "    </jobs>\n"
           + "  </stage>\n"
           + "</pipeline>";
   String md5 = goConfigDao.md5OfConfigFile();
   ModelAndView mav = controller.postPipelineAsXmlPartial(0, groupName, badXml, md5, response);
   assertThat(response.getStatus(), is(SC_CONFLICT));
   assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
   Map<String, String> json = (Map) mav.getModel().get("json");
   assertThat(json.get("result").toString(), containsString("Label is invalid"));
   assertThat(json.get("originalContent"), is(badXml));
 }
Beispiel #22
0
 /** {@inheritDoc} */
 public void doReturnFromFlow(ModelAndView model, int subFlowId, Long entityId) {
   if (entityId != null) {
     Hazard hazard = ((HazardForm) model.getModel().get("form")).getEntity();
     switch (subFlowId) {
       case TYPE_SUBFLOW_ID:
         {
           hazard.setType(EntityWithIdHelper.createEntity(Type.class, entityId));
           break;
         }
       case LABSUPPLY_SUBFLOW_ID:
         {
           hazard.setLabSupply(EntityWithIdHelper.createEntity(LabSupply.class, entityId));
           break;
         }
       case HAZARDCONTAINER_SUBFLOW_ID:
         {
           hazard.setContainer(EntityWithIdHelper.createEntity(Container.class, entityId));
           break;
         }
       default:
         {
           throw new IllegalArgumentException("Wrong subFlowId");
         }
     }
   }
 }
  protected ModelAndView invokeHandlerMethod(
      HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    AnnotationHandlerMethodResolver methodResolver = getMethodResolver(handler);
    Method handlerMethod = methodResolver.resolveHandlerMethod(request);

    if (logger.isDebugEnabled()) {
      logger.debug("Method for " + request.getRequestURI() + ": " + handlerMethod);
    }

    ServletWebRequest webRequest = new ServletWebRequest(request, response);
    ExtendedModelMap implicitModel = new BindingAwareModelMap();

    TypeConverter typeConverter = methodInvoker.getTypeConverter();

    Set<Method> modelAttributeMethods = methodResolver.getModelAttributeMethods();
    for (Method method : modelAttributeMethods) {
      methodInvoker.invokeModelAttributeMethod(
          method, handler, webRequest, implicitModel, typeConverter);
    }

    Object result =
        methodInvoker.invokeHandlerMethod(
            handlerMethod, handler, webRequest, implicitModel, typeConverter);
    ModelAndView mav =
        methodInvoker.getModelAndView(
            handlerMethod, handler.getClass(), result, implicitModel, webRequest);
    methodInvoker.updateModelAttributes(
        handler, (mav != null ? mav.getModel() : null), implicitModel, webRequest);

    return mav;
  }
 private void addXmlAnnotations(ModelAndView mav, String style) {
   List<ConceptAnnotation> annotations =
       (List<ConceptAnnotation>) mav.getModel().get("annotations");
   mav.addObject("mimetype", "text/xml");
   if (annotations != null) {
     Document doc = DocumentFactory.getInstance().createDocument();
     Element mappings = doc.addElement("mappings");
     for (ConceptAnnotation annotation : annotations) {
       Element mapping = mappings.addElement("mapping");
       mapping.addAttribute("id", String.valueOf(annotation.getOid()));
       mapping.addAttribute("start", String.valueOf(annotation.getBegin()));
       mapping.addAttribute("end", String.valueOf(annotation.getEnd()));
       mapping.addAttribute("pname", annotation.getPname());
       mapping.addAttribute("group", annotation.getStygroup());
       mapping.addAttribute("codes", StringUtils.replace(annotation.getStycodes(), "\"", ""));
       mapping.setText(annotation.getCoveredText());
     }
     OutputFormat outputFormat =
         "compact".equals(style)
             ? OutputFormat.createCompactFormat()
             : OutputFormat.createPrettyPrint();
     StringWriter swriter = new StringWriter();
     XMLWriter writer = new XMLWriter(swriter, outputFormat);
     try {
       writer.write(doc);
       writer.flush();
       mav.addObject("stringAnnotations", swriter.toString());
     } catch (IOException e) {
       logger.warn("IOException writing XML to buffer", e);
     }
   }
 }
 private void addJsonAnnotations(ModelAndView mav, String style, boolean prefix) {
   if (prefix) {
     mav.addObject("mapPrefix", "map");
     mav.addObject("mimetype", "application/x-javascript");
   } else {
     mav.addObject("mimetype", "application/json");
   }
   List<ConceptAnnotation> annotations =
       (List<ConceptAnnotation>) mav.getModel().get("annotations");
   if (annotations != null) {
     JSONArray mappings = new JSONArray();
     for (ConceptAnnotation annotation : annotations) {
       JSONObject mapping = new JSONObject();
       mapping.accumulate("id", String.valueOf(annotation.getOid()));
       mapping.accumulate("start", String.valueOf(annotation.getBegin()));
       mapping.accumulate("end", String.valueOf(annotation.getEnd()));
       mapping.accumulate("pname", annotation.getPname());
       mapping.accumulate("group", annotation.getStygroup());
       mapping.accumulate("codes", StringUtils.replace(annotation.getStycodes(), "\"", ""));
       mapping.accumulate("text", annotation.getCoveredText());
       mappings.put(mapping);
     }
     mav.addObject(
         "stringAnnotations", "pretty".equals(style) ? mappings.toString(2) : mappings.toString());
   }
 }
  /** Test doing geochemistry filter and getting all values */
  @Test
  public void testYilgarnGeochemistryFilter() throws Exception {
    final String serviceUrl = "http://service/wfs";
    final String geologicName = "filter info";
    final int maxFeatures = 0;
    final String bbox = null;
    final String expectedGML = "<gml/>";

    context.checking(
        new Expectations() {
          {
            oneOf(mockWfsService)
                .getWfsResponse(
                    with(equal(serviceUrl)),
                    with(equal("gsml:GeologicUnit")),
                    with(any(String.class)),
                    with(equal(maxFeatures)),
                    with(equal((String) null)));
            will(returnValue(new WFSResponse(expectedGML, mockMethod)));

            allowing(mockMethod).getURI();
            will(returnValue(new URI(serviceUrl, true)));
          }
        });
    ModelAndView modelAndView =
        controller.doYilgarnGeochemistryFilter(serviceUrl, geologicName, bbox, maxFeatures);
    Assert.assertNotNull(modelAndView);
    Map<String, Object> model = modelAndView.getModel();
    Assert.assertEquals(true, model.get("success"));
    Assert.assertNotNull(model.get("data"));
  }
  @RequestMapping("/update")
  public ModelAndView updatePaytype(
      String id, HttpServletResponse response, HttpServletRequest request) throws Exception {
    ModelAndView view = new ModelAndView();
    Report report = reportLogService.findById(id);
    User user = SessionUtils.getUser(request);
    if (user != null && user.getCompany() != null) {
      List<PayGroup> payGroups = tmsService.findAllPageGroups(user.getCompany().getId());
      view.getModelMap().put("payGroupList", payGroups);
    }
    view.getModelMap().put("reportTypeList", ReportType.values());
    List<String> pagings = new ArrayList<String>();
    pagings.add("Postion");
    pagings.add("Employee");
    view.getModelMap().put("pagingList", pagings);

    List<String> sorts = new ArrayList<String>();
    sorts.add("surname");
    sorts.add("Firstname");
    sorts.add("Employee No");
    view.getModelMap().put("sortList", sorts);
    view.getModel().put("report", new ReportVo(report));
    view.setViewName("admin/report/savereport");
    return view;
  }
  /** Test doing geochemistry filter and getting the count of all values fails gracefully */
  @Test
  public void testYilgarnGeochemistryFilterCountError() throws Exception {
    final String serviceUrl = "http://service/wfs";
    final String geologicName = "filter info";
    final int maxFeatures = 134;
    final String bbox = null;

    context.checking(
        new Expectations() {
          {
            oneOf(mockWfsService)
                .getWfsFeatureCount(
                    with(equal(serviceUrl)),
                    with(equal("gsml:GeologicUnit")),
                    with(any(String.class)),
                    with(equal(maxFeatures)),
                    with((String) null));
            will(throwException(new PortalServiceException(mockMethod, new ConnectException())));

            allowing(mockMethod).getURI();
            will(returnValue(new URI(serviceUrl, true)));
          }
        });
    ModelAndView modelAndView =
        controller.doYilgarnGeochemistryCount(serviceUrl, geologicName, bbox, maxFeatures);
    Assert.assertNotNull(modelAndView);
    Map<String, Object> model = modelAndView.getModel();
    Assert.assertEquals(false, model.get("success"));
  }
  /**
   * Test located specimen feature can do a basic transform
   *
   * @throws Exception the exception
   */
  @Test
  public void testLocatedSpecimenFeature_SimpleTransform() throws Exception {

    final String serviceUrl = "http://fake.com/wfs";
    final String featureId = "feature_id";
    final String materialClass = "matclass";
    final YilgarnObservationRecord[] mockObservations = new YilgarnObservationRecord[] {};
    final YilgarnLocatedSpecimenRecord mockLocSpecRecord =
        context.mock(YilgarnLocatedSpecimenRecord.class);

    context.checking(
        new Expectations() {
          {
            oneOf(mockGeochemService).getLocatedSpecimens(serviceUrl, featureId);
            will(returnValue(mockLocSpecRecord));

            allowing(mockLocSpecRecord).getMaterialClass();
            will(returnValue(materialClass));
            allowing(mockLocSpecRecord).getRelatedObservations();
            will(returnValue(mockObservations));
          }
        });

    ModelAndView modelAndView = controller.doLocatedSpecimenFeature(serviceUrl, featureId);
    Assert.assertNotNull(modelAndView);
    Map<String, Object> model = modelAndView.getModel();
    Assert.assertEquals(true, model.get("success"));

    ModelMap data = (ModelMap) model.get("data");
    Assert.assertNotNull(data);
    Assert.assertSame(mockObservations, data.get("records"));
  }
Beispiel #30
0
  private Map<?, ?> renderView() throws Exception {
    final ModelAndView modelAndView = this.getModelAndViewUponServiceValidationWithSecurePgtUrl();
    final MockHttpServletRequest req = new MockHttpServletRequest(new MockServletContext());
    req.setAttribute(
        RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE,
        new GenericWebApplicationContext(req.getServletContext()));

    final Cas30ResponseView view = new Cas30ResponseView();
    view.setServicesManager(this.servicesManager);
    view.setCasAttributeEncoder(new DefaultCasAttributeEncoder(this.servicesManager));
    view.setView(
        new View() {
          @Override
          public String getContentType() {
            return "text/html";
          }

          @Override
          public void render(
              final Map<String, ?> map,
              final HttpServletRequest request,
              final HttpServletResponse response)
              throws Exception {
            map.forEach(request::setAttribute);
          }
        });

    final MockHttpServletResponse resp = new MockHttpServletResponse();
    view.render(modelAndView.getModel(), req, resp);
    return (Map<?, ?>)
        req.getAttribute(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES);
  }