src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
NestedPatch extends AbstractNestedMutateOperation implements OASOperation { @Override public OperationType operationType() { return operationType; } NestedPatch(MetaResource metaResource, MetaResourceField metaResourceField, MetaResource relatedMetaResource); @Override OperationType operationType(); @Override boolean isEnabled(); @Override String getDescription(); @Override Operation operation(); @Override String path(); static OperationType operationType; } | @Test void operationType() { NestedPatch NestedPatch = new NestedPatch(metaResource, metaResourceField, relatedMetaResource); Assert.assertEquals(OperationType.PATCH, NestedPatch.operationType()); } |
NestedPatch extends AbstractNestedMutateOperation implements OASOperation { @Override public boolean isEnabled() { return metaResource.isReadable() && metaResourceField.isUpdatable(); } NestedPatch(MetaResource metaResource, MetaResourceField metaResourceField, MetaResource relatedMetaResource); @Override OperationType operationType(); @Override boolean isEnabled(); @Override String getDescription(); @Override Operation operation(); @Override String path(); static OperationType operationType; } | @Test void isEnabledTrueWhenReadableAndFieldUpdatable() { NestedPatch NestedPatch = new NestedPatch(metaResource, metaResourceField, relatedMetaResource); Assert.assertTrue(metaResource.isReadable()); metaResourceField.setUpdatable(true); Assert.assertTrue(NestedPatch.isEnabled()); }
@Test void isEnabledFalseWhenReadableAndFieldNotUpdatable() { NestedPatch NestedPatch = new NestedPatch(metaResource, metaResourceField, relatedMetaResource); Assert.assertTrue(metaResource.isReadable()); metaResource.setUpdatable(false); Assert.assertFalse(NestedPatch.isEnabled()); }
@Test void isEnabledFalseWhenNotReadableAndFieldUpdatable() { NestedPatch NestedPatch = new NestedPatch(metaResource, metaResourceField, relatedMetaResource); metaResource.setReadable(false); metaResourceField.setUpdatable(true); Assert.assertFalse(NestedPatch.isEnabled()); }
@Test void isEnabledFalseWhenNotReadableAndFieldNotUpdatable() { NestedPatch NestedPatch = new NestedPatch(metaResource, metaResourceField, relatedMetaResource); metaResource.setReadable(false); metaResourceField.setUpdatable(false); Assert.assertFalse(NestedPatch.isEnabled()); } |
NestedPatch extends AbstractNestedMutateOperation implements OASOperation { @Override public String getDescription() { return "Update " + metaResource.getResourceType() + " relationship to a " + relatedMetaResource.getResourceType() + " resource"; } NestedPatch(MetaResource metaResource, MetaResourceField metaResourceField, MetaResource relatedMetaResource); @Override OperationType operationType(); @Override boolean isEnabled(); @Override String getDescription(); @Override Operation operation(); @Override String path(); static OperationType operationType; } | @Test void getDescription() { NestedPatch NestedPatch = new NestedPatch(metaResource, metaResourceField, relatedMetaResource); Assert.assertEquals("Update ResourceType relationship to a RelatedResourceType resource", NestedPatch.getDescription()); } |
NestedPatch extends AbstractNestedMutateOperation implements OASOperation { @Override public Operation operation() { Operation operation = super.operation(); ApiResponse responseSchema = OASUtils.oneToMany(metaResourceField) ? new ResourceReferencesResponse(relatedMetaResource).$ref() : new ResourceReferenceResponse(relatedMetaResource).$ref(); responses.put("200", responseSchema); return operation.responses(apiResponsesFromMap(responses)); } NestedPatch(MetaResource metaResource, MetaResourceField metaResourceField, MetaResource relatedMetaResource); @Override OperationType operationType(); @Override boolean isEnabled(); @Override String getDescription(); @Override Operation operation(); @Override String path(); static OperationType operationType; } | @Test void operation() { Operation operation = new NestedPatch(metaResource, metaResourceField, relatedMetaResource).operation(); Assert.assertTrue(operation.getResponses().containsKey("200")); } |
NestedPatch extends AbstractNestedMutateOperation implements OASOperation { @Override public String path() { return OASUtils.getNestedPath(metaResource, metaResourceField); } NestedPatch(MetaResource metaResource, MetaResourceField metaResourceField, MetaResource relatedMetaResource); @Override OperationType operationType(); @Override boolean isEnabled(); @Override String getDescription(); @Override Operation operation(); @Override String path(); static OperationType operationType; } | @Test void path() { NestedPatch NestedPatch = new NestedPatch(metaResource, metaResourceField, relatedMetaResource); Assert.assertEquals("/ResourcePath/{id}/someRelatedResource", NestedPatch.path()); } |
RelationshipPatch extends AbstractNestedMutateOperation implements OASOperation { @Override public OperationType operationType() { return operationType; } RelationshipPatch(MetaResource metaResource, MetaResourceField metaResourceField, MetaResource relatedMetaResource); @Override OperationType operationType(); @Override boolean isEnabled(); @Override String getDescription(); @Override Operation operation(); @Override String path(); static final OperationType operationType; } | @Test void operationType() { RelationshipPatch RelationshipPatch = new RelationshipPatch(metaResource, metaResourceField, relatedMetaResource); Assert.assertEquals(OperationType.PATCH, RelationshipPatch.operationType()); } |
RelationshipPatch extends AbstractNestedMutateOperation implements OASOperation { @Override public boolean isEnabled() { return metaResource.isReadable() && metaResourceField.isUpdatable(); } RelationshipPatch(MetaResource metaResource, MetaResourceField metaResourceField, MetaResource relatedMetaResource); @Override OperationType operationType(); @Override boolean isEnabled(); @Override String getDescription(); @Override Operation operation(); @Override String path(); static final OperationType operationType; } | @Test void isEnabledTrueWhenReadableAndFieldUpdatable() { RelationshipPatch RelationshipPatch = new RelationshipPatch(metaResource, metaResourceField, relatedMetaResource); Assert.assertTrue(metaResource.isReadable()); metaResourceField.setUpdatable(true); Assert.assertTrue(RelationshipPatch.isEnabled()); }
@Test void isEnabledFalseWhenReadableAndFieldNotUpdatable() { RelationshipPatch RelationshipPatch = new RelationshipPatch(metaResource, metaResourceField, relatedMetaResource); Assert.assertTrue(metaResource.isReadable()); metaResource.setUpdatable(false); Assert.assertFalse(RelationshipPatch.isEnabled()); }
@Test void isEnabledFalseWhenNotReadableAndFieldUpdatable() { RelationshipPatch RelationshipPatch = new RelationshipPatch(metaResource, metaResourceField, relatedMetaResource); metaResource.setReadable(false); metaResourceField.setUpdatable(true); Assert.assertFalse(RelationshipPatch.isEnabled()); }
@Test void isEnabledFalseWhenNotReadableAndFieldNotUpdatable() { RelationshipPatch RelationshipPatch = new RelationshipPatch(metaResource, metaResourceField, relatedMetaResource); metaResource.setReadable(false); metaResourceField.setUpdatable(false); Assert.assertFalse(RelationshipPatch.isEnabled()); } |
RelationshipPatch extends AbstractNestedMutateOperation implements OASOperation { @Override public String getDescription() { return "Update " + metaResource.getResourceType() + " relationship to a " + relatedMetaResource.getResourceType() + " resource"; } RelationshipPatch(MetaResource metaResource, MetaResourceField metaResourceField, MetaResource relatedMetaResource); @Override OperationType operationType(); @Override boolean isEnabled(); @Override String getDescription(); @Override Operation operation(); @Override String path(); static final OperationType operationType; } | @Test void getDescription() { RelationshipPatch RelationshipPatch = new RelationshipPatch(metaResource, metaResourceField, relatedMetaResource); Assert.assertEquals("Update ResourceType relationship to a RelatedResourceType resource", RelationshipPatch.getDescription()); } |
RelationshipPatch extends AbstractNestedMutateOperation implements OASOperation { @Override public Operation operation() { Operation operation = super.operation(); ApiResponse responseSchema = OASUtils.oneToMany(metaResourceField) ? new ResourceReferencesResponse(relatedMetaResource).$ref() : new ResourceReferenceResponse(relatedMetaResource).$ref(); responses.put("200", responseSchema); return operation.responses(apiResponsesFromMap(responses)); } RelationshipPatch(MetaResource metaResource, MetaResourceField metaResourceField, MetaResource relatedMetaResource); @Override OperationType operationType(); @Override boolean isEnabled(); @Override String getDescription(); @Override Operation operation(); @Override String path(); static final OperationType operationType; } | @Test void operation() { Operation operation = new RelationshipPatch(metaResource, metaResourceField, relatedMetaResource).operation(); Assert.assertTrue(operation.getResponses().containsKey("200")); } |
RelationshipPatch extends AbstractNestedMutateOperation implements OASOperation { @Override public String path() { return OASUtils.getRelationshipsPath(metaResource, metaResourceField); } RelationshipPatch(MetaResource metaResource, MetaResourceField metaResourceField, MetaResource relatedMetaResource); @Override OperationType operationType(); @Override boolean isEnabled(); @Override String getDescription(); @Override Operation operation(); @Override String path(); static final OperationType operationType; } | @Test void path() { RelationshipPatch RelationshipPatch = new RelationshipPatch(metaResource, metaResourceField, relatedMetaResource); Assert.assertEquals("/ResourcePath/{id}/relationships/someRelatedResource", RelationshipPatch.path()); } |
OASGenerator { @VisibleForTesting static String generateOpenApiContent(OpenAPI openApi, OutputFormat outputFormat, Boolean sort) { if (sort) { ObjectMapper objectMapper = outputFormat.mapper(); objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY); try { return objectMapper.writer(new DefaultPrettyPrinter()).writeValueAsString(openApi); } catch (JsonProcessingException e) { LOGGER.error("Sorting failed!"); return outputFormat.pretty(openApi); } } else { return outputFormat.pretty(openApi); } } OASGenerator(File outputDir, MetaLookup lookup, OpenAPIGeneratorConfig config); void run(); } | @Test public void testGenerateOpenApiContentGeneratesYamlUnsorted() throws IOException { compare( "gold/unsorted.yaml", OASGenerator.generateOpenApiContent(openApi, OutputFormat.YAML, false)); }
@Test public void testGenerateOpenApiContentGeneratesYamlSorted() throws IOException { compare( "gold/sorted.yaml", OASGenerator.generateOpenApiContent(openApi, OutputFormat.YAML, true)); }
@Test public void testGenerateOpenApiContentGeneratesJsonUnsorted() throws IOException { compare( "gold/unsorted.json", OASGenerator.generateOpenApiContent(openApi, OutputFormat.JSON, false)); }
@Test public void testGenerateOpenApiContentGeneratesJsonSorted() throws IOException { compare( "gold/sorted.json", OASGenerator.generateOpenApiContent(openApi, OutputFormat.JSON, true)); } |
ResourceReferencesResponseSchema extends AbstractSchemaGenerator { public Schema schema() { return new ObjectSchema() .addProperties( "data", new ArraySchema() .items(new ResourceReference(metaResource).$ref())); } ResourceReferencesResponseSchema(MetaResource metaResource); Schema schema(); } | @Test void schema() { Schema schema = new ResourceReferencesResponseSchema(metaResource).schema(); Assert.assertTrue(schema instanceof ObjectSchema); Assert.assertTrue(schema.getProperties().containsKey("data")); Assert.assertEquals(1, schema.getProperties().size()); Schema data = (Schema) schema.getProperties().get("data"); Assert.assertTrue(data instanceof ArraySchema); Assert.assertEquals( "#/components/schemas/ResourceTypeResourceReference", ((ArraySchema)data).getItems().get$ref() ); } |
TypeSchema extends AbstractSchemaGenerator { public Schema schema() { Schema typeSchema = new StringSchema() .description("The JSON:API resource type (" + metaResource.getResourceType() + ")"); typeSchema.addEnumItemObject(metaResource.getResourceType()); return typeSchema; } TypeSchema(MetaResource metaResource); Schema schema(); } | @Test void schema() { final Schema typeSchema = new TypeSchema(metaResource).schema(); assertNotNull(typeSchema); assertEquals(StringSchema.class, typeSchema.getClass()); assertIterableEquals(singletonList("ResourceType"), typeSchema.getEnum()); } |
ApiError extends AbstractSchemaGenerator { public Schema schema() { return new ObjectSchema() .addProperties( "id", new StringSchema() .description("a unique identifier for this particular occurrence of the problem")) .addProperties("links", new ObjectSchema() .addProperties( "about", new StringSchema() .description("a link that leads to further details about this particular occurrence of the problem"))) .addProperties( "status", new StringSchema() .description("the HTTP status code applicable to this problem, expressed as a string value")) .addProperties( "code", new StringSchema() .description("an application-specific error code, expressed as a string value")) .addProperties( "title", new StringSchema() .description("a short, human-readable summary of the problem that SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization")) .addProperties( "detail", new StringSchema() .description("a human-readable explanation specific to this occurrence of the problem. Like 'title', this field’s value can be localized.")) .addProperties( "source", new ObjectSchema() .addProperties( "pointer", new StringSchema() .description("a JSON Pointer [RFC6901] to the associated entity in the request document")) .addProperties( "parameter", new StringSchema() .description("a string indicating which URI query parameter caused the error"))) .addProperties( "meta", new Meta().$ref()) .additionalProperties(false); } Schema schema(); } | @Test void schema() { Schema schema = new ApiError().schema(); Assert.assertTrue(schema instanceof ObjectSchema); Assert.assertTrue(schema.getProperties().containsKey("id")); Assert.assertTrue(schema.getProperties().containsKey("links")); Assert.assertTrue(schema.getProperties().containsKey("status")); Assert.assertTrue(schema.getProperties().containsKey("code")); Assert.assertTrue(schema.getProperties().containsKey("title")); Assert.assertTrue(schema.getProperties().containsKey("title")); Assert.assertTrue(schema.getProperties().containsKey("detail")); Assert.assertTrue(schema.getProperties().containsKey("source")); Assert.assertTrue(schema.getProperties().containsKey("meta")); Assert.assertEquals(8, schema.getProperties().size()); } |
ResourceReferenceResponseSchema extends AbstractSchemaGenerator { public Schema schema() { return new ObjectSchema() .addProperties( "data", new ResourceReference(metaResource).$ref()); } ResourceReferenceResponseSchema(MetaResource metaResource); Schema schema(); } | @Test void schema() { Schema schema = new ResourceReferenceResponseSchema(metaResource).schema(); Assert.assertTrue(schema instanceof ObjectSchema); Assert.assertTrue(schema.getProperties().containsKey("data")); Assert.assertEquals(1, schema.getProperties().size()); Schema data = (Schema) schema.getProperties().get("data"); Assert.assertEquals( "#/components/schemas/ResourceTypeResourceReference", data.get$ref() ); } |
PostResourceData extends AbstractSchemaGenerator { @Override public Schema schema() { return new ComposedSchema().allOf( OASUtils.getIncludedSchemaRefs( new PostResourceReference(metaResource), new ResourcePostAttributes(metaResource), new ResourcePostRelationships(metaResource) )); } PostResourceData(MetaResource metaResource); @Override Schema schema(); } | @Test public void schema() { additionalMetaResourceField.setInsertable(true); final Schema dataSchema = new PostResourceData(metaResource).schema(); assertNotNull(dataSchema); assertEquals(ComposedSchema.class, dataSchema.getClass()); final List<Schema> allOf = ((ComposedSchema) dataSchema).getAllOf(); assertNotNull(allOf); assertEquals(2, allOf.size()); assertEquals( "#/components/schemas/ResourceTypePostResourceReference", allOf.get(0).get$ref(), "Post resource uses a special <Type>PostResourceReference in which the id is optional"); assertEquals("#/components/schemas/ResourceTypeResourcePostAttributes", allOf.get(1).get$ref()); } |
PostResources extends AbstractSchemaGenerator { @Override public Schema schema() { return new ObjectSchema() .addRequiredItem("data") .addProperties("data", new ArraySchema() .items(new PostResourceData(metaResource).$ref())); } PostResources(MetaResource metaResource); @Override Schema schema(); } | @Test void schema() { Schema requestSchema = new PostResources(metaResource).schema(); assertNotNull(requestSchema); assertEquals(ObjectSchema.class, requestSchema.getClass()); ObjectSchema topLevelSchema = (ObjectSchema) requestSchema; assertIterableEquals(singleton("data"), topLevelSchema.getProperties().keySet()); Schema dataSchema = topLevelSchema.getProperties().get("data"); assertEquals(ArraySchema.class, dataSchema.getClass()); Schema itemSchema = ((ArraySchema) dataSchema).getItems(); assertNotNull(itemSchema); assertEquals("#/components/schemas/ResourceTypePostResourceData", itemSchema.get$ref()); } |
Links extends AbstractSchemaGenerator { public Schema schema() { return new ComposedSchema() .allOf( Arrays.asList( new ObjectSchema() .additionalProperties( new Link().$ref()), new Pagination().$ref() )) .description("Link members related to the primary data."); } Schema schema(); } | @Test void schema() { Schema schema = new Links().schema(); Assert.assertTrue(schema instanceof ComposedSchema); List<Schema> allOf = ((ComposedSchema) schema).getAllOf(); Assert.assertEquals(2, allOf.size()); Assert.assertTrue(allOf.get(0) instanceof ObjectSchema); Assert.assertEquals(new Pagination().$ref().get$ref(), allOf.get(1).get$ref()); } |
ResourceRelationships extends AbstractResourceAttributes { @Override public Schema schema() { return super.schema() .description("Relationships between the resource and other JSON:API resources"); } ResourceRelationships(MetaResource metaResource); @Override Schema schema(); } | @Test void schema() { Schema schema = new ResourceRelationships(metaResource).schema(); assertNotNull(schema); assertEquals(ObjectSchema.class, schema.getClass()); assertIterableEquals(singleton("relationships"), schema.getProperties().keySet()); Schema relationshipsSchema = ((ObjectSchema) schema).getProperties().get("relationships"); assertNotNull(relationshipsSchema); assertEquals(ObjectSchema.class, relationshipsSchema.getClass()); assertIterableEquals(singleton("resourceRelation"), relationshipsSchema.getProperties().keySet()); Schema resourceRelationSchema = ((ObjectSchema) relationshipsSchema).getProperties().get("resourceRelation"); assertNotNull(resourceRelationSchema); assertEquals(ObjectSchema.class, resourceRelationSchema.getClass()); Map<String, Schema> resourceRelationProps = ((ObjectSchema) resourceRelationSchema).getProperties(); assertIterableEquals(Stream.of("data", "links").collect(Collectors.toSet()), new HashSet<>(resourceRelationProps.keySet())); Schema dataSchema = resourceRelationProps.get("data"); assertNotNull(dataSchema); assertEquals(ComposedSchema.class, dataSchema.getClass()); List<Schema> dataOneOfSchema = ((ComposedSchema) dataSchema).getOneOf(); assertNotNull(dataOneOfSchema); assertEquals(2, dataOneOfSchema.size()); assertEquals("#/components/schemas/RelatedResourceTypeResourceReference", dataOneOfSchema.get(1).get$ref()); } |
PatchResource extends AbstractSchemaGenerator { @Override public Schema schema() { return new ObjectSchema() .addRequiredItem("data") .addProperties("data", new ComposedSchema().allOf( OASUtils.getIncludedSchemaRefs( new ResourceReference(metaResource), new ResourcePatchAttributes(metaResource), new ResourcePatchRelationships(metaResource) ))); } PatchResource(MetaResource metaResource); @Override Schema schema(); } | @Test void schema() { relationshipMetaResourceField.setUpdatable(true); Schema requestSchema = new PatchResource(metaResource).schema(); ObjectSchema topLevelSchema = (ObjectSchema) requestSchema; assertIterableEquals(singleton("data"), topLevelSchema.getProperties().keySet()); Schema dataSchema = topLevelSchema.getProperties().get("data"); assertEquals(ComposedSchema.class, dataSchema.getClass()); List<Schema> allOf = ((ComposedSchema) dataSchema).getAllOf(); assertEquals(2, allOf.size()); assertEquals("#/components/schemas/ResourceTypeResourceReference", allOf.get(0).get$ref()); assertEquals("#/components/schemas/ResourceTypeResourcePatchRelationships", allOf.get(1).get$ref()); } |
PostResourceReference extends AbstractSchemaGenerator { public Schema schema() { MetaAttribute metaAttribute = getPrimaryKeyMetaResourceField(metaResource); return new ObjectSchema() .addProperties( "type", new TypeSchema(metaResource).schema()) .addProperties( "id", new ResourceAttribute(metaResource, metaAttribute).$ref()) .required(Collections.singletonList("type")); } PostResourceReference(MetaResource metaResource); Schema schema(); } | @Test void schema() { Schema schema = new PostResourceReference(metaResource).schema(); Assert.assertTrue(schema instanceof ObjectSchema); Assert.assertTrue(schema.getProperties().containsKey("type")); Assert.assertTrue(schema.getProperties().containsKey("id")); Assert.assertEquals(2, schema.getProperties().size()); Assert.assertEquals(schema.getRequired().get(0), "type"); Assert.assertEquals(1, schema.getRequired().size()); } |
Info extends AbstractSchemaGenerator { public Schema schema() { return new ObjectSchema() .addProperties("jsonapi", new JsonApi().$ref()) .addProperties( "meta", new Meta().$ref()) .addProperties( "links", new Links().$ref()) .required(Collections.singletonList("meta")) .additionalProperties(false); } Schema schema(); } | @Test void schema() { Schema schema = new Info().schema(); Assert.assertTrue(schema instanceof ObjectSchema); Assert.assertTrue(schema.getProperties().containsKey("jsonapi")); Assert.assertTrue(schema.getProperties().containsKey("links")); Assert.assertTrue(schema.getProperties().containsKey("meta")); Assert.assertEquals(3, schema.getProperties().size()); } |
ResourceAttribute extends AbstractSchemaGenerator { public Schema schema() { Schema schema = OASUtils.transformMetaResourceField(metaAttribute.getType()); if (metaAttribute.isPrimaryKeyAttribute()) { schema.setDescription("The JSON:API resource ID"); } schema.nullable(metaAttribute.isNullable()); OASAnnotations.getInstance().applyFromModel(schema, metaResource, metaAttribute); return schema; } ResourceAttribute(MetaResource metaResource, MetaAttribute metaAttribute); Schema schema(); } | @Test void schemaPrimaryKey() { MetaResource metaResource = getTestMetaResource(); MetaResourceField metaResourceField = (MetaResourceField) metaResource.getChildren().get(0); Schema schema = new ResourceAttribute(metaResource, metaResourceField).schema(); Assert.assertTrue(schema instanceof StringSchema); Assert.assertEquals("The JSON:API resource ID", schema.getDescription()); }
@Test void schema() { MetaResource metaResource = getTestMetaResource(); MetaResourceField additionalMetaResourceField = (MetaResourceField) metaResource.getChildren().get(1); Schema schema = new ResourceAttribute(metaResource, additionalMetaResourceField).schema(); Assert.assertTrue(schema instanceof StringSchema); Assert.assertNull(schema.getDescription()); }
@Test void schemaNullable() { MetaResource metaResource = getTestMetaResource(); MetaResourceField additionalMetaResourceField = (MetaResourceField) metaResource.getChildren().get(1); additionalMetaResourceField.setNullable(true); Schema schema = new ResourceAttribute(metaResource, additionalMetaResourceField).schema(); Assert.assertTrue(schema instanceof StringSchema); Assert.assertTrue(schema.getNullable()); }
@Test @Disabled void notNullable() { MetaResource metaResource = getTestMetaResource(); MetaResourceField additionalMetaResourceField = (MetaResourceField) metaResource.getChildren().get(1); additionalMetaResourceField.setNullable(false); Schema schema = new ResourceAttribute(metaResource, additionalMetaResourceField).schema(); Assert.assertTrue(schema instanceof StringSchema); Assert.assertFalse(schema.getNullable()); } |
Meta extends AbstractSchemaGenerator { public Schema schema() { return new ObjectSchema() .description("Non-standard meta-information that can not be represented as an attribute or relationship.") .additionalProperties(true); } Schema schema(); } | @Test void schema() { Schema schema = new Meta().schema(); Assert.assertTrue(schema instanceof ObjectSchema); Assert.assertTrue((boolean) schema.getAdditionalProperties()); Assert.assertNull(schema.getProperties()); } |
Link extends AbstractSchemaGenerator { public Schema schema() { return new ComposedSchema() .oneOf( Arrays.asList( new StringSchema() .description("A string containing the link's URL.") .format("uri"), new ObjectSchema() .required(Collections.singletonList("href")) .addProperties( "href", new StringSchema() .format("uri") .description("A string containing the link's URL.")) .addProperties( "meta", new Meta().$ref()))) .description("A link **MUST** be represented as either: a string containing the link's URL or a link object."); } Schema schema(); } | @Test void schema() { Schema schema = new Link().schema(); Assert.assertTrue(schema instanceof ComposedSchema); List<Schema> oneOf = ((ComposedSchema) schema).getOneOf(); Assert.assertEquals(2, oneOf.size()); StringSchema stringSchema = (StringSchema) oneOf.get(0); Assert.assertEquals("uri", stringSchema.getFormat()); ObjectSchema objectSchema = (ObjectSchema) oneOf.get(1); Assert.assertEquals(Collections.singletonList("href"), objectSchema.getRequired()); Assert.assertTrue(objectSchema.getProperties().containsKey("href")); Assert.assertTrue(objectSchema.getProperties().containsKey("meta")); Assert.assertEquals(2, objectSchema.getProperties().size()); } |
ResourceReference extends AbstractSchemaGenerator { public Schema schema() { return new PostResourceReference(metaResource) .schema() .required(Arrays.asList("id", "type")); } ResourceReference(MetaResource metaResource); Schema schema(); } | @Test void schema() { Schema schema = new ResourceReference(metaResource).schema(); Assert.assertTrue(schema instanceof ObjectSchema); Assert.assertTrue(schema.getProperties().containsKey("id")); Assert.assertTrue(schema.getProperties().containsKey("type")); Assert.assertEquals(2, schema.getProperties().size()); Assert.assertTrue(schema.getRequired().contains("id")); Assert.assertTrue(schema.getRequired().contains("type")); Assert.assertEquals(2, schema.getRequired().size()); } |
PostResource extends AbstractSchemaGenerator { @Override public Schema schema() { return new ObjectSchema() .addRequiredItem("data") .addProperties("data", new PostResourceData(metaResource).$ref()); } PostResource(MetaResource metaResource); @Override Schema schema(); } | @Test void schema() { Schema requestSchema = new PostResource(metaResource).schema(); assertNotNull(requestSchema); assertEquals(ObjectSchema.class, requestSchema.getClass()); ObjectSchema topLevelSchema = (ObjectSchema) requestSchema; assertIterableEquals(singleton("data"), topLevelSchema.getProperties().keySet()); Schema dataSchema = topLevelSchema.getProperties().get("data"); assertEquals("#/components/schemas/ResourceTypePostResourceData", dataSchema.get$ref()); } |
ResourceSchema extends AbstractSchemaGenerator { public Schema schema() { return new ComposedSchema().allOf( OASUtils.getIncludedSchemaRefs( new ResourceReference(metaResource), new ResourceAttributes(metaResource), new ResourceRelationships(metaResource), new ResourceLinks(metaResource) )).addRequiredItem("attributes"); } ResourceSchema(MetaResource metaResource); Schema schema(); } | @Test void schema() { Schema resourceSchema = new ResourceSchema(metaResource).schema(); assertNotNull(resourceSchema); assertEquals(ComposedSchema.class, resourceSchema.getClass()); assertIterableEquals(singletonList("attributes"), resourceSchema.getRequired()); List<Schema> allOf = ((ComposedSchema) resourceSchema).getAllOf(); assertNotNull(allOf); List<String> allOfItems = allOf.stream().map(Schema::get$ref).collect(toList()); assertIterableEquals(Stream.of( "#/components/schemas/ResourceTypeResourceReference", "#/components/schemas/ResourceTypeResourceAttributes", "#/components/schemas/ResourceTypeResourceRelationships", "#/components/schemas/ResourceTypeResourceLinks" ).collect(toList()), allOfItems); } |
Success extends AbstractSchemaGenerator { public Schema schema() { return new ObjectSchema() .description("A JSON:API document with a single resource") .addProperties("jsonapi", new JsonApi().$ref()) .addProperties( "included", new ArraySchema() .items( new ObjectSchema() .addProperties( "type", new StringSchema() .description("The JSON:API resource type")) .addProperties( "id", new StringSchema() .description("The JSON:API resource ID")) .addProperties( "attributes", new ObjectSchema() .additionalProperties(true))) .uniqueItems(true) .description("Included resources")) .addProperties( "meta", new Meta().$ref()) .addProperties( "links", new Links().$ref()) .required(Collections.singletonList("data")); } Schema schema(); } | @Test void schema() { Schema schema = new Success().schema(); Assert.assertTrue(schema instanceof ObjectSchema); Assert.assertTrue(schema.getProperties().containsKey("jsonapi")); Assert.assertTrue(schema.getProperties().containsKey("links")); Assert.assertTrue(schema.getProperties().containsKey("meta")); Assert.assertTrue(schema.getProperties().containsKey("included")); Assert.assertEquals(4, schema.getProperties().size()); } |
ResourceResponseSchema extends AbstractSchemaGenerator { public Schema schema() { return new ComposedSchema() .allOf( Arrays.asList( new Success().$ref(), new Schema() .addProperties( "data", new ResourceSchema(metaResource).$ref()) .required(Collections.singletonList("data")))); } ResourceResponseSchema(MetaResource metaResource); Schema schema(); } | @Test void schema() { Schema schema = new ResourceResponseSchema(metaResource).schema(); Assert.assertTrue(schema instanceof ComposedSchema); List<Schema> allOf = ((ComposedSchema) schema).getAllOf(); Assert.assertEquals(2, allOf.size()); Assert.assertEquals("#/components/schemas/Success", allOf.get(0).get$ref()); Schema dataSchema = allOf.get(1); Schema data = (Schema) dataSchema.getProperties().get("data"); Assert.assertEquals( "#/components/schemas/ResourceTypeResourceSchema", data.get$ref() ); } |
ResourcesResponseSchema extends AbstractSchemaGenerator { public Schema schema() { return new ComposedSchema() .allOf( Arrays.asList( new Success().$ref(), new Schema() .addProperties( "data", new ArraySchema() .items(new ResourceSchema(metaResource).$ref())) .required(Collections.singletonList("data")))); } ResourcesResponseSchema(MetaResource metaResource); Schema schema(); } | @Test void schema() { Schema schema = new ResourcesResponseSchema(metaResource).schema(); Assert.assertTrue(schema instanceof ComposedSchema); List<Schema> allOf = ((ComposedSchema) schema).getAllOf(); Assert.assertEquals(2, allOf.size()); Assert.assertEquals("#/components/schemas/Success", allOf.get(0).get$ref()); Schema dataSchema = allOf.get(1); Assert.assertEquals(1, dataSchema.getRequired().size()); Assert.assertTrue(dataSchema.getRequired().contains("data")); Schema data = (Schema) dataSchema.getProperties().get("data"); Assert.assertTrue(data instanceof ArraySchema); Assert.assertEquals( "#/components/schemas/ResourceTypeResourceSchema", ((ArraySchema) data).getItems().get$ref() ); } |
ResourcePermission { @Override public boolean equals(Object obj) { if (obj != null && obj.getClass() == ResourcePermission.class) { ResourcePermission p = (ResourcePermission) obj; return p.deleteAllowed == deleteAllowed && p.getAllowed == getAllowed && p.patchAllowed == patchAllowed && p.postAllowed == postAllowed; } return false; } 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; } | @Test public void testEquals() { EqualsVerifier.forClass(ResourceIdentifier.class).usingGetClass().suppress(Warning.NONFINAL_FIELDS).verify(); Assert.assertEquals(ResourcePermission.ALL, ResourcePermission.ALL); Assert.assertEquals(ResourcePermission.DELETE, ResourcePermission.DELETE); Assert.assertEquals(ResourcePermission.GET, ResourcePermission.GET); Assert.assertEquals(ResourcePermission.POST, ResourcePermission.POST); Assert.assertNotEquals(ResourcePermission.DELETE, ResourcePermission.ALL); Assert.assertNotEquals(ResourcePermission.DELETE, ResourcePermission.GET); Assert.assertNotEquals(ResourcePermission.DELETE, ResourcePermission.PATCH); Assert.assertNotEquals(ResourcePermission.DELETE, ResourcePermission.POST); Assert.assertNotEquals(ResourcePermission.DELETE, "not a resource permission"); } |
JsonApi extends AbstractSchemaGenerator { public Schema schema() { return new ObjectSchema() .addProperties( "version", new StringSchema()) .additionalProperties(false); } Schema schema(); } | @Test void schema() { Schema schema = new JsonApi().schema(); Assert.assertTrue(schema instanceof ObjectSchema); Assert.assertTrue(schema.getProperties().containsKey("version")); Assert.assertEquals(1, schema.getProperties().size()); } |
Failure extends AbstractSchemaGenerator { public Schema schema() { return new ObjectSchema() .addProperties("jsonapi", new JsonApi().$ref()) .addProperties( "errors", new ArraySchema() .items(new ApiError().$ref()) .uniqueItems(true)) .addProperties( "meta", new Meta().$ref()) .addProperties( "links", new Links().$ref()) .required(Collections.singletonList("errors")) .additionalProperties(false); } Schema schema(); } | @Test void schema() { Schema schema = new Failure().schema(); Assert.assertTrue(schema instanceof ObjectSchema); Assert.assertTrue(schema.getProperties().containsKey("jsonapi")); Assert.assertTrue(schema.getProperties().containsKey("errors")); Assert.assertTrue(schema.getProperties().containsKey("links")); Assert.assertTrue(schema.getProperties().containsKey("meta")); Assert.assertEquals(4, schema.getProperties().size()); } |
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(); } | @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()); } |
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(); } | @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() ); } |
NoContent extends AbstractResponseGenerator { public ApiResponse response() { return new ApiResponse() .description("No Content"); } ApiResponse response(); } | @Test void response() { ApiResponse apiResponse = new NoContent().response(); Assert.assertEquals("No Content", apiResponse.getDescription()); Assert.assertNull(apiResponse.getContent()); } |
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(); } | @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() ); } |
StaticResponses { public static Map<String, ApiResponse> generateStandardApiResponses() { return OASMergeUtil.mergeApiResponses(generateStandardApiSuccessResponses(), OASErrors.generateStandardApiErrorResponses()); } static Map<String, ApiResponse> generateStandardApiResponses(); } | @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")); } |
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(); } | @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() ); } |
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(); } | @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() ); } |
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); } | @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()); } |
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; } | @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()); } |
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(); } | @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()); } |
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(); } | @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() ); } |
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(); } | @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); } |
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(); } | @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()); } |
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(); } | @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); } |
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(); } | @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()); } |
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(); } | @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); } } |
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); } | @Test public void notAField() { TSFunction function = new TSFunction(); Assert.assertFalse(function.isField()); } |
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; } | @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()); } |
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); } | @Test(expected = UnsupportedOperationException.class) public void cannotCastToField() { TSFunction function = new TSFunction(); function.asField(); } |
TSGenerator { protected TSMetaTransformationContext createMetaTransformationContext() { return new TSMetaTransformationContextImpl(); } TSGenerator(File outputDir, MetaLookup lookup, TSGeneratorConfig config); void run(); void transformMetaToTypescript(); void runProcessors(); } | @Test(expected = UnsupportedOperationException.class) public void throwExceptionWhenMetaElementNotMappedToNpmPackage() { TSMetaTransformationContext transformationContext = generator.createMetaTransformationContext(); MetaElement metaElement = Mockito.mock(MetaElement.class); metaElement.setId("does.not.exist"); transformationContext.getNpmPackage(metaElement); }
@Test(expected = UnsupportedOperationException.class) public void throwExceptionWhenMetaElementNotMappedToDirectory() { TSMetaTransformationContext transformationContext = generator.createMetaTransformationContext(); MetaElement metaElement = Mockito.mock(MetaElement.class); metaElement.setId("does.not.exist"); transformationContext.getDirectory(metaElement); }
@Test public void testResourcesMappedToRootDirectory() { MetaResource element = new MetaResource(); element.setImplementationType(Task.class); element.setId("resources.task"); TSMetaTransformationContext context = generator.createMetaTransformationContext(); Assert.assertEquals("", context.getDirectory(element)); }
@Test public void testDataObjectsMappedToRootDirectoryByDefault() { MetaResource element = new MetaResource(); element.setImplementationType(ProjectData.class); element.setId("sometehing.task"); TSMetaTransformationContext context = generator.createMetaTransformationContext(); Assert.assertEquals("", context.getDirectory(element)); Assert.assertEquals("@packageNameNotSpecified", context.getNpmPackage(element)); }
@Test public void testDirectoryMapping() { MetaResource element = new MetaResource(); element.setImplementationType(ProjectData.class); element.setId("a.b.task"); config.getNpm().getDirectoryMapping().put("a", "x"); TSMetaTransformationContext context = generator.createMetaTransformationContext(); Assert.assertEquals("/x/b", context.getDirectory(element)); Assert.assertEquals("@packageNameNotSpecified", context.getNpmPackage(element)); }
@Test public void testNestedDirectoryMapping() { MetaResource element = new MetaResource(); element.setImplementationType(ProjectData.class); element.setId("a.b.task"); config.getNpm().getDirectoryMapping().put("a", "x/y"); TSMetaTransformationContext context = generator.createMetaTransformationContext(); Assert.assertEquals("/x/y/b", context.getDirectory(element)); Assert.assertEquals("@packageNameNotSpecified", context.getNpmPackage(element)); }
@Test public void testNestedDirectoryMappingIgnoresLeadingSlash() { MetaResource element = new MetaResource(); element.setImplementationType(ProjectData.class); element.setId("a.b.task"); config.getNpm().getDirectoryMapping().put("a", "/x/y"); TSMetaTransformationContext context = generator.createMetaTransformationContext(); Assert.assertEquals("/x/y/b", context.getDirectory(element)); Assert.assertEquals("@packageNameNotSpecified", context.getNpmPackage(element)); }
@Test public void testNestedDirectoryMappingIgnoresTrailingSlash() { MetaResource element = new MetaResource(); element.setImplementationType(ProjectData.class); element.setId("a.b.task"); config.getNpm().getDirectoryMapping().put("a", "x/y/"); TSMetaTransformationContext context = generator.createMetaTransformationContext(); Assert.assertEquals("/x/y/b", context.getDirectory(element)); Assert.assertEquals("@packageNameNotSpecified", context.getNpmPackage(element)); }
@Test public void testEmptyDirectoryMapping() { MetaResource element = new MetaResource(); element.setImplementationType(ProjectData.class); element.setId("a.b.task"); config.getNpm().getDirectoryMapping().put("a", ""); TSMetaTransformationContext context = generator.createMetaTransformationContext(); Assert.assertEquals("/b", context.getDirectory(element)); Assert.assertEquals("@packageNameNotSpecified", context.getNpmPackage(element)); }
@Test public void testRootDirectoryMapping() { MetaResource element = new MetaResource(); element.setImplementationType(ProjectData.class); element.setId("a.b.task"); config.getNpm().getDirectoryMapping().put("a.b", ""); TSMetaTransformationContext context = generator.createMetaTransformationContext(); Assert.assertEquals("/", context.getDirectory(element)); Assert.assertEquals("@packageNameNotSpecified", context.getNpmPackage(element)); }
@Test public void testRootDirectoryMappingIgnoresSlash() { MetaResource element = new MetaResource(); element.setImplementationType(ProjectData.class); element.setId("a.b.task"); config.getNpm().getDirectoryMapping().put("a.b", "/"); TSMetaTransformationContext context = generator.createMetaTransformationContext(); Assert.assertEquals("/", context.getDirectory(element)); Assert.assertEquals("@packageNameNotSpecified", context.getNpmPackage(element)); } |
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(); } | @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); } |
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); } | @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()); } |
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; } | @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()); } |
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(); } | @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()); } |
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(); } | @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(); } |
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; } | @Test public void length() { Assert.assertEquals(2, path.length()); } |
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; } | @Test public void getLast() { Assert.assertEquals(attr2, path.getLast()); }
@Test public void getLastForEmptyPath() { Assert.assertNull(MetaAttributePath.EMPTY_PATH.getLast()); } |
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; } | @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()); } |
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; } | @Test public void getElement() { Assert.assertEquals(attr1, path.getElement(0)); Assert.assertEquals(attr2, path.getElement(1)); } |
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; } | @Test public void subPath() { MetaAttributePath subPath = path.subPath(1); Assert.assertEquals(1, subPath.length()); Assert.assertEquals(attr2, subPath.getElement(0)); } |
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; } | @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()); } |
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; } | @Test public void render() { Assert.assertEquals("a.b", path.toString()); } |
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; } | @Test public void equals() { Assert.assertTrue(path.equals(path)); Assert.assertFalse(path.equals(new Object())); } |
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); } | @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")); } |
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); } | @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)); } |
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); } | @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()); } |
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; } | @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)); } |
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); } | @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()); } |
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); } | @Test public void checkForwardIsLazy() { impl.isLazy(); Mockito.verify(mapAttr, Mockito.times(1)).isLazy(); } |
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); } | @Test public void checkForwardIsDerived() { impl.isDerived(); Mockito.verify(mapAttr, Mockito.times(1)).isDerived(); } |
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); } | @Test(expected = UnsupportedOperationException.class) public void checkGetAnnotationsNotSupported() { impl.getAnnotations(); } |
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); } | @Test(expected = UnsupportedOperationException.class) public void checkGetAnnotationNotSupported() { impl.getAnnotation(null); } |
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); } | @Test(expected = UnsupportedOperationException.class) public void checkSetOppositeAttributeNotSupported() { impl.setOppositeAttribute(null); } |
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); } | @Test public void checkForwardIsAssociation() { impl.isAssociation(); Mockito.verify(mapAttr, Mockito.times(1)).isAssociation(); } |
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); } | @Test(expected = UnsupportedOperationException.class) public void getVersionNotSupported() { impl.isVersion(); } |
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); } | @Test(expected = UnsupportedOperationException.class) public void isIdNotSupported() { impl.isId(); } |
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); } | @Test(expected = UnsupportedOperationException.class) public void getOppositeAttributeNotSupported() { impl.getOppositeAttribute(); } |
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; } | @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()); } |
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); } | @Test(expected = UnsupportedOperationException.class) public void getValueNotSupported() { impl.getValue(null); } |
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); } | @Test(expected = UnsupportedOperationException.class) public void addValueNotSupported() { impl.addValue(null, null); } |
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); } | @Test(expected = UnsupportedOperationException.class) public void removeValueNotSupported() { impl.removeValue(null, null); } |
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); } | @Test(expected = UnsupportedOperationException.class) public void setValueNotSupported() { impl.setValue(null, null); } |
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; } | @Test public void testToKeyStringWithNull() { MetaKey key = new MetaKey(); Assert.assertNull(key.toKeyString(null)); } |
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(); } | @Test(expected = IllegalStateException.class) public void checkDataObjectCast() { new MetaKey().asDataObject(); } |
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(); } | @Test(expected = IllegalStateException.class) public void checkTypeCast() { new MetaKey().asType(); } |
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(); } | @Test public void testGetResourceType() { Assert.assertEquals(TestEntity.class, repo.getResourceClass()); } |
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(); } | @Test public void testGetEntityType() { Assert.assertEquals(TestEntity.class, repo.getEntityClass()); } |
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; } | @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)); } |
MyService { public int calculateUserAge(User user) { return Period.between(user.getDateOfBirth(), LocalDate.now()).getYears(); } int calculateUserAge(User user); } | @Test public void testService() { MyService myService = new MyService(); User user = new User("John", "[email protected]"); user.setDateOfBirth(LocalDate.of(1980, Month.APRIL, 20)); logger.info("Age of user {} is {}", () -> user.getName(), () -> myService.calculateUserAge(user)); } |
EmployeeService { public double calculateBonus(Employee user) { return 0.1 * user.getSalary(); } double calculateBonus(Employee user); } | @Test public void testParameter() { Employee employee = new Employee("[email protected]", "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)); } |
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; } | @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)); } |
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; } | @Test public void testflushIfNeeded() { boolean flushed = Castle.flushIfNeeded("https: Assert.assertTrue(flushed); flushed = Castle.flushIfNeeded("https: Assert.assertFalse(flushed); } |
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; } | @Test public void testReset() { Castle.reset(); Assert.assertNull(Castle.userId()); } |
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; } | @Test public void testWhiteList() { Assert.assertFalse(Castle.isUrlWhiteListed("invalid url")); } |
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; } | @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); } |
Solve { Solve() { } Solve(); int solve(int dimension, int[][] gridCopy); static int[] rc2box(int i, int j); } | @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)); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.