method2testcases
stringlengths
118
6.63k
### Question: GaxSchemaModule extends SchemaModule { protected ImmutableList<GraphQLFieldDefinition> serviceToFields( Class<?> client, ImmutableList<String> methodWhitelist) { return getMethods(client, methodWhitelist) .map( methodWrapper -> { try { methodWrapper.setAccessible(true); ParameterizedType callable = (ParameterizedType) methodWrapper.getGenericReturnType(); GraphQLOutputType responseType = getReturnType(callable); Class<? extends Message> requestMessageClass = (Class<? extends Message>) callable.getActualTypeArguments()[0]; Descriptors.Descriptor requestDescriptor = (Descriptors.Descriptor) requestMessageClass.getMethod("getDescriptor").invoke(null); Message requestMessage = ((Message.Builder) requestMessageClass.getMethod("newBuilder").invoke(null)) .buildPartial(); Provider<?> service = getProvider(client); GqlInputConverter inputConverter = GqlInputConverter.newBuilder().add(requestDescriptor.getFile()).build(); DataFetcher dataFetcher = (DataFetchingEnvironment env) -> { Message input = inputConverter.createProtoBuf( requestDescriptor, requestMessage.toBuilder(), env.getArgument("input")); try { Object callableInstance = methodWrapper.invoke(service.get()); Method method = callableInstance.getClass().getMethod("futureCall", Object.class); method.setAccessible(true); Object[] methodParameterValues = new Object[] {input}; return method.invoke(callableInstance, methodParameterValues); } catch (Exception e) { throw new RuntimeException(e); } }; return GraphQLFieldDefinition.newFieldDefinition() .name(transformName(methodWrapper.getName())) .argument(GqlInputConverter.createArgument(requestDescriptor, "input")) .type(responseType) .dataFetcher(dataFetcher) .build(); } catch (Exception e) { throw new RuntimeException(e); } }) .collect(ImmutableList.toImmutableList()); } }### Answer: @Test public void schemaModuleShouldProvideQueryAndMutationFields() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind(FirestoreClient.class).toProvider(() -> null); } }, new GaxSchemaModule() { @Override protected void configureSchema() { addQueryList( serviceToFields( FirestoreClient.class, ImmutableList.of("getDocument", "listDocuments"))); addMutationList( serviceToFields( FirestoreClient.class, ImmutableList.of("createDocument", "updateDocument", "deleteDocument"))); } }); SchemaBundle schemaBundle = SchemaBundle.combine(injector.getInstance(KEY)); assertThat(schemaBundle.queryFields()).hasSize(2); assertThat(schemaBundle.mutationFields()).hasSize(3); assertThat(schemaBundle.modifications()).isEmpty(); }
### Question: GqlInputConverter { static GraphQLArgument createArgument(Descriptor descriptor, String name) { return GraphQLArgument.newArgument().name(name).type(getInputTypeReference(descriptor)).build(); } private GqlInputConverter( BiMap<String, Descriptor> descriptorMapping, BiMap<String, EnumDescriptor> enumMapping); static Builder newBuilder(); Message createProtoBuf( Descriptor descriptor, Message.Builder builder, Map<String, Object> input); }### Answer: @Test public void unknownProtoShouldPass() { Truth.assertThat(GqlInputConverter.createArgument(Proto1.getDescriptor(), "input")).isNotNull(); } @Test public void inputConverterShouldCreateArgument() { GraphQLArgument argument = GqlInputConverter.createArgument(Proto1.getDescriptor(), "input"); Truth.assertThat(argument.getName()).isEqualTo("input"); Truth.assertThat(((GraphQLNamedType) argument.getType()).getName()) .isEqualTo("Input_javatests_com_google_api_graphql_rejoiner_proto_Proto1"); } @Test public void inputConverterShouldCreateArgumentForMessagesInSameFile() { GraphQLArgument argument = GqlInputConverter.createArgument(Proto2.getDescriptor(), "input"); Truth.assertThat(argument.getName()).isEqualTo("input"); Truth.assertThat(((GraphQLNamedType) argument.getType()).getName()) .isEqualTo("Input_javatests_com_google_api_graphql_rejoiner_proto_Proto2"); }
### Question: ProtoToGql { static String getReferenceName(GenericDescriptor descriptor) { return CharMatcher.anyOf(".").replaceFrom(descriptor.getFullName(), "_"); } private ProtoToGql(); }### Answer: @Test public void getReferenceNameShouldReturnCorrectValueForMessages() { assertThat(ProtoToGql.getReferenceName(Proto1.getDescriptor())) .isEqualTo("javatests_com_google_api_graphql_rejoiner_proto_Proto1"); assertThat(ProtoToGql.getReferenceName(Proto2.getDescriptor())) .isEqualTo("javatests_com_google_api_graphql_rejoiner_proto_Proto2"); } @Test public void getReferenceNameShouldReturnCorrectValueForInnerMessages() { assertThat(ProtoToGql.getReferenceName(InnerProto.getDescriptor())) .isEqualTo("javatests_com_google_api_graphql_rejoiner_proto_Proto1_InnerProto"); } @Test public void getReferenceNameShouldReturnCorrectValueForEnums() { assertThat(ProtoToGql.getReferenceName(TestEnum.getDescriptor())) .isEqualTo("javatests_com_google_api_graphql_rejoiner_proto_Proto2_TestEnum"); }
### Question: QueryResponseToProto { public static <T extends Message> T buildMessage(T message, Map<String, Object> fields) { @SuppressWarnings("unchecked") T populatedMessage = (T) buildMessage(message.toBuilder(), fields); return populatedMessage; } private QueryResponseToProto(); static T buildMessage(T message, Map<String, Object> fields); }### Answer: @Test public void getReferenceNameShouldReturnCorrectValueForMessages() { ProtoTruth.assertThat( QueryResponseToProto.buildMessage( TestProto.Proto1.getDefaultInstance(), ImmutableMap.of( "id", "abc", "intField", 123, "testProto", ImmutableMap.of("innerId", "abc_inner", "enums", ImmutableList.of("FOO"))))) .isEqualTo( Proto1.newBuilder() .setId("abc") .setIntField(123) .setTestProto( Proto2.newBuilder() .setInnerId("abc_inner") .addEnumsValue(Proto2.TestEnum.FOO_VALUE)) .build()); }
### Question: Type { public static ModifiableType find(String typeReferenceName) { return new ModifiableType(typeReferenceName); } private Type(); static ModifiableType find(String typeReferenceName); static ModifiableType find(GenericDescriptor typeDescriptor); }### Answer: @Test public void removeFieldShouldRemoveField() throws Exception { TypeModification typeModification = Type.find("project").removeField("name"); assertThat(typeModification.apply(OBJECT_TYPE).getFieldDefinition("project")).isNull(); } @Test public void removeFieldShouldIgnoreUnknownField() throws Exception { Type.find("project").removeField("unknown_field").apply(OBJECT_TYPE); }
### Question: ExecutionResultToProtoAsync { public static <T extends Message> CompletableFuture<ProtoExecutionResult<T>> toProtoExecutionResult( T message, CompletableFuture<ExecutionResult> executionResultCompletableFuture) { return executionResultCompletableFuture.thenApply( executionResult -> ProtoExecutionResult.create( QueryResponseToProto.buildMessage(message, executionResult.getData()), errorsToProto(executionResult.getErrors()))); } static CompletableFuture<ProtoExecutionResult<T>> toProtoExecutionResult( T message, CompletableFuture<ExecutionResult> executionResultCompletableFuture); static CompletableFuture<T> toProtoMessage( T message, CompletableFuture<ExecutionResult> executionResultCompletableFuture); }### Answer: @Test public void toProtoExecutionResultShouldReturnData() throws ExecutionException, InterruptedException { CompletableFuture<ProtoExecutionResult<Proto1>> executionResultCompletableFuture = ExecutionResultToProtoAsync.toProtoExecutionResult( Proto1.getDefaultInstance(), CompletableFuture.completedFuture( ExecutionResultImpl.newExecutionResult() .data( ImmutableMap.of( "id", "abc", "intField", 123, "testProto", ImmutableMap.of( "innerId", "abc_inner", "enums", ImmutableList.of("FOO")))) .build())); ProtoTruth.assertThat(executionResultCompletableFuture.get().message()) .isEqualTo( Proto1.newBuilder() .setId("abc") .setIntField(123) .setTestProto( Proto2.newBuilder() .setInnerId("abc_inner") .addEnumsValue(Proto2.TestEnum.FOO_VALUE)) .build()); Truth.assertThat(executionResultCompletableFuture.get().errors()).isEmpty(); } @Test public void toProtoExecutionResultShouldReturnDataAndError() throws ExecutionException, InterruptedException { ExceptionWhileDataFetching exceptionWhileDataFetching = new ExceptionWhileDataFetching( ExecutionPath.rootPath(), new RuntimeException("hello world"), new SourceLocation(10, 20)); CompletableFuture<ProtoExecutionResult<Proto1>> executionResultCompletableFuture = ExecutionResultToProtoAsync.toProtoExecutionResult( Proto1.getDefaultInstance(), CompletableFuture.completedFuture( ExecutionResultImpl.newExecutionResult() .data( ImmutableMap.of( "id", "abc", "intField", 123, "testProto", ImmutableMap.of( "innerId", "abc_inner", "enums", ImmutableList.of("FOO")))) .addError(exceptionWhileDataFetching) .build())); ProtoTruth.assertThat(executionResultCompletableFuture.get().message()) .isEqualTo( Proto1.newBuilder() .setId("abc") .setIntField(123) .setTestProto( Proto2.newBuilder() .setInnerId("abc_inner") .addEnumsValue(Proto2.TestEnum.FOO_VALUE)) .build()); ProtoTruth.assertThat(executionResultCompletableFuture.get().errors()) .containsExactly( GraphqlError.newBuilder() .setMessage("Exception while fetching data () : hello world") .addLocations( com.google.api.graphql.SourceLocation.newBuilder().setLine(10).setColumn(20)) .setType(ErrorType.DATA_FETCHING_EXCEPTION) .build()); }
### Question: TableWidget extends Composite implements HasValueChangeHandlers<List<String>>, ValueChangeHandler<List<String>>, ClickHandler { protected int getLastPageIndex() { int lastPageIndex = 0; if (maxRows > 0) { final int nbOfValues = availableValues.size(); if (nbOfValues > 0) { lastPageIndex = nbOfValues / maxRows - 1; if (nbOfValues % maxRows > 0) { lastPageIndex++; } } } return lastPageIndex; } TableWidget(final ReducedFormWidget widgetData, final List<String> selectedItems); void setValue(final List<String> selectedItems, final boolean fireEvents); List<String> getValue(); void setAvailableValues(final List<List<ReducedFormFieldAvailableValue>> availableValues); @Override void onClick(final ClickEvent clickEvent); @Override void onValueChange(final ValueChangeEvent<List<String>> event); @Override HandlerRegistration addValueChangeHandler(final ValueChangeHandler<List<String>> handler); }### Answer: @Test public void should_get_last_page_index_work_with_an_empty_available_values_list() throws Exception { when(formWidget.getTableAvailableValues()).thenReturn(new ArrayList<List<ReducedFormFieldAvailableValue>>()); when(formWidget.getMaxRows()).thenReturn(10); final TableWidget tableWidget = new TableWidget(formWidget, new ArrayList<String>()); Assert.assertEquals("The last page index should be 0 in case the available values list is empty", 0, tableWidget.getLastPageIndex()); } @Test public void should_get_last_page_index_work_with_an_available_values_list() throws Exception { final ArrayList<List<ReducedFormFieldAvailableValue>> availableValuesList = new ArrayList<List<ReducedFormFieldAvailableValue>>(); for (int i = 0; i < 5; i++) { availableValuesList.add(new ArrayList<ReducedFormFieldAvailableValue>()); } when(formWidget.getTableAvailableValues()).thenReturn(availableValuesList); when(formWidget.getMaxRows()).thenReturn(2); final TableWidget tableWidget = new TableWidget(formWidget, new ArrayList<String>()); Assert.assertEquals("The last page index should be 2 in case there is 5 rows of available values and 2 rows max by page", 2, tableWidget.getLastPageIndex()); } @Test public void should_get_last_page_index_work_with_an_available_values_list_matching_the_max_item_per_page() throws Exception { final ArrayList<List<ReducedFormFieldAvailableValue>> availableValuesList = new ArrayList<List<ReducedFormFieldAvailableValue>>(); for (int i = 0; i < 4; i++) { availableValuesList.add(new ArrayList<ReducedFormFieldAvailableValue>()); } when(formWidget.getTableAvailableValues()).thenReturn(availableValuesList); when(formWidget.getMaxRows()).thenReturn(4); final TableWidget tableWidget = new TableWidget(formWidget, new ArrayList<String>()); Assert.assertEquals("The last page index should be 0 in case there is 4 rows of available values and 4 rows max by page", 0, tableWidget.getLastPageIndex()); }
### Question: PostMessageEventListener { public void onMessageEvent(final String eventData) { try { final JSONValue root = JSONParser.parseStrict(eventData); final JSONObject fullJSONMessage = root.isObject(); if (isActionWatched(fullJSONMessage)) { handleJSONMessage(fullJSONMessage); } } catch (final Exception e) { GWT.log("Error while parsing content of message", e); } } void onMessageEvent(final String eventData); abstract String getActionToWatch(); }### Answer: @Test public void onSuccessOrError_should_not_be_called_with_action_not_watched() throws Exception { final String jsonMessage = "{\"message\":\"error\",\"action\":\"\"}"; customPostMessageEventListener.setActionToWatch("Start process"); customPostMessageEventListener.onMessageEvent(jsonMessage); verify(customPostMessageEventListener, never()).success(anyString()); verify(customPostMessageEventListener, never()).error(anyString(), anyInt()); } @Test public void onSuccessOrError_should_be_called_with_valid_json() throws Exception { final String jsonMessage = "{\"message\":\"error\",\"action\":\"\"}"; customPostMessageEventListener.setActionToWatch(""); customPostMessageEventListener.onMessageEvent(jsonMessage); verify(customPostMessageEventListener).error(anyString(), anyInt()); } @Test public void onSuccessOrError_should_not_be_called_with_invalid_json() throws Exception { final String jsonMessage = "{\"message\":\"success\",action\":\"Start process\"}"; customPostMessageEventListener.setActionToWatch("Start process"); customPostMessageEventListener.onMessageEvent(jsonMessage); verify(customPostMessageEventListener, never()).success(anyString()); verify(customPostMessageEventListener, never()).error(anyString(), anyInt()); }
### Question: LogoutUrl { public void setParameter(String key, String value) { builder.addParameter(key, value); } LogoutUrl(UrlBuilder builder, String locale); void setParameter(String key, String value); @Override String toString(); static final String LOGOUT_URL; }### Answer: @Test public void testWeCanSetAParameter() throws Exception { LogoutUrl logoutUrl = new LogoutUrl(builder, "fr"); logoutUrl.setParameter("aParameter", "itsValue"); new LogoutUrl(builder, "fr"); verify(builder).addParameter("aParameter", "itsValue"); }
### Question: VariableUtils { public static void inject(HtmlAccessor accessor, String name, SafeHtml value) { accessor.setInnerHTML(replaceAll(accessor.getInnerHTML(), name, value)); } static void inject(HtmlAccessor accessor, String name, SafeHtml value); }### Answer: @Test public void testWeCanReplaceASpecificVariable() throws Exception { doReturn("<p>This is %variable1% for variable1 but not for variable2</p>") .when(accessor) .getInnerHTML(); VariableUtils.inject(accessor, "variable1", SafeHtmlUtils.fromTrustedString("working")); verify(accessor).setInnerHTML("<p>This is working for variable1 but not for variable2</p>"); } @Test public void testWeHtmlWithoutVariableStayTheSame() throws Exception { doReturn("<p class='aside'>This is a test</p>") .when(accessor) .getInnerHTML(); VariableUtils.inject(accessor, "variable", SafeHtmlUtils.fromTrustedString("value")); verify(accessor).setInnerHTML("<p class='aside'>This is a test</p>"); } @Test public void testWeCanReplaceMultipleVariables() throws Exception { doReturn("<p class='%variable%'>This is %variable%</p>") .when(accessor) .getInnerHTML(); VariableUtils.inject(accessor, "variable", SafeHtmlUtils.fromTrustedString("working")); verify(accessor).setInnerHTML("<p class='working'>This is working</p>"); }
### Question: ProcessFormService { public long ensureProcessDefinitionId(final APISession apiSession, final long processDefinitionId, final long processInstanceId, final long taskInstanceId) throws ArchivedProcessInstanceNotFoundException, ActivityInstanceNotFoundException, BonitaException { if (processDefinitionId != -1L) { return processDefinitionId; } else if (processInstanceId != -1L) { return getProcessDefinitionIdFromProcessInstanceId(apiSession, processInstanceId); } else { return getProcessDefinitionIdFromTaskId(apiSession, taskInstanceId); } } String getProcessPath(final APISession apiSession, final long processDefinitionId); String encodePathSegment(final String stringToEncode); long getProcessDefinitionId(final APISession apiSession, final String processName, final String processVersion); long getTaskInstanceId(final APISession apiSession, final long processInstanceId, final String taskName, final long userId); String getTaskName(final APISession apiSession, final long taskInstanceId); long ensureProcessDefinitionId(final APISession apiSession, final long processDefinitionId, final long processInstanceId, final long taskInstanceId); boolean isAllowedToSeeTask(final APISession apiSession, final long taskInstanceId, final long enforcedUserId, final boolean assignTask); boolean isAllowedToSeeProcessInstance(final APISession apiSession, final long processInstanceId, final long enforcedUserId); boolean isAllowedToStartProcess(final APISession apiSession, final long processDefinitionId, final long enforcedUserId); boolean isAllowedAsAdminOrProcessSupervisor(final HttpServletRequest request, final APISession apiSession, final long processDefinitionId, final long taskInstanceId, final long userId, final boolean assignTask); }### Answer: @Test public void ensureProcessDefinitionId_with_processDefinitionId() throws Exception { assertEquals(42L, processFormService.ensureProcessDefinitionId(apiSession, 42L, -1L, -1L)); }
### Question: ProcessFormService { public String getTaskName(final APISession apiSession, final long taskInstanceId) throws ActivityInstanceNotFoundException, BonitaException { if (taskInstanceId != -1L) { final ProcessAPI processAPI = getProcessAPI(apiSession); try { final ActivityInstance activity = processAPI.getActivityInstance(taskInstanceId); return activity.getName(); } catch (final ActivityInstanceNotFoundException e) { final ArchivedActivityInstance activity = processAPI.getArchivedActivityInstance(taskInstanceId); return activity.getName(); } } return null; } String getProcessPath(final APISession apiSession, final long processDefinitionId); String encodePathSegment(final String stringToEncode); long getProcessDefinitionId(final APISession apiSession, final String processName, final String processVersion); long getTaskInstanceId(final APISession apiSession, final long processInstanceId, final String taskName, final long userId); String getTaskName(final APISession apiSession, final long taskInstanceId); long ensureProcessDefinitionId(final APISession apiSession, final long processDefinitionId, final long processInstanceId, final long taskInstanceId); boolean isAllowedToSeeTask(final APISession apiSession, final long taskInstanceId, final long enforcedUserId, final boolean assignTask); boolean isAllowedToSeeProcessInstance(final APISession apiSession, final long processInstanceId, final long enforcedUserId); boolean isAllowedToStartProcess(final APISession apiSession, final long processDefinitionId, final long enforcedUserId); boolean isAllowedAsAdminOrProcessSupervisor(final HttpServletRequest request, final APISession apiSession, final long processDefinitionId, final long taskInstanceId, final long userId, final boolean assignTask); }### Answer: @Test public void getTaskName_with_taskInstanceId() throws Exception { final ActivityInstance activityInstance = mock(ActivityInstance.class); when(activityInstance.getName()).thenReturn("myTask"); when(processAPI.getActivityInstance(42L)).thenReturn(activityInstance); assertEquals("myTask", processFormService.getTaskName(apiSession, 42L)); } @Test public void getTaskName_with_taskInstanceId_on_archived_instance() throws Exception { final ArchivedActivityInstance archivedActivityInstance = mock(ArchivedActivityInstance.class); when(archivedActivityInstance.getName()).thenReturn("myTask"); when(processAPI.getActivityInstance(42L)).thenThrow(ActivityInstanceNotFoundException.class); when(processAPI.getArchivedActivityInstance(42L)).thenReturn(archivedActivityInstance); assertEquals("myTask", processFormService.getTaskName(apiSession, 42L)); }
### Question: ProcessFormService { public long getProcessDefinitionId(final APISession apiSession, final String processName, final String processVersion) throws ProcessDefinitionNotFoundException, BonitaException { if (processName != null && processVersion != null) { try { return getProcessAPI(apiSession).getProcessDefinitionId(processName, processVersion); } catch (final ProcessDefinitionNotFoundException e) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Wrong parameters for process name and version", e); } } } return -1L; } String getProcessPath(final APISession apiSession, final long processDefinitionId); String encodePathSegment(final String stringToEncode); long getProcessDefinitionId(final APISession apiSession, final String processName, final String processVersion); long getTaskInstanceId(final APISession apiSession, final long processInstanceId, final String taskName, final long userId); String getTaskName(final APISession apiSession, final long taskInstanceId); long ensureProcessDefinitionId(final APISession apiSession, final long processDefinitionId, final long processInstanceId, final long taskInstanceId); boolean isAllowedToSeeTask(final APISession apiSession, final long taskInstanceId, final long enforcedUserId, final boolean assignTask); boolean isAllowedToSeeProcessInstance(final APISession apiSession, final long processInstanceId, final long enforcedUserId); boolean isAllowedToStartProcess(final APISession apiSession, final long processDefinitionId, final long enforcedUserId); boolean isAllowedAsAdminOrProcessSupervisor(final HttpServletRequest request, final APISession apiSession, final long processDefinitionId, final long taskInstanceId, final long userId, final boolean assignTask); }### Answer: @Test public void getProcessDefinitionId_with_no_version() throws Exception { assertEquals(-1L, processFormService.getProcessDefinitionId(apiSession, "myProcess", null)); } @Test public void getProcessDefinitionId_with_no_name_and_version() throws Exception { assertEquals(-1L, processFormService.getProcessDefinitionId(apiSession, null, null)); }
### Question: ProcessFormService { public boolean isAllowedToSeeProcessInstance(final APISession apiSession, final long processInstanceId, final long enforcedUserId) throws BonitaException { final ProcessAPI processAPI = getProcessAPI(apiSession); return processAPI.isInvolvedInProcessInstance(enforcedUserId, processInstanceId); } String getProcessPath(final APISession apiSession, final long processDefinitionId); String encodePathSegment(final String stringToEncode); long getProcessDefinitionId(final APISession apiSession, final String processName, final String processVersion); long getTaskInstanceId(final APISession apiSession, final long processInstanceId, final String taskName, final long userId); String getTaskName(final APISession apiSession, final long taskInstanceId); long ensureProcessDefinitionId(final APISession apiSession, final long processDefinitionId, final long processInstanceId, final long taskInstanceId); boolean isAllowedToSeeTask(final APISession apiSession, final long taskInstanceId, final long enforcedUserId, final boolean assignTask); boolean isAllowedToSeeProcessInstance(final APISession apiSession, final long processInstanceId, final long enforcedUserId); boolean isAllowedToStartProcess(final APISession apiSession, final long processDefinitionId, final long enforcedUserId); boolean isAllowedAsAdminOrProcessSupervisor(final HttpServletRequest request, final APISession apiSession, final long processDefinitionId, final long taskInstanceId, final long userId, final boolean assignTask); }### Answer: @Test public void isAllowedToSeeProcessInstance_should_return_true() throws Exception { when(processAPI.isInvolvedInProcessInstance(1L, 42L)).thenReturn(true); final boolean isAllowedToSeeProcessInstance = processFormService.isAllowedToSeeProcessInstance(apiSession, 42L, 1L); assertTrue(isAllowedToSeeProcessInstance); } @Test public void isAllowedToSeeProcessInstance_should_return_false() throws Exception { when(processAPI.isInvolvedInProcessInstance(1L, 42L)).thenReturn(false); final boolean isAllowedToSeeProcessInstance = processFormService.isAllowedToSeeProcessInstance(apiSession, 42L, 1L); assertFalse(isAllowedToSeeProcessInstance); }
### Question: ProcessFormService { public boolean isAllowedToStartProcess(final APISession apiSession, final long processDefinitionId, final long enforcedUserId) throws BonitaException { if (ActivationState.ENABLED.equals(getProcessAPI(apiSession).getProcessDeploymentInfo(processDefinitionId).getActivationState())) { final Map<String, Serializable> parameters = new HashMap<String, Serializable>(); parameters.put("USER_ID_KEY", enforcedUserId); parameters.put("PROCESS_DEFINITION_ID_KEY", processDefinitionId); return (Boolean) getCommandAPI(apiSession).execute("canStartProcessDefinition", parameters); } return false; } String getProcessPath(final APISession apiSession, final long processDefinitionId); String encodePathSegment(final String stringToEncode); long getProcessDefinitionId(final APISession apiSession, final String processName, final String processVersion); long getTaskInstanceId(final APISession apiSession, final long processInstanceId, final String taskName, final long userId); String getTaskName(final APISession apiSession, final long taskInstanceId); long ensureProcessDefinitionId(final APISession apiSession, final long processDefinitionId, final long processInstanceId, final long taskInstanceId); boolean isAllowedToSeeTask(final APISession apiSession, final long taskInstanceId, final long enforcedUserId, final boolean assignTask); boolean isAllowedToSeeProcessInstance(final APISession apiSession, final long processInstanceId, final long enforcedUserId); boolean isAllowedToStartProcess(final APISession apiSession, final long processDefinitionId, final long enforcedUserId); boolean isAllowedAsAdminOrProcessSupervisor(final HttpServletRequest request, final APISession apiSession, final long processDefinitionId, final long taskInstanceId, final long userId, final boolean assignTask); }### Answer: @Test public void isAllowedToStartProcess_should_return_true() throws Exception { final Map<String, Serializable> parameters = new HashMap<String, Serializable>(); parameters.put("USER_ID_KEY", 1L); parameters.put("PROCESS_DEFINITION_ID_KEY", 42L); when(commandAPI.execute("canStartProcessDefinition", parameters)).thenReturn(true); final ProcessDeploymentInfo processDeploymentInfo = mock(ProcessDeploymentInfo.class); when(processDeploymentInfo.getActivationState()).thenReturn(ActivationState.ENABLED); when(processAPI.getProcessDeploymentInfo(42L)).thenReturn(processDeploymentInfo); final boolean isAllowedToStartProcess = processFormService.isAllowedToStartProcess(apiSession, 42L, 1L); assertTrue(isAllowedToStartProcess); } @Test public void isAllowedToStartProcess_should_return_false() throws Exception { final Map<String, Serializable> parameters = new HashMap<String, Serializable>(); parameters.put("USER_ID_KEY", 1L); parameters.put("PROCESS_DEFINITION_ID_KEY", 42L); when(commandAPI.execute("canStartProcessDefinition", parameters)).thenReturn(false); final ProcessDeploymentInfo processDeploymentInfo = mock(ProcessDeploymentInfo.class); when(processDeploymentInfo.getActivationState()).thenReturn(ActivationState.ENABLED); when(processAPI.getProcessDeploymentInfo(42L)).thenReturn(processDeploymentInfo); final boolean isAllowedToStartProcess = processFormService.isAllowedToStartProcess(apiSession, 42L, 1L); assertFalse(isAllowedToStartProcess); } @Test public void isAllowedToStartProcess_should_return_false_if_process_not_enabled() throws Exception { final ProcessDeploymentInfo processDeploymentInfo = mock(ProcessDeploymentInfo.class); when(processDeploymentInfo.getActivationState()).thenReturn(ActivationState.DISABLED); when(processAPI.getProcessDeploymentInfo(42L)).thenReturn(processDeploymentInfo); final boolean isAllowedToStartProcess = processFormService.isAllowedToStartProcess(apiSession, 42L, 1L); assertFalse(isAllowedToStartProcess); }
### Question: ProcessFormService { public String getProcessPath(final APISession apiSession, final long processDefinitionId) throws BonitaException, UnsupportedEncodingException { final ProcessDeploymentInfo processDeploymentInfo = getProcessAPI(apiSession).getProcessDeploymentInfo(processDefinitionId); return encodePathSegment(processDeploymentInfo.getName()) + "/" + encodePathSegment(processDeploymentInfo.getVersion()); } String getProcessPath(final APISession apiSession, final long processDefinitionId); String encodePathSegment(final String stringToEncode); long getProcessDefinitionId(final APISession apiSession, final String processName, final String processVersion); long getTaskInstanceId(final APISession apiSession, final long processInstanceId, final String taskName, final long userId); String getTaskName(final APISession apiSession, final long taskInstanceId); long ensureProcessDefinitionId(final APISession apiSession, final long processDefinitionId, final long processInstanceId, final long taskInstanceId); boolean isAllowedToSeeTask(final APISession apiSession, final long taskInstanceId, final long enforcedUserId, final boolean assignTask); boolean isAllowedToSeeProcessInstance(final APISession apiSession, final long processInstanceId, final long enforcedUserId); boolean isAllowedToStartProcess(final APISession apiSession, final long processDefinitionId, final long enforcedUserId); boolean isAllowedAsAdminOrProcessSupervisor(final HttpServletRequest request, final APISession apiSession, final long processDefinitionId, final long taskInstanceId, final long userId, final boolean assignTask); }### Answer: @Test public void getProcessDefinitionUUID_should_return_valid_UUID() throws Exception { final ProcessDeploymentInfo processDeploymentInfo = mock(ProcessDeploymentInfo.class); when(processDeploymentInfo.getName()).thenReturn("processName"); when(processDeploymentInfo.getVersion()).thenReturn("processVersion"); when(processAPI.getProcessDeploymentInfo(1L)).thenReturn(processDeploymentInfo); final String uuid = processFormService.getProcessPath(apiSession, 1L); assertEquals("processName/processVersion", uuid); } @Test public void getProcessDefinitionUUID_should_return_valid_UUID_with_special_characters() throws Exception { final ProcessDeploymentInfo processDeploymentInfo = mock(ProcessDeploymentInfo.class); when(processDeploymentInfo.getName()).thenReturn("process Name/é"); when(processDeploymentInfo.getVersion()).thenReturn("process Version ø"); when(processAPI.getProcessDeploymentInfo(1L)).thenReturn(processDeploymentInfo); final String uuid = processFormService.getProcessPath(apiSession, 1L); assertEquals("process%20Name/%C3%A9/process%20Version%20%C3%B8", uuid); }
### Question: ProcessFormServlet extends HttpServlet { @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { long processDefinitionId = -1L; long processInstanceId = -1L; long taskInstanceId = -1L; String taskName = null; final List<String> pathSegments = resourceRenderer.getPathSegments(request.getPathInfo()); final String user = request.getParameter(USER_ID_PARAM); final long userId = convertToLong(USER_ID_PARAM, user); final HttpSession session = request.getSession(); final APISession apiSession = (APISession) session.getAttribute(SessionUtil.API_SESSION_PARAM_KEY); try { if (pathSegments.size() > 1) { taskInstanceId = getTaskInstanceId(apiSession, pathSegments, userId); processInstanceId = getProcessInstanceId(pathSegments); processDefinitionId = getProcessDefinitionId(apiSession, pathSegments); } if (processDefinitionId == -1L && processInstanceId == -1L && taskInstanceId == -1L) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Either process name and version are required or process instance Id (with or without task name) or task instance Id."); return; } processDefinitionId = processFormService.ensureProcessDefinitionId(apiSession, processDefinitionId, processInstanceId, taskInstanceId); taskName = processFormService.getTaskName(apiSession, taskInstanceId); redirectToPageServlet(request, response, apiSession, processDefinitionId, processInstanceId, taskInstanceId, taskName); } catch (final Exception e) { handleException(response, processDefinitionId, taskName, processInstanceId != -1L, e); } } }### Answer: @Test public void should_get_not_found_when_invalid_processInstanceId() throws Exception { when(hsRequest.getPathInfo()).thenReturn("/processInstance/42/"); when(processFormService.ensureProcessDefinitionId(apiSession, -1L, 42L, -1L)).thenThrow(ArchivedProcessInstanceNotFoundException.class); formServlet.doGet(hsRequest, hsResponse); verify(hsResponse, times(1)).sendError(404, "Cannot find the process instance"); }
### Question: AuthenticationFilter extends ExcludingPatternFilter { protected void doAuthenticationFiltering(final HttpServletRequestAccessor requestAccessor, final HttpServletResponse response, final TenantIdAccessor tenantIdAccessor, final FilterChain chain) throws ServletException, IOException { try { if (!isAuthorized(requestAccessor, response, tenantIdAccessor, chain)) { cleanHttpSession(requestAccessor.getHttpSession()); if (requestAccessor.asHttpServletRequest().getMethod().equals("GET")) { response.sendRedirect(createLoginPageUrl(requestAccessor, tenantIdAccessor).getLocation()); } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } } } catch (TenantIsPausedException e) { handleTenantPausedException(requestAccessor, response, e); } catch (final EngineUserNotFoundOrInactive e) { handleUserNotFoundOrInactiveException(requestAccessor, response, e); } } AuthenticationFilter(); String getDefaultExcludedPages(); @Override void proceedWithFiltering(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }### Answer: @Test public void testFilter() throws Exception { when(httpRequest.getSession()).thenReturn(httpSession); doAnswer(new Answer<Object>() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { return null; } }).when(authenticationFilter).doAuthenticationFiltering(any(HttpServletRequestAccessor.class), any(HttpServletResponse.class), any(TenantIdAccessor.class), any(FilterChain.class)); authenticationFilter.doFilter(httpRequest, httpResponse, chain); verify(authenticationFilter, times(1)).doAuthenticationFiltering(any(HttpServletRequestAccessor.class), any(HttpServletResponse.class), any(TenantIdAccessor.class), any(FilterChain.class)); } @Test public void testFilterWithExcludedURL() throws Exception { final String url = "test"; when(httpRequest.getRequestURL()).thenReturn(new StringBuffer(url)); doReturn(true).when(authenticationFilter).matchExcludePatterns(url); authenticationFilter.doFilter(httpRequest, httpResponse, chain); verify(authenticationFilter, times(0)).doAuthenticationFiltering(request, httpResponse, tenantIdAccessor, chain); verify(chain, times(1)).doFilter(httpRequest, httpResponse); }
### Question: AuthenticationFilter extends ExcludingPatternFilter { protected void redirectTo(final HttpServletRequestAccessor request, final HttpServletResponse response, final long tenantId, final String pagePath) throws ServletException { try { response.sendRedirect(request.asHttpServletRequest().getContextPath() + pagePath); } catch (final IOException e) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, e.getMessage()); } } } AuthenticationFilter(); String getDefaultExcludedPages(); @Override void proceedWithFiltering(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }### Answer: @Test public void testRedirectTo() throws Exception { final String context = "/bonita"; when(httpRequest.getContextPath()).thenReturn(context); final long tenantId = 0L; authenticationFilter.redirectTo(request, httpResponse, tenantId, AuthenticationFilter.MAINTENANCE_JSP); verify(httpResponse, times(1)).sendRedirect(context + AuthenticationFilter.MAINTENANCE_JSP); verify(httpRequest, times(1)).getContextPath(); }
### Question: AuthenticationFilter extends ExcludingPatternFilter { protected RedirectUrl makeRedirectUrl(final HttpServletRequestAccessor httpRequest) { final RedirectUrlBuilder builder = new RedirectUrlBuilder(httpRequest.getRequestedUri()); builder.appendParameters(httpRequest.getParameterMap()); return builder.build(); } AuthenticationFilter(); String getDefaultExcludedPages(); @Override void proceedWithFiltering(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }### Answer: @Test public void testMakeRedirectUrl() throws Exception { when(request.getRequestedUri()).thenReturn("/portal/homepage"); final RedirectUrl redirectUrl = authenticationFilter.makeRedirectUrl(request); verify(request, times(1)).getRequestedUri(); assertThat(redirectUrl.getUrl()).isEqualToIgnoringCase("/portal/homepage"); } @Test public void testMakeRedirectUrlFromRequestUrl() throws Exception { when(request.getRequestedUri()).thenReturn("portal/homepage"); when(httpRequest.getRequestURL()).thenReturn(new StringBuffer("http: final RedirectUrl redirectUrl = authenticationFilter.makeRedirectUrl(request); verify(request, times(1)).getRequestedUri(); verify(httpRequest, never()).getRequestURI(); assertThat(redirectUrl.getUrl()).isEqualToIgnoringCase("portal/homepage"); }
### Question: TokenGenerator { public String createOrLoadToken(final HttpSession session) { Object apiTokenFromClient = session.getAttribute(API_TOKEN); if (apiTokenFromClient == null) { apiTokenFromClient = new APIToken().getToken(); session.setAttribute(API_TOKEN, apiTokenFromClient); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Bonita API Token generated: " + apiTokenFromClient); } } return apiTokenFromClient.toString(); } @Deprecated void setTokenToResponseCookie(HttpServletRequest request, HttpServletResponse res, Object apiTokenFromClient); String createOrLoadToken(final HttpSession session); void setTokenToResponseHeader(final HttpServletResponse res, final String token); static final String API_TOKEN; static final String X_BONITA_API_TOKEN; }### Answer: @Test public void should_create_token_and_store_it_in_session() throws Exception { final String token = tokenGenerator.createOrLoadToken(session); assertThat(token).isNotEmpty(); assertThat(session.getAttribute(TokenGenerator.API_TOKEN)).isEqualTo(token); } @Test public void should_load_token_from_session() throws Exception { session.setAttribute(TokenGenerator.API_TOKEN, BONITA_TOKEN_VALUE); final String token = tokenGenerator.createOrLoadToken(session); assertThat(token).isNotEmpty(); assertThat(token).isEqualTo(BONITA_TOKEN_VALUE); }
### Question: TokenGenerator { @Deprecated public void setTokenToResponseCookie(HttpServletRequest request, HttpServletResponse res, Object apiTokenFromClient) { PortalCookies portalCookies = new PortalCookies(); portalCookies.addCSRFTokenCookieToResponse(request, res, apiTokenFromClient); } @Deprecated void setTokenToResponseCookie(HttpServletRequest request, HttpServletResponse res, Object apiTokenFromClient); String createOrLoadToken(final HttpSession session); void setTokenToResponseHeader(final HttpServletResponse res, final String token); static final String API_TOKEN; static final String X_BONITA_API_TOKEN; }### Answer: @Test public void testSetTokenToResponseCookie() throws Exception { portalCookies.addCSRFTokenCookieToResponse(request, response, BONITA_TOKEN_VALUE); final Cookie csrfCookie = response.getCookie(BONITA_TOKEN_NAME); assertThat(csrfCookie.getName()).isEqualTo(BONITA_TOKEN_NAME); assertThat(csrfCookie.getPath()).isEqualTo(CONTEXT_PATH); assertThat(csrfCookie.getValue()).isEqualTo(BONITA_TOKEN_VALUE); assertThat(csrfCookie.getSecure()).isFalse(); }
### Question: TokenGenerator { public void setTokenToResponseHeader(final HttpServletResponse res, final String token) { if(res.containsHeader(X_BONITA_API_TOKEN)){ res.setHeader(X_BONITA_API_TOKEN, token); } else { res.addHeader(X_BONITA_API_TOKEN, token); } } @Deprecated void setTokenToResponseCookie(HttpServletRequest request, HttpServletResponse res, Object apiTokenFromClient); String createOrLoadToken(final HttpSession session); void setTokenToResponseHeader(final HttpServletResponse res, final String token); static final String API_TOKEN; static final String X_BONITA_API_TOKEN; }### Answer: @Test public void testSetTokenToResponseHeader() throws Exception { tokenGenerator.setTokenToResponseHeader(response, BONITA_TOKEN_VALUE); assertThat(response.getHeader(BONITA_TOKEN_NAME)).isEqualTo(BONITA_TOKEN_VALUE); }
### Question: AlreadyLoggedInRule extends AuthenticationRule { @Override public boolean doAuthorize(final HttpServletRequestAccessor request, HttpServletResponse response, final TenantIdAccessor tenantIdAccessor) throws ServletException { if (isUserAlreadyLoggedIn(request, tenantIdAccessor)) { ensureUserSession(request.asHttpServletRequest(), request.getHttpSession(), request.getApiSession()); return true; } return false; } @Override boolean doAuthorize(final HttpServletRequestAccessor request, HttpServletResponse response, final TenantIdAccessor tenantIdAccessor); }### Answer: @Test public void testIfRuleAuthorizeAlreadyLoggedUser() throws Exception { doReturn(apiSession).when(request).getApiSession(); doReturn("").when(httpSession).getAttribute(SessionUtil.USER_SESSION_PARAM_KEY); final boolean authorization = rule.doAuthorize(request, response, tenantAccessor); assertThat(authorization, is(true)); } @Test public void testIfRuleDoesntAuthorizeNullSession() throws Exception { doReturn(null).when(request).getApiSession(); final boolean authorization = rule.doAuthorize(request, response, tenantAccessor); assertFalse(authorization); }
### Question: TokenValidatorFilter extends AbstractAuthorizationFilter { @Override boolean checkValidCondition(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { if (isCsrfProtectionEnabled() && !isSafeMethod(httpRequest.getMethod())) { String headerFromRequest = getCSRFToken(httpRequest); String apiToken = (String) httpRequest.getSession().getAttribute("api_token"); if (headerFromRequest == null || !headerFromRequest.equals(apiToken)) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Token Validation failed, expected: " + apiToken + ", received: " + headerFromRequest); } httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return false; } } return true; } }### Answer: @Test public void should_check_csrf_token_from_request_header() throws Exception { request.addHeader("X-Bonita-API-Token", SESSION_CSRF_TOKEN); boolean valid = filter.checkValidCondition(request, response); assertThat(valid).isTrue(); } @Test public void should_not_check_csrf_token_for_GET_request() throws Exception { request.setMethod("GET"); boolean valid = filter.checkValidCondition(request, response); assertThat(valid).isTrue(); } @Test public void should_not_check_csrf_token_for_HEAD_request() throws Exception { request.setMethod("HEAD"); boolean valid = filter.checkValidCondition(request, response); assertThat(valid).isTrue(); } @Test public void should_set_401_status_when_csrf_request_header_is_wrong() throws Exception { request.addHeader("X-Bonita-API-Token", "notAValidToken"); boolean valid = filter.checkValidCondition(request, response); assertThat(valid).isFalse(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void should_set_401_status_when_csrf_request_header_is_not_set() throws Exception { boolean valid = filter.checkValidCondition(request, response); assertThat(valid).isFalse(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void should_check_csrf_token_from_request_parameter() throws Exception { request.addParameter("CSRFToken", SESSION_CSRF_TOKEN); boolean valid = filter.checkValidCondition(request, response); assertThat(valid).isTrue(); } @Test public void should_set_401_status_when_csrf_request_parameter_is_wrong() throws Exception { request.addParameter("CSRFToken", "notAValidToken"); boolean valid = filter.checkValidCondition(request, response); assertThat(valid).isFalse(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void should_check_csrf_token_from_request_form_data() throws Exception { request = mockMultipartRequestFor(SESSION_CSRF_TOKEN); boolean valid = filter.checkValidCondition(request, response); assertThat(valid).isTrue(); } @Test public void should_set_401_status_when_csrf_form_data_is_wrong() throws Exception { request = mockMultipartRequestFor("notAValidToken"); boolean valid = filter.checkValidCondition(request, response); assertThat(valid).isFalse(); assertThat(response.getStatus()).isEqualTo(401); }
### Question: V6FormsAutoLoginRule extends AuthenticationRule { @Override public boolean doAuthorize(final HttpServletRequestAccessor request, HttpServletResponse response, final TenantIdAccessor tenantIdAccessor) throws ServletException { final long tenantId = tenantIdAccessor.ensureTenantId(); return doAutoLogin(request, response, tenantId); } @Override boolean doAuthorize(final HttpServletRequestAccessor request, HttpServletResponse response, final TenantIdAccessor tenantIdAccessor); }### Answer: @Test public void testWeAreNotAutoLoggedWhenNotConfigured() throws Exception { doReturn("process3--2.9").when(request).getAutoLoginScope(); doReturn(1L).when(tenantAccessor).getRequestedTenantId(); when(autoLoginCredentialsFinder.getCredential(new ProcessIdentifier("process3--2.9"),1L)).thenReturn(null); final boolean authorized = rule.doAuthorize(request, response, tenantAccessor); assertFalse(authorized); }
### Question: RestAPIAuthorizationFilter extends AbstractAuthorizationFilter { protected boolean checkPermissions(final HttpServletRequest request) throws ServletException { final RestRequestParser restRequestParser = new RestRequestParser(request).invoke(); return checkPermissions(request, restRequestParser.getApiName(), restRequestParser.getResourceName(), restRequestParser.getResourceQualifiers()); } RestAPIAuthorizationFilter(final boolean reload); RestAPIAuthorizationFilter(); static final String SCRIPT_TYPE_AUTHORIZATION_PREFIX; }### Answer: @Test public void should_checkPermissions_parse_the_request() throws Exception { doReturn("API/bpm/case/15").when(request).getPathInfo(); final RestAPIAuthorizationFilter restAPIAuthorizationFilterSpy = spy(restAPIAuthorizationFilter); doReturn(true).when(restAPIAuthorizationFilterSpy).checkPermissions(eq(request), eq("bpm"), eq("case"), eq(APIID.makeAPIID(15l))); restAPIAuthorizationFilterSpy.checkPermissions(request); verify(restAPIAuthorizationFilterSpy).checkPermissions(eq(request), eq("bpm"), eq("case"), eq(APIID.makeAPIID(15l))); }
### Question: RestAPIAuthorizationFilter extends AbstractAuthorizationFilter { protected boolean staticCheck(final APICallContext apiCallContext, final Set<String> permissionsOfUser, final Set<String> resourcePermissions, final String username) { for (final String resourcePermission : resourcePermissions) { if (permissionsOfUser.contains(resourcePermission)) { return true; } } if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Unauthorized access to " + apiCallContext.getMethod() + " " + apiCallContext.getApiName() + "/" + apiCallContext.getResourceName() + (apiCallContext.getResourceId() != null ? "/" + apiCallContext.getResourceId() : "") + " attempted by " + username + " required permissions: " + resourcePermissions); } return false; } RestAPIAuthorizationFilter(final boolean reload); RestAPIAuthorizationFilter(); static final String SCRIPT_TYPE_AUTHORIZATION_PREFIX; }### Answer: @Test public void test_staticCheck_authorized() throws Exception { final Set<String> userPermissions = new HashSet<String>(Arrays.asList("MyPermission", "AnOtherPermission")); final List<String> resourcePermissions = Arrays.asList("CasePermission", "AnOtherPermission"); returnPermissionFor("GET", "bpm", "case", null, resourcePermissions); final boolean isAuthorized = restAPIAuthorizationFilter.staticCheck(new APICallContext("GET", "bpm", "case", null), userPermissions, new HashSet<String>(resourcePermissions), username); assertThat(isAuthorized).isTrue(); } @Test public void test_staticCheck_unauthorized() throws Exception { final Set<String> userPermissions = new HashSet<String>(Arrays.asList("MyPermission", "AnOtherPermission")); final List<String> resourcePermissions = Arrays.asList("CasePermission", "SecondPermission"); returnPermissionFor("GET", "bpm", "case", null, resourcePermissions); final boolean isAuthorized = restAPIAuthorizationFilter.staticCheck(new APICallContext("GET", "bpm", "case", null), userPermissions, new HashSet<String>(resourcePermissions), username); assertThat(isAuthorized).isFalse(); }
### Question: RestAPIAuthorizationFilter extends AbstractAuthorizationFilter { protected boolean dynamicCheck(final APICallContext apiCallContext, final Set<String> userPermissions, final Set<String> resourceAuthorizations, final APISession apiSession) throws ServletException { checkResourceAuthorizationsSyntax(resourceAuthorizations); if (checkDynamicPermissionsWithUsername(resourceAuthorizations, apiSession) || checkDynamicPermissionsWithProfiles(resourceAuthorizations, userPermissions)) { return true; } final String resourceClassname = getResourceClassname(resourceAuthorizations); if (resourceClassname != null) { return checkDynamicPermissionsWithScript(apiCallContext, resourceClassname, apiSession); } return false; } RestAPIAuthorizationFilter(final boolean reload); RestAPIAuthorizationFilter(); static final String SCRIPT_TYPE_AUTHORIZATION_PREFIX; }### Answer: @Test public void should_dynamicCheck_return_false_on_resource_with_no_script() throws Exception { final boolean isAuthorized = restAPIAuthorizationFilter.dynamicCheck(new APICallContext("GET", "bpm", "case", null, "", ""), new HashSet<String>(), new HashSet<String>(), apiSession); assertThat(isAuthorized).isFalse(); }
### Question: RestAPIAuthorizationFilter extends AbstractAuthorizationFilter { @Override protected boolean checkValidCondition(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) throws ServletException { try { if (httpRequest.getRequestURI().matches(PLATFORM_API_URI_REGEXP)) { return platformAPIsCheck(httpRequest, httpResponse); } else { return tenantAPIsCheck(httpRequest, httpResponse); } } catch (final Exception e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } throw new ServletException(e); } } RestAPIAuthorizationFilter(final boolean reload); RestAPIAuthorizationFilter(); static final String SCRIPT_TYPE_AUTHORIZATION_PREFIX; }### Answer: @Test public void should_checkValidCondition_check_session_is_platform() throws ServletException { doReturn("API/platform/plop").when(request).getRequestURI(); doReturn(mock(PlatformSession.class)).when(httpSession).getAttribute(RestAPIAuthorizationFilter.PLATFORM_SESSION_PARAM_KEY); final boolean isValid = restAPIAuthorizationFilter.checkValidCondition(request, response); assertThat(isValid).isTrue(); } @Test public void should_checkValidCondition_check_session_is_platform_with_API_toolkit() throws ServletException { doReturn("APIToolkit/platform/plop").when(request).getRequestURI(); doReturn(mock(PlatformSession.class)).when(httpSession).getAttribute(RestAPIAuthorizationFilter.PLATFORM_SESSION_PARAM_KEY); final boolean isValid = restAPIAuthorizationFilter.checkValidCondition(request, response); assertThat(isValid).isTrue(); } @Test public void should_checkValidCondition_check_unauthorized_if_no_platform_session() throws ServletException { doReturn("API/platform/plop").when(request).getRequestURI(); doReturn(null).when(httpSession).getAttribute(RestAPIAuthorizationFilter.PLATFORM_SESSION_PARAM_KEY); final boolean isValid = restAPIAuthorizationFilter.checkValidCondition(request, response); assertThat(isValid).isFalse(); verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } @Test public void should_checkValidCondition_check_unauthorized_if_no_tenant_session() throws ServletException { doReturn(null).when(httpSession).getAttribute(SessionUtil.API_SESSION_PARAM_KEY); doReturn("API/bpm/case/15").when(request).getRequestURI(); final boolean isValid = restAPIAuthorizationFilter.checkValidCondition(request, response); assertThat(isValid).isFalse(); verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } @Test(expected = ServletException.class) public void should_checkValidCondition_catch_runtime() throws ServletException { doThrow(new RuntimeException()).when(request).getRequestURI(); restAPIAuthorizationFilter.checkValidCondition(request, response); }
### Question: RestAPIAuthorizationFilter extends AbstractAuthorizationFilter { protected boolean checkResourceAuthorizationsSyntax(final Set<String> resourceAuthorizations) { boolean valid = true; for (final String resourceAuthorization : resourceAuthorizations) { if (!resourceAuthorization.matches("(" + PermissionsBuilder.USER_TYPE_AUTHORIZATION_PREFIX + "|" + PermissionsBuilder.PROFILE_TYPE_AUTHORIZATION_PREFIX + "|" + SCRIPT_TYPE_AUTHORIZATION_PREFIX + ")\\|.+")) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Error while getting dynamic authoriations. Unknown syntax: " + resourceAuthorization + " defined in dynamic-permissions-checks.properties"); } valid = false; } } return valid; } RestAPIAuthorizationFilter(final boolean reload); RestAPIAuthorizationFilter(); static final String SCRIPT_TYPE_AUTHORIZATION_PREFIX; }### Answer: @Test public void checkResourceAuthorizationsSyntax_should_return_false_if_syntax_is_invalid() throws Exception { final RestAPIAuthorizationFilter restAPIAuthorizationFilterSpy = spy(restAPIAuthorizationFilter); final Set<String> resourceAuthorizations = new HashSet<String>(); resourceAuthorizations.add("any string"); final boolean isValid = restAPIAuthorizationFilterSpy.checkResourceAuthorizationsSyntax(resourceAuthorizations); assertThat(isValid).isFalse(); } @Test public void checkResourceAuthorizationsSyntax_should_return_true_if_syntax_is_valid() throws Exception { final RestAPIAuthorizationFilter restAPIAuthorizationFilterSpy = spy(restAPIAuthorizationFilter); final Set<String> resourceAuthorizations = new HashSet<String>(Arrays.asList("user|any.username", "profile|any.profile", "check|className")); final boolean isValid = restAPIAuthorizationFilterSpy.checkResourceAuthorizationsSyntax(resourceAuthorizations); assertThat(isValid).isTrue(); }
### Question: TokenGeneratorFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; final HttpServletResponse res = (HttpServletResponse) response; final String apiTokenFromClient = tokenGenerator.createOrLoadToken(req.getSession()); tokenGenerator.setTokenToResponseHeader(res, apiTokenFromClient); portalCookies.addCSRFTokenCookieToResponse(req, res, apiTokenFromClient); chain.doFilter(req, res); } @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void init(final FilterConfig filterConfig); @Override void destroy(); }### Answer: @Test public void should_add_security_token_in_headers_and_in_cookies_when_token_already_exists() throws Exception { session.setAttribute(TokenGenerator.API_TOKEN, bonitaTokenValue); response.addHeader(bonitaTokenName, bonitaTokenValue); tokenGeneratorFilter.doFilter(request, response, filterChain); final Cookie csrfCookie = response.getCookie(bonitaTokenName); assertThat(csrfCookie.getName()).isEqualTo(bonitaTokenName); assertThat(csrfCookie.getPath()).isEqualTo(contextPath); assertThat(csrfCookie.getValue()).isEqualTo(bonitaTokenValue); assertThat(session.getAttribute(TokenGenerator.API_TOKEN)).isEqualTo(bonitaTokenValue); assertThat(response.getHeader(bonitaTokenName)).isEqualTo(bonitaTokenValue); verify(filterChain).doFilter(request, response); } @Test public void should_add_security_token_in_headers_and_in_cookies_when_no_previous_call() throws Exception { tokenGeneratorFilter.doFilter(request, response, filterChain); final Cookie csrfCookie = response.getCookie(bonitaTokenName); assertThat(csrfCookie.getName()).isEqualTo(bonitaTokenName); assertThat(csrfCookie.getPath()).isEqualTo(contextPath); assertThat(csrfCookie.getValue()).isNotEqualTo(bonitaTokenValue); assertThat(session.getAttribute(TokenGenerator.API_TOKEN)).isEqualTo(csrfCookie.getValue()); assertThat(response.getHeader(bonitaTokenName)).isEqualTo(csrfCookie.getValue()); verify(filterChain).doFilter(request, response); }
### Question: MultiReadHttpServletRequest extends HttpServletRequestWrapper { @Override public ServletInputStream getInputStream() throws IOException { if (readBytes == null) { readInputStream(); } return new CachedServletInputStream(); } MultiReadHttpServletRequest(final HttpServletRequest request); @Override ServletInputStream getInputStream(); @Override BufferedReader getReader(); }### Answer: @Test public void should_getInputStream_work_when_called_twice() throws Exception { ServletInputStream fakeInputStream = null; try { fakeInputStream = new FakeServletInputStream(); doReturn(fakeInputStream).when(request).getInputStream(); final MultiReadHttpServletRequest multiReadHttpServletRequest = new MultiReadHttpServletRequest(request); final InputStream inputStream = multiReadHttpServletRequest.getInputStream(); Assert.assertEquals("body content", IOUtils.toString(inputStream)); final InputStream inputStream2 = multiReadHttpServletRequest.getInputStream(); Assert.assertEquals("body content", IOUtils.toString(inputStream2)); } finally { if (fakeInputStream != null) { fakeInputStream.close(); } } }
### Question: AutoLoginCredentialsFinder { public AutoLoginCredentials getCredential(ProcessIdentifier processIdentifier, long tenantId){ AutoLoginCredentials autoLoginCredentials = getAutoLoginCredentials(processIdentifier, tenantId); return autoLoginCredentials; } AutoLoginCredentialsFinder(ConfigurationFilesManager configurationFilesManager); AutoLoginCredentials getCredential(ProcessIdentifier processIdentifier, long tenantId); }### Answer: @Test public void should_retrieve_credentials_when_autologin_available_for_the_requested_process_and_tenant() throws Exception{ when(configurationFilesManager.getTenantAutoLoginConfiguration(TENANT_ID)).thenReturn(autoLoginConfiguration); AutoLoginCredentials autoLoginCredentials = autoLoginCredentialsFinder.getCredential(new ProcessIdentifier("my process", "2.0"), TENANT_ID); assertThat(autoLoginCredentials.getUserName()).isEqualTo("john.bates"); assertThat(autoLoginCredentials.getPassword()).isEqualTo("bpm"); } @Test public void should_retrieve_empty_credentials_when_autologin_not_available_for_the_requested_process_and_tenant() throws Exception{ when(configurationFilesManager.getTenantAutoLoginConfiguration(TENANT_ID)).thenReturn(autoLoginConfiguration); AutoLoginCredentials autoLoginCredentials = autoLoginCredentialsFinder.getCredential(new ProcessIdentifier("process without autologin", "1.0"), TENANT_ID); assertThat(autoLoginCredentials).isEqualTo(null); } @Test public void should_retrieve_empty_credentials_when_cannot_read_configuration() throws Exception{ when(configurationFilesManager.getTenantAutoLoginConfiguration(TENANT_ID)).thenReturn(null); AutoLoginCredentials autoLoginCredentials = autoLoginCredentialsFinder.getCredential(new ProcessIdentifier("process without autologin", "1.0"), TENANT_ID); assertThat(autoLoginCredentials).isEqualTo(null); }
### Question: TenantIdAccessor { public long getRequestedTenantId() throws ServletException { return parseTenantId(request.getTenantId()); } TenantIdAccessor(HttpServletRequestAccessor request); long getRequestedTenantId(); long ensureTenantId(); long getDefaultTenantId(); long getTenantIdFromRequestOrCookie(); }### Answer: @Test public void testIfWeRetrieveRequestedTenantId() throws Exception { doReturn("5").when(requestAccessor).getTenantId(); TenantIdAccessor accessor = new TenantIdAccessor(requestAccessor); assertEquals(5L, accessor.getRequestedTenantId()); } @Test public void testNullTenantId() throws Exception { doReturn(null).when(requestAccessor).getTenantId(); TenantIdAccessor accessor = new TenantIdAccessor(requestAccessor); assertEquals(-1L, accessor.getRequestedTenantId()); }
### Question: TenantIdAccessor { public long ensureTenantId() throws ServletException { long tenantId = parseTenantId(request.getTenantId()); if(tenantId < 0) { return getDefaultTenantId(); } return getRequestedTenantId(); } TenantIdAccessor(HttpServletRequestAccessor request); long getRequestedTenantId(); long ensureTenantId(); long getDefaultTenantId(); long getTenantIdFromRequestOrCookie(); }### Answer: @Test(expected = ServletException.class) public void testInvalidTenantIdThrowsException() throws Exception { doReturn("invalid").when(requestAccessor).getTenantId(); new TenantIdAccessor(requestAccessor).ensureTenantId(); }
### Question: TenantIdAccessor { public long getTenantIdFromRequestOrCookie() throws ServletException { String tenantId = request.getTenantId(); if (tenantId == null) { tenantId = portalCookies.getTenantCookieFromRequest(request.asHttpServletRequest()); } if (tenantId == null) { return getDefaultTenantId(); } return parseTenantId(tenantId); } TenantIdAccessor(HttpServletRequestAccessor request); long getRequestedTenantId(); long ensureTenantId(); long getDefaultTenantId(); long getTenantIdFromRequestOrCookie(); }### Answer: @Test public void should_retrieve_tenant_id_from_request_when_set_in_request_parameters() throws Exception { request.setCookies(new Cookie("bonita.tenant", "123")); doReturn("5").when(requestAccessor).getTenantId(); long tenantId = tenantIdAccessor.getTenantIdFromRequestOrCookie(); assertThat(tenantId).isEqualTo(5); } @Test public void should_retrieve_tenant_id_from_cookies_when_not_set_in_request_parameters() throws Exception { request.setCookies(new Cookie("bonita.tenant", "123")); long tenantId = tenantIdAccessor.getTenantIdFromRequestOrCookie(); assertThat(tenantId).isEqualTo(123); }
### Question: LogoutServlet extends HttpServlet { protected String sanitizeLoginPageUrl(final String loginURL) { return new RedirectUrlBuilder(new URLProtector().protectRedirectUrl(loginURL)).build().getUrl(); } }### Answer: @Test public void testtSanitizeLoginPageUrlEmptyLoginPageUrl() throws Exception { String loginPage = logoutServlet.sanitizeLoginPageUrl(""); assertThat(loginPage).isEqualToIgnoringCase(""); } @Test public void testtSanitizeLoginPageUrlFromMaliciousRedirectShouldReturnBrokenUrl() throws Exception { try { logoutServlet.sanitizeLoginPageUrl("http: fail("building a login page with a different host on the redirectURL should fail"); } catch (Exception e) { if (!(e.getCause() instanceof URISyntaxException)) { fail("Exception root cause should be a URISyntaxException"); } } } @Test public void testtSanitizeLoginPageUrlFromMaliciousRedirectShouldReturnBrokenUrl2() throws Exception { String loginPage = logoutServlet.sanitizeLoginPageUrl("test.com"); assertThat(loginPage).isEqualToIgnoringCase("test.com"); } @Test public void testSanitizeLoginPageUrlShouldReturnCorrectUrl() throws Exception { String loginPage = logoutServlet.sanitizeLoginPageUrl("portal/homepage?p=test#poutpout"); assertThat(loginPage).isEqualToIgnoringCase("portal/homepage?p=test#poutpout"); }
### Question: LogoutServlet extends HttpServlet { protected String getURLToRedirectTo(final HttpServletRequestAccessor requestAccessor, final long tenantId) throws AuthenticationManagerNotFoundException, UnsupportedEncodingException, ConsumerNotFoundException, ServletException { final AuthenticationManager authenticationManager = getAuthenticationManager(tenantId); final HttpServletRequest request = requestAccessor.asHttpServletRequest(); final String redirectURL = createRedirectUrl(requestAccessor, tenantId); final String logoutPage = authenticationManager.getLogoutPageURL(requestAccessor, redirectURL); String redirectionPage = null; if (logoutPage != null) { redirectionPage = logoutPage; } else { final String loginPageURLFromRequest = request.getParameter(LOGIN_URL_PARAM_NAME); if (loginPageURLFromRequest != null) { redirectionPage = sanitizeLoginPageUrl(loginPageURLFromRequest); } else { LoginUrl loginPageURL = new LoginUrl(authenticationManager, redirectURL, requestAccessor); redirectionPage = loginPageURL.getLocation(); } } return redirectionPage; } }### Answer: @Test public void testGetURLToRedirectToFromAuthenticationManagerLogin() throws Exception { doReturn("loginURL").when(authenticationManager).getLoginPageURL(eq(requestAccessor), anyString()); String loginPage = logoutServlet.getURLToRedirectTo(requestAccessor, 1L); assertThat(loginPage).isEqualTo("loginURL"); } @Test public void testGetURLToRedirectToFromRequest() throws Exception { doReturn(null).when(authenticationManager).getLoginPageURL(eq(requestAccessor), anyString()); doReturn("redirectURLFromRequest").when(request).getParameter(LogoutServlet.LOGIN_URL_PARAM_NAME); String loginPage = logoutServlet.getURLToRedirectTo(requestAccessor, 1L); assertThat(loginPage).isEqualTo("redirectURLFromRequest"); }
### Question: LogoutServlet extends HttpServlet { protected String createRedirectUrl(final HttpServletRequestAccessor request, final long tenantId) throws ServletException { final String redirectUrlFromRequest = request.getRedirectUrl(); String redirectUrl = redirectUrlFromRequest != null ? redirectUrlFromRequest : getDefaultRedirectUrl(tenantId); return new RedirectUrlBuilder(redirectUrl).build().getUrl(); } }### Answer: @Test public void testCreateRedirectUrlWithDefaultRedirect() throws Exception { doReturn(null).when(requestAccessor).getRedirectUrl(); String redirectURL = logoutServlet.createRedirectUrl(requestAccessor, 1L); assertThat(redirectURL).isEqualTo(AuthenticationManager.DEFAULT_DIRECT_URL); } @Test public void testCreateRedirectUrlWithDefaultRedirectAndNonDefaultTenant() throws Exception { doReturn(null).when(requestAccessor).getRedirectUrl(); String redirectURL = logoutServlet.createRedirectUrl(requestAccessor, 3L); assertThat(redirectURL).isEqualTo(AuthenticationManager.DEFAULT_DIRECT_URL + "?tenant=3"); } @Test public void testCreateRedirectUrl() throws Exception { doReturn("redirectURL").when(requestAccessor).getRedirectUrl(); String redirectURL = logoutServlet.createRedirectUrl(requestAccessor, 1L); assertThat(redirectURL).isEqualTo("redirectURL"); }
### Question: LoginServlet extends HttpServlet { public String dropPassword(final String content) { String tmp = content; if (content != null && content.contains("password")) { tmp = tmp.replaceAll("[&]?password=([^&|#]*)?", ""); } return tmp; } String dropPassword(final String content); }### Answer: @Test public void testPasswordIsDroppedWhenParameterIsLast() throws Exception { final LoginServlet servlet = new LoginServlet(); final String cleanQueryString = servlet.dropPassword("?username=walter.bates&password=bpm"); assertThat(cleanQueryString, is("?username=walter.bates")); } @Test public void testPasswordIsDroppedWhenParameterIsBeforeHash() throws Exception { final LoginServlet servlet = new LoginServlet(); final String cleanQueryString = servlet.dropPassword("?username=walter.bates&password=bpm#hash"); assertThat(cleanQueryString, is("?username=walter.bates#hash")); } @Test public void testUrlIsDroppedWhenParameterIsFirstAndBeforeHash() throws Exception { final LoginServlet servlet = new LoginServlet(); final String cleanQueryString = servlet.dropPassword("?username=walter.bates&password=bpm#hash"); assertThat(cleanQueryString, is("?username=walter.bates#hash")); } @Test public void testUrlStayTheSameIfNoPasswordArePresent() throws Exception { final LoginServlet servlet = new LoginServlet(); final String cleanQueryString = servlet.dropPassword("?param=value#dhash"); assertThat(cleanQueryString, is("?param=value#dhash")); } @Test public void testPasswordIsDroppedEvenIfQueryMarkUpIsntThere() throws Exception { final LoginServlet servlet = new LoginServlet(); final String cleanQueryString = servlet.dropPassword("password=bpm#dhash1&dhash2"); assertThat(cleanQueryString, is("#dhash1&dhash2")); } @Test public void testUrlStayEmptyIfParameterIsEmpty() throws Exception { final LoginServlet servlet = new LoginServlet(); final String cleanQueryString = servlet.dropPassword(""); assertThat(cleanQueryString, is("")); } @Test public void testDropPasswordOnRealUrl() throws Exception { final LoginServlet servlet = new LoginServlet(); final String cleanUrl = servlet .dropPassword( "?username=walter.bates&password=bpm&redirectUrl=http%3A%2F%2Flocalhost%3A8080%2Fbonita%2Fportal%2Fhomepage%3Fui%3Dform%26locale%3Den%23form%3DPool-\n" + "-1.0%24entry%26process%3D8506394779365952706%26mode%3Dapp"); assertThat(cleanUrl, is("?username=walter.bates&redirectUrl=http%3A%2F%2Flocalhost%3A8080%2Fbonita%2Fportal%2Fhomepage%3Fui%3Dform%26locale%3Den%23form%3DPool-\n" + "-1.0%24entry%26process%3D8506394779365952706%26mode%3Dapp")); }
### Question: LoginServlet extends HttpServlet { @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException { try { request.setCharacterEncoding(StandardCharsets.UTF_8.name()); } catch (final UnsupportedEncodingException e) { throw new ServletException(e); } if (request.getContentType() != null && !MediaType.APPLICATION_WWW_FORM.equals(ContentType.readMediaType(request.getContentType()))) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "The only content type supported by this service is application/x-www-form-urlencoded. The content-type request header needs to be set accordingly."); } response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); } else { handleLogin(request, response); } } String dropPassword(final String content); }### Answer: @Test public void should_send_error_415_when_login_with_wrong_content_type() throws Exception { final LoginServlet servlet = spy(new LoginServlet()); doReturn("application/json").when(req).getContentType(); servlet.doPost(req, resp); verify(resp).setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); }
### Question: URLProtector { public String protectRedirectUrl(String redirectUrl) { if (redirectUrl != null && !redirectUrl.startsWith("portal")) { return removeTokenFromUrl(redirectUrl, new ArrayList<String>(tokens)); } return redirectUrl; } String protectRedirectUrl(String redirectUrl); }### Answer: @Test public void testProtectRedirectUrlShouldRemoveHTTPFromURL() { assertEquals("google", urlProtecter.protectRedirectUrl("httpgoogle")); } @Test public void testProtectRedirectUrlShouldRemoveHTTPSFromURL() { assertEquals("google", urlProtecter.protectRedirectUrl("httpsgoogle")); } @Test public void testProtectRedirectUrlShouldNotChangeURL() { assertEquals("mobile/#home", urlProtecter.protectRedirectUrl("mobile/#home")); assertEquals("/bonita/mobile/#login", urlProtecter.protectRedirectUrl("/bonita/mobile/#login")); assertEquals("/bonita/portal", urlProtecter.protectRedirectUrl("/bonita/portal")); } @Test public void testProtectRedirectUrlRedirectingtoCaseListingUser() { assertEquals("#?_p=caselistinguser", urlProtecter.protectRedirectUrl("#?_p=caselistinguser")); } @Test public void testProtectRedirectUrlIsNotChangedIfStartingWithBonitaPortal() { assertEquals("portal/homepage#?_p=caselistinguser&test=http: urlProtecter.protectRedirectUrl("portal/homepage#?_p=caselistinguser&test=http: } @Test public void it_should_filter_capital_letters(){ assertEquals(":.google.com", urlProtecter.protectRedirectUrl("HTTPS: } @Test public void it_should_filter_double_backslash() { assertEquals(".google.com", urlProtecter.protectRedirectUrl(" assertEquals("google.com", urlProtecter.protectRedirectUrl(" }
### Question: PlatformLoginServlet extends HttpServlet { @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { boolean redirectAfterLogin = true; final String redirectAfterLoginStr = request.getParameter(AuthenticationManager.REDIRECT_AFTER_LOGIN_PARAM_NAME); if (Boolean.FALSE.toString().equals(redirectAfterLoginStr)) { redirectAfterLogin = false; } PlatformSession platformSession; PlatformLoginAPI platformLoginAPI; final String username = request.getParameter(USERNAME_PARAM); final String password = request.getParameter(PASSWORD_PARAM); try { platformLoginAPI = getPlatformLoginAPI(); platformSession = platformLoginAPI.login(username, password); request.getSession().setAttribute(PLATFORMSESSION, platformSession); String csrfToken = tokenGenerator.createOrLoadToken(request.getSession()); portalCookies.addCSRFTokenCookieToResponse(request, response, csrfToken); if (redirectAfterLogin) { response.sendRedirect(PLATFORM_PAGE); } } catch (final InvalidPlatformCredentialsException e) { LOGGER.log(Level.FINEST, "Wrong username or password", e); response.sendError(HttpServletResponse.SC_FORBIDDEN, "Wrong username or password"); } catch (final Exception e) { LOGGER.log(Level.SEVERE, ERROR_MESSAGE, e); if (redirectAfterLogin) { try { request.setAttribute(LOGIN_FAIL_MESSAGE, LOGIN_FAIL_MESSAGE); getServletContext().getRequestDispatcher(LOGIN_PAGE).forward(request, response); } catch (final IOException ioe) { LOGGER.log(Level.SEVERE, "Error while redirecting to login.jsp", ioe); throw new ServletException(ERROR_MESSAGE, e); } } else { throw new ServletException(ERROR_MESSAGE, e); } } } static final String ERROR_MESSAGE; }### Answer: @Test public void should_send_error_403_on_wrong_credential() throws Exception { doThrow(new InvalidPlatformCredentialsException("")).when(platformLoginAPI).login(JOHN, DOE); platformLoginServlet.doPost(httpServletRequest, httpServletResponse); verify(httpServletResponse).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString()); } @Test(expected = ServletException.class) public void should_throw_exception_on_internal_error() throws Exception { doThrow(new PlatformLoginException("")).when(platformLoginAPI).login(JOHN, DOE); platformLoginServlet.doPost(httpServletRequest, httpServletResponse); }
### Question: RedirectUrlBuilder { public RedirectUrl build() { return new RedirectUrl(urlBuilder.build()); } RedirectUrlBuilder(final String redirectUrl); RedirectUrl build(); void appendParameters(final Map<String, String[]> parameters); void appendParameter(String name, String... values); }### Answer: @Test public void testWeCanBuildHashTaggedParamAreKept() throws Exception { final RedirectUrlBuilder redirectUrlBuilder = new RedirectUrlBuilder("myredirecturl?parambeforehash=true#hashparam=true"); final String url = redirectUrlBuilder.build().getUrl(); assertEquals("myredirecturl?parambeforehash=true#hashparam=true", url); } @Test public void testPostParamsAreNotAddedToTheUrl() { final Map<String, String[]> parameters = new HashMap<String, String[]>(); parameters.put("postParam", someValues("true")); final RedirectUrlBuilder redirectUrlBuilder = new RedirectUrlBuilder("myredirecturl?someparam=value#hashparam=true"); final String url = redirectUrlBuilder.build().getUrl(); assertEquals("myredirecturl?someparam=value#hashparam=true", url); }
### Question: ProcessInstanceExpressionsEvaluator { public Map<String, Serializable> evaluate(ProcessInstanceAccessor instance, final Map<Expression, Map<String, Serializable>> expressions, boolean atProcessInstanciation) throws BPMEngineException, BPMExpressionEvaluationException { if (atProcessInstanciation) { return evaluateExpressionsAtProcessInstanciation(instance.getId(), expressions); } else if (instance.isArchived()) { return evaluateExpressionsOnCompleted(instance.getId(), expressions); } else { return evaluateExpressionsOnProcessInstance(instance.getId(), expressions); } } ProcessInstanceExpressionsEvaluator(ExpressionEvaluatorEngineClient engineEvaluator); Map<String, Serializable> evaluate(ProcessInstanceAccessor instance, final Map<Expression, Map<String, Serializable>> expressions, boolean atProcessInstanciation); }### Answer: @Test public void testEvaluateExpressionOnCompletedProcessInstance() throws Exception { when(processInstance.getId()).thenReturn(2L); when(processInstance.isArchived()).thenReturn(true); when(engineEvaluator.evaluateExpressionsOnCompletedProcessInstance(2L, someExpressions)) .thenReturn(aKnownResultSet()); Map<String, Serializable> evaluated = evaluator.evaluate(processInstance, someExpressions, false); assertEquals(aKnownResultSet(), evaluated); }
### Question: TenantIdAccessorFactory { @SuppressWarnings("unchecked") public static TenantIdAccessor getTenantIdAccessor(HttpServletRequestAccessor requestAccessor) { ServerProperties serverProperties = ServerProperties.getInstance(); String tenantIdAccessorClassName = serverProperties.getValue(TENANTIDACCESSOR_PROPERTY_NAME); TenantIdAccessor tenantIdAccessor; if (tenantIdAccessorClassName == null || tenantIdAccessorClassName.isEmpty()) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "auth.TenantIdAccessor is undefined. Using default implementation : " + TenantIdAccessor.class.getName()); } tenantIdAccessor = new TenantIdAccessor(requestAccessor); } else { try { Constructor<TenantIdAccessor> constructor = (Constructor<TenantIdAccessor>) Class.forName(tenantIdAccessorClassName).getConstructor(HttpServletRequestAccessor.class); tenantIdAccessor = constructor.newInstance(requestAccessor); } catch (Exception e) { LOGGER.log(Level.SEVERE, "The TenantIdAccessor specified " + tenantIdAccessorClassName + " could not be instantiated! Using default implementation : " + TenantIdAccessor.class.getName(), e); tenantIdAccessor = new TenantIdAccessor(requestAccessor); } } return tenantIdAccessor; } @SuppressWarnings("unchecked") static TenantIdAccessor getTenantIdAccessor(HttpServletRequestAccessor requestAccessor); }### Answer: @Test public void should_return_TenantIdAccessor() { assertThat(TenantIdAccessorFactory.getTenantIdAccessor(requestAccessor)).isInstanceOf(TenantIdAccessor.class); }
### Question: PortalCookies { public String getTenantCookieFromRequest(HttpServletRequest request) { return getCookieValue(request, TENANT_COOKIE_NAME); } void addCSRFTokenCookieToResponse(HttpServletRequest request, HttpServletResponse res, Object apiTokenFromClient); void invalidateRootCookie(HttpServletResponse res, Cookie cookie, String path); boolean isCSRFTokenCookieSecure(); void addTenantCookieToResponse(HttpServletResponse response, Long tenantId); String getTenantCookieFromRequest(HttpServletRequest request); Cookie getCookie(HttpServletRequest request, String name); }### Answer: @Test public void should_get_tenant_cookie_from_request() throws Exception { request.setCookies(new Cookie("bonita.tenant", "123")); String tenant = portalCookies.getTenantCookieFromRequest(request); assertThat(tenant).isEqualTo("123"); }
### Question: PortalCookies { public Cookie getCookie(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { return cookie; } } } return null; } void addCSRFTokenCookieToResponse(HttpServletRequest request, HttpServletResponse res, Object apiTokenFromClient); void invalidateRootCookie(HttpServletResponse res, Cookie cookie, String path); boolean isCSRFTokenCookieSecure(); void addTenantCookieToResponse(HttpServletResponse response, Long tenantId); String getTenantCookieFromRequest(HttpServletRequest request); Cookie getCookie(HttpServletRequest request, String name); }### Answer: @Test public void should_get_cookie_by_name_from_request() throws Exception { Cookie cookie = new Cookie("bonita.tenant", "123"); request.setCookies(cookie); Cookie fetchedCookie = portalCookies.getCookie(request, "bonita.tenant"); assertThat(fetchedCookie).isEqualTo(cookie); }
### Question: WidgetExpressionEntry { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } WidgetExpressionEntry other = (WidgetExpressionEntry) obj; if (entry == null) { if (other.entry != null) { return false; } } else if (!entry.equals(other.entry)) { return false; } return true; } WidgetExpressionEntry(String widgetId, ExpressionId expressionId); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testTwoWidgetExpressionEntryEqualAREEquals() { WidgetExpressionEntry widget1 = new WidgetExpressionEntry("widgetId", ExpressionId.WIDGET_DISPLAY_CONDITION); WidgetExpressionEntry widget2 = new WidgetExpressionEntry("widgetId", ExpressionId.WIDGET_DISPLAY_CONDITION); boolean result = widget1.equals(widget2); assertTrue(result); } @Test public void testWidgetExpressionEntryIsNotEqualsToNull() { WidgetExpressionEntry widget = new WidgetExpressionEntry("widgetId", ExpressionId.WIDGET_DISPLAY_CONDITION); boolean result = widget.equals(null); assertFalse(result); }
### Question: TenantFileUploadServlet extends FileUploadServlet { @Override protected void setUploadSizeMax(final ServletFileUpload serviceFileUpload, final HttpServletRequest request) { serviceFileUpload.setFileSizeMax(getConsoleProperties(getAPISession(request).getTenantId()).getMaxSize() * MEGABYTE); } }### Answer: @Test public void should_throw_fileTooBigException_when_file_is_bigger_in_than_conf_file() throws Exception { final ServletFileUpload serviceFileUpload = mock(ServletFileUpload.class); when(consoleProperties.getMaxSize()).thenReturn(1L); fileUploadServlet.setUploadSizeMax(serviceFileUpload, request); verify(serviceFileUpload).setFileSizeMax(FileUploadServlet.MEGABYTE); }
### Question: FileUploadServlet extends HttpServlet { protected String getExtension(final String fileName) { String extension = ""; final String filenameLastSegment = getFilenameLastSegment(fileName); final int dotPos = filenameLastSegment.lastIndexOf('.'); if (dotPos > -1) { extension = filenameLastSegment.substring(dotPos); } return extension; } @Override void init(); @Override @SuppressWarnings("unchecked") void doPost(final HttpServletRequest request, final HttpServletResponse response); static final String RESPONSE_SEPARATOR; static final int MEGABYTE; }### Answer: @Test public void getExtension_should_return_proper_extension() throws IOException { final String filename = "C:\\Users\\Desktop\\process.bar"; final String extension = fileUploadServlet.getExtension(filename); assertThat(extension).isEqualTo(".bar"); } @Test public void getExtension_should_return_an_empty_extension() throws IOException { final String filename = "C:\\Users\\Desktop\\process"; final String extension = fileUploadServlet.getExtension(filename); assertThat(extension).isEqualTo(""); } @Test public void getExtension_should_return_a_proper_extension_without_taking_care_of_dots() throws IOException { final String filename = "C:\\Users\\Deskt.op\\proc.ess.bar"; final String extension = fileUploadServlet.getExtension(filename); assertThat(extension).isEqualTo(".bar"); } @Test public void getExtension_should_return_proper_extension_for_short_filename() throws IOException { final String filename = "process.bar"; final String extension = fileUploadServlet.getExtension(filename); assertThat(extension).isEqualTo(".bar"); } @Test public void getExtension_should_return_proper_extension_for_linux_like_paths() throws IOException { final String filename = "/Users/Deskt.op/proc.ess.bar"; final String extension = fileUploadServlet.getExtension(filename); assertThat(extension).isEqualTo(".bar"); } @Test public void getExtension_should_return_an_empty_extension_for_parent_folder_filename() throws IOException { final String filename = "../../../"; final String extension = fileUploadServlet.getExtension(filename); assertThat(extension).isEqualTo(""); }
### Question: FileUploadServlet extends HttpServlet { protected String getFilenameLastSegment(final String fileName) { int slashPos = fileName.lastIndexOf("/"); if (slashPos == -1) { slashPos = fileName.lastIndexOf("\\"); } return fileName.substring(slashPos+1); } @Override void init(); @Override @SuppressWarnings("unchecked") void doPost(final HttpServletRequest request, final HttpServletResponse response); static final String RESPONSE_SEPARATOR; static final int MEGABYTE; }### Answer: @Test public void getFilenameLastSegment_should_return_proper_filename() { final String filename = "C:\\Users\\Desktop\\process.bar"; final String filenameLastSegment = fileUploadServlet.getFilenameLastSegment(filename); assertThat(filenameLastSegment).isEqualTo("process.bar"); } @Test public void getFilenameLastSegment_should_return_proper_filename_for_linux_paths() { final String filename = "/Users/Deskt.op/process.bar"; final String filenameLastSegment = fileUploadServlet.getFilenameLastSegment(filename); assertThat(filenameLastSegment).isEqualTo("process.bar"); } @Test public void getFilenameLastSegment_should_return_an_empty_filename_for_parent_folder_filename() throws IOException { final String filename = "../../../"; final String filenameLastSegment = fileUploadServlet.getFilenameLastSegment(filename); assertThat(filenameLastSegment).isEqualTo(""); }
### Question: UrlBuilder { public String build() { if (!parameters.isEmpty()) { uriBuilder.setParameters(parameters); } return uriBuilder.toString(); } UrlBuilder(final String urlString); void appendParameter(final String key, final String... values); void appendParameters(final Map<String, String[]> parameters); String build(); }### Answer: @Test public void should_leave_path_unchanged() throws Exception { urlBuilder = new UrlBuilder("http: assertThat(urlBuilder.build()).isEqualTo("http: } @Test public void should_leave_path_unchanged2() throws Exception { urlBuilder = new UrlBuilder("http: assertThat(urlBuilder.build()).isEqualTo("http: } @Test public void should_leave_path_with_space_unchanged() throws Exception { urlBuilder = new UrlBuilder("http: assertThat(urlBuilder.build()).isEqualTo("http: } @Test public void should_leave_URL_without_querystring_unchanged() throws Exception { urlBuilder = new UrlBuilder("http: assertThat(urlBuilder.build()).isEqualTo("http: }
### Question: FormFieldValuesUtil { protected List<Expression> getExpressionsToEvaluation(final List<FormWidget> widgets, final Map<String, Serializable> resolvedDisplayExp, final Map<String, Object> context) { final List<Expression> expressionsToEvaluate = new ArrayList<Expression>(); for (final FormWidget formWidget : widgets) { if (isAuthorized(resolvedDisplayExp, formWidget.getId())) { expressionsToEvaluate.addAll(getWidgetExpressions(formWidget, context)); } } return expressionsToEvaluate; } FormFieldValue getFieldValue(final Object value, final FormWidget formWidget, final Locale locale); List<ReducedFormFieldAvailableValue> getAvailableValues(final Object availableValuesObject, final String widgetId); List<List<ReducedFormFieldAvailableValue>> getTableAvailableValues(final Object tableAvailableValuesObject, final String widgetId); void setFormWidgetValues(final long tenantID, final FormWidget formWidget, final Map<String, Serializable> evaluatedExpressions, final Map<String, Object> context); @SuppressWarnings("unchecked") void setTablesParams(final FormWidget formWidget, final Map<String, Serializable> evaluatedExpressions, final Map<String, Object> context); void setFormWidgetsValues(final long tenantID, final List<FormWidget> widgets, final Map<String, Object> context); void storeWidgetsInCacheAndSetCacheID(final long tenantID, final String formID, final String pageID, final String locale, final Date processDeployementDate, final List<FormWidget> formWidgets); static final String EXPRESSION_KEY_SEPARATOR; }### Answer: @Test public void testWeRetrieveExpressionOfDisplayedWidgetOnly() throws Exception { final List<FormWidget> widgets = Arrays.asList( aWidgetWithLabelExpression("widget1"), aWidgetWithLabelExpression("widget2")); final Map<String, Serializable> resolvedDisplayExp = new HashMap<String, Serializable>(); resolvedDisplayExp.put(new WidgetExpressionEntry("widget1", ExpressionId.WIDGET_DISPLAY_CONDITION) .toString(), true); resolvedDisplayExp.put(new WidgetExpressionEntry("widget2", ExpressionId.WIDGET_DISPLAY_CONDITION) .toString(), false); final List<Expression> expressions = util.getExpressionsToEvaluation( widgets, resolvedDisplayExp, new HashMap<String, Object>()); assertEquals(1, expressions.size()); assertEquals("widget1:label", expressions.get(0).getName()); } @Test public void testWeRetrieveExpressionOfWidgetWithoutDisplayExpressions() throws Exception { final List<FormWidget> widgets = Arrays.asList(aWidgetWithLabelExpression("widget")); final List<Expression> expressions = util.getExpressionsToEvaluation( widgets, new HashMap<String, Serializable>(), new HashMap<String, Object>()); assertEquals(1, expressions.size()); assertEquals("widget:label", expressions.get(0).getName()); } @Test public void testWeDoNotRetrieveDisplayExpressionOfWidgetNotDisplayed() { final FormWidget widget = new FormWidget(); widget.setId("widget"); final Expression expression = new Expression(); expression.setName("expression"); widget.setDisplayConditionExpression(expression); final Map<String, Serializable> resolvedDisplayExp = new HashMap<String, Serializable>(); resolvedDisplayExp.put(new WidgetExpressionEntry("widget", ExpressionId.WIDGET_DISPLAY_CONDITION) .toString(), false); final List<Expression> expressions = util.getExpressionsToEvaluation( Arrays.asList(widget), resolvedDisplayExp, new HashMap<String, Object>()); assertTrue(expressions.isEmpty()); }
### Question: ContractTypeConverter { public ContractDefinition getAdaptedContractDefinition(final ContractDefinition contract) { final List<ConstraintDefinition> constraints = contract.getConstraints(); final List<InputDefinition> inputDefinitions = adaptContractInputList(contract.getInputs()); final ContractDefinitionImpl contractDefinition = getContractDefinition(constraints, inputDefinitions); return contractDefinition; } ContractTypeConverter(final String[] datePatterns); Map<String, Serializable> getProcessedInput(final ContractDefinition processContract, final Map<String, Serializable> inputs, final long maxSizeForTenant, final long tenantId); void deleteTemporaryFiles(Map<String, Serializable> inputs, long tenantId); ContractDefinition getAdaptedContractDefinition(final ContractDefinition contract); static final String[] ISO_8601_DATE_PATTERNS; }### Answer: @Test public void getAdaptedContractDefinition_should_return_a_converter_contract() throws IOException { final ContractDefinitionImpl processContract = new ContractDefinitionImpl(); final List<InputDefinition> inputDefinitions = new ArrayList<>(); inputDefinitions.add(new InputDefinitionImpl(InputDefinition.FILE_INPUT_FILENAME, Type.TEXT, "Name of the file", false)); inputDefinitions.add(new InputDefinitionImpl(InputDefinition.FILE_INPUT_CONTENT, Type.BYTE_ARRAY, "Content of the file", false)); processContract.addInput(new InputDefinitionImpl("inputFile", "this is a input file", false, Type.FILE, inputDefinitions)); final ContractDefinition adaptedContractDefinition = contractTypeConverter.getAdaptedContractDefinition(processContract); final InputDefinition tempPathFileInputDefinition = adaptedContractDefinition.getInputs().get(0).getInputs().get(1); assertThat(tempPathFileInputDefinition.getType()).isEqualTo(Type.TEXT); assertThat(tempPathFileInputDefinition.getName()).isEqualTo(ContractTypeConverter.FILE_TEMP_PATH); assertThat(tempPathFileInputDefinition.getDescription()).isEqualTo(ContractTypeConverter.TEMP_PATH_DESCRIPTION); }
### Question: AuthenticationManagerFactory { public static AuthenticationManager getAuthenticationManager(final long tenantId) throws AuthenticationManagerNotFoundException { String authenticationManagerName = null; if (!map.containsKey(tenantId)) { try { authenticationManagerName = getManagerImplementationClassName(tenantId); final AuthenticationManager authenticationManager = (AuthenticationManager) Class.forName(authenticationManagerName).newInstance(); map.put(tenantId, authenticationManager); } catch (final Exception e) { final String message = "The AuthenticationManager implementation " + authenticationManagerName + " does not exist!"; throw new AuthenticationManagerNotFoundException(message); } } return map.get(tenantId); } static AuthenticationManager getAuthenticationManager(final long tenantId); }### Answer: @Test public void testGetLoginManager() throws AuthenticationManagerNotFoundException { assertNotNull("Cannot get the login manager", AuthenticationManagerFactory.getAuthenticationManager(0L)); }
### Question: StandardAuthenticationManagerImpl implements AuthenticationManager { @Override public String getLoginPageURL(final HttpServletRequestAccessor request, final String redirectURL) throws ServletException { final StringBuilder url = new StringBuilder(); String context = request.asHttpServletRequest().getContextPath(); final String servletPath = request.asHttpServletRequest().getServletPath(); if (StringUtils.isNotBlank(servletPath) && servletPath.startsWith("/mobile")) { context += "/mobile"; } url.append(context).append(AuthenticationManager.LOGIN_PAGE).append("?"); long tenantId = getTenantId(request); if (tenantId != getDefaultTenantId()) { url.append(AuthenticationManager.TENANT).append("=").append(tenantId).append("&"); } String localeFromRequestedURL = LocaleUtils.getLocaleFromRequestURL(request.asHttpServletRequest()); if (localeFromRequestedURL != null) { url.append(LocaleUtils.PORTAL_LOCALE_PARAM).append("=").append(localeFromRequestedURL).append("&"); } url.append(AuthenticationManager.REDIRECT_URL).append("=").append(redirectURL); return url.toString(); } @Override String getLoginPageURL(final HttpServletRequestAccessor request, final String redirectURL); @Override Map<String, Serializable> authenticate(final HttpServletRequestAccessor requestAccessor, final Credentials credentials); @Override String getLogoutPageURL(final HttpServletRequestAccessor request, final String redirectURL); }### Answer: @Test public void testGetSimpleLoginpageURL() throws Exception { String redirectUrl = "%2Fportal%2Fhomepage"; String loginURL = standardLoginManagerImpl.getLoginPageURL(requestAccessor, redirectUrl); assertThat(loginURL).isEqualToIgnoringCase("bonita/login.jsp?tenant=1&redirectUrl=%2Fportal%2Fhomepage"); } @Test public void testGetLoginpageURLWithLocale() throws Exception { String redirectUrl = "%2Fportal%2Fhomepage"; request.setParameter("_l", "es"); String loginURL = standardLoginManagerImpl.getLoginPageURL(requestAccessor, redirectUrl); assertThat(loginURL).isEqualToIgnoringCase("bonita/login.jsp?tenant=1&_l=es&redirectUrl=%2Fportal%2Fhomepage"); } @Test public void testGetLoginpageURLFromPortal() throws Exception { String redirectUrl = "%2Fportal%2Fhomepage"; request.setServletPath("/portal/"); String loginURL = standardLoginManagerImpl.getLoginPageURL(requestAccessor, redirectUrl); assertThat(loginURL).isEqualToIgnoringCase("bonita/login.jsp?tenant=1&redirectUrl=%2Fportal%2Fhomepage"); } @Test public void testGetLoginpageURLFromMobile() throws Exception { String redirectUrl = "%2Fmobile%2F"; request.setServletPath("/mobile/#login"); String loginURL = standardLoginManagerImpl.getLoginPageURL(requestAccessor, redirectUrl); assertThat(loginURL).isEqualToIgnoringCase("bonita/mobile/login.jsp?tenant=1&redirectUrl=%2Fmobile%2F"); } @Test public void should_add_tenant_parameter_contained_in_request_params() throws Exception { request.setParameter("tenant", "4"); request.setCookies(new Cookie("bonita.tenant", "123")); String redirectUrl = "%2Fportal%2Fhomepage"; String loginURL = standardLoginManagerImpl.getLoginPageURL(requestAccessor, redirectUrl); assertThat(loginURL).isEqualToIgnoringCase("bonita/login.jsp?tenant=4&redirectUrl=%2Fportal%2Fhomepage"); } @Test public void should_add_tenant_parameter_from_cookie_if_not_in_request() throws Exception { request.removeAllParameters(); request.setCookies(new Cookie("bonita.tenant", "123")); String redirectUrl = "%2Fportal%2Fhomepage"; String loginURL = standardLoginManagerImpl.getLoginPageURL(requestAccessor, redirectUrl); assertThat(loginURL).isEqualToIgnoringCase("bonita/login.jsp?tenant=123&redirectUrl=%2Fportal%2Fhomepage"); }
### Question: PageResourceProviderImpl implements PageResourceProvider { @Override public File getPageDirectory() { return pageDirectory; } PageResourceProviderImpl(final String pageName, final long tenantId); PageResourceProviderImpl(final Page page, final long tenantId); private PageResourceProviderImpl(final String pageName, final long tenantId, final Long pageId, final Long processDefinitionId); @Override InputStream getResourceAsStream(final String resourceName); @Override File getResourceAsFile(final String resourceName); @Override String getResourceURL(final String resourceName); @Override String getBonitaThemeCSSURL(); @Override File getPageDirectory(); File getTempPageFile(); void setResourceClassLoader(final ClassLoader resourceClassLoader); @Override ResourceBundle getResourceBundle(final String name, final Locale locale); @Override String getPageName(); @Override Page getPage(final PageAPI pageAPI); @Override String getFullPageName(); }### Answer: @Test public void should_pagedirectory_be_distinct() throws Exception { assertThat(pageResourceProvider.getPageDirectory()).as("should be distinct").isNotEqualTo(pageResourceProviderWithProcessDefinition.getPageDirectory()); }
### Question: PageResourceProviderImpl implements PageResourceProvider { public File getTempPageFile() { return pageTempFile; } PageResourceProviderImpl(final String pageName, final long tenantId); PageResourceProviderImpl(final Page page, final long tenantId); private PageResourceProviderImpl(final String pageName, final long tenantId, final Long pageId, final Long processDefinitionId); @Override InputStream getResourceAsStream(final String resourceName); @Override File getResourceAsFile(final String resourceName); @Override String getResourceURL(final String resourceName); @Override String getBonitaThemeCSSURL(); @Override File getPageDirectory(); File getTempPageFile(); void setResourceClassLoader(final ClassLoader resourceClassLoader); @Override ResourceBundle getResourceBundle(final String name, final Locale locale); @Override String getPageName(); @Override Page getPage(final PageAPI pageAPI); @Override String getFullPageName(); }### Answer: @Test public void should_temp_page_file_be_distinct() throws Exception { assertThat(pageResourceProvider.getTempPageFile()).as("should be page name").isNotEqualTo(pageResourceProviderWithProcessDefinition.getTempPageFile()); }
### Question: PageResourceProviderImpl implements PageResourceProvider { @Override public String getFullPageName() { return fullPageName; } PageResourceProviderImpl(final String pageName, final long tenantId); PageResourceProviderImpl(final Page page, final long tenantId); private PageResourceProviderImpl(final String pageName, final long tenantId, final Long pageId, final Long processDefinitionId); @Override InputStream getResourceAsStream(final String resourceName); @Override File getResourceAsFile(final String resourceName); @Override String getResourceURL(final String resourceName); @Override String getBonitaThemeCSSURL(); @Override File getPageDirectory(); File getTempPageFile(); void setResourceClassLoader(final ClassLoader resourceClassLoader); @Override ResourceBundle getResourceBundle(final String name, final Locale locale); @Override String getPageName(); @Override Page getPage(final PageAPI pageAPI); @Override String getFullPageName(); }### Answer: @Test public void should_testGetFullPageName_return_unique_key() throws Exception { assertThat(pageResourceProvider.getFullPageName()).as("should be page name").isEqualTo(PAGE_NAME); assertThat(pageResourceProvider.getFullPageName()).as("should be page name").isNotEqualTo(pageResourceProviderWithProcessDefinition.getFullPageName()); }
### Question: PageResourceProviderImpl implements PageResourceProvider { @Override public Page getPage(final PageAPI pageAPI) throws PageNotFoundException { if (pageId != null) { return pageAPI.getPage(pageId); } return pageAPI.getPageByName(getPageName()); } PageResourceProviderImpl(final String pageName, final long tenantId); PageResourceProviderImpl(final Page page, final long tenantId); private PageResourceProviderImpl(final String pageName, final long tenantId, final Long pageId, final Long processDefinitionId); @Override InputStream getResourceAsStream(final String resourceName); @Override File getResourceAsFile(final String resourceName); @Override String getResourceURL(final String resourceName); @Override String getBonitaThemeCSSURL(); @Override File getPageDirectory(); File getTempPageFile(); void setResourceClassLoader(final ClassLoader resourceClassLoader); @Override ResourceBundle getResourceBundle(final String name, final Locale locale); @Override String getPageName(); @Override Page getPage(final PageAPI pageAPI); @Override String getFullPageName(); }### Answer: @Test public void should_getPage_by_name() throws Exception { pageResourceProvider.getPage(pageApi); verify(pageApi).getPageByName(PAGE_NAME); } @Test public void should_getPage_by_id() throws Exception { pageResourceProviderWithProcessDefinition.getPage(pageApi); verify(pageApi,never()).getPageByName(anyString()); verify(pageApi).getPage(PAGE_ID); }
### Question: PageContextHelper { public String getCurrentProfile() { return request.getParameter(PROFILE_PARAM); } PageContextHelper(HttpServletRequest request); String getCurrentProfile(); Locale getCurrentLocale(); APISession getApiSession(); static final String PROFILE_PARAM; static final String ATTRIBUTE_API_SESSION; }### Answer: @Test public void should_return_CurrentProfile() throws Exception { doReturn(MY_PROFILE).when(request).getParameter(PageContextHelper.PROFILE_PARAM); pageContextHelper = new PageContextHelper(request); final String currentProfile = pageContextHelper.getCurrentProfile(); assertThat(currentProfile).isEqualTo(MY_PROFILE); }
### Question: PageContextHelper { public Locale getCurrentLocale() { return LocaleUtils.getUserLocale(request); } PageContextHelper(HttpServletRequest request); String getCurrentProfile(); Locale getCurrentLocale(); APISession getApiSession(); static final String PROFILE_PARAM; static final String ATTRIBUTE_API_SESSION; }### Answer: @Test public void should_getCurrentLocale_return_request_parameter() throws Exception { doReturn(locale.toString()).when(request).getParameter(LocaleUtils.LOCALE_PARAM); pageContextHelper = new PageContextHelper(request); final Locale returnedLocale = pageContextHelper.getCurrentLocale(); assertThat(returnedLocale).isEqualToComparingFieldByField(locale); } @Test public void should_getCurrentLocale_return_cookie_locale() throws Exception { Cookie[] cookieList = new Cookie[1]; cookieList[0] = new Cookie(LocaleUtils.LOCALE_COOKIE_NAME, locale.getLanguage()); doReturn(null).when(request).getParameter(LocaleUtils.LOCALE_PARAM); doReturn(cookieList).when(request).getCookies(); pageContextHelper = new PageContextHelper(request); final Locale returnedLocale = pageContextHelper.getCurrentLocale(); assertThat(returnedLocale).isEqualToComparingFieldByField(locale); } @Test public void should_getCurrentLocale_return_default_locale() throws Exception { Cookie[] cookieList = new Cookie[1]; cookieList[0] = new Cookie("otherCookie", "otherValue"); doReturn(null).when(request).getParameter(LocaleUtils.LOCALE_PARAM); doReturn(cookieList).when(request).getCookies(); pageContextHelper = new PageContextHelper(request); final Locale returnedLocale = pageContextHelper.getCurrentLocale(); assertThat(returnedLocale.toString()).isEqualTo(LocaleUtils.DEFAULT_LOCALE); }
### Question: PageContextHelper { public APISession getApiSession() { final HttpSession httpSession = request.getSession(); return (APISession) httpSession.getAttribute(ATTRIBUTE_API_SESSION); } PageContextHelper(HttpServletRequest request); String getCurrentProfile(); Locale getCurrentLocale(); APISession getApiSession(); static final String PROFILE_PARAM; static final String ATTRIBUTE_API_SESSION; }### Answer: @Test public void should_return_ApiSession() throws Exception { doReturn(httpSession).when(request).getSession(); doReturn(apiSession).when(httpSession).getAttribute(pageContextHelper.ATTRIBUTE_API_SESSION); pageContextHelper = new PageContextHelper(request); final APISession returnedApiSession = pageContextHelper.getApiSession(); assertThat(returnedApiSession).isEqualTo(apiSession); }
### Question: CustomPageRequestModifier { public void redirectToValidPageUrl(final HttpServletRequest request, final HttpServletResponse response) throws IOException { final StringBuilder taskURLBuilder = new StringBuilder(request.getContextPath()); taskURLBuilder.append(request.getServletPath()) .append(request.getPathInfo()) .append("/"); if(!StringUtil.isBlank(request.getQueryString())){ taskURLBuilder.append("?").append(request.getQueryString()); } response.sendRedirect(response.encodeRedirectURL(taskURLBuilder.toString())); } void redirectToValidPageUrl(final HttpServletRequest request, final HttpServletResponse response); void forwardIfRequestIsAuthorized(final HttpServletRequest request, final HttpServletResponse response, final String apiPathShouldStartWith, final String apiPath); }### Answer: @Test public void redirect_with_trailing_slash_should_not_encode_parameter() throws Exception { when(request.getContextPath()).thenReturn("bonita/"); when(request.getServletPath()).thenReturn("apps/"); when(request.getPathInfo()).thenReturn("myapp/mypage"); when(request.getQueryString()).thenReturn("time=12:00"); when(response.encodeRedirectURL("bonita/apps/myapp/mypage/?time=12:00")).thenReturn("bonita/apps/myapp/mypage/?time=12:00"); CustomPageRequestModifier customPageRequestModifier = new CustomPageRequestModifier(); customPageRequestModifier.redirectToValidPageUrl(request, response); verify(response).sendRedirect("bonita/apps/myapp/mypage/?time=12:00"); } @Test public void redirect_with_trailing_slash_should_not_add_question_mark() throws Exception { when(request.getContextPath()).thenReturn("bonita/"); when(request.getServletPath()).thenReturn("apps/"); when(request.getPathInfo()).thenReturn("myapp/mypage"); when(response.encodeRedirectURL("bonita/apps/myapp/mypage/")).thenReturn("bonita/apps/myapp/mypage/"); CustomPageRequestModifier customPageRequestModifier = new CustomPageRequestModifier(); customPageRequestModifier.redirectToValidPageUrl(request, response); verify(response).sendRedirect("bonita/apps/myapp/mypage/"); }
### Question: CustomPageRequestModifier { public void forwardIfRequestIsAuthorized(final HttpServletRequest request, final HttpServletResponse response, final String apiPathShouldStartWith, final String apiPath) throws IOException, ServletException { try { URI uri = new URI(apiPath); if (!uri.normalize().toString().startsWith(apiPathShouldStartWith)) { final String message = "attempt to access unauthorized path " + apiPath; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, message); } response.sendError(HttpServletResponse.SC_FORBIDDEN, message); } else { request.getRequestDispatcher(apiPath).forward(request, response); } }catch (URISyntaxException e) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, e.getMessage()); } response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } } void redirectToValidPageUrl(final HttpServletRequest request, final HttpServletResponse response); void forwardIfRequestIsAuthorized(final HttpServletRequest request, final HttpServletResponse response, final String apiPathShouldStartWith, final String apiPath); }### Answer: @Test public void check_should_not_authorize_requests_to_other_paths() throws Exception { String apiPath = "/API/living/../../WEB-INF/web.xml"; CustomPageRequestModifier customPageRequestModifier = new CustomPageRequestModifier(); customPageRequestModifier.forwardIfRequestIsAuthorized(request, response, "/API", apiPath); verify(response).sendError(HttpServletResponse.SC_FORBIDDEN, "attempt to access unauthorized path " + apiPath); verify(request, never()).getRequestDispatcher(anyString()); } @Test public void check_should_authorize_valid_requests() throws Exception { String apiPath = "/API/living/0"; when(request.getRequestDispatcher(apiPath)).thenReturn(requestDispatcher); CustomPageRequestModifier customPageRequestModifier = new CustomPageRequestModifier(); customPageRequestModifier.forwardIfRequestIsAuthorized(request, response, "/API", apiPath); verify(request).getRequestDispatcher(apiPath); verify(response, never()).sendError(anyInt(), anyString()); }
### Question: CustomPageService { void addPermissionsToCompoundPermissions(final String pageName, final Set<String> customPagePermissions, final CompoundPermissionsMapping compoundPermissionsMapping, final ResourcesPermissionsMapping resourcesPermissionsMapping) throws IOException { customPagePermissions.addAll(resourcesPermissionsMapping.getPropertyAsSet(GET_SYSTEM_SESSION)); customPagePermissions.addAll(resourcesPermissionsMapping.getPropertyAsSet(GET_PORTAL_PROFILE)); customPagePermissions.addAll(resourcesPermissionsMapping.getPropertyAsSet(GET_IDENTITY_USER)); compoundPermissionsMapping.setPropertyAsSet(pageName, customPagePermissions); } GroovyClassLoader getPageClassloader(final APISession apiSession, final PageResourceProvider pageResourceProvider); void ensurePageFolderIsPresent(final APISession apiSession, final PageResourceProvider pageResourceProvider); void ensurePageFolderIsUpToDate(final APISession apiSession, final PageResourceProvider pageResourceProvider); @SuppressWarnings("unchecked") Class<?> registerPage(final GroovyClassLoader pageClassLoader, final PageResourceProvider pageResourceProvider); Class<?> registerRestApiPage(final GroovyClassLoader pageClassLoader, final File restApiControllerFile); void verifyPageClass(final File tempPageDirectory, APISession session); PageController loadPage(final Class<PageController> pageClass); RestApiController loadRestApiPage(final Class<RestApiController> restApiControllerClass); void removePage(final APISession apiSession, final String pageName); void removePage(final APISession apiSession, final Page page); File getGroovyPageFile(final File pageDirectory); File getPageFile(final File pageDirectory, final String fileName); Properties getPageProperties(final APISession apiSession, final byte[] zipContent, final boolean checkIfItAlreadyExists, final Long processDefinitionId); Set<String> getCustomPagePermissions(final Properties pageProperties, final ResourcesPermissionsMapping resourcesPermissionsMapping, final boolean alsoReturnResourcesNotFound); Page getPage(final APISession apiSession, final String pageName, final long processDefinitionId); Page getPage(final APISession apiSession, final long pageId); void removeRestApiExtensionPermissions(final ResourcesPermissionsMapping resourcesPermissionsMapping, final PageResourceProvider pageResourceProvider, final APISession apiSession); PageResourceProvider getPageResourceProvider(final Page page, final long tenantId); static void clearCachedClassloaders(); void writePageToTemp(Page page, PageResourceProvider pageResourceProvider, File unzipPageTempFolder, ResourcesPermissionsMapping resourcesPermissionsMapping, CompoundPermissionsMapping compoundPermissionsMapping, APISession session); static final String GET_SYSTEM_SESSION; static final String GET_PORTAL_PROFILE; static final String GET_IDENTITY_USER; static final String PAGE_CONTROLLER_FILENAME; static final String PAGE_INDEX_NAME; static final String PAGE_INDEX_FILENAME; static final String LASTUPDATE_FILENAME; static final String RESOURCES_PROPERTY; static final String PROPERTY_CONTENT_TYPE; static final String PROPERTY_API_EXTENSIONS; static final String PROPERTY_METHOD_MASK; static final String PROPERTY_PATH_TEMPLATE_MASK; static final String PROPERTY_PERMISSIONS_MASK; static final String RESOURCE_PERMISSION_KEY_MASK; static final String RESOURCE_PERMISSION_VALUE; static final String EXTENSION_SEPARATOR; static final String NAME_PROPERTY; }### Answer: @Test public void should_add_Custom_Page_permissions_to_CompoundPermissions() throws Exception { final HashSet<String> customPagePermissions = new HashSet<>(Arrays.asList("Organization Visualization", "Organization Managment")); customPageService.addPermissionsToCompoundPermissions("customPage1", customPagePermissions, compoundPermissionsMapping, resourcesPermissionsMapping); verify(compoundPermissionsMapping).setPropertyAsSet("customPage1", customPagePermissions); }
### Question: CustomPageService { protected GroovyClassLoader buildPageClassloader(final APISession apiSession, final String pageName, final File pageDirectory) throws CompilationFailedException, IOException { GroovyClassLoader pageClassLoader = PAGES_CLASSLOADERS.get(pageName); final BDMClientDependenciesResolver bdmDependenciesResolver = new BDMClientDependenciesResolver(apiSession); if (pageClassLoader == null || getConsoleProperties(apiSession).isPageInDebugMode() || isOutdated(pageClassLoader, bdmDependenciesResolver)) { synchronized (CustomPageService.class) { pageClassLoader = new GroovyClassLoader(getParentClassloader(pageName, new CustomPageDependenciesResolver(pageName, pageDirectory, getWebBonitaConstantsUtils(apiSession)), bdmDependenciesResolver)); pageClassLoader.addClasspath(pageDirectory.getPath()); PAGES_CLASSLOADERS.put(pageName, pageClassLoader); } } return pageClassLoader; } GroovyClassLoader getPageClassloader(final APISession apiSession, final PageResourceProvider pageResourceProvider); void ensurePageFolderIsPresent(final APISession apiSession, final PageResourceProvider pageResourceProvider); void ensurePageFolderIsUpToDate(final APISession apiSession, final PageResourceProvider pageResourceProvider); @SuppressWarnings("unchecked") Class<?> registerPage(final GroovyClassLoader pageClassLoader, final PageResourceProvider pageResourceProvider); Class<?> registerRestApiPage(final GroovyClassLoader pageClassLoader, final File restApiControllerFile); void verifyPageClass(final File tempPageDirectory, APISession session); PageController loadPage(final Class<PageController> pageClass); RestApiController loadRestApiPage(final Class<RestApiController> restApiControllerClass); void removePage(final APISession apiSession, final String pageName); void removePage(final APISession apiSession, final Page page); File getGroovyPageFile(final File pageDirectory); File getPageFile(final File pageDirectory, final String fileName); Properties getPageProperties(final APISession apiSession, final byte[] zipContent, final boolean checkIfItAlreadyExists, final Long processDefinitionId); Set<String> getCustomPagePermissions(final Properties pageProperties, final ResourcesPermissionsMapping resourcesPermissionsMapping, final boolean alsoReturnResourcesNotFound); Page getPage(final APISession apiSession, final String pageName, final long processDefinitionId); Page getPage(final APISession apiSession, final long pageId); void removeRestApiExtensionPermissions(final ResourcesPermissionsMapping resourcesPermissionsMapping, final PageResourceProvider pageResourceProvider, final APISession apiSession); PageResourceProvider getPageResourceProvider(final Page page, final long tenantId); static void clearCachedClassloaders(); void writePageToTemp(Page page, PageResourceProvider pageResourceProvider, File unzipPageTempFolder, ResourcesPermissionsMapping resourcesPermissionsMapping, CompoundPermissionsMapping compoundPermissionsMapping, APISession session); static final String GET_SYSTEM_SESSION; static final String GET_PORTAL_PROFILE; static final String GET_IDENTITY_USER; static final String PAGE_CONTROLLER_FILENAME; static final String PAGE_INDEX_NAME; static final String PAGE_INDEX_FILENAME; static final String LASTUPDATE_FILENAME; static final String RESOURCES_PROPERTY; static final String PROPERTY_CONTENT_TYPE; static final String PROPERTY_API_EXTENSIONS; static final String PROPERTY_METHOD_MASK; static final String PROPERTY_PATH_TEMPLATE_MASK; static final String PROPERTY_PERMISSIONS_MASK; static final String RESOURCE_PERMISSION_KEY_MASK; static final String RESOURCE_PERMISSION_VALUE; static final String EXTENSION_SEPARATOR; static final String NAME_PROPERTY; }### Answer: @Test public void should_add_page_root_folder_in_classpath() throws Exception { final File pageDir = new File(getClass().getResource("/ARootPageFolder").getFile()); final GroovyClassLoader classloader = customPageService.buildPageClassloader(apiSession, "pageName", pageDir); assertThat(classloader.loadClass("AbstractIndex")).isNotNull(); assertThat(classloader.loadClass("Index")).isNotNull(); assertThat(classloader.loadClass("org.company.test.Util")).isNotNull(); assertThat(classloader.getResource("org/company/test/config.properties")).isNotNull(); }
### Question: CustomPageDependenciesResolver { public File getTempFolder() { if (libTempFolder == null) { throw new IllegalStateException("Custom page dependencies must be resolved first."); } return libTempFolder; } CustomPageDependenciesResolver(final String pageName, final File pageDirectory, final WebBonitaConstantsUtils webBonitaConstantsUtils); Map<String, byte[]> resolveCustomPageDependencies(); static File removePageLibTempFolder(final String pageName); File getTempFolder(); }### Answer: @Test public void should_throw_an_IllegalStateException_when_accessing_tmp_folder_before_resolving_libraries() throws Exception { final CustomPageDependenciesResolver resolver = newCustomPageDependenciesResolver(null); expectedException.expect(IllegalStateException.class); resolver.getTempFolder(); }
### Question: CustomPageDependenciesResolver { public Map<String, byte[]> resolveCustomPageDependencies() { final File customPageLibDirectory = new File(pageDirectory, LIB_FOLDER_NAME); if (customPageLibDirectory.exists()) { this.libTempFolder = new File(this.webBonitaConstantsUtils.getTempFolder(), pageName + Long.toString(new Date().getTime())); if (!this.libTempFolder.exists()) { this.libTempFolder.mkdirs(); } removePageLibTempFolder(pageName); PAGES_LIB_TMPDIR.put(pageName, this.libTempFolder); return loadLibraries(customPageLibDirectory); } return Collections.emptyMap(); } CustomPageDependenciesResolver(final String pageName, final File pageDirectory, final WebBonitaConstantsUtils webBonitaConstantsUtils); Map<String, byte[]> resolveCustomPageDependencies(); static File removePageLibTempFolder(final String pageName); File getTempFolder(); }### Answer: @Test public void should_resolve_dependencies_return_an_empty_map_if_no_lib_folder_is_found_in_custom_page() throws Exception { final CustomPageDependenciesResolver resolver = newCustomPageDependenciesResolver(null); final Map<String, byte[]> dependenciesContent = resolver.resolveCustomPageDependencies(); assertThat(dependenciesContent).isEmpty(); }
### Question: CustomPageChildFirstClassLoader extends MonoParentJarFileClassLoader implements VersionedClassloader { public void addCustomPageResources() throws IOException { addBDMDependencies(); addOtherDependencies(); } CustomPageChildFirstClassLoader(String pageName, CustomPageDependenciesResolver customPageDependenciesResolver, BDMClientDependenciesResolver bdmDependenciesResolver, ClassLoader parent); void addCustomPageResources(); @Override InputStream getResourceAsStream(final String name); void release(); @Override String toString(); @Override String getVersion(); @Override boolean hasVersion(String version); }### Answer: @Test public void should_add_custom_page_jar_resources_in_classloader_urls() throws Exception { classLoader = newClassloader(); when(customPageDependenciesResolver.resolveCustomPageDependencies()).thenReturn(loadedResources("util.jar")); classLoader.addCustomPageResources(); assertThat(classLoader.getURLs()).hasSize(1); } @Test public void should_not_add_duplicated_bdm_dependencies_in_lib_folder_in_classloader() throws Exception { classLoader = newClassloader(); when(customPageDependenciesResolver.resolveCustomPageDependencies()) .thenReturn(loadedResources("util.jar", "bdm-model.jar", "bdm-dao.jar", "javassist-3.18.1-GA.jar")); when(bdmDependenciesResolver.isABDMDependency("bdm-model.jar")).thenReturn(true); when(bdmDependenciesResolver.isABDMDependency("bdm-dao.jar")).thenReturn(true); when(bdmDependenciesResolver.isABDMDependency("javassist-3.18.1-GA.jar")).thenReturn(true); classLoader.addCustomPageResources(); assertThat(classLoader.getURLs()).hasSize(1); } @Test public void should__add_bdm_dependencies_in_classloader_before_other_dependencies() throws Exception { classLoader = spy(newClassloader()); final URL[] bdmDependenciesURLs = bdmDependenciesURLs(); when(bdmDependenciesResolver.getBDMDependencies()).thenReturn(bdmDependenciesURLs); when(customPageDependenciesResolver.resolveCustomPageDependencies()) .thenReturn(loadedResources("util.jar")); when(bdmDependenciesResolver.isABDMDependency("bdm-model.jar")).thenReturn(true); when(bdmDependenciesResolver.isABDMDependency("bdm-dao.jar")).thenReturn(true); when(bdmDependenciesResolver.isABDMDependency("javassist-3.18.1-GA.jar")).thenReturn(true); classLoader.addCustomPageResources(); final InOrder order = inOrder(classLoader,customPageDependenciesResolver); order.verify(classLoader).addURLs(bdmDependenciesURLs); order.verify(customPageDependenciesResolver).resolveCustomPageDependencies(); assertThat(classLoader.getURLs()).hasSize(4); }
### Question: ResourceRenderer { public void renderFile(final HttpServletRequest request, final HttpServletResponse response, final File resourceFile, final APISession apiSession) throws CompilationFailedException, IllegalAccessException, IOException, BonitaException { byte[] content; response.setCharacterEncoding("UTF-8"); try { content = getFileContent(resourceFile, response); response.setContentType(request.getSession().getServletContext() .getMimeType(resourceFile.getName())); response.setContentLength(content.length); response.setBufferSize(content.length); try (OutputStream out = response.getOutputStream()) { out.write(content, 0, content.length); } response.flushBuffer(); }catch (final FileNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); }catch (final IOException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, "Error while generating the response.", e); } throw new BonitaException(e.getMessage(), e); } } void renderFile(final HttpServletRequest request, final HttpServletResponse response, final File resourceFile, final APISession apiSession); List<String> getPathSegments(final String pathInfo); }### Answer: @Test public void renderFile_should_build_a_valid_response() throws BonitaException, URISyntaxException, IOException, IllegalAccessException, InstantiationException { final File resourceFile = getResourceFile(); final long contentLength = resourceFile.length(); when(servletContext.getMimeType("file.css")).thenReturn("text/css"); resourceRenderer.renderFile(req, res, resourceFile, apiSession); verify(res).setCharacterEncoding("UTF-8"); verify(servletContext).getMimeType("file.css"); verify(res).setContentType("text/css"); verify(res).setContentLength((int) contentLength); verify(res).setBufferSize((int) contentLength); verify(outputStream).write(any(byte[].class), eq(0), eq((int) contentLength)); verify(res).flushBuffer(); verify(outputStream).close(); } @Test(expected = BonitaException.class) public void renderFile_should_throw_bonita_exception_on_ioexception() throws BonitaException, URISyntaxException, IOException, IllegalAccessException, InstantiationException { final File resourceFile = getResourceFile(); doThrow(new IOException()).when(outputStream).write(any(byte[].class), any(int.class), any(int.class)); resourceRenderer.renderFile(req, res, resourceFile, apiSession); } @Test(expected = BonitaException.class) public void getResourceFile_should_throw_BonitaException_on_passing_null_resources_folder() throws Exception { resourceRenderer.renderFile(req, res, null, apiSession); } @Test public void getResourceFile_should_sendError404_on_passing_none_existing_resources() throws Exception { final File noneExistingFile = new File("NoneExistingFile.css"); resourceRenderer.renderFile(req, res, noneExistingFile, apiSession); verify(res).sendError(HttpServletResponse.SC_NOT_FOUND, "Cannot find the resource file " + noneExistingFile.getName()); }
### Question: ResourceRenderer { public List<String> getPathSegments(final String pathInfo) throws UnsupportedEncodingException { final List<String> segments = new ArrayList<>(); if (pathInfo != null) { for (final String segment : pathInfo.split("/")) { if (!segment.isEmpty()) { segments.add(URLDecoder.decode(segment, "UTF-8")); } } } return segments; } void renderFile(final HttpServletRequest request, final HttpServletResponse response, final File resourceFile, final APISession apiSession); List<String> getPathSegments(final String pathInfo); }### Answer: @Test public void getPathSegments_should_return_expected_token_list() throws UnsupportedEncodingException { when(req.getPathInfo()).thenReturn("a/b"); final List<String> tokens = resourceRenderer.getPathSegments("a/b"); assertThat(tokens).hasSize(2).containsExactly("a", "b"); } @Test public void getPathSegments_should_return_expected_token_list_ondouble_slash() throws UnsupportedEncodingException { when(req.getPathInfo()).thenReturn("a final List<String> tokens = resourceRenderer.getPathSegments("a assertThat(tokens).hasSize(2).containsExactly("a", "b"); } @Test public void getPathSegments_should_return_expected_token_list_if_no_slash() throws UnsupportedEncodingException { when(req.getPathInfo()).thenReturn("a"); final List<String> tokens = resourceRenderer.getPathSegments("a"); assertThat(tokens).hasSize(1).containsExactly("a"); }
### Question: PageRenderer { public PageResourceProviderImpl getPageResourceProvider(final String pageName, final long tenantId) { return new PageResourceProviderImpl(pageName, tenantId); } PageRenderer(final ResourceRenderer resourceRenderer); void displayCustomPage(final HttpServletRequest request, final HttpServletResponse response, final APISession apiSession, final String pageName); void displayCustomPage(final HttpServletRequest request, final HttpServletResponse response, final APISession apiSession, final String pageName, final Locale currentLocale); void displayCustomPage(final HttpServletRequest request, final HttpServletResponse response, final APISession apiSession, final long pageId); void displayCustomPage(final HttpServletRequest request, final HttpServletResponse response, final APISession apiSession, final long pageId, final Locale currentLocale); void ensurePageFolderIsPresent(final APISession apiSession, final PageResourceProviderImpl pageResourceProvider); String getCurrentProfile(final HttpServletRequest request); Locale getCurrentLocale(final HttpServletRequest request); PageResourceProviderImpl getPageResourceProvider(final String pageName, final long tenantId); PageResourceProviderImpl getPageResourceProvider(final long pageId, final APISession apiSession); static final String PROFILE_PARAM; static final String LOCALE_PARAM; static final String DEFAULT_LOCALE; static final String LOCALE_COOKIE_NAME; }### Answer: @Test public void should_get_pageResourceProvider_by_pageId() throws Exception { final String pageName = "pageName"; doReturn(pageName).when(page).getName(); doReturn(page).when(customPageService).getPage(apiSession, 42L); final PageResourceProviderImpl pageResourceProvider = pageRenderer.getPageResourceProvider(42L, apiSession); assertThat(pageResourceProvider.getPageName()).isEqualTo(pageName); } @Test public void should_get_pageResourceProvider_by_pageName() throws Exception { final String pageName = "pageName"; doReturn(pageName).when(page).getName(); final PageResourceProviderImpl pageResourceProvider = pageRenderer.getPageResourceProvider(pageName,1L); assertThat(pageResourceProvider.getPageName()).isEqualTo(pageName); }
### Question: PageMappingService { public PageReference getPage(final HttpServletRequest request, final APISession apiSession, final String mappingKey, final Locale locale, final boolean executeAuthorizationRules) throws BonitaException { final Map<String, Serializable> context = new HashMap<>(); Map<String, String[]> parametersMapCopy = request.getParameterMap().entrySet().stream() .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().clone())); context.put(URLAdapterConstants.QUERY_PARAMETERS, (Serializable) parametersMapCopy); context.put(AuthorizationRuleConstants.IS_ADMIN, isLoggedUserAdmin(request)); context.put(URLAdapterConstants.LOCALE, locale.toString()); context.put(URLAdapterConstants.CONTEXT_PATH, request.getContextPath()); final PageAPI pageAPI = getPageAPI(apiSession); final PageURL pageURL = pageAPI.resolvePageOrURL(mappingKey, context, executeAuthorizationRules); return new PageReference(pageURL.getPageId(), pageURL.getUrl()); } PageReference getPage(final HttpServletRequest request, final APISession apiSession, final String mappingKey, final Locale locale, final boolean executeAuthorizationRules); }### Answer: @SuppressWarnings("unchecked") @Test public void getPage() throws Exception { final PageURL pageURL = mock(PageURL.class); when(pageURL.getUrl()).thenReturn("/externalURL"); when(pageURL.getPageId()).thenReturn(null); ArgumentCaptor<Map> contextCaptor = ArgumentCaptor.forClass(Map.class); when(pageAPI.resolvePageOrURL(eq("process/processName/processVersion"), anyMap(), eq(true))).thenReturn(pageURL); final Set<String> userPermissions = new HashSet<>(); when(httpSession.getAttribute(SessionUtil.PERMISSIONS_SESSION_PARAM_KEY)).thenReturn(userPermissions); final PageReference returnedPageReference = pageMappingService.getPage(hsRequest, apiSession, "process/processName/processVersion", new Locale("en"), true); verify(pageAPI).resolvePageOrURL(eq("process/processName/processVersion"), contextCaptor.capture(), eq(true)); Map<String, Serializable> capturedContext = contextCaptor.getValue(); assertEquals("/bonita", (String)capturedContext.get(URLAdapterConstants.CONTEXT_PATH)); assertEquals("en", (String)capturedContext.get(URLAdapterConstants.LOCALE)); assertEquals(false, (Boolean)capturedContext.get(AuthorizationRuleConstants.IS_ADMIN)); assertEquals("value", ((Map<String, String[]>)capturedContext.get(URLAdapterConstants.QUERY_PARAMETERS)).get("key")[0]); assertNotNull(returnedPageReference); assertEquals(null, returnedPageReference.getPageId()); assertEquals("/externalURL", returnedPageReference.getURL()); }
### Question: ConsoleServiceFactory implements ServiceFactory { @Override public Service getService(final String calledToolToken) { if (OrganizationImportService.TOKEN.equals(calledToolToken)) { return new OrganizationImportService(); } else if (ProcessActorImportService.TOKEN.equals(calledToolToken)) { return new ProcessActorImportService(); } else if (ApplicationsImportService.TOKEN.equals(calledToolToken)) { return new ApplicationsImportService(); } throw new ServiceNotFoundException(calledToolToken); } @Override Service getService(final String calledToolToken); }### Answer: @Test public void getService_should_return_OrganizationImportService_when_organization_import() throws Exception { ConsoleServiceFactory consoleServiceFacotry = new ConsoleServiceFactory(); Service service = consoleServiceFacotry.getService("/organization/import"); assertThat(service).isInstanceOf(OrganizationImportService.class); } @Test public void getService_should_return_ProcessActorImportService_when_bpm_process_importActors() throws Exception { ConsoleServiceFactory consoleServiceFacotry = new ConsoleServiceFactory(); Service service = consoleServiceFacotry.getService("/bpm/process/importActors"); assertThat(service).isInstanceOf(ProcessActorImportService.class); } @Test(expected=ServiceNotFoundException.class) public void getService_should_throw_ServiceNotFoundException_when_invalid_input(){ ConsoleServiceFactory consoleServiceFacotry = new ConsoleServiceFactory(); consoleServiceFacotry.getService("invalidService"); }
### Question: ApplicationsImportService extends BonitaImportService { @Override public ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString) throws ExecutionException, ImportException, AlreadyExistsException, InvalidSessionException, BonitaHomeNotSetException, ServerAPIException, UnknownAPITypeException { final ApplicationImportPolicy importPolicy = ApplicationImportPolicy.valueOf(importPolicyAsString); final List<ImportStatus> ImportStatusList = getApplicationAPI().importApplications(fileContent, importPolicy); return new ImportStatusMessages(ImportStatusList); } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_importFileContent_call_ApplicationAPI_with_valid_param() throws Exception { spiedApplicationImportService.importFileContent(new byte[0], "FAIL_ON_DUPLICATES"); verify(applicationAPI).importApplications(new byte[0], ApplicationImportPolicy.FAIL_ON_DUPLICATES); } @Test public void should_importFileContent_return_ImportStatusMessages() throws Exception { final ArrayList<ImportStatus> statusList = new ArrayList<ImportStatus>(); statusList.add(new ImportStatus("status")); doReturn(statusList).when(applicationAPI).importApplications(new byte[0], ApplicationImportPolicy.FAIL_ON_DUPLICATES); final ImportStatusMessages importStatusMessages = spiedApplicationImportService.importFileContent(new byte[0], "FAIL_ON_DUPLICATES"); assertEquals(importStatusMessages.getImported().size(), 1); } @Test(expected = IllegalArgumentException.class) public void should_importFileContent_with_invalid_policy_throw_error() throws Exception { spiedApplicationImportService.importFileContent(new byte[0], "NOT_AUTHORIZED_POLICY"); }
### Question: ApplicationsImportService extends BonitaImportService { @Override protected Logger getLogger() { return LOGGER; } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_Logger_log_using_expected_class_name() throws Exception { assertEquals(spiedApplicationImportService.getLogger().getName(), "org.bonitasoft.console.server.service.ApplicationsImportService"); }
### Question: ApplicationsImportService extends BonitaImportService { @Override protected String getFileReadingError() { return _("Error during Application import file reading."); } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_FileReadingError_talk_about_application() throws Exception { assertEquals(spiedApplicationImportService.getFileReadingError(), "Error during Application import file reading."); }
### Question: ApplicationsImportService extends BonitaImportService { @Override protected String getFileFormatExceptionMessage() { return _("Can't import Applications.", getLocale()); } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_getFileFormatExceptionMessage_talk_about_application() throws Exception { assertEquals(spiedApplicationImportService.getFileFormatExceptionMessage(), "Can't import Applications."); }
### Question: ApplicationsImportService extends BonitaImportService { @Override protected String getAlreadyExistsExceptionMessage(final AlreadyExistsException e) { return _("Can't import applications. An application '%token%' already exists", getLocale(), new Arg("token", e.getName())); } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_AlreadyExistsExceptionMessage_talk_about_application() throws Exception { final AlreadyExistsException alreadyExistsException = new AlreadyExistsException("name", "token"); assertEquals(spiedApplicationImportService.getAlreadyExistsExceptionMessage(alreadyExistsException), "Can't import applications. An application 'token' already exists"); }
### Question: ApplicationsImportService extends BonitaImportService { @Override public String getToken() { return TOKEN; } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_getToken_return_expected_name() throws Exception { assertEquals(spiedApplicationImportService.getToken(), "/application/import"); }
### Question: ApplicationsImportService extends BonitaImportService { @Override public String getFileUploadParamName() { return FILE_UPLOAD; } @Override String getToken(); @Override String getFileUploadParamName(); @Override ImportStatusMessages importFileContent(final byte[] fileContent, final String importPolicyAsString); final static String TOKEN; static final String FILE_UPLOAD; }### Answer: @Test public void should_getFileUploadParamName_return_expected_name() throws Exception { assertEquals(spiedApplicationImportService.getFileUploadParamName(), "applicationsDataUpload"); }
### Question: ApplicationsExportServlet extends ExportByIdsServlet { @Override protected byte[] exportResources(final long[] ids, final APISession apiSession) throws BonitaHomeNotSetException, ServerAPIException, UnknownAPITypeException, ExecutionException, ExportException { final ApplicationAPI applicationAPI = getApplicationAPI(apiSession); return applicationAPI.exportApplications(ids); } }### Answer: @Test public void should_call_engine_export_with_the_good_id() throws Exception { spiedApplicationsExportServlet.exportResources(new long[] { 1 }, session); verify(applicationAPI, times(1)).exportApplications(new long[] { 1 }); }
### Question: ApplicationsExportServlet extends ExportByIdsServlet { @Override protected Logger getLogger() { return LOGGER; } }### Answer: @Test public void should_logger_log_with_name_of_the_Servlet() throws Exception { assertThat(spiedApplicationsExportServlet.getLogger().getName()).isEqualTo("org.bonitasoft.console.server.servlet.ApplicationsExportServlet"); }
### Question: ApplicationsExportServlet extends ExportByIdsServlet { @Override protected String getFileExportName() { return EXPORT_FILE_NAME; } }### Answer: @Test public void should_getFileExportName_return_a_valide_file_name() throws Exception { assertThat(spiedApplicationsExportServlet.getFileExportName()).isEqualTo("applicationDescriptorFile.xml"); }
### Question: BonitaExportServlet extends HttpServlet { @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { OutputStream out = null; try { final byte[] resourceBytes = exportResources(request); setResponseHeaders(request, response); out = response.getOutputStream(); out.write(resourceBytes); out.flush(); } catch (final InvalidSessionException e) { String message = "Session expired. Please log in again."; if (getLogger().isLoggable(Level.FINE)) { getLogger().log(Level.FINE, message, e); } response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message); } catch (final FileNotFoundException e) { String message = "There is no BDM Access control installed."; if (getLogger().isLoggable(Level.INFO)) { getLogger().log(Level.INFO, message); } response.sendError(HttpServletResponse.SC_NOT_FOUND, message); } catch (final Exception e) { if (getLogger().isLoggable(Level.SEVERE)) { getLogger().log(Level.SEVERE, e.getMessage(), e); } throw new ServletException(e.getMessage(), e); } finally { try { if (out != null) { out.close(); } } catch (final IOException e) { getLogger().log(Level.SEVERE, e.getMessage(), e); } } } }### Answer: @Test(expected = ServletException.class) public void should_do_get_without_session_return_servlet_exception() throws Exception { given(hsRequest.getSession()).willReturn(httpSession); given(httpSession.getAttribute("apiSession")).willReturn(null); spiedApplicationsExportServlet.doGet(hsRequest, hsResponse); }
### Question: MenuFactory { public List<Menu> create(final List<ApplicationMenu> menuList) throws ApplicationPageNotFoundException, SearchException { return collect(menuList, new RootMenuCollector()); } MenuFactory(final ApplicationAPI applicationApi); List<Menu> create(final List<ApplicationMenu> menuList); }### Answer: @Test public void should_create_a_MenuLink_with_the_page_token_it_is_pointing_at_when_menu_is_a_link() throws Exception { MenuFactory factory = new MenuFactory(applicationApi); assertThat(factory.create(asList((ApplicationMenu) aMenuLink)).get(0).getHtml()) .isEqualTo("<li><a href=\"token\">link</a></li>"); } @Test public void should_create_an_empty_MenuContainer() throws Exception { MenuFactory factory = new MenuFactory(applicationApi); assertThat(factory.create(asList((ApplicationMenu) aMenuContainer)).get(0).getHtml()) .isEqualTo(new StringBuilder() .append("<li class=\"dropdown\"><a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">container <span class=\"caret\"></span></a>") .append("<ul class=\"dropdown-menu\" role=\"menu\">") .append("</ul></li>").toString()); } @Test public void should_create_a_MenuContainer_containing_a_MenuLink() throws Exception { MenuFactory factory = new MenuFactory(applicationApi); assertThat(factory.create(asList((ApplicationMenu) aMenuContainer, aNestedMenuLink)).get(0).getHtml()) .isEqualTo(new StringBuilder() .append("<li class=\"dropdown\"><a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">container <span class=\"caret\"></span></a>") .append("<ul class=\"dropdown-menu\" role=\"menu\">") .append("<li><a href=\"token\">nested-link</a></li>") .append("</ul></li>").toString()); }
### Question: RootMenuCollector implements Collector { @Override public boolean isCollectible(final ApplicationMenu menu) { return menu.getParentId() == null; } @Override boolean isCollectible(final ApplicationMenu menu); }### Answer: @Test public void should_be_collectible_when_the_menu_has_no_parentId() { menu.setParentId(null); assertThat(collector.isCollectible(menu)).isTrue(); } @Test public void should_not_be_collectible_when_the_menu_has_a_parentId() { menu.setParentId(3L); assertThat(collector.isCollectible(menu)).isFalse(); }
### Question: ChildrenMenuCollector implements Collector { @Override public boolean isCollectible(final ApplicationMenu menu) { return parentId.equals(menu.getParentId()); } ChildrenMenuCollector(final Long parentId); @Override boolean isCollectible(final ApplicationMenu menu); }### Answer: @Test public void should_be_collectible_when_menu_parentId_is_the_given_parentId() { menu.setParentId(1L); assertThat(collector.isCollectible(menu)).isTrue(); } @Test public void should_not_be_collectible_when_menu_parentId_is_not_the_given_parentId() { menu.setParentId(2L); assertThat(collector.isCollectible(menu)).isFalse(); } @Test public void should_not_be_collectible_when_menu_parentId_is_null() { menu.setParentId(null); assertThat(collector.isCollectible(menu)).isFalse(); }
### Question: ApplicationModel { public List<Menu> getMenuList() throws SearchException, ApplicationPageNotFoundException { return factory.create(applicationApi.searchApplicationMenus(new SearchOptionsBuilder(0, Integer.MAX_VALUE) .filter(ApplicationMenuSearchDescriptor.APPLICATION_ID, application.getId()) .sort(ApplicationMenuSearchDescriptor.INDEX, Order.ASC).done()) .getResult()); } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_sort_application_menu_search() throws Exception { givenSearchApplicationMenusWillReturns(Collections.<ApplicationMenu> emptyList()); model.getMenuList(); final ArgumentCaptor<SearchOptions> captor = ArgumentCaptor.forClass(SearchOptions.class); verify(applicationApi).searchApplicationMenus(captor.capture()); final Sort sort = captor.getValue().getSorts().get(0); assertThat(sort.getField()).isEqualTo(ApplicationMenuSearchDescriptor.INDEX); assertThat(sort.getOrder()).isEqualTo(Order.ASC); } @Test public void should_create_menu_using_menuList() throws Exception { final List<ApplicationMenu> menuList = Arrays.<ApplicationMenu> asList(new ApplicationMenuImpl("name", 1L, 2L, 1)); givenSearchApplicationMenusWillReturns(menuList); model.getMenuList(); verify(factory).create(menuList); }
### Question: ApplicationModel { public boolean authorize(final APISession session) { for (final Profile userProfile : getUserProfiles(session)) { if (userProfile.getId() == application.getProfileId()) { return true; } } return false; } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_authorize_a_user_with_the_configured_application_profile() throws Exception { final ProfileImpl profile1 = new ProfileImpl("user"); profile1.setId(1L); final ProfileImpl profile2 = new ProfileImpl("administrator"); profile1.setId(2L); given(profileApi.getProfilesForUser(1L, 0, Integer.MAX_VALUE, ProfileCriterion.ID_ASC)) .willReturn(asList((Profile) profile1, profile2)); given(session.getUserId()).willReturn(1L); application.setProfileId(2L); assertThat(model.authorize(session)).isTrue(); } @Test public void should_not_authorize_a_user_without_the_configured_application_profile() throws Exception { final ProfileImpl profile1 = new ProfileImpl("user"); profile1.setId(1L); final ProfileImpl profile2 = new ProfileImpl("administrator"); profile1.setId(2L); given(profileApi.getProfilesForUser(1L, 0, Integer.MAX_VALUE, ProfileCriterion.ID_ASC)) .willReturn(asList((Profile) profile1, profile2)); given(session.getUserId()).willReturn(1L); application.setProfileId(3L); assertThat(model.authorize(session)).isFalse(); }
### Question: ApplicationModel { public long getId() { return application.getId(); } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_getId_return_applicationId() throws Exception { assertThat(model.getId()).isEqualTo(1L); }
### Question: ApplicationModel { public String getApplicationHomePage() throws ApplicationPageNotFoundException { return applicationApi.getApplicationHomePage(application.getId()).getToken() + "/"; } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_ApplicationHomePage_return_valide_path() throws Exception { given(applicationApi.getApplicationHomePage(1L)).willReturn(new ApplicationPageImpl(1, 1, "pageToken")); assertThat(model.getApplicationHomePage()).isEqualTo("pageToken/"); }
### Question: ApplicationModel { public String getApplicationLayoutName() throws PageNotFoundException { return pageApi.getPage(application.getLayoutId()).getName(); } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_getApplicationLayoutName_return_valide_name() throws Exception { given(page.getName()).willReturn("layoutPage"); given(pageApi.getPage(1L)).willReturn(page); String appLayoutName = model.getApplicationLayoutName(); assertThat(appLayoutName).isEqualTo("layoutPage"); }
### Question: ApplicationModel { public String getApplicationThemeName() throws PageNotFoundException { return pageApi.getPage(application.getThemeId()).getName(); } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_getApplicationThemeName_return_valide_name() throws Exception { given(page.getName()).willReturn("themePage"); given(pageApi.getPage(2L)).willReturn(page); String appLayoutName = model.getApplicationThemeName(); assertThat(appLayoutName).isEqualTo("themePage"); }
### Question: ApplicationModel { public boolean hasPage(final String pageToken) { try { applicationApi.getApplicationPage(application.getToken(), pageToken); return true; } catch (final ApplicationPageNotFoundException e) { return false; } } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_hasPage_return_true() throws Exception { given(applicationApi.getApplicationPage("token", "pageToken")).willReturn(new ApplicationPageImpl(1, 1, "pageToken")); assertThat(model.hasPage("pageToken")).isEqualTo(true); } @Test public void should_hasPage_return_false() throws Exception { given(applicationApi.getApplicationPage("token", "pageToken")).willThrow(new ApplicationPageNotFoundException("")); assertThat(model.hasPage("pageToken")).isEqualTo(false); }
### Question: ApplicationModel { public boolean hasProfileMapped() { return application.getProfileId() != null; } ApplicationModel( final ApplicationAPI applicationApi, final PageAPI pageApi, final ProfileAPI profileApi, final Application application, final MenuFactory factory); long getId(); String getApplicationLayoutName(); String getApplicationThemeName(); Long getApplicationThemeId(); String getApplicationHomePage(); boolean hasPage(final String pageToken); boolean authorize(final APISession session); boolean hasProfileMapped(); Page getCustomPage(final String pageToken); List<Menu> getMenuList(); }### Answer: @Test public void should_check_that_application_has_a_profile_mapped_to_it() throws Exception { application.setProfileId(1L); assertThat(model.hasProfileMapped()).isEqualTo(true); application.setProfileId(null); assertThat(model.hasProfileMapped()).isEqualTo(false); }
### Question: ApplicationModelFactory { public ApplicationModel createApplicationModel(final String name) throws CreationException { try { final SearchResult<Application> result = applicationApi.searchApplications( new SearchOptionsBuilder(0, 1) .filter(ApplicationSearchDescriptor.TOKEN, name) .done()); if (result.getCount() == 0) { throw new CreationException("No application found with name " + name); } return new ApplicationModel( applicationApi, customPageApi, profileApi, result.getResult().get(0), new MenuFactory(applicationApi)); } catch (final SearchException e) { throw new CreationException("Error while searching for the application " + name, e); } } ApplicationModelFactory(final ApplicationAPI applicationApi, final PageAPI customPageApi, final ProfileAPI profileApi); ApplicationModel createApplicationModel(final String name); }### Answer: @Test(expected = CreationException.class) public void should_throw_create_error_exception_when_search_fail() throws Exception { given(applicationApi.searchApplications(any(SearchOptions.class))).willThrow(SearchException.class); factory.createApplicationModel("foo"); } @Test(expected = CreationException.class) public void should_throw_create_error_exception_when_application_is_not_found() throws Exception { given(applicationApi.searchApplications(any(SearchOptions.class))).willReturn( new SearchResultImpl<Application>(0, Collections.<Application> emptyList())); factory.createApplicationModel("foo"); } @Test public void should_return_application_found() throws Exception { final ApplicationImpl application = new ApplicationImpl("foobar", "1.0", "bazqux"); application.setId(3); given(applicationApi.searchApplications(any(SearchOptions.class))).willReturn( new SearchResultImpl<Application>(1, asList((Application) application))); given(applicationApi.getApplicationHomePage(3)).willReturn(new ApplicationPageImpl(1, 1, "home")); final ApplicationModel model = factory.createApplicationModel("foo"); assertThat(model.getApplicationHomePage()).isEqualTo("home/"); } @Test public void should_filter_search_using_given_name() throws Exception { final ArgumentCaptor<SearchOptions> captor = ArgumentCaptor.forClass(SearchOptions.class); given(applicationApi.searchApplications(any(SearchOptions.class))).willReturn( new SearchResultImpl<Application>(1, asList(mock(Application.class)))); factory.createApplicationModel("bar"); verify(applicationApi).searchApplications(captor.capture()); final SearchFilter filter = captor.getValue().getFilters().get(0); assertThat(filter.getField()).isEqualTo("token"); assertThat(filter.getValue()).isEqualTo("bar"); }