method2testcases stringlengths 118 6.63k |
|---|
### Question:
Pagination extends AbstractSchemaGenerator { public Schema schema() { return new ObjectSchema() .addProperties( "first", new StringSchema() .description("The first page of data") .format("uri") .nullable(true)) .addProperties( "last", new StringSchema() .description("The last page of data") .format("uri") .nullable(true)) .addProperties( "prev", new StringSchema() .description("The previous page of data") .format("uri") .nullable(true)) .addProperties( "next", new StringSchema() .description("The next page of data") .format("uri") .nullable(true)); } Schema schema(); }### Answer:
@Test void schema() { Schema schema = new Pagination().schema(); Assert.assertTrue(schema instanceof ObjectSchema); Stream.of("first", "last", "prev", "next").forEach( key -> { Schema subSchema = (Schema) schema.getProperties().get(key); Assert.assertTrue(subSchema instanceof StringSchema); Assert.assertTrue(subSchema.getNullable()); Assert.assertEquals("uri", subSchema.getFormat()); } ); Assert.assertEquals(4, schema.getProperties().size()); } |
### Question:
ResourceReferencesResponse extends AbstractResponseGenerator { public ApiResponse response() { return new ApiResponse() .description(HttpStatus.toMessage(200)) .content( new Content() .addMediaType( "application/vnd.api+json", new MediaType() .schema(new ResourceReferencesResponseSchema(metaResource).$ref()))); } ResourceReferencesResponse(MetaResource metaResource); ApiResponse response(); }### Answer:
@Test void response() { ApiResponse apiResponse = new ResourceReferencesResponse(metaResource).response(); Assert.assertNotNull(apiResponse); Assert.assertEquals("OK", apiResponse.getDescription()); Content content = apiResponse.getContent(); Assert.assertEquals(1, content.size()); Schema schema = content.get("application/vnd.api+json").getSchema(); Assert.assertEquals( "#/components/schemas/ResourceTypeResourceReferencesResponseSchema", schema.get$ref() ); } |
### Question:
NoContent extends AbstractResponseGenerator { public ApiResponse response() { return new ApiResponse() .description("No Content"); } ApiResponse response(); }### Answer:
@Test void response() { ApiResponse apiResponse = new NoContent().response(); Assert.assertEquals("No Content", apiResponse.getDescription()); Assert.assertNull(apiResponse.getContent()); } |
### Question:
ResourceResponse extends AbstractResponseGenerator { public ApiResponse response() { return new ApiResponse() .description(HttpStatus.toMessage(200)) .content( new Content() .addMediaType( "application/vnd.api+json", new MediaType() .schema(new ResourceResponseSchema(metaResource).$ref()))); } ResourceResponse(MetaResource metaResource); ApiResponse response(); }### Answer:
@Test void response() { ApiResponse apiResponse = new ResourceResponse(metaResource).response(); Assert.assertNotNull(apiResponse); Assert.assertEquals("OK", apiResponse.getDescription()); Content content = apiResponse.getContent(); Assert.assertEquals(1, content.size()); Schema schema = content.get("application/vnd.api+json").getSchema(); Assert.assertEquals( "#/components/schemas/ResourceTypeResourceResponseSchema", schema.get$ref() ); } |
### Question:
StaticResponses { public static Map<String, ApiResponse> generateStandardApiResponses() { return OASMergeUtil.mergeApiResponses(generateStandardApiSuccessResponses(), OASErrors.generateStandardApiErrorResponses()); } static Map<String, ApiResponse> generateStandardApiResponses(); }### Answer:
@Test void generateStandardApiResponses() { Map<String, ApiResponse> apiResponseMap = StaticResponses.generateStandardApiResponses(); Assert.assertEquals(16, apiResponseMap.size()); Assert.assertNotNull(apiResponseMap.get("NoContent")); Assert.assertNotNull(apiResponseMap.get("400")); Assert.assertNotNull(apiResponseMap.get("401")); Assert.assertNotNull(apiResponseMap.get("403")); Assert.assertNotNull(apiResponseMap.get("404")); Assert.assertNotNull(apiResponseMap.get("405")); Assert.assertNotNull(apiResponseMap.get("409")); Assert.assertNotNull(apiResponseMap.get("412")); Assert.assertNotNull(apiResponseMap.get("415")); Assert.assertNotNull(apiResponseMap.get("422")); Assert.assertNotNull(apiResponseMap.get("500")); Assert.assertNotNull(apiResponseMap.get("501")); Assert.assertNotNull(apiResponseMap.get("502")); Assert.assertNotNull(apiResponseMap.get("503")); Assert.assertNotNull(apiResponseMap.get("504")); Assert.assertNotNull(apiResponseMap.get("505")); } |
### Question:
ResourcesResponse extends AbstractResponseGenerator { public ApiResponse response() { return new ApiResponse() .description(HttpStatus.toMessage(200)) .content( new Content() .addMediaType( "application/vnd.api+json", new MediaType() .schema(new ResourcesResponseSchema(metaResource).$ref()))); } ResourcesResponse(MetaResource metaResource); ApiResponse response(); }### Answer:
@Test void response() { ApiResponse apiResponse = new ResourcesResponse(metaResource).response(); Assert.assertNotNull(apiResponse); Assert.assertEquals("OK", apiResponse.getDescription()); Content content = apiResponse.getContent(); Assert.assertEquals(1, content.size()); Schema schema = content.get("application/vnd.api+json").getSchema(); Assert.assertEquals( "#/components/schemas/ResourceTypeResourcesResponseSchema", schema.get$ref() ); } |
### Question:
ResourceReferenceResponse extends AbstractResponseGenerator { public ApiResponse response() { return new ApiResponse() .description(HttpStatus.toMessage(200)) .content( new Content() .addMediaType( "application/vnd.api+json", new MediaType() .schema(new ResourceReferenceResponseSchema(metaResource).$ref()))); } ResourceReferenceResponse(MetaResource metaResource); ApiResponse response(); }### Answer:
@Test void response() { ApiResponse apiResponse = new ResourceReferenceResponse(metaResource).response(); Assert.assertNotNull(apiResponse); Assert.assertEquals("OK", apiResponse.getDescription()); Content content = apiResponse.getContent(); Assert.assertEquals(1, content.size()); Schema schema = content.get("application/vnd.api+json").getSchema(); Assert.assertEquals( "#/components/schemas/ResourceTypeResourceReferenceResponseSchema", schema.get$ref() ); } |
### Question:
OASMergeUtil { public static Operation mergeOperations(Operation thisOperation, Operation thatOperation) { if (thatOperation == null) { return thisOperation; } if (thatOperation.getTags() != null) { thisOperation.setTags( mergeTags(thisOperation.getTags(), thatOperation.getTags()) ); } if (thatOperation.getExternalDocs() != null) { thisOperation.setExternalDocs( mergeExternalDocumentation(thisOperation.getExternalDocs(), thatOperation.getExternalDocs()) ); } if (thatOperation.getParameters() != null) { thisOperation.setParameters( mergeParameters(thisOperation.getParameters(), thatOperation.getParameters()) ); } if (thatOperation.getRequestBody() != null) { thisOperation.setRequestBody(thatOperation.getRequestBody()); } if (thatOperation.getResponses() != null) { thisOperation.setResponses(thatOperation.getResponses()); } if (thatOperation.getCallbacks() != null) { thisOperation.setCallbacks(thatOperation.getCallbacks()); } if (thatOperation.getDeprecated() != null) { thisOperation.setDeprecated(thatOperation.getDeprecated()); } if (thatOperation.getSecurity() != null) { thisOperation.setSecurity(thatOperation.getSecurity()); } if (thatOperation.getServers() != null) { thisOperation.setServers(thatOperation.getServers()); } if (thatOperation.getExtensions() != null) { thisOperation.setExtensions(thatOperation.getExtensions()); } if (thatOperation.getOperationId() != null) { thisOperation.setOperationId(thatOperation.getOperationId()); } if (thatOperation.getSummary() != null) { thisOperation.setSummary(thatOperation.getSummary()); } if (thatOperation.getDescription() != null) { thisOperation.setDescription(thatOperation.getDescription()); } if (thatOperation.getExtensions() != null) { thisOperation.setExtensions(thatOperation.getExtensions()); } return thisOperation; } @SafeVarargs static Map<String, ApiResponse> mergeApiResponses(Map<String, ApiResponse>... maps); static Operation mergeOperations(Operation thisOperation, Operation thatOperation); static Parameter mergeParameter(Parameter thisParameter, Parameter thatParameter); static Schema mergeSchema(Schema thisSchema, Schema thatSchema); }### Answer:
@Test public void testMergeOperations() { Operation thatOperation = new Operation(); Operation thisOperation = new Operation(); thisOperation.setOperationId("new id"); thisOperation.setSummary("new summary"); thisOperation.setDescription("new description"); Map<String, Object> extensions = new HashMap<>(); extensions.put("new schema", new Schema()); thisOperation.setExtensions(extensions); Assert.assertSame(thisOperation, OASMergeUtil.mergeOperations(thisOperation, null)); Operation afterMerge = OASMergeUtil.mergeOperations(thatOperation, thisOperation); Assert.assertEquals("new id", afterMerge.getOperationId()); Assert.assertEquals("new summary", afterMerge.getSummary()); Assert.assertEquals("new description", afterMerge.getDescription()); Assert.assertSame(extensions, afterMerge.getExtensions()); thatOperation.setOperationId("existing id"); thatOperation.setSummary("existing summary"); thatOperation.setDescription("existing description"); Map<String, Object> existingExtensions = new HashMap<>(); extensions.put("existing schema", new Schema()); thisOperation.setExtensions(extensions); afterMerge = OASMergeUtil.mergeOperations(thisOperation, thatOperation); Assert.assertEquals("existing id", afterMerge.getOperationId()); Assert.assertEquals("existing summary", afterMerge.getSummary()); Assert.assertEquals("existing description", afterMerge.getDescription()); Assert.assertSame(extensions, afterMerge.getExtensions()); } |
### Question:
MetaAttributePath implements Iterable<MetaAttribute> { public MetaAttributePath concat(MetaAttribute... pathElements) { ArrayList<MetaAttribute> list = new ArrayList<>(); list.addAll(Arrays.asList(this.pathElements)); list.addAll(Arrays.asList(pathElements)); return to(list.toArray(newArray(0))); } MetaAttributePath(List<? extends MetaAttribute> pathElements); MetaAttributePath(MetaAttribute... pathElements); MetaAttributePath subPath(int startIndex); MetaAttributePath subPath(int startIndex, int endIndex); int length(); MetaAttribute getElement(int index); MetaAttribute getLast(); MetaAttributePath concat(MetaAttribute... pathElements); String render(String delimiter); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<MetaAttribute> iterator(); static final char PATH_SEPARATOR_CHAR; static final String PATH_SEPARATOR; static final MetaAttributePath EMPTY_PATH; }### Answer:
@Test public void concat() { MetaAttribute attr3 = Mockito.mock(MetaAttribute.class); Mockito.when(attr3.getName()).thenReturn("c"); Assert.assertEquals("a.b.c", path.concat(attr3).toString()); } |
### Question:
NestedFilter extends AbstractParameterGenerator { public Parameter parameter() { return new Parameter() .name("filter") .description("Customizable query (experimental)") .in("query") .schema( new ObjectSchema() .addProperties( "AND", new ObjectSchema() .additionalProperties(true) .nullable(true)) .addProperties( "OR", new ObjectSchema() .additionalProperties(true) .nullable(true)) .addProperties( "NOT", new ObjectSchema() .additionalProperties(true) .nullable(true)) .additionalProperties(true)); } Parameter parameter(); }### Answer:
@Test void parameter() { Parameter parameter = new NestedFilter().parameter(); Assert.assertEquals("filter", parameter.getName()); Assert.assertEquals("query", parameter.getIn()); Assert.assertEquals("Customizable query (experimental)", parameter.getDescription()); Assert.assertNull(parameter.getRequired()); Schema schema = parameter.getSchema(); Assert.assertTrue(schema instanceof ObjectSchema); Assert.assertEquals(true, schema.getAdditionalProperties()); Assert.assertEquals(3, schema.getProperties().size()); ObjectSchema andSchema = (ObjectSchema) schema.getProperties().get("AND"); Assert.assertEquals(true, andSchema.getAdditionalProperties()); Assert.assertTrue(andSchema.getNullable()); ObjectSchema orSchema = (ObjectSchema) schema.getProperties().get("OR"); Assert.assertEquals(true, orSchema.getAdditionalProperties()); Assert.assertTrue(orSchema.getNullable()); ObjectSchema notSchema = (ObjectSchema) schema.getProperties().get("NOT"); Assert.assertEquals(true, notSchema.getAdditionalProperties()); Assert.assertTrue(notSchema.getNullable()); } |
### Question:
PrimaryKey extends AbstractParameterGenerator { public Parameter parameter() { MetaResourceField metaResourceField = OASUtils.getPrimaryKeyMetaResourceField(metaResource); return new Parameter() .name(metaResourceField.getName()) .in("path") .schema(new ResourceAttribute(metaResource, metaResourceField).$ref()); } PrimaryKey(MetaResource metaResource); Parameter parameter(); }### Answer:
@Test void parameter() { Parameter parameter = new PrimaryKey(metaResource).parameter(); Assert.assertEquals("id", parameter.getName()); Assert.assertEquals("path", parameter.getIn()); Assert.assertTrue(parameter.getRequired()); Schema schema = parameter.getSchema(); Assert.assertEquals( "#/components/schemas/ResourceTypeIdResourceAttribute", schema.get$ref() ); } |
### Question:
FieldFilter extends AbstractParameterGenerator { public Parameter parameter() { return new Parameter() .name("filter[" + metaResourceField.getName() + "]") .description("Filter by " + metaResourceField.getName() + " (csv)") .in("query") .schema(new StringSchema()); } FieldFilter(MetaResource metaResource, MetaResourceField metaResourceField); Parameter parameter(); }### Answer:
@Test void parameter() { Parameter parameter = new FieldFilter(metaResource, metaResourceField).parameter(); Assert.assertEquals("filter[id]", parameter.getName()); Assert.assertEquals("query", parameter.getIn()); Assert.assertEquals("Filter by id (csv)", parameter.getDescription()); Assert.assertNull(parameter.getRequired()); Schema schema = parameter.getSchema(); Assert.assertTrue(schema instanceof StringSchema); } |
### Question:
Fields extends AbstractParameterGenerator { public Parameter parameter() { return new Parameter() .name("fields") .description(metaResource.getResourceType() + " fields to include (csv)") .in("query") .schema(new StringSchema() ._default( OASUtils.attributes(metaResource, true) .map(MetaElement::getName) .collect(joining(",")))); } Fields(MetaResource metaResource); Parameter parameter(); }### Answer:
@Test void parameter() { Parameter parameter = new Fields(metaResource).parameter(); Assert.assertEquals("fields", parameter.getName()); Assert.assertEquals("query", parameter.getIn()); Assert.assertEquals("ResourceType fields to include (csv)", parameter.getDescription()); Assert.assertNull(parameter.getRequired()); Schema schema = parameter.getSchema(); Assert.assertTrue(schema instanceof StringSchema); Assert.assertEquals("id,name,resourceRelation", schema.getDefault()); } |
### Question:
Include extends AbstractParameterGenerator { public Parameter parameter() { return new Parameter() .name("include") .description(metaResource.getResourceType() + " relationships to include (csv)") .in("query") .schema(new StringSchema() ._default( metaResource .getAttributes() .stream() .filter(MetaAttribute::isAssociation) .map(e -> e.getType().getElementType().getName()) .collect(joining(",")))); } Include(MetaResource metaResource); Parameter parameter(); }### Answer:
@Test void parameter() { Parameter parameter = new Include(metaResource).parameter(); Assert.assertEquals("include", parameter.getName()); Assert.assertEquals("query", parameter.getIn()); Assert.assertEquals("ResourceType relationships to include (csv)", parameter.getDescription()); Assert.assertNull(parameter.getRequired()); Schema schema = parameter.getSchema(); Assert.assertTrue(schema instanceof StringSchema); } |
### Question:
Sort extends AbstractParameterGenerator { public Parameter parameter() { return new Parameter() .name("sort") .description(metaResource.getResourceType() + " sort order (csv)") .in("query") .schema(new StringSchema() .example( OASUtils.sortAttributes(metaResource, true) .map(MetaElement::getName) .collect(joining(",")))); } Sort(MetaResource metaResource); Parameter parameter(); }### Answer:
@Test void parameterNoSortableAttributes() { MetaResource metaResource = getTestMetaResource(); MetaResourceField metaResourceField = (MetaResourceField) metaResource.getChildren().get(0); MetaResourceField additionalMetaResourceField = (MetaResourceField) metaResource.getChildren().get(1); metaResourceField.setSortable(false); additionalMetaResourceField.setSortable(false); Parameter parameter = new Sort(metaResource).parameter(); Assert.assertEquals("sort", parameter.getName()); Assert.assertEquals("query", parameter.getIn()); Assert.assertEquals("ResourceType sort order (csv)", parameter.getDescription()); Assert.assertNull(parameter.getRequired()); Schema schema = parameter.getSchema(); Assert.assertTrue(schema instanceof StringSchema); Assert.assertEquals("", schema.getExample()); }
@Test void parameterSortableAttribute() { MetaResource metaResource = getTestMetaResource(); MetaResourceField metaResourceField = (MetaResourceField) metaResource.getChildren().get(0); MetaResourceField additionalMetaResourceField = (MetaResourceField) metaResource.getChildren().get(1); metaResourceField.setSortable(false); additionalMetaResourceField.setSortable(true); Parameter parameter = new Sort(metaResource).parameter(); Assert.assertEquals("sort", parameter.getName()); Assert.assertEquals("query", parameter.getIn()); Assert.assertEquals("ResourceType sort order (csv)", parameter.getDescription()); Assert.assertNull(parameter.getRequired()); Schema schema = parameter.getSchema(); Assert.assertTrue(schema instanceof StringSchema); Assert.assertEquals("name", schema.getExample()); }
@Test void parameterSortableAttributes() { MetaResource metaResource = getTestMetaResource(); MetaResourceField metaResourceField = (MetaResourceField) metaResource.getChildren().get(0); MetaResourceField additionalMetaResourceField = (MetaResourceField) metaResource.getChildren().get(1); metaResourceField.setSortable(true); additionalMetaResourceField.setSortable(true); Parameter parameter = new Sort(metaResource).parameter(); Assert.assertEquals("sort", parameter.getName()); Assert.assertEquals("query", parameter.getIn()); Assert.assertEquals("ResourceType sort order (csv)", parameter.getDescription()); Assert.assertNull(parameter.getRequired()); Schema schema = parameter.getSchema(); Assert.assertTrue(schema instanceof StringSchema); Assert.assertEquals("id,name", schema.getExample()); } |
### Question:
OASErrors { public static Map<String, ApiResponse> generateStandardApiErrorResponses() { Map<String, ApiResponse> responses = new LinkedHashMap<>(); List<Integer> responseCodes = getStandardHttpStatusCodes(); for (Integer responseCode : responseCodes) { if (responseCode >= 400 && responseCode <= 599) { ApiResponse apiResponse = new ApiResponse(); apiResponse.description(HttpStatus.toMessage(responseCode)); apiResponse.content(new Content() .addMediaType("application/vnd.api+json", new MediaType().schema(new Failure().$ref())) ); responses.put(responseCode.toString(), apiResponse); } } return responses; } static Map<String, ApiResponse> generateStandardApiErrorResponses(); }### Answer:
@Test public void test() { Map<String, ApiResponse> apiResponseCodes = OASErrors.generateStandardApiErrorResponses(); for (Map.Entry<String, ApiResponse> entry : apiResponseCodes.entrySet()) { Assert.assertTrue(entry.getKey().startsWith("4") || entry.getKey().startsWith("5")); ApiResponse apiResponse = entry.getValue(); Assert.assertNotNull(apiResponse.getDescription()); Schema schema = apiResponse.getContent().get("application/vnd.api+json").getSchema(); Assert.assertEquals(new Failure().$ref(), schema); } } |
### Question:
TSFunction extends TSMember implements TSExportedElement { @Override public boolean isField() { return false; } @Override void accept(TSVisitor visitor); List<String> getStatements(); List<TSParameter> getParameters(); void setExported(boolean exported); @Override boolean isExported(); void addParameter(TSParameter parameter); @Override boolean isField(); @Override TSField asField(); TSFunctionType getFunctionType(); void setFunctionType(TSFunctionType functionType); }### Answer:
@Test public void notAField() { TSFunction function = new TSFunction(); Assert.assertFalse(function.isField()); } |
### Question:
MetaAttributePath implements Iterable<MetaAttribute> { @Override public String toString() { return render(PATH_SEPARATOR); } MetaAttributePath(List<? extends MetaAttribute> pathElements); MetaAttributePath(MetaAttribute... pathElements); MetaAttributePath subPath(int startIndex); MetaAttributePath subPath(int startIndex, int endIndex); int length(); MetaAttribute getElement(int index); MetaAttribute getLast(); MetaAttributePath concat(MetaAttribute... pathElements); String render(String delimiter); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<MetaAttribute> iterator(); static final char PATH_SEPARATOR_CHAR; static final String PATH_SEPARATOR; static final MetaAttributePath EMPTY_PATH; }### Answer:
@Test public void toStringForEmptyPath() { Assert.assertEquals("", MetaAttributePath.EMPTY_PATH.toString()); }
@Test public void toStringForSingleAttributePath() { MetaAttribute attr3 = Mockito.mock(MetaAttribute.class); Mockito.when(attr3.getName()).thenReturn("c"); path = new MetaAttributePath(Arrays.asList(attr3)); Assert.assertEquals("c", path.toString()); } |
### Question:
TSFunction extends TSMember implements TSExportedElement { @Override public TSField asField() { throw new UnsupportedOperationException(); } @Override void accept(TSVisitor visitor); List<String> getStatements(); List<TSParameter> getParameters(); void setExported(boolean exported); @Override boolean isExported(); void addParameter(TSParameter parameter); @Override boolean isField(); @Override TSField asField(); TSFunctionType getFunctionType(); void setFunctionType(TSFunctionType functionType); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void cannotCastToField() { TSFunction function = new TSFunction(); function.asField(); } |
### Question:
TSGenerator { protected TSElement transform(MetaElement element, TSMetaTransformationOptions options) { if (elementSourceMap.containsKey(element)) { return elementSourceMap.get(element); } if (postProcessing) { throw new IllegalStateException("cannot add further element while post processing: " + element.getId()); } for (TSMetaTransformation transformation : transformations) { if (transformation.accepts(element)) { LOGGER.debug("transforming type {} of type {} with {}", element.getId(), element.getClass().getSimpleName(), transformation); TSElement tsElement = transformation.transform(element, createMetaTransformationContext(), options); transformedElements.add(tsElement); return tsElement; } } throw new IllegalStateException("unexpected element: " + element); } TSGenerator(File outputDir, MetaLookup lookup, TSGeneratorConfig config); void run(); void transformMetaToTypescript(); void runProcessors(); }### Answer:
@Test(expected = IllegalStateException.class) public void throwExceptionWhenTransformingUnknownMetaElement() { MetaElement metaElement = Mockito.mock(MetaElement.class); metaElement.setId("does.not.exist"); TSMetaTransformationOptions options = Mockito.mock(TSMetaTransformationOptions.class); generator.transform(metaElement, options); } |
### Question:
TSImportProcessor implements TSSourceProcessor { @Override public List<TSSource> process(List<TSSource> sources) { for (TSSource source : sources) { transform(source); sortImports(source); } return sources; } @Override List<TSSource> process(List<TSSource> sources); }### Answer:
@Test public void sameDirectoryImport() { List<TSSource> updatedSources = processor.process(sources); Assert.assertEquals(sources.size(), updatedSources.size()); Assert.assertEquals(1, classSource.getImports().size()); TSImport tsImport = classSource.getImports().get(0); Assert.assertEquals("./some-interface", tsImport.getPath()); }
@Test public void childDirectoryImport() { interfaceSource.setDirectory("someDir/child-dir"); processor.process(sources); TSImport tsImport = classSource.getImports().get(0); Assert.assertEquals("./child-dir/some-interface", tsImport.getPath()); }
@Test public void parentDirectoryImport() { interfaceSource.setDirectory(null); processor.process(sources); TSImport tsImport = classSource.getImports().get(0); Assert.assertEquals("../some-interface", tsImport.getPath()); }
@Test public void siblingDirectoryImport() { interfaceSource.setDirectory("other-dir"); processor.process(sources); TSImport tsImport = classSource.getImports().get(0); Assert.assertEquals("../other-dir/some-interface", tsImport.getPath()); }
@Test public void checkArrayElementTypeImported() { TSField field = new TSField(); field.setName("someField"); field.setType(new TSArrayType(interfaceType)); classType.addDeclaredMember(field); processor.process(sources); TSImport tsImport = classSource.getImports().get(0); Assert.assertEquals("./some-interface", tsImport.getPath()); }
@Test public void checkParameterizedTypeImported() { TSInterfaceType parameterType = new TSInterfaceType(); parameterType.setName("ParamInterface"); TSSource paramSource = new TSSource(); paramSource.addElement(parameterType); paramSource.setNpmPackage("@crnk/test"); paramSource.setDirectory("someDir"); paramSource.setName("some-param"); sources.add(paramSource); TSField field = new TSField(); field.setName("someField"); field.setType(new TSParameterizedType(interfaceType, parameterType)); classType.addDeclaredMember(field); processor.process(sources); Assert.assertEquals(2, classSource.getImports().size()); Assert.assertEquals("./some-interface", classSource.getImports().get(0).getPath()); Assert.assertEquals("./some-param", classSource.getImports().get(1).getPath()); }
@Test public void checkModuleImport() { TSInterfaceType moduleInterface = new TSInterfaceType(); moduleInterface.setName("SomeInterface"); TSModule module = new TSModule(); module.setName("SomeModule"); module.addElement(moduleInterface); TSSource moduleSource = new TSSource(); moduleSource.addElement(module); moduleSource.setNpmPackage("@crnk/test"); moduleSource.setDirectory("someDir"); moduleSource.setName("some-module"); sources.add(moduleSource); TSField field = new TSField(); field.setName("someField"); field.setType(moduleInterface); classType.setImplementedInterfaces(new ArrayList<>()); classType.addDeclaredMember(field); processor.process(sources); Assert.assertEquals(1, classSource.getImports().size()); TSImport intImport = classSource.getImports().get(0); Assert.assertEquals("./some-module", intImport.getPath()); Assert.assertEquals(1, intImport.getTypeNames().size()); Assert.assertEquals("SomeModule", intImport.getTypeNames().iterator().next()); } |
### Question:
MetaAttributePath implements Iterable<MetaAttribute> { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(pathElements); return result; } MetaAttributePath(List<? extends MetaAttribute> pathElements); MetaAttributePath(MetaAttribute... pathElements); MetaAttributePath subPath(int startIndex); MetaAttributePath subPath(int startIndex, int endIndex); int length(); MetaAttribute getElement(int index); MetaAttribute getLast(); MetaAttributePath concat(MetaAttribute... pathElements); String render(String delimiter); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<MetaAttribute> iterator(); static final char PATH_SEPARATOR_CHAR; static final String PATH_SEPARATOR; static final MetaAttributePath EMPTY_PATH; }### Answer:
@Test public void testHashCode() { MetaAttribute attr3 = Mockito.mock(MetaAttribute.class); Mockito.when(attr3.getName()).thenReturn("c"); MetaAttributePath path2 = new MetaAttributePath(Arrays.asList(attr3)); MetaAttributePath path3 = new MetaAttributePath(Arrays.asList(attr3)); Assert.assertNotEquals(path2.hashCode(), path.hashCode()); Assert.assertEquals(path2.hashCode(), path3.hashCode()); } |
### Question:
UIModule implements Module { @Override public void setupModule(ModuleContext context) { this.context = context; if(config.isBrowserEnabled()) { context.addHttpRequestProcessor(new UIHttpRequestProcessor(config)); setupHomeExtension(context); } if (config != null && config.isPresentationModelEnabled()) { Supplier<List<PresentationService>> servicesSupplier = config.getServices(); if (servicesSupplier == null) { servicesSupplier = () -> Arrays.asList(new PresentationService("local", null, initMetaModule())); } presentationManager = new PresentationManager(servicesSupplier, context.getModuleRegistry().getHttpRequestContextProvider()); config.getPresentationElementFactories().forEach(it -> presentationManager.registerFactory(it)); explorerRepository = new ExplorerRepository(presentationManager); context.addRepository(explorerRepository); editorRepository = new EditorRepository(presentationManager); context.addRepository(editorRepository); } MetaModuleExtension metaExtension = new MetaModuleExtension(); metaExtension.addProvider(presentationMetaProvider); context.addExtension(metaExtension); } protected UIModule(); protected UIModule(UIModuleConfig config); static UIModule create(UIModuleConfig config); String getModuleName(); @Override void setupModule(ModuleContext context); PresentationManager getPresentationManager(); ExplorerRepository getExplorerRepository(); EditorRepository getEditorRepository(); UIModuleConfig getConfig(); }### Answer:
@Test public void testDisableBrowser() { UIModuleConfig config = new UIModuleConfig(); config.setBrowserEnabled(false); UIModule module = new UIModule(config); ModuleRegistry moduleRegistry = Mockito.mock(ModuleRegistry.class); Module.ModuleContext context = Mockito.mock(Module.ModuleContext.class); Mockito.when(context.getModuleRegistry()).thenReturn(moduleRegistry); module.setupModule(context); Mockito.verify(context, Mockito.times(0)).addHttpRequestProcessor(Mockito.any(HttpRequestProcessor.class)); }
@Test public void testDisablePresentationModel() { UIModuleConfig config = new UIModuleConfig(); config.setPresentationModelEnabled(false); UIModule module = new UIModule(config); ModuleRegistry moduleRegistry = Mockito.mock(ModuleRegistry.class); Module.ModuleContext context = Mockito.mock(Module.ModuleContext.class); Mockito.when(context.getModuleRegistry()).thenReturn(moduleRegistry); module.setupModule(context); Mockito.verify(context, Mockito.times(0)).addRepository(Mockito.any()); } |
### Question:
UIModule implements Module { public static UIModule create(UIModuleConfig config) { return new UIModule(config); } protected UIModule(); protected UIModule(UIModuleConfig config); static UIModule create(UIModuleConfig config); String getModuleName(); @Override void setupModule(ModuleContext context); PresentationManager getPresentationManager(); ExplorerRepository getExplorerRepository(); EditorRepository getEditorRepository(); UIModuleConfig getConfig(); }### Answer:
@Test public void checkHomeModuleExtension() { HomeModule homeModule = HomeModule.create(); UIModule uiModule = UIModule.create(new UIModuleConfig()); CrnkBoot boot = new CrnkBoot(); boot.addModule(homeModule); boot.addModule(uiModule); boot.boot(); List<String> list = homeModule.list("/", new QueryContext()); Assert.assertTrue(list.contains("browse/")); }
@Test public void checkHomeModuleIsOptional() { CrnkBoot boot = new CrnkBoot(); UIModule uiModule = UIModule.create(new UIModuleConfig()); boot.addModule(uiModule); boot.boot(); } |
### Question:
MetaAttributePath implements Iterable<MetaAttribute> { public int length() { return pathElements.length; } MetaAttributePath(List<? extends MetaAttribute> pathElements); MetaAttributePath(MetaAttribute... pathElements); MetaAttributePath subPath(int startIndex); MetaAttributePath subPath(int startIndex, int endIndex); int length(); MetaAttribute getElement(int index); MetaAttribute getLast(); MetaAttributePath concat(MetaAttribute... pathElements); String render(String delimiter); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<MetaAttribute> iterator(); static final char PATH_SEPARATOR_CHAR; static final String PATH_SEPARATOR; static final MetaAttributePath EMPTY_PATH; }### Answer:
@Test public void length() { Assert.assertEquals(2, path.length()); } |
### Question:
MetaAttributePath implements Iterable<MetaAttribute> { public MetaAttribute getLast() { if (pathElements != null && pathElements.length > 0) { return pathElements[pathElements.length - 1]; } return null; } MetaAttributePath(List<? extends MetaAttribute> pathElements); MetaAttributePath(MetaAttribute... pathElements); MetaAttributePath subPath(int startIndex); MetaAttributePath subPath(int startIndex, int endIndex); int length(); MetaAttribute getElement(int index); MetaAttribute getLast(); MetaAttributePath concat(MetaAttribute... pathElements); String render(String delimiter); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<MetaAttribute> iterator(); static final char PATH_SEPARATOR_CHAR; static final String PATH_SEPARATOR; static final MetaAttributePath EMPTY_PATH; }### Answer:
@Test public void getLast() { Assert.assertEquals(attr2, path.getLast()); }
@Test public void getLastForEmptyPath() { Assert.assertNull(MetaAttributePath.EMPTY_PATH.getLast()); } |
### Question:
MetaAttributePath implements Iterable<MetaAttribute> { @Override public Iterator<MetaAttribute> iterator() { return Collections.unmodifiableList(Arrays.asList(pathElements)).iterator(); } MetaAttributePath(List<? extends MetaAttribute> pathElements); MetaAttributePath(MetaAttribute... pathElements); MetaAttributePath subPath(int startIndex); MetaAttributePath subPath(int startIndex, int endIndex); int length(); MetaAttribute getElement(int index); MetaAttribute getLast(); MetaAttributePath concat(MetaAttribute... pathElements); String render(String delimiter); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<MetaAttribute> iterator(); static final char PATH_SEPARATOR_CHAR; static final String PATH_SEPARATOR; static final MetaAttributePath EMPTY_PATH; }### Answer:
@Test public void iterator() { Iterator<MetaAttribute> iterator = path.iterator(); Assert.assertTrue(iterator.hasNext()); Assert.assertEquals("a", iterator.next().getName()); Assert.assertEquals("b", iterator.next().getName()); Assert.assertFalse(iterator.hasNext()); } |
### Question:
MetaAttributePath implements Iterable<MetaAttribute> { public MetaAttribute getElement(int index) { return pathElements[index]; } MetaAttributePath(List<? extends MetaAttribute> pathElements); MetaAttributePath(MetaAttribute... pathElements); MetaAttributePath subPath(int startIndex); MetaAttributePath subPath(int startIndex, int endIndex); int length(); MetaAttribute getElement(int index); MetaAttribute getLast(); MetaAttributePath concat(MetaAttribute... pathElements); String render(String delimiter); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<MetaAttribute> iterator(); static final char PATH_SEPARATOR_CHAR; static final String PATH_SEPARATOR; static final MetaAttributePath EMPTY_PATH; }### Answer:
@Test public void getElement() { Assert.assertEquals(attr1, path.getElement(0)); Assert.assertEquals(attr2, path.getElement(1)); } |
### Question:
MetaAttributePath implements Iterable<MetaAttribute> { public MetaAttributePath subPath(int startIndex) { MetaAttribute[] range = Arrays.copyOfRange(pathElements, startIndex, pathElements.length); return new MetaAttributePath(range); } MetaAttributePath(List<? extends MetaAttribute> pathElements); MetaAttributePath(MetaAttribute... pathElements); MetaAttributePath subPath(int startIndex); MetaAttributePath subPath(int startIndex, int endIndex); int length(); MetaAttribute getElement(int index); MetaAttribute getLast(); MetaAttributePath concat(MetaAttribute... pathElements); String render(String delimiter); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<MetaAttribute> iterator(); static final char PATH_SEPARATOR_CHAR; static final String PATH_SEPARATOR; static final MetaAttributePath EMPTY_PATH; }### Answer:
@Test public void subPath() { MetaAttributePath subPath = path.subPath(1); Assert.assertEquals(1, subPath.length()); Assert.assertEquals(attr2, subPath.getElement(0)); } |
### Question:
ResourcePermission { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (deleteAllowed ? 1231 : 1237); result = prime * result + (getAllowed ? 1231 : 1237); result = prime * result + (patchAllowed ? 1231 : 1237); result = prime * result + (postAllowed ? 1231 : 1237); return result; } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); static final ResourcePermission create(boolean push, boolean get, boolean patch, boolean delete); static ResourcePermission fromMethod(HttpMethod method); boolean isPostAllowed(); boolean isGetAllowed(); boolean isPatchAllowed(); boolean isDeleteAllowed(); @JsonIgnore boolean isEmpty(); ResourcePermission or(ResourcePermission other); ResourcePermission and(ResourcePermission other); ResourcePermission xor(ResourcePermission other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final ResourcePermission EMPTY; static final ResourcePermission ALL; static final ResourcePermission GET; static final ResourcePermission POST; static final ResourcePermission PATCH; static final ResourcePermission DELETE; }### Answer:
@Test public void testHashCode() { Assert.assertEquals(ResourcePermission.ALL.hashCode(), ResourcePermission.ALL.hashCode()); Assert.assertNotEquals(ResourcePermission.DELETE.hashCode(), ResourcePermission.ALL.hashCode()); Assert.assertNotEquals(ResourcePermission.GET.hashCode(), ResourcePermission.ALL.hashCode()); Assert.assertNotEquals(ResourcePermission.POST.hashCode(), ResourcePermission.PATCH.hashCode()); Assert.assertNotEquals(ResourcePermission.POST.hashCode(), ResourcePermission.GET.hashCode()); } |
### Question:
MetaAttributePath implements Iterable<MetaAttribute> { public String render(String delimiter) { if (pathElements.length == 0) { return ""; } else if (pathElements.length == 1) { return pathElements[0].getName(); } else { StringBuilder builder = new StringBuilder(pathElements[0].getName()); for (int i = 1; i < pathElements.length; i++) { builder.append(delimiter); builder.append(pathElements[i].getName()); } return builder.toString(); } } MetaAttributePath(List<? extends MetaAttribute> pathElements); MetaAttributePath(MetaAttribute... pathElements); MetaAttributePath subPath(int startIndex); MetaAttributePath subPath(int startIndex, int endIndex); int length(); MetaAttribute getElement(int index); MetaAttribute getLast(); MetaAttributePath concat(MetaAttribute... pathElements); String render(String delimiter); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<MetaAttribute> iterator(); static final char PATH_SEPARATOR_CHAR; static final String PATH_SEPARATOR; static final MetaAttributePath EMPTY_PATH; }### Answer:
@Test public void render() { Assert.assertEquals("a.b", path.toString()); } |
### Question:
MetaAttributePath implements Iterable<MetaAttribute> { @Override public boolean equals(Object obj) { if (obj instanceof MetaAttributePath) { MetaAttributePath other = (MetaAttributePath) obj; return Arrays.equals(pathElements, other.pathElements); } return false; } MetaAttributePath(List<? extends MetaAttribute> pathElements); MetaAttributePath(MetaAttribute... pathElements); MetaAttributePath subPath(int startIndex); MetaAttributePath subPath(int startIndex, int endIndex); int length(); MetaAttribute getElement(int index); MetaAttribute getLast(); MetaAttributePath concat(MetaAttribute... pathElements); String render(String delimiter); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<MetaAttribute> iterator(); static final char PATH_SEPARATOR_CHAR; static final String PATH_SEPARATOR; static final MetaAttributePath EMPTY_PATH; }### Answer:
@Test public void equals() { Assert.assertTrue(path.equals(path)); Assert.assertFalse(path.equals(new Object())); } |
### Question:
MetaDataObject extends MetaType { public MetaAttributePath resolvePath(List<String> attrPath, boolean includeSubTypes) { MetaAttributeFinder finder = includeSubTypes ? SUBTYPE_ATTRIBUTE_FINDER : DEFAULT_ATTRIBUTE_FINDER; return resolvePath(attrPath, finder); } @JsonIgnore // TODO MetaAttribute getVersionAttribute(); List<? extends MetaAttribute> getAttributes(); void setAttributes(List<MetaAttribute> attributes); List<? extends MetaAttribute> getDeclaredAttributes(); void setDeclaredAttributes(List<MetaAttribute> declaredAttributes); MetaAttribute getAttribute(String name); MetaAttributePath resolvePath(List<String> attrPath, boolean includeSubTypes); MetaAttributePath resolvePath(List<String> attrPath); MetaAttributePath resolvePath(List<String> attrPath, MetaAttributeFinder finder); MetaAttribute findAttribute(String name, boolean includeSubTypes); boolean hasAttribute(String name); MetaDataObject getSuperType(); void setSuperType(MetaDataObject superType); List<MetaDataObject> getSubTypes(boolean transitive, boolean self); @JsonIgnore boolean isAbstract(); Set<MetaDataObject> getSubTypes(); void setSubTypes(Set<MetaDataObject> subTypes); Set<MetaInterface> getInterfaces(); void setInterfaces(Set<MetaInterface> interfaces); MetaPrimaryKey getPrimaryKey(); void setPrimaryKey(MetaPrimaryKey key); Set<MetaKey> getDeclaredKeys(); void setDeclaredKeys(Set<MetaKey> declaredKeys); void addDeclaredKey(MetaKey key); void addSubType(MetaDataObject subType); boolean isInsertable(); void setInsertable(boolean insertable); boolean isUpdatable(); void setUpdatable(boolean updatable); boolean isDeletable(); void setDeletable(boolean deletable); boolean isReadable(); void setReadable(boolean readable); }### Answer:
@Test(expected = IllegalArgumentException.class) public void checkResolvePathWithNullNotAllowed() { MetaResource meta = resourceProvider.getMeta(Task.class); meta.resolvePath(null); }
@Test public void checkResolveEmptyPath() { MetaResource meta = resourceProvider.getMeta(Task.class); Assert.assertEquals(MetaAttributePath.EMPTY_PATH, meta.resolvePath(new ArrayList<String>())); }
@Test public void checkResolveMapPath() { MetaResource meta = resourceProvider.getMeta(Project.class); MetaAttributePath path = meta.resolvePath(Arrays.asList("data", "customData", "test")); Assert.assertEquals(2, path.length()); Assert.assertEquals("data", path.getElement(0).getName()); MetaMapAttribute mapAttr = (MetaMapAttribute) path.getElement(1); Assert.assertEquals("test", mapAttr.getKey()); Assert.assertEquals("customData", mapAttr.getName()); }
@Test(expected = IllegalArgumentException.class) public void checkResolveInvalidPath() { MetaResource meta = resourceProvider.getMeta(Project.class); meta.resolvePath(Arrays.asList("name", "doesNotExist")); } |
### Question:
MetaDataObject extends MetaType { public MetaAttribute findAttribute(String name, boolean includeSubTypes) { if (hasAttribute(name)) { return getAttribute(name); } if (includeSubTypes) { List<? extends MetaDataObject> transitiveSubTypes = getSubTypes(true, true); for (MetaDataObject subType : transitiveSubTypes) { if (subType.hasAttribute(name)) { return subType.getAttribute(name); } } } throw new IllegalStateException("attribute " + name + " not found in " + getName()); } @JsonIgnore // TODO MetaAttribute getVersionAttribute(); List<? extends MetaAttribute> getAttributes(); void setAttributes(List<MetaAttribute> attributes); List<? extends MetaAttribute> getDeclaredAttributes(); void setDeclaredAttributes(List<MetaAttribute> declaredAttributes); MetaAttribute getAttribute(String name); MetaAttributePath resolvePath(List<String> attrPath, boolean includeSubTypes); MetaAttributePath resolvePath(List<String> attrPath); MetaAttributePath resolvePath(List<String> attrPath, MetaAttributeFinder finder); MetaAttribute findAttribute(String name, boolean includeSubTypes); boolean hasAttribute(String name); MetaDataObject getSuperType(); void setSuperType(MetaDataObject superType); List<MetaDataObject> getSubTypes(boolean transitive, boolean self); @JsonIgnore boolean isAbstract(); Set<MetaDataObject> getSubTypes(); void setSubTypes(Set<MetaDataObject> subTypes); Set<MetaInterface> getInterfaces(); void setInterfaces(Set<MetaInterface> interfaces); MetaPrimaryKey getPrimaryKey(); void setPrimaryKey(MetaPrimaryKey key); Set<MetaKey> getDeclaredKeys(); void setDeclaredKeys(Set<MetaKey> declaredKeys); void addDeclaredKey(MetaKey key); void addSubType(MetaDataObject subType); boolean isInsertable(); void setInsertable(boolean insertable); boolean isUpdatable(); void setUpdatable(boolean updatable); boolean isDeletable(); void setDeletable(boolean deletable); boolean isReadable(); void setReadable(boolean readable); }### Answer:
@Test public void checkResolveSubtypeAttribute() { MetaResource meta = resourceProvider.getMeta(Task.class); Assert.assertNotNull(meta.findAttribute("subTypeValue", true)); }
@Test(expected = IllegalStateException.class) public void checkCannotResolveSubtypeAttributeWithoutIncludingSubtypes() { MetaResource meta = resourceProvider.getMeta(Task.class); meta.findAttribute("subTypeValue", false); }
@Test(expected = IllegalStateException.class) public void checkResolveInvalidAttribute() { MetaResource meta = resourceProvider.getMeta(Task.class); Assert.assertNotNull(meta.findAttribute("doesNotExist", true)); } |
### Question:
MetaDataObject extends MetaType { public MetaAttribute getAttribute(String name) { setupCache(); MetaAttribute attr = attrMap.get(name); PreconditionUtil.assertNotNull(getName() + "." + name, attr); return attr; } @JsonIgnore // TODO MetaAttribute getVersionAttribute(); List<? extends MetaAttribute> getAttributes(); void setAttributes(List<MetaAttribute> attributes); List<? extends MetaAttribute> getDeclaredAttributes(); void setDeclaredAttributes(List<MetaAttribute> declaredAttributes); MetaAttribute getAttribute(String name); MetaAttributePath resolvePath(List<String> attrPath, boolean includeSubTypes); MetaAttributePath resolvePath(List<String> attrPath); MetaAttributePath resolvePath(List<String> attrPath, MetaAttributeFinder finder); MetaAttribute findAttribute(String name, boolean includeSubTypes); boolean hasAttribute(String name); MetaDataObject getSuperType(); void setSuperType(MetaDataObject superType); List<MetaDataObject> getSubTypes(boolean transitive, boolean self); @JsonIgnore boolean isAbstract(); Set<MetaDataObject> getSubTypes(); void setSubTypes(Set<MetaDataObject> subTypes); Set<MetaInterface> getInterfaces(); void setInterfaces(Set<MetaInterface> interfaces); MetaPrimaryKey getPrimaryKey(); void setPrimaryKey(MetaPrimaryKey key); Set<MetaKey> getDeclaredKeys(); void setDeclaredKeys(Set<MetaKey> declaredKeys); void addDeclaredKey(MetaKey key); void addSubType(MetaDataObject subType); boolean isInsertable(); void setInsertable(boolean insertable); boolean isUpdatable(); void setUpdatable(boolean updatable); boolean isDeletable(); void setDeletable(boolean deletable); boolean isReadable(); void setReadable(boolean readable); }### Answer:
@Test public void checkNestedObject() { MetaJsonObject meta = resourceProvider.getMeta(ProjectData.class); Assert.assertEquals("ProjectData", meta.getName()); Assert.assertEquals("resources.types.projectdata", meta.getId()); Assert.assertNotNull(meta.getAttribute("data").getType()); } |
### Question:
ResourcePermission { public ResourcePermission xor(ResourcePermission other) { boolean mergePush = postAllowed ^ other.postAllowed; boolean mergeGet = getAllowed ^ other.getAllowed; boolean mergePatch = patchAllowed ^ other.patchAllowed; boolean mergeDelete = deleteAllowed ^ other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); static final ResourcePermission create(boolean push, boolean get, boolean patch, boolean delete); static ResourcePermission fromMethod(HttpMethod method); boolean isPostAllowed(); boolean isGetAllowed(); boolean isPatchAllowed(); boolean isDeleteAllowed(); @JsonIgnore boolean isEmpty(); ResourcePermission or(ResourcePermission other); ResourcePermission and(ResourcePermission other); ResourcePermission xor(ResourcePermission other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final ResourcePermission EMPTY; static final ResourcePermission ALL; static final ResourcePermission GET; static final ResourcePermission POST; static final ResourcePermission PATCH; static final ResourcePermission DELETE; }### Answer:
@Test public void xor() { Assert.assertTrue(ResourcePermission.DELETE.xor(ResourcePermission.DELETE).isEmpty()); Assert.assertTrue(ResourcePermission.GET.xor(ResourcePermission.GET).isEmpty()); Assert.assertEquals(ResourcePermission.create(false, true, false, true), ResourcePermission.GET.xor(ResourcePermission.DELETE)); } |
### Question:
MetaMapAttribute extends MetaAttribute { public Object getKey() { MetaType keyType = mapType.getKeyType(); TypeParser typeParser = new TypeParser(); return typeParser.parse(keyString, (Class) keyType.getImplementationClass()); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test public void getKey() { MetaType keyType = Mockito.mock(MetaType.class); Mockito.when(keyType.getImplementationClass()).thenReturn((Class) Integer.class); Mockito.when(mapType.getKeyType()).thenReturn(keyType); Assert.assertEquals(Integer.valueOf(13), impl.getKey()); } |
### Question:
MetaMapAttribute extends MetaAttribute { @Override public boolean isLazy() { return mapAttr.isLazy(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test public void checkForwardIsLazy() { impl.isLazy(); Mockito.verify(mapAttr, Mockito.times(1)).isLazy(); } |
### Question:
MetaMapAttribute extends MetaAttribute { @Override public boolean isDerived() { return mapAttr.isDerived(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test public void checkForwardIsDerived() { impl.isDerived(); Mockito.verify(mapAttr, Mockito.times(1)).isDerived(); } |
### Question:
MetaMapAttribute extends MetaAttribute { @Override public Collection<Annotation> getAnnotations() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void checkGetAnnotationsNotSupported() { impl.getAnnotations(); } |
### Question:
MetaMapAttribute extends MetaAttribute { @Override public <T extends Annotation> T getAnnotation(Class<T> clazz) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void checkGetAnnotationNotSupported() { impl.getAnnotation(null); } |
### Question:
MetaMapAttribute extends MetaAttribute { public void setOppositeAttribute(MetaAttribute oppositeAttr) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void checkSetOppositeAttributeNotSupported() { impl.setOppositeAttribute(null); } |
### Question:
MetaMapAttribute extends MetaAttribute { @Override public boolean isAssociation() { return mapAttr.isAssociation(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test public void checkForwardIsAssociation() { impl.isAssociation(); Mockito.verify(mapAttr, Mockito.times(1)).isAssociation(); } |
### Question:
MetaMapAttribute extends MetaAttribute { @Override public boolean isVersion() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void getVersionNotSupported() { impl.isVersion(); } |
### Question:
MetaMapAttribute extends MetaAttribute { public boolean isId() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void isIdNotSupported() { impl.isId(); } |
### Question:
MetaMapAttribute extends MetaAttribute { @Override public MetaAttribute getOppositeAttribute() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void getOppositeAttributeNotSupported() { impl.getOppositeAttribute(); } |
### Question:
ResourcePermission { public ResourcePermission and(ResourcePermission other) { boolean mergePush = postAllowed && other.postAllowed; boolean mergeGet = getAllowed && other.getAllowed; boolean mergePatch = patchAllowed && other.patchAllowed; boolean mergeDelete = deleteAllowed && other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); static final ResourcePermission create(boolean push, boolean get, boolean patch, boolean delete); static ResourcePermission fromMethod(HttpMethod method); boolean isPostAllowed(); boolean isGetAllowed(); boolean isPatchAllowed(); boolean isDeleteAllowed(); @JsonIgnore boolean isEmpty(); ResourcePermission or(ResourcePermission other); ResourcePermission and(ResourcePermission other); ResourcePermission xor(ResourcePermission other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final ResourcePermission EMPTY; static final ResourcePermission ALL; static final ResourcePermission GET; static final ResourcePermission POST; static final ResourcePermission PATCH; static final ResourcePermission DELETE; }### Answer:
@Test public void and() { Assert.assertEquals(ResourcePermission.DELETE, ResourcePermission.DELETE.or(ResourcePermission.DELETE)); Assert.assertEquals(ResourcePermission.GET, ResourcePermission.GET.or(ResourcePermission.GET)); Assert.assertTrue(ResourcePermission.GET.and(ResourcePermission.DELETE).isEmpty()); } |
### Question:
MetaMapAttribute extends MetaAttribute { @Override public Object getValue(Object dataObject) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void getValueNotSupported() { impl.getValue(null); } |
### Question:
MetaMapAttribute extends MetaAttribute { @Override public void addValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void addValueNotSupported() { impl.addValue(null, null); } |
### Question:
MetaMapAttribute extends MetaAttribute { @Override public void removeValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void removeValueNotSupported() { impl.removeValue(null, null); } |
### Question:
MetaMapAttribute extends MetaAttribute { @Override public void setValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void setValueNotSupported() { impl.setValue(null, null); } |
### Question:
MetaKey extends MetaElement { public String toKeyString(Object id) { if (id == null) { return null; } PreconditionUtil.assertEquals("compound primary key not supported", 1, elements.size()); MetaAttribute keyAttr = elements.get(0); MetaType keyType = keyAttr.getType(); if (keyType instanceof MetaDataObject) { MetaDataObject embType = (MetaDataObject) keyType; return toEmbeddableKeyString(embType, id); } else { return id.toString(); } } List<MetaAttribute> getElements(); void setElements(List<MetaAttribute> elements); boolean isUnique(); void setUnique(boolean unique); @JsonIgnore MetaAttribute getUniqueElement(); String toKeyString(Object id); static final String ID_ELEMENT_SEPARATOR; }### Answer:
@Test public void testToKeyStringWithNull() { MetaKey key = new MetaKey(); Assert.assertNull(key.toKeyString(null)); } |
### Question:
MetaElement implements Cloneable { public MetaDataObject asDataObject() { if (!(this instanceof MetaDataObject)) { throw new IllegalStateException(getName() + " not a MetaDataObject"); } return (MetaDataObject) this; } MetaElement getParent(); void setParent(MetaElement parent); List<MetaElement> getChildren(); void setChildren(List<MetaElement> children); void addChild(MetaElement child); Map<String, MetaNature> getNatures(); void setNatures(Map<String, MetaNature> natures); MetaType asType(); MetaDataObject asDataObject(); void setParent(MetaElement parent, boolean attach); @Override String toString(); final String getId(); void setId(String id); String getName(); void setName(String name); @JsonIgnore boolean hasId(); MetaElement duplicate(); }### Answer:
@Test(expected = IllegalStateException.class) public void checkDataObjectCast() { new MetaKey().asDataObject(); } |
### Question:
MetaElement implements Cloneable { public MetaType asType() { if (!(this instanceof MetaType)) { throw new IllegalStateException(getName() + " not a MetaEntity"); } return (MetaType) this; } MetaElement getParent(); void setParent(MetaElement parent); List<MetaElement> getChildren(); void setChildren(List<MetaElement> children); void addChild(MetaElement child); Map<String, MetaNature> getNatures(); void setNatures(Map<String, MetaNature> natures); MetaType asType(); MetaDataObject asDataObject(); void setParent(MetaElement parent, boolean attach); @Override String toString(); final String getId(); void setId(String id); String getName(); void setName(String name); @JsonIgnore boolean hasId(); MetaElement duplicate(); }### Answer:
@Test(expected = IllegalStateException.class) public void checkTypeCast() { new MetaKey().asType(); } |
### Question:
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { @Override public Class<T> getResourceClass() { return repositoryConfig.getResourceClass(); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }### Answer:
@Test public void testGetResourceType() { Assert.assertEquals(TestEntity.class, repo.getResourceClass()); } |
### Question:
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { public Class<?> getEntityClass() { return repositoryConfig.getEntityClass(); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }### Answer:
@Test public void testGetEntityType() { Assert.assertEquals(TestEntity.class, repo.getEntityClass()); } |
### Question:
ResourcePermission { public ResourcePermission or(ResourcePermission other) { boolean mergePush = postAllowed || other.postAllowed; boolean mergeGet = getAllowed || other.getAllowed; boolean mergePatch = patchAllowed || other.patchAllowed; boolean mergeDelete = deleteAllowed || other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); static final ResourcePermission create(boolean push, boolean get, boolean patch, boolean delete); static ResourcePermission fromMethod(HttpMethod method); boolean isPostAllowed(); boolean isGetAllowed(); boolean isPatchAllowed(); boolean isDeleteAllowed(); @JsonIgnore boolean isEmpty(); ResourcePermission or(ResourcePermission other); ResourcePermission and(ResourcePermission other); ResourcePermission xor(ResourcePermission other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final ResourcePermission EMPTY; static final ResourcePermission ALL; static final ResourcePermission GET; static final ResourcePermission POST; static final ResourcePermission PATCH; static final ResourcePermission DELETE; }### Answer:
@Test public void or() { Assert.assertEquals(ResourcePermission.DELETE, ResourcePermission.DELETE.or(ResourcePermission.DELETE)); Assert.assertEquals(ResourcePermission.GET, ResourcePermission.GET.or(ResourcePermission.GET)); Assert.assertEquals(ResourcePermission.create(false, true, false, true), ResourcePermission.GET.or(ResourcePermission.DELETE)); } |
### Question:
MyService { public int calculateUserAge(User user) { return Period.between(user.getDateOfBirth(), LocalDate.now()).getYears(); } int calculateUserAge(User user); }### Answer:
@Test public void testService() { MyService myService = new MyService(); User user = new User("John", "john@yahoo.com"); user.setDateOfBirth(LocalDate.of(1980, Month.APRIL, 20)); logger.info("Age of user {} is {}", () -> user.getName(), () -> myService.calculateUserAge(user)); } |
### Question:
EmployeeService { public double calculateBonus(Employee user) { return 0.1 * user.getSalary(); } double calculateBonus(Employee user); }### Answer:
@Test public void testParameter() { Employee employee = new Employee("john@gmail.com", "John", 2000); if (logger.isDebugEnabled()) { logger.debug("The bonus for employee: " + employee.getName() + " is " + employeeService.calculateBonus(employee)); } logger.debug("The bonus for employee {} is {}", employee.getName(), employeeService.calculateBonus(employee)); } |
### Question:
Castle { public static String clientId() { return instance.identifier; } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); static final String clientIdHeaderName; }### Answer:
@Test public void testDeviceIdentifier() { Assert.assertNotNull(Castle.clientId()); }
@Test public void testRequestInterceptor() throws IOException { Request request = new Request.Builder() .url("https: .build(); Response response = client.newCall(request).execute(); Assert.assertEquals(Castle.clientId(), response.request().header(Castle.clientIdHeaderName)); request = new Request.Builder() .url("https: .build(); response = client.newCall(request).execute(); Assert.assertEquals(null, response.request().header(Castle.clientIdHeaderName)); } |
### Question:
Castle { public static boolean flushIfNeeded(String url) { if (isUrlWhiteListed(url)) { flush(); return true; } return false; } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); static final String clientIdHeaderName; }### Answer:
@Test public void testflushIfNeeded() { boolean flushed = Castle.flushIfNeeded("https: Assert.assertTrue(flushed); flushed = Castle.flushIfNeeded("https: Assert.assertFalse(flushed); } |
### Question:
Castle { public static void reset() { Castle.flush(); Castle.userId(null); Castle.userSignature(null); } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); static final String clientIdHeaderName; }### Answer:
@Test public void testReset() { Castle.reset(); Assert.assertNull(Castle.userId()); } |
### Question:
Castle { static boolean isUrlWhiteListed(String urlString) { try { URL url = new URL(urlString); String baseUrl = url.getProtocol() + ": if (Castle.configuration().baseURLWhiteList() != null && !Castle.configuration().baseURLWhiteList().isEmpty()) { if (Castle.configuration().baseURLWhiteList().contains(baseUrl)) { return true; } } } catch (MalformedURLException e) { e.printStackTrace(); } return false; } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); static final String clientIdHeaderName; }### Answer:
@Test public void testWhiteList() { Assert.assertFalse(Castle.isUrlWhiteListed("invalid url")); } |
### Question:
Castle { public static String userAgent() { return Utils.sanitizeHeader(String.format(Locale.US, "%s/%s (%d) (%s %s; Android %s; Castle %s)", instance.appName, instance.appVersion, instance.appBuild, Build.MANUFACTURER, Build.MODEL, Build.VERSION.RELEASE, BuildConfig.VERSION_NAME)); } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); static final String clientIdHeaderName; }### Answer:
@Test @Config(manifest = "AndroidManifest.xml") public void testUserAgent() { String regex = "[a-zA-Z0-9\\s._-]+/[0-9]+\\.[0-9]+\\.?[0-9]*(-[a-zA-Z0-9]*)? \\([a-zA-Z0-9-_.]+\\) \\([a-zA-Z0-9\\s]+; Android [0-9]+\\.?[0-9]*; Castle [0-9]+\\.[0-9]+\\.?[0-9]*(-[a-zA-Z0-9]*)?\\)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(Castle.userAgent()); Assert.assertTrue(matcher.matches()); matcher = pattern.matcher("io.castle.android.test/1.0 (1) (Google Nexus 5x; Android 9.0; Castle 1.1.1)"); Assert.assertTrue(matcher.matches()); matcher = pattern.matcher("io.castle.android.test/1.0-SNAPSHOT (1) (Google Nexus 5x; Android 9.0; Castle 1.1.1-SNAPSHOT)"); Assert.assertTrue(matcher.matches()); String result = Utils.sanitizeHeader("[Ţŕéļļö one two]/2020.5.13837-production (13837) (motorola Moto G (4); Android 7.0; Castle 1.1.2)"); Assert.assertEquals("[ one two]/2020.5.13837-production (13837) (motorola Moto G (4); Android 7.0; Castle 1.1.2)", result); } |
### Question:
Solve { Solve() { } Solve(); int solve(int dimension, int[][] gridCopy); static int[] rc2box(int i, int j); }### Answer:
@Test public void testInvalidGrid() { Solve grid1 = new Solve(); int[][] grid = { { 4, 8, 3, 7, 6, 9, 2, 1, 5 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 0 } }; assertEquals(0, grid1.solve(9, grid)); }
@Test public void testGameGrid() { Solve grid1 = new Solve(); GameGrid grid = new GameGrid(9); assertTrue(0< grid1.solve(9, grid.grid)); } |
### Question:
MatrixController { @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody public String find(@PathVariable String petId, @MatrixVariable int q) { logger.info("petId:{},q:{}",petId,q); return petId + q; } @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody String find(@PathVariable String petId, @MatrixVariable int q); @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody String find1(
@MatrixVariable(name="q", pathVar="ownerId") int q1,
@MatrixVariable(name="q", pathVar="petId") int q2); }### Answer:
@Test public void find() throws Exception { this.mockMvc.perform(get("/matrix/find/42;q=11;r=22")) .andExpect(status().isOk()) .andExpect(content().string("4211")); } |
### Question:
MatrixController { @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody public String find1( @MatrixVariable(name="q", pathVar="ownerId") int q1, @MatrixVariable(name="q", pathVar="petId") int q2) { return String.valueOf(q1+q2); } @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody String find(@PathVariable String petId, @MatrixVariable int q); @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody String find1(
@MatrixVariable(name="q", pathVar="ownerId") int q1,
@MatrixVariable(name="q", pathVar="petId") int q2); }### Answer:
@Test public void find1() throws Exception { this.mockMvc.perform(get("/matrix/owners/42;q=11/pets/11;q=22")) .andExpect(status().isOk()) .andExpect(content().string("33")); } |
### Question:
JsonController { @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User get(){ return new User(20,"李四","F"); } @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@PathVariable String name, Model model); }### Answer:
@Test public void getUser() throws Exception { logger.info("JsonControllerTest getUser is running"); this.mockMvc.perform(get("/json/get").accept(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.name").value("李四")); } |
### Question:
JsonController { @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@PathVariable String name, Model model){ logger.info("name : {}",name); return new User(20,name,"男"); } @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@PathVariable String name, Model model); }### Answer:
@Test public void postUser() throws Exception { logger.info("JsonControllerTest postUser is running"); this.mockMvc.perform(post("/json/post/haha").accept(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.name").value("haha")); } |
### Question:
XmlController { @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User get(){ return new User(21,"张三","男"); } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); }### Answer:
@Test public void getUser() throws Exception { logger.info("XmlControllerTest getUser is running"); this.mockMvc.perform(get("/xml/get")).andExpect(status().isOk()).andExpect(content().contentType ("application/xml")).andExpect(xpath("/user/name", new HashMap<String, String>()).string("张三")); } |
### Question:
XmlController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User post(@RequestBody User user){ logger.info(user.toString()); return user; } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); }### Answer:
@Test public void postUser() throws Exception { logger.info("XmlControllerTest postUser is running"); User user = new User(10, "王五", "男"); String content = JaxbUtils.toXml(user); logger.info("content:{}", content); this.mockMvc.perform(post("/xml/post").contentType(MediaType.APPLICATION_XML_VALUE).content(content)) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_XML_VALUE)).andExpect(xpath ("/user/sex", new HashMap<String, String>()).string("男")); } |
### Question:
XmlController { @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public House postHouse(@RequestBody House house){ logger.info(house.toString()); return house; } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); }### Answer:
@Test public void postHouse() throws Exception { logger.info("XmlControllerTest postHouse is running"); User user = new User(30, "王五", "男"); House house = new House(user,"南京"); String content = JaxbUtils.toXml(house); logger.info("content:{}", content); this.mockMvc.perform(post("/xml/postHouse").contentType(MediaType.APPLICATION_XML_VALUE).content(content)) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_XML_VALUE)).andExpect(xpath ("/house/user/sex", new HashMap<String, String>()).string("男")); } |
### Question:
ValidController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@RequestBody @Valid User user){ return user; } @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@RequestBody @Valid User user); }### Answer:
@Test public void postTest() throws Exception { User user = new User(50, "王五", "男"); String content = JSON.toJSONString(user); logger.info("content:{}", content); this.mockMvc.perform(post("/valid/post").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content(content)) .andExpect(content().string("4211")); } |
### Question:
ModelRef { static public boolean validateId(String id){ return (id != null) && (id).matches(REGEX_ID); } ModelRef(ModelRef modelRef); ModelRef(Principal owner, String id); @Override int hashCode(); @Override boolean equals(Object object); Principal getOwner(); String getId(); static boolean validateId(String id); static final String PATH_VALUE_ID; }### Answer:
@Test public void validateId(){ assertTrue(ModelRef.validateId("com.mycompany.Test")); assertTrue(ModelRef.validateId("Test_v1")); assertTrue(ModelRef.validateId("Test_v1.0")); assertFalse(ModelRef.validateId(".")); assertFalse(ModelRef.validateId("-Test")); } |
### Question:
CsvUtil { static public CsvPreference getFormat(String delimiterChar, String quoteChar){ char delimiter = ','; char quote = '\"'; if(delimiterChar != null){ delimiterChar = decodeDelimiter(delimiterChar); if(delimiterChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV delimiter character: \"" + delimiterChar + "\""); } delimiter = delimiterChar.charAt(0); } if(quoteChar != null){ quoteChar = decodeQuote(quoteChar); if(quoteChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV quote character: \"" + quoteChar + "\""); } quote = quoteChar.charAt(0); } CsvPreference format = createFormat(delimiter, quote); return format; } private CsvUtil(); static CsvPreference getFormat(String delimiterChar, String quoteChar); static CsvPreference getFormat(BufferedReader reader); static CsvPreference createFormat(char delimiterChar, char quoteChar); static TableEvaluationRequest readTable(BufferedReader reader, CsvPreference format); static void writeTable(TableEvaluationResponse tableResponse, BufferedWriter writer, CsvPreference format); }### Answer:
@Test public void getFormat() throws IOException { CsvPreference first; CsvPreference second; String csv = "1\tone\n" + "2\ttwo\n" + "3\tthree"; try(BufferedReader reader = new BufferedReader(new StringReader(csv))){ first = CsvUtil.getFormat(reader); second = CsvUtil.getFormat(reader); } assertNotSame(first.getEncoder(), second.getEncoder()); } |
### Question:
WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException> { @Override public Response toResponse(WebApplicationException exception){ Response response = exception.getResponse(); Throwable throwable = exception; Map<Throwable, Throwable> throwableMap = new IdentityHashMap<>(); while(true){ Throwable cause = throwable.getCause(); throwableMap.put(throwable, cause); if((cause == null) || throwableMap.containsKey(cause)){ break; } throwable = cause; } String message = throwable.getMessage(); if((message == null) || ("").equals(message)){ Response.Status status = (Response.Status)response.getStatusInfo(); message = status.getReasonPhrase(); } if(message.startsWith("HTTP ")){ message = message.replaceFirst("^HTTP (\\d)+ ", ""); } SimpleResponse entity = new SimpleResponse(); entity.setMessage(message); return (Response.fromResponse(response).entity(entity).type(MediaType.APPLICATION_JSON)).build(); } @Override Response toResponse(WebApplicationException exception); }### Answer:
@Test public void toResponse(){ assertEquals("Not Found", getMessage(new NotFoundException())); assertEquals("Resource \"id\" not found", getMessage(new NotFoundException("Resource \"id\" not found"))); assertEquals("Bad Request", getMessage(new BadRequestException(new IllegalArgumentException()))); assertEquals("Bad \"id\" value", getMessage(new BadRequestException(new IllegalArgumentException("Bad \"id\" value")))); assertEquals("Bad Request", getMessage(new BadRequestException(new UnmarshalException(new IOException())))); assertEquals("Resource \"id\" is incomplete", getMessage(new BadRequestException(new UnmarshalException(new EOFException("Resource \"id\" is incomplete"))))); UnmarshalException selfRefException = new UnmarshalException((Throwable)null); selfRefException.setLinkedException(new UnmarshalException(selfRefException)); assertEquals("Bad Request", getMessage(new BadRequestException(selfRefException))); } |
### Question:
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); static DecoratingWith<T> proxy(final Class<T> type); static DecoratingWith<T> proxy(final Class<T> primaryType, final Class<?> ... types); static DecoratingVisitor<U, U> proxy(final U delegate); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> type); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> primaryType, final Class<?> ... types); }### Answer:
@Test(expected = MyException.class) public void shouldInterceptInvocationException() throws Exception { final Throwable[] thrown = new Throwable[1]; final MyException decoratedException = new MyException(); foo = Decorating.proxy(new MethodMissingImpl(), Foo.class).visiting(new Decorator<Foo>() { private static final long serialVersionUID = 1L; @Override public Exception decorateInvocationException(Foo proxy, Method method, Object[] args, Exception cause) { thrown[0] = cause; return decoratedException; } }).build(); foo.getSomething("value"); fail("Mock should have thrown exception"); }
@Test public void serializeWithJDK() throws IOException, ClassNotFoundException { useSerializedProxy(serializeWithJDK( Decorating.proxy(CharSequence.class).with("Test").visiting(new AssertingDecorator()).build(getFactory()))); }
@Test public void serializeWithXStream() { useSerializedProxy(serializeWithXStream( Decorating.proxy(CharSequence.class).with("Test").visiting(new AssertingDecorator()).build(getFactory()))); }
@Test public void serializeWithXStreamInPureReflectionMode() { useSerializedProxy(serializeWithXStreamAndPureReflection( Decorating.proxy(CharSequence.class).with("Test").visiting(new AssertingDecorator()).build(getFactory()))); }
@Test public void canDeferDecorationUntilAfterProxyInstantiation() throws Exception { final Decorator<WithCallsInConstructor> nullDecorator = new Decorator<WithCallsInConstructor>() {}; final WithCallsInConstructor obj = new WithCallsInConstructor(); obj.setS("custom"); assertEquals("sanity check", "custom", obj.getS()); final WithCallsInConstructor withCallsInConstructor = Decorating.proxy(WithCallsInConstructor.class).with(obj).visiting(nullDecorator).build(new CglibProxyFactory(true)); assertEquals("This won't be expected by most users, but it is \"correct\" nonetheless", "default", withCallsInConstructor.getS()); assertEquals("And this was passed on to the underlying object too", "default", obj.getS()); final WithCallsInConstructor obj2 = new WithCallsInConstructor(); obj2.setS("custom"); assertEquals("sanity check", "custom", obj2.getS()); final WithCallsInConstructor withoutCallsInConstructor = Decorating.proxy(WithCallsInConstructor.class).with(obj2).visiting(nullDecorator).build(new CglibProxyFactory(false)); assertEquals("And this is what most users would expect - setting interceptDuringConstruction to false", "custom", withoutCallsInConstructor.getS()); assertEquals("And this was not passed on to the underlying object either", "custom", obj2.getS()); } |
### Question:
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }### Answer:
@Test public void callWithArgumentsIsDelegated() throws Exception { Foo fooMock = mock(Foo.class); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); foo.call(42, "Arthur"); verify(fooMock).call(42, "Arthur"); }
@Test public void callWillReturnValue() throws Exception { Foo fooMock = mock(Foo.class); when(fooMock.call("Arthur")).thenReturn(42); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); assertEquals(42, foo.call("Arthur")); verify(fooMock).call("Arthur"); }
@Test(expected=NoSuchElementException.class) public void callWillThrowCheckedException() throws Exception { Foo fooMock = mock(Foo.class); when(fooMock.call("Arthur")).thenThrow(new NoSuchElementException("JUnit")); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); foo.call("Arthur"); }
@Test(expected=ArithmeticException.class) public void callWillThrowRuntimeException() throws Exception { Foo fooMock = mock(Foo.class); when(fooMock.call("Arthur")).thenThrow(new ArithmeticException("JUnit")); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); foo.call("Arthur"); }
@Test public void callWillCallToString() throws Exception { Foo fooMock = mock(Foo.class); when(fooMock.toString()).thenReturn("Arthur"); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); assertEquals("Arthur", foo.toString()); }
@Test public void callIsDelegated() throws Exception { Foo fooMock = mock(Foo.class); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); foo.call(); verify(fooMock).call(); } |
### Question:
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); static FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type); static FailoverWithOrExceptingOrBuild<T> proxy(final Class<T> primaryType, final Class<?> ... types); static FailoverExceptingOrBuild<T> proxy(final T... delegates); }### Answer:
@Test public void shouldFailoverToNextOnSpecialException() { FailsOnNthCall first = new FailsOnNthCallImpl(1); FailsOnNthCall second = new FailsOnNthCallImpl(1); FailsOnNthCall failover = Failover.proxy(FailsOnNthCall.class) .with(first, second) .excepting(RuntimeException.class) .build(getFactory()); assertEquals(0, first.dunIt()); assertEquals(0, second.dunIt()); failover.doIt(); assertEquals(1, first.dunIt()); assertEquals(0, second.dunIt()); failover.doIt(); assertEquals(1, first.dunIt()); assertEquals(1, second.dunIt()); }
@Test public void serializeWithJDK() throws IOException, ClassNotFoundException { final FailsOnNthCall failover = Failover.proxy(FailsOnNthCall.class) .with(new FailsOnNthCallImpl(1), new FailsOnNthCallImpl(1)) .excepting(RuntimeException.class) .build(getFactory()); failover.doIt(); useSerializedProxy(serializeWithJDK(failover)); }
@Test public void serializeWithXStream() { final FailsOnNthCall failover = Failover.proxy(FailsOnNthCall.class) .with(new FailsOnNthCallImpl(1), new FailsOnNthCallImpl(1)) .excepting(RuntimeException.class) .build(getFactory()); failover.doIt(); useSerializedProxy(serializeWithXStream(failover)); }
@Test public void serializeWithXStreamInPureReflectionMode() { final FailsOnNthCall failover = Failover.proxy(FailsOnNthCall.class) .with(new FailsOnNthCallImpl(1), new FailsOnNthCallImpl(1)) .excepting(RuntimeException.class) .build(getFactory()); failover.doIt(); useSerializedProxy(serializeWithXStreamAndPureReflection(failover)); } |
### Question:
Delegating { public static <T> DelegatingWith<T> proxy(Class<T> type) { return new DelegatingWith<T>(new Delegating<T>(type)); } private Delegating(Class<T> type); static DelegatingWith<T> proxy(Class<T> type); }### Answer:
@Test public void shouldSupportIndirectRecursion() { Faculty fac = new Faculty() { public int calc(int i, Faculty fac) { return i == 1 ? 1 : i * fac.calc(i - 1, fac); } }; Faculty proxy = Delegating.proxy(Faculty.class).with(fac).build(getFactory()); assertEquals(120, fac.calc(5, fac)); assertEquals(120, proxy.calc(5, proxy)); } |
### Question:
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); static EchoingWithOrTo<T> proxy(final Class<T> type); }### Answer:
@Test public void shouldEchoMethodNameAndArgs() throws Exception { Writer out = new StringWriter(); Simple foo = Echoing.proxy(Simple.class).to(new PrintWriter(out)).build(getFactory()); foo.doSomething(); assertContains("Simple.doSomething()", out); }
@Test public void shouldDelegateCalls() throws Exception { Writer out = new StringWriter(); Simple foo = Echoing.proxy(Simple.class).with(simpleMock).to(new PrintWriter(out)).build(getFactory()); foo.doSomething(); verify(simpleMock).doSomething(); }
@Test public void shouldRecursivelyReturnEchoProxiesForInterfaces() throws Exception { Inner innerMock = mock(Inner.class); Outer outerMock = mock(Outer.class); StringWriter out = new StringWriter(); Outer outer = Echoing.proxy(Outer.class).with(outerMock).to(new PrintWriter(out)).build(getFactory()); when(outerMock.getInner()).thenReturn(innerMock); when(innerMock.getName()).thenReturn("inner"); String result = outer.getInner().getName(); assertEquals("inner", result); assertContains("Outer.getInner()", out); assertContains("Inner.getName()", out); verify(outerMock).getInner(); verify(innerMock).getName(); }
@Test public void shouldRecursivelyReturnEchoProxiesEvenForMissingImplementations() throws Exception { StringWriter out = new StringWriter(); Outer outer = Echoing.proxy(Outer.class).to(new PrintWriter(out)).build(getFactory()); outer.getInner().getName(); assertContains("Outer.getInner()", out); assertContains("Inner.getName()", out); } |
### Question:
CglibProxyFactory extends AbstractProxyFactory { public boolean canProxy(final Class<?> type) { return !Modifier.isFinal(type.getModifiers()); } CglibProxyFactory(); CglibProxyFactory(boolean interceptDuringConstruction); T createProxy(final Invoker invoker, final Class<?>... types); boolean canProxy(final Class<?> type); boolean isProxyClass(final Class<?> type); }### Answer:
@Test public void shouldDenyProxyGenerationForFinalClasses() throws Exception { ProxyFactory factory = new CglibProxyFactory(); assertFalse(factory.canProxy(String.class)); } |
### Question:
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }### Answer:
@Test public void mostCommonSuperclassForClassesWithACommonBaseClass() { assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new StringWriter(), new OutputStreamWriter(System.out))); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), new StringWriter())); }
@Test public void mostCommonSuperclassForClassesAreInSameHierarchy() { assertEquals(OutputStreamWriter.class, ReflectionUtils.getMostCommonSuperclass(new FileWriter(FileDescriptor.out), new OutputStreamWriter(System.out))); assertEquals(OutputStreamWriter.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), new FileWriter(FileDescriptor.out))); }
@Test public void mostCommonSuperclassForClassesInSameOrDifferentHierarchy() { assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new FileWriter(FileDescriptor.out), new StringWriter(), new OutputStreamWriter(System.out))); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new FileWriter(FileDescriptor.out), new OutputStreamWriter(System.out), new StringWriter())); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new StringWriter(), new FileWriter(FileDescriptor.out), new OutputStreamWriter(System.out))); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), new FileWriter(FileDescriptor.out), new StringWriter())); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new StringWriter(), new OutputStreamWriter(System.out), new FileWriter(FileDescriptor.out))); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), new StringWriter(), new FileWriter(FileDescriptor.out))); }
@Test public void mostCommonSuperclassForUnmatchingObjects() { assertEquals(Object.class, ReflectionUtils.getMostCommonSuperclass(1, new OutputStreamWriter(System.out))); assertEquals(Object.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), 1)); }
@Test public void mostCommonSuperclassForEmptyArray() { assertEquals(Object.class, ReflectionUtils.getMostCommonSuperclass()); }
@Test public void mostCommonSuperclassForNullElements() { assertEquals(Object.class, ReflectionUtils.getMostCommonSuperclass(null, null)); }
@Test public void mostCommonSuperclassForCollections() { assertEquals(AbstractList.class, ReflectionUtils.getMostCommonSuperclass(new LinkedList<Object>(), new Vector<Object>())); } |
### Question:
ReflectionUtils { public static Set<Class<?>> getAllInterfaces(Object... objects) { final Set<Class<?>> interfaces = new HashSet<Class<?>>(); for (Object object : objects) { if (object != null) { getInterfaces(object.getClass(), interfaces); } } interfaces.remove(InvokerReference.class); return interfaces; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }### Answer:
@Test public void allInterfacesOfListShouldBeFound() { Set<Class<?>> interfaces = ReflectionUtils.getAllInterfaces(BeanContextServices.class); assertTrue(interfaces.contains(BeanContextServices.class)); assertTrue(interfaces.contains(BeanContext.class)); assertTrue(interfaces.contains(Collection.class)); assertTrue(interfaces.contains(BeanContextServicesListener.class)); assertTrue(interfaces.contains(EventListener.class)); } |
### Question:
ReflectionUtils { public static void writeMethod(final ObjectOutputStream out, final Method method) throws IOException { out.writeObject(method.getDeclaringClass()); out.writeObject(method.getName()); out.writeObject(method.getParameterTypes()); } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }### Answer:
@Test public void methodCanBeSerialized() throws IOException, ClassNotFoundException { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); ObjectOutputStream outStream = new ObjectOutputStream(outBuffer); ReflectionUtils.writeMethod(outStream, ReflectionUtils.equals); outStream.close(); ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); ObjectInputStream inStream = new ObjectInputStream(inBuffer); assertSame(Object.class, inStream.readObject()); assertEquals("equals", inStream.readObject()); assertTrue(Arrays.equals(new Class[]{Object.class}, (Object[]) inStream.readObject())); inStream.close(); } |
### Question:
ReflectionUtils { public static Method readMethod(final ObjectInputStream in) throws IOException, ClassNotFoundException { final Class<?> type = Class.class.cast(in.readObject()); final String name = String.class.cast(in.readObject()); final Class<?>[] parameters = Class[].class.cast(in.readObject()); try { return type.getMethod(name, parameters); } catch (final NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }### Answer:
@Test public void methodCanBeDeserialized() throws IOException, ClassNotFoundException { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); ObjectOutputStream outStream = new ObjectOutputStream(outBuffer); outStream.writeObject(Object.class); outStream.writeObject("equals"); outStream.writeObject(new Class[]{Object.class}); outStream.close(); ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); ObjectInputStream inStream = new ObjectInputStream(inBuffer); assertEquals(ReflectionUtils.equals, ReflectionUtils.readMethod(inStream)); }
@Test public void unknownDeserializedMethodThrowsInvalidObjectException() throws IOException, ClassNotFoundException { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); ObjectOutputStream outStream = new ObjectOutputStream(outBuffer); outStream.writeObject(Object.class); outStream.writeObject("equals"); outStream.writeObject(new Class[0]); outStream.close(); ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); ObjectInputStream inStream = new ObjectInputStream(inBuffer); try { ReflectionUtils.readMethod(inStream); fail("Thrown " + InvalidObjectException.class.getName() + " expected"); } catch (final InvalidObjectException e) { } } |
### Question:
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); static FutureWith<T> proxy(Class<T> primaryType); static FutureWith<T> proxy(Class<T> primaryType, Class<?>... types); static FutureBuild<T> proxy(T target); }### Answer:
@Test public void shouldReturnNullObjectAsIntermediateResultAndSwapWhenMethodCompletesWithCast() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(slowService).build(getFactory()); List<String> stuff = fastService.getList(); assertTrue(stuff.isEmpty()); latch.countDown(); Thread.sleep(100); assertEquals(1, stuff.size()); assertEquals("yo", stuff.get(0)); }
@Test public void shouldReturnNullObjectAsIntermediateResultAndSwapWhenMethodCompletesWithGenerics() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(Service.class).with(slowService).build(getFactory()); List<String> stuff = fastService.getList(); assertTrue(stuff.isEmpty()); latch.countDown(); Thread.sleep(100); assertEquals(1, stuff.size()); assertEquals("yo", stuff.get(0)); }
@Test public void shouldHandleVoidMethodsWithCast() { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(slowService).build(getFactory()); fastService.methodReturnsVoid(); }
@Test public void shouldHandleVoidMethodsWithGenerics() { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(Service.class).with(slowService).build(getFactory()); fastService.methodReturnsVoid(); } |
### Question:
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }### Answer:
@Test public void testBlobDataIsCreated() { assertThat(restoreBlobStrategy.createRestoreData(restoreBlobData).getBlobData(), is(restoreBlobData)); }
@Test(expected = IllegalStateException.class) public void testIfBlobDataNameIsEmptyExceptionIsThrown() { when(rRestoreBlobData.getBlobData().getBlobName()).thenReturn(""); restoreBlobStrategy.createRestoreData(restoreBlobData); } |
### Question:
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Nonnull @Override protected List<HashAlgorithm> getHashAlgorithms() { return ImmutableList.of(SHA1); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }### Answer:
@Test public void testCorrectHashAlgorithmsAreSupported() { assertThat(restoreBlobStrategy.getHashAlgorithms(), containsInAnyOrder(SHA1)); } |
### Question:
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected String getAssetPath(@Nonnull final RRestoreBlobData rRestoreBlobData) { return rRestoreBlobData.getBlobData().getBlobName(); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }### Answer:
@Test public void testAppropriatePathIsReturned() { assertThat(restoreBlobStrategy.getAssetPath(rRestoreBlobData), is(ARCHIVE_PATH)); } |
### Question:
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean assetExists(@Nonnull final RRestoreBlobData rRestoreBlobData) { RRestoreFacet facet = getRestoreFacet(rRestoreBlobData); return facet.assetExists(getAssetPath(rRestoreBlobData)); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }### Answer:
@Test public void testPackageIsRestored() throws Exception { restoreBlobStrategy.restore(properties, blob, TEST_BLOB_STORE_NAME, false); verify(rRestoreFacet).assetExists(ARCHIVE_PATH); verify(rRestoreFacet).restore(any(AssetBlob.class), eq(ARCHIVE_PATH)); verifyNoMoreInteractions(rRestoreFacet); } |
### Question:
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean componentRequired(final RRestoreBlobData data) { RRestoreFacet facet = getRestoreFacet(data); final String path = data.getBlobData().getBlobName(); return facet.componentRequired(path); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }### Answer:
@Test public void testComponentIsRequiredForGz() { boolean expected = true; when(rRestoreFacet.componentRequired(ARCHIVE_PATH)).thenReturn(expected); assertThat(restoreBlobStrategy.componentRequired(rRestoreBlobData), is(expected)); verify(rRestoreFacet).componentRequired(ARCHIVE_PATH); verifyNoMoreInteractions(rRestoreFacet); } |
### Question:
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected Query getComponentQuery(final RRestoreBlobData data) throws IOException { RRestoreFacet facet = getRestoreFacet(data); RestoreBlobData blobData = data.getBlobData(); Map<String, String> attributes; try (InputStream inputStream = blobData.getBlob().getInputStream()) { attributes = facet.extractComponentAttributesFromArchive(blobData.getBlobName(), inputStream); } return facet.getComponentQuery(attributes); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }### Answer:
@Test public void testComponentQuery() throws IOException { restoreBlobStrategy.getComponentQuery(rRestoreBlobData); verify(rRestoreFacet, times(1)).getComponentQuery(anyMapOf(String.class, String.class)); } |
### Question:
XssSanitizerService { public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); } String sanitize(String html); }### Answer:
@Test public void test() throws Exception { String unsafe = "<a href='javascript:alert('XSS')'>часто</a> используемый в печати и вэб-дизайне"; String safe = xssSanitizerService.sanitize(unsafe); Assertions.assertEquals("часто используемый в печати и вэб-дизайне", safe); }
@Test public void testNoClosed() throws Exception { String unsafe = "<a href='javascript:alert('XSS')'>часто используемый в печати и вэб-дизайне"; String safe = xssSanitizerService.sanitize(unsafe); Assertions.assertEquals("часто используемый в печати и вэб-дизайне", safe); } |
### Question:
SettingsController { @GetMapping(API+CONFIG) public SettingsDTO getConfig(@AuthenticationPrincipal UserAccountDetailsDTO userAccount){ Iterable<RuntimeSettings> runtimeSettings = runtimeSettingsRepository.findAll(); SettingsDTO settingsDTOPartial = StreamSupport.stream(runtimeSettings.spliterator(), false) .reduce( new SettingsDTO(), (settingsDTO, runtimeSettings1) -> { if (runtimeSettings1.getKey() == null) { throw new RuntimeException("Null key is not supported"); } switch (runtimeSettings1.getKey()) { case IMAGE_BACKGROUND: settingsDTO.setImageBackground(runtimeSettings1.getValue()); break; case HEADER: settingsDTO.setHeader(runtimeSettings1.getValue()); break; case SUB_HEADER: settingsDTO.setSubHeader(runtimeSettings1.getValue()); break; case TITLE_TEMPLATE: settingsDTO.setTitleTemplate(runtimeSettings1.getValue()); break; case BACKGROUND_COLOR: settingsDTO.setBackgroundColor(runtimeSettings1.getValue()); break; default: LOGGER.warn("Unknown key " + runtimeSettings1.getKey()); } return settingsDTO; }, (settingsDTO, settingsDTO2) -> { throw new UnsupportedOperationException("Parallel is not supported");} ); boolean canShowSettings = blogSecurityService.hasSettingsPermission(userAccount); settingsDTOPartial.setCanShowSettings(canShowSettings); settingsDTOPartial.setCanShowApplications(applicationConfig.isEnableApplications()); settingsDTOPartial.setAvailableRoles(Arrays.asList(UserRole.ROLE_ADMIN, UserRole.ROLE_USER)); return settingsDTOPartial; } @GetMapping(API+CONFIG) SettingsDTO getConfig(@AuthenticationPrincipal UserAccountDetailsDTO userAccount); @Transactional @PostMapping(value = API+CONFIG, consumes = {"multipart/form-data"}) @PreAuthorize("@blogSecurityService.hasSettingsPermission(#userAccount)") SettingsDTO putConfig(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount,
@RequestPart(value = DTO_PART) SettingsDTO dto,
@RequestPart(value = IMAGE_PART, required = false) MultipartFile imagePart
); static final String IMAGE_PART; static final String DTO_PART; static final String IMAGE_BACKGROUND; }### Answer:
@Test public void getConfig() throws Exception { mockMvc.perform( get(Constants.Urls.API+ Constants.Urls.CONFIG) .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) ) .andExpect(status().isOk()) .andExpect(jsonPath("$.titleTemplate").value("%s | nkonev's blog")) .andExpect(jsonPath("$.header").value("Блог Конева Никиты")) .andExpect(jsonPath("$.canShowSettings").value(false)) .andExpect(jsonPath("$.removeImageBackground").doesNotExist()) .andReturn(); } |
### Question:
PostController { @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization addPost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.addPost(userAccount, postDTO); } @GetMapping(Constants.Urls.API + Constants.Urls.POST) Wrapper<PostDTO> getPosts(
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) PostDTOExtended getPost(
@PathVariable(Constants.PathVariables.POST_ID) long id,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).READ_MY)") @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.MY) List<PostDTO> getMyPosts(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount,
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString // TODO implement
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization addPost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization updatePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postId, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).DELETE)") @DeleteMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) void deletePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@PathVariable(Constants.PathVariables.POST_ID) long postId
); }### Answer:
@Test public void testAnonymousCannotAddPostUnit() throws Exception { Assertions.assertThrows(AuthenticationCredentialsNotFoundException.class, () -> { postController.addPost(null, PostDtoBuilder.startBuilding().build()); }); } |
### Question:
PostConverter { public static String getYouTubeVideoId(String iframeSrcUrl) { UriComponents build = UriComponentsBuilder.fromHttpUrl(iframeSrcUrl).build(); List<String> pathSegments = build.getPathSegments(); return pathSegments.get(pathSegments.size() - 1); } PostDTOWithAuthorization convertToDto(Post saved, UserAccountDetailsDTO userAccount); Post convertToPost(PostDTO postDTO, Post forUpdate); static String getYouTubeVideoId(String iframeSrcUrl); IndexPost toElasticsearchPost(com.github.nkonev.blog.entity.jdbc.Post jpaPost); static void cleanTags(PostDTO postDTO); static String cleanHtmlTags(String html); PostDTO convertToPostDTO(Post post); }### Answer:
@Test public void testGetYouTubeId() { String youtubeVideoId = PostConverter.getYouTubeVideoId("https: Assertions.assertEquals("eoDsxos6xhM", youtubeVideoId); } |
### Question:
PostConverter { String getTitleImg(PostDTO postDTO) { String titleImg = postDTO.getTitleImg(); if (setFirstImageAsTitle && StringUtils.isEmpty(titleImg)) { try { Document document = Jsoup.parse(postDTO.getText()); Elements images = document.getElementsByTag("img"); if (!images.isEmpty()) { Element element = images.get(0); return element.attr("src"); } Elements iframes = document.getElementsByTag("iframe"); if (!iframes.isEmpty()) { Element element = iframes.get(0); String iframeSrcUrl = element.attr("src"); if (iframeSrcUrl.contains("youtube.com")) { String youtubeVideoId = getYouTubeVideoId(iframeSrcUrl); String youtubeThumbnailUrl = youtubeThumbnailUrlTemplate.replace("__VIDEO_ID__", youtubeVideoId); return imageDownloader.downloadImageAndSave(youtubeThumbnailUrl, imagePostTitleUploadController); } } } catch (RuntimeException e) { if (LOGGER.isDebugEnabled()){ LOGGER.warn("Error during parse image from content: {}", e.getMessage(), e); } else { LOGGER.warn("Error during parse image from content: {}", e.getMessage()); } return null; } } return titleImg; } PostDTOWithAuthorization convertToDto(Post saved, UserAccountDetailsDTO userAccount); Post convertToPost(PostDTO postDTO, Post forUpdate); static String getYouTubeVideoId(String iframeSrcUrl); IndexPost toElasticsearchPost(com.github.nkonev.blog.entity.jdbc.Post jpaPost); static void cleanTags(PostDTO postDTO); static String cleanHtmlTags(String html); PostDTO convertToPostDTO(Post post); }### Answer:
@Test public void shouldSetFirstImgWhenTitleImgEmpty() { PostDTO postDTO = new PostDTO(); postDTO.setText("Hello, I contains images. This is first. <img src=\"http: postDTO.setTitle("Title"); String titleImg = postConverter.getTitleImg(postDTO); Assertions.assertEquals("http: }
@Test public void shouldDownloadYoutubePreviewWhenTitleImgEmptyAndContentHasNotImages() { PostDTO postDTO = new PostDTO(); postDTO.setText("Hello, I contains youtube videos. " + " This is first. <iframe allowfullscreen=\"true\" src=\"https: " This is second. <iframe allowfullscreen=\"true\" src=\"https: postDTO.setTitle("Title"); String titleImg = postConverter.getTitleImg(postDTO); Assertions.assertNotNull(titleImg); String imageId = titleImg .replace("/api/image/post/title/", "") .replace(".png", ""); Assertions.assertFalse(StringUtils.isEmpty(imageId)); Integer integer = jdbcTemplate.queryForObject("select count(*) from images.post_title_image where id = :id\\:\\:uuid", Map.of("id", imageId), Integer.class); Assertions.assertEquals(1, integer); } |
### Question:
JettyServerWrapper extends Server { HttpServiceContext getOrCreateContext(final Model model) { return getOrCreateContext(model.getContextModel()); } JettyServerWrapper(ServerModel serverModel, ThreadPool threadPool); HandlerCollection getRootHandlerCollection(); void configureContext(final Map<String, Object> attributes, final Integer timeout, final String cookie,
final String domain, final String path, final String url, final Boolean cookieHttpOnly,
final Boolean sessionCookieSecure, final String workerName, final Boolean lazy, final String directory,
Integer maxAge, final Boolean showStacks); void setServerConfigDir(File serverConfigDir); File getServerConfigDir(); URL getServerConfigURL(); void setServerConfigURL(URL serverConfigURL); String getDefaultAuthMethod(); void setDefaultAuthMethod(String defaultAuthMethod); String getDefaultRealmName(); void setDefaultRealmName(String defaultRealmName); }### Answer:
@SuppressWarnings("unchecked") @Test public void getOrCreateContextDoesNotRegisterMultipleServletContextsForSameContextModelSingleThreaded() throws Exception { final JettyServerWrapper jettyServerWrapperUnderTest = new JettyServerWrapper( serverModelMock, new QueuedThreadPool()); try { jettyServerWrapperUnderTest.start(); HttpServiceContext context = jettyServerWrapperUnderTest.getOrCreateContext(contextModelMock); context.start(); context = jettyServerWrapperUnderTest.getOrCreateContext(contextModelMock); context.start(); verify(bundleContextMock, times(1)).registerService( same(ServletContext.class), any(ServletContext.class), any(Dictionary.class)); } finally { jettyServerWrapperUnderTest.stop(); } }
@SuppressWarnings("unchecked") @Test public void getOrCreateContextDoesNotRegisterMultipleServletContextsForSameContextModelMultiThreaded() throws Exception { final JettyServerWrapper jettyServerWrapperUnderTest = new JettyServerWrapper( serverModelMock, new QueuedThreadPool()); try { jettyServerWrapperUnderTest.start(); final CountDownLatch countDownLatch = new CountDownLatch(1); final Runnable getOrCreateContextRunnable = new Runnable() { @Override public void run() { try { countDownLatch.await(); HttpServiceContext context = jettyServerWrapperUnderTest .getOrCreateContext(contextModelMock); context.start(); } catch (final InterruptedException ex) { } catch (final Exception ex) { exceptionInRunnable = ex; } } }; final ExecutorService executor = Executors .newFixedThreadPool(NUMBER_OF_CONCURRENT_EXECUTIONS); for (int i = 0; i < NUMBER_OF_CONCURRENT_EXECUTIONS; i++) { executor.execute(getOrCreateContextRunnable); } countDownLatch.countDown(); executor.shutdown(); final boolean terminated = executor.awaitTermination(10, TimeUnit.SECONDS); if (exceptionInRunnable != null) { try { throw exceptionInRunnable; } finally { exceptionInRunnable = null; } } assertTrue("could not shutdown the executor within the timeout", terminated); verify(bundleContextMock, times(1)).registerService( same(ServletContext.class), any(ServletContext.class), any(Dictionary.class)); } finally { jettyServerWrapperUnderTest.stop(); } } |
### Question:
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }### Answer:
@Test public void replaceSlashes07() { assertEquals("Replaced", "/foo/bar/car/", Path.replaceSlashes("/foo }
@Test public void replaceSlashesWithNull() { assertEquals("Replaced", null, Path.replaceSlashes(null)); }
@Test public void replaceSlashes01() { assertEquals("Replaced", "/foo/bar/", Path.replaceSlashes("/foo/bar/")); }
@Test public void replaceSlashes02() { assertEquals("Replaced", "/", Path.replaceSlashes("/")); }
@Test public void replaceSlashes03() { assertEquals("Replaced", "/", Path.replaceSlashes(" }
@Test public void replaceSlashes04() { assertEquals("Replaced", "/foo/bar", Path.replaceSlashes(" }
@Test public void replaceSlashes05() { assertEquals("Replaced", "foo/bar/", Path.replaceSlashes("foo/bar }
@Test public void replaceSlashes06() { assertEquals("Replaced", "foo/bar", Path.replaceSlashes("foo } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.