comment
stringlengths 22
3.02k
| method_body
stringlengths 46
368k
| target_code
stringlengths 0
181
| method_body_after
stringlengths 12
368k
| context_before
stringlengths 11
634k
| context_after
stringlengths 11
632k
|
|---|---|---|---|---|---|
Do we already have positive tests for this?
|
public void setup() {
compileResult = BCompileUtil.compile("test-src/annotations/annot_attachments_negative.bal");
Assert.assertEquals(compileResult.getErrorCount(), 266);
}
|
Assert.assertEquals(compileResult.getErrorCount(), 266);
|
public void setup() {
compileResult = BCompileUtil.compile("test-src/annotations/annot_attachments_negative.bal");
Assert.assertEquals(compileResult.getErrorCount(), 266);
}
|
class AnnotationAttachmentNegativeTest {
private CompileResult compileResult;
@BeforeClass
@Test
public void testInvalidAttachmentOnType() {
int index = 0;
int line = 39;
validateError(compileResult, index++, "annotation 'v2' is not allowed on type", line, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on type", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on type", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on type", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnObjectType() {
int index = 13;
int line = 80;
validateError(compileResult, index++, "annotation 'v3' is not allowed on class", line, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on class", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on class", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on class", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnObjectMethodDefinition() {
int index = 25;
int line = 117;
validateError(compileResult, index++, "annotation 'v1' is not allowed on object_method, function",
line, 5);
validateError(compileResult, index++, "annotation 'v2' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v6' is not allowed on object_method, function",
line += 6, 5);
validateError(compileResult, index++, "annotation 'v7' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v8' is not allowed on object_method, function",
++line, 5);
validateError(compileResult, index++, "annotation 'v9' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v10' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v11' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v12' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v13' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index, "annotation 'v15' is not allowed on object_method, function",
line + 3, 5);
}
@Test
public void testInvalidAttachmentOnObjectMethodDeclaration() {
int index = 36;
int line = 155;
validateError(compileResult, index++, "annotation 'v1' is not allowed on object_method, function",
line, 5);
validateError(compileResult, index++, "annotation 'v2' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v6' is not allowed on object_method, function",
line += 6, 5);
validateError(compileResult, index++, "annotation 'v7' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v8' is not allowed on object_method, function",
++line, 5);
validateError(compileResult, index++, "annotation 'v9' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v10' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v11' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v12' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v13' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index, "annotation 'v15' is not allowed on object_method, function",
line + 3, 5);
}
@Test
public void testInvalidAttachmentOnFunction() {
int index = 47;
int line = 230;
validateError(compileResult, index++, "annotation 'v1' is not allowed on function", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on function", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on function", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on function", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnParam() {
int index = 60;
int line = 271;
validateError(compileResult, index++, "annotation 'v1' is not allowed on parameter", line, 31);
validateError(compileResult, index++, "annotation 'v2' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v3' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v4' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v5' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v7' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v8' is not allowed on parameter", ++line, 29);
validateError(compileResult, index++, "annotation 'v9' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v10' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v11' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v12' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v13' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index, "annotation 'v15' is not allowed on parameter", line + 3, 29);
}
@Test
public void testInvalidAttachmentOnReturn() {
int index = 73;
int line = 307;
validateError(compileResult, index++, "annotation 'v1' is not allowed on return", line, 53);
validateError(compileResult, index++, "annotation 'v2' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v3' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v4' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v5' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v6' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v8' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v9' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v10' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v11' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v12' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v13' is not allowed on return", line += 3, 53);
validateError(compileResult, index, "annotation 'v15' is not allowed on return", line + 3, 53);
}
@Test
public void testInvalidAttachmentOnListener() {
int index = 86;
int line = 349;
validateError(compileResult, index++, "annotation 'v1' is not allowed on listener", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on listener", ++line, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on listener", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on listener", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnService() {
int index = 99;
int line = 388;
validateError(compileResult, index++, "annotation 'v1' is not allowed on service", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on service", ++line, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on service", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on service", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnResource() {
int index = 112;
int line = 427;
validateError(compileResult, index++, "annotation 'v1' is not allowed on object_method, function", line,
5);
validateError(compileResult, index++, "annotation 'v2' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index++, "annotation 'v6' is not allowed on object_method, function", line += 6,
5);
validateError(compileResult, index++, "annotation 'v7' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index++, "annotation 'v8' is not allowed on object_method, function", ++line,
5);
validateError(compileResult, index++, "annotation 'v9' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index++, "annotation 'v10' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index++, "annotation 'v11' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index++, "annotation 'v12' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index++, "annotation 'v13' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index, "annotation 'v15' is not allowed on object_method, function", line + 3, 5);
}
@Test
public void testInvalidAttachmentOnAnnotation() {
int index = 123;
int line = 490;
validateError(compileResult, index++, "annotation 'v1' is not allowed on annotation", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on annotation", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on annotation", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnVar() {
int index = 136;
int line = 529;
validateError(compileResult, index++, "annotation 'v1' is not allowed on var", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on var", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on var", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on var", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnLetVar() {
int index = 149;
int line = 568;
validateError(compileResult, index++, "annotation 'v1' is not allowed on var", line, 13);
validateError(compileResult, index++, "annotation 'v2' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v3' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v4' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v5' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v6' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v7' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v8' is not allowed on var", ++line, 13);
validateError(compileResult, index++, "annotation 'v9' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v10' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v12' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v13' is not allowed on var", line += 3, 13);
validateError(compileResult, index, "annotation 'v15' is not allowed on var", line + 3, 13);
}
@Test
public void testInvalidAttachmentOnConst() {
int index = 162;
int line = 606;
validateError(compileResult, index++, "annotation 'v1' is not allowed on const", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on const", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on const", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on const", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnExternal() {
int index = 175;
int line = 645;
validateError(compileResult, index++, "annotation 'v1' is not allowed on external", line, 62);
validateError(compileResult, index++, "annotation 'v2' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v3' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v4' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v5' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v6' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v7' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v8' is not allowed on external", ++line, 61);
validateError(compileResult, index++, "annotation 'v9' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v10' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v11' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v12' is not allowed on external", line += 3, 61);
validateError(compileResult, index, "annotation 'v15' is not allowed on external", line + 3, 61);
}
@Test
public void testInvalidAttachmentOnServiceVariable() {
int index = 188;
int line = 683;
validateError(compileResult, index++, "annotation 'v8' is not allowed on var", line, 1);
validateError(compileResult, index++, "annotation 'v1' is not allowed on service", line += 4, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on service", ++line, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on service", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on service", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnWorker() {
int index = 202;
int line = 733;
validateError(compileResult, index++, "annotation 'v1' is not allowed on worker", line, 5);
validateError(compileResult, index++, "annotation 'v2' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v3' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v4' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v5' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v6' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v7' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v8' is not allowed on worker", ++line, 5);
validateError(compileResult, index++, "annotation 'v9' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v10' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v11' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v12' is not allowed on worker", line += 3, 5);
validateError(compileResult, index, "annotation 'v13' is not allowed on worker", line + 3, 5);
}
@Test
public void testInvalidAttachmentOnStart() {
int index = 215;
int line = 776;
validateError(compileResult, index++, "action invocation as an expression not allowed here", line, 1);
validateError(compileResult, index++, "annotation 'v1' is not allowed on worker", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on worker", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on worker", line += 3, 1);
validateError(compileResult, index, "annotation 'v13' is not allowed on worker", line + 3, 1);
}
@Test
public void testInvalidAttachmentForField() {
int index = 229;
validateError(compileResult, index++, "annotation 'v16' is not allowed on var", 819, 1);
validateError(compileResult, index++, "annotation 'v16' is not allowed on function", 821, 1);
validateError(compileResult, index++, "annotation 'v17' is not allowed on function", 822, 1);
validateError(compileResult, index++, "annotation 'v18' is not allowed on function", 823, 1);
validateError(compileResult, index++, "annotation 'v16' is not allowed on type", 828, 1);
validateError(compileResult, index++, "annotation 'v17' is not allowed on type", 829, 1);
validateError(compileResult, index++, "annotation 'v18' is not allowed on type", 830, 1);
validateError(compileResult, index++, "annotation 'v17' is not allowed on record_field, field", 832, 5);
validateError(compileResult, index++, "annotation 'v16' is not allowed on class", 835, 1);
validateError(compileResult, index++, "annotation 'v17' is not allowed on class", 836, 1);
validateError(compileResult, index++, "annotation 'v18' is not allowed on class", 837, 1);
validateError(compileResult, index, "annotation 'v18' is not allowed on object_field, field", 839, 5);
}
@Test
public void testInvalidAttachmentForTypeConversionExpr() {
int index = 241;
validateError(compileResult, index++, "annotation 'v16' is not allowed on type", 847, 17);
}
@Test
public void testInvalidAttachmentForClass() {
int index = 242;
validateError(compileResult, index++, "annotation 'v19' is not allowed on class", 852, 6);
}
@Test
public void testQualifiedNameInInvalidAttachmentError() {
validateError(compileResult, 243,
"annotation 'ballerina/lang.annotations:1.0.0:tainted' is not allowed on class", 859, 1);
}
@Test
public void testInvalidAttachmentWithValue() {
validateError(compileResult, 244,
"no annotation value expected for annotation 'ballerina/lang.annotations:1.0.0:tainted'",
864, 10);
validateError(compileResult, 245, "no annotation value expected for annotation 'v7'",
869, 35);
}
@Test
public void testInvalidAttachmentWithoutValue() {
validateError(compileResult, 246, "annotation value expected for annotation of " +
"record type 'Annot' with required fields", 871, 1);
validateError(compileResult, 247, "annotation value expected for annotation of " +
"record type 'Annot' with required fields", 874, 1);
validateError(compileResult, 248, "annotation value expected for annotation of " +
"record type 'Annot' with required fields", 875, 22);
validateError(compileResult, 249, "annotation value expected for annotation of " +
"record type 'Annot' with required fields", 881, 1);
validateError(compileResult, 250, "annotation value expected for annotation of " +
"record type 'Annot' with required fields", 882, 1);
}
@Test
public void testInvalidAttachmentCount() {
validateError(compileResult, 251, "cannot specify more than one annotation value for " +
"annotation 'ballerina/lang.annotations:1.0.0:tainted'", 886, 1);
validateError(compileResult, 252,
"cannot specify more than one annotation value for annotation 'v1'", 888, 1);
}
@Test
public void testInvalidAttachmentOnServiceClass() {
int index = 253;
int line = 892;
validateError(compileResult, index++, "annotation 'v1' is not allowed on class", line, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on class", line += 6, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on class", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on class", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on class", line + 3, 1);
}
}
|
class AnnotationAttachmentNegativeTest {
private CompileResult compileResult;
@BeforeClass
@Test
public void testInvalidAttachmentOnType() {
int index = 0;
int line = 39;
validateError(compileResult, index++, "annotation 'v2' is not allowed on type", line, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on type", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on type", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on type", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on type", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnObjectType() {
int index = 13;
int line = 80;
validateError(compileResult, index++, "annotation 'v3' is not allowed on class", line, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on class", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on class", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on class", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnObjectMethodDefinition() {
int index = 25;
int line = 117;
validateError(compileResult, index++, "annotation 'v1' is not allowed on object_method, function",
line, 5);
validateError(compileResult, index++, "annotation 'v2' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v6' is not allowed on object_method, function",
line += 6, 5);
validateError(compileResult, index++, "annotation 'v7' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v8' is not allowed on object_method, function",
++line, 5);
validateError(compileResult, index++, "annotation 'v9' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v10' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v11' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v12' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v13' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index, "annotation 'v15' is not allowed on object_method, function",
line + 3, 5);
}
@Test
public void testInvalidAttachmentOnObjectMethodDeclaration() {
int index = 36;
int line = 155;
validateError(compileResult, index++, "annotation 'v1' is not allowed on object_method, function",
line, 5);
validateError(compileResult, index++, "annotation 'v2' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v6' is not allowed on object_method, function",
line += 6, 5);
validateError(compileResult, index++, "annotation 'v7' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v8' is not allowed on object_method, function",
++line, 5);
validateError(compileResult, index++, "annotation 'v9' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v10' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v11' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v12' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index++, "annotation 'v13' is not allowed on object_method, function",
line += 3, 5);
validateError(compileResult, index, "annotation 'v15' is not allowed on object_method, function",
line + 3, 5);
}
@Test
public void testInvalidAttachmentOnFunction() {
int index = 47;
int line = 230;
validateError(compileResult, index++, "annotation 'v1' is not allowed on function", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on function", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on function", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on function", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on function", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnParam() {
int index = 60;
int line = 271;
validateError(compileResult, index++, "annotation 'v1' is not allowed on parameter", line, 31);
validateError(compileResult, index++, "annotation 'v2' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v3' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v4' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v5' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v7' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v8' is not allowed on parameter", ++line, 29);
validateError(compileResult, index++, "annotation 'v9' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v10' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v11' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v12' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index++, "annotation 'v13' is not allowed on parameter", line += 3, 29);
validateError(compileResult, index, "annotation 'v15' is not allowed on parameter", line + 3, 29);
}
@Test
public void testInvalidAttachmentOnReturn() {
int index = 73;
int line = 307;
validateError(compileResult, index++, "annotation 'v1' is not allowed on return", line, 53);
validateError(compileResult, index++, "annotation 'v2' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v3' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v4' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v5' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v6' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v8' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v9' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v10' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v11' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v12' is not allowed on return", line += 3, 53);
validateError(compileResult, index++, "annotation 'v13' is not allowed on return", line += 3, 53);
validateError(compileResult, index, "annotation 'v15' is not allowed on return", line + 3, 53);
}
@Test
public void testInvalidAttachmentOnListener() {
int index = 86;
int line = 349;
validateError(compileResult, index++, "annotation 'v1' is not allowed on listener", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on listener", ++line, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on listener", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on listener", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on listener", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnService() {
int index = 99;
int line = 388;
validateError(compileResult, index++, "annotation 'v1' is not allowed on service", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on service", ++line, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on service", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on service", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnResource() {
int index = 112;
int line = 427;
validateError(compileResult, index++, "annotation 'v1' is not allowed on object_method, function", line,
5);
validateError(compileResult, index++, "annotation 'v2' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index++, "annotation 'v6' is not allowed on object_method, function", line += 6,
5);
validateError(compileResult, index++, "annotation 'v7' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index++, "annotation 'v8' is not allowed on object_method, function", ++line,
5);
validateError(compileResult, index++, "annotation 'v9' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index++, "annotation 'v10' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index++, "annotation 'v11' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index++, "annotation 'v12' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index++, "annotation 'v13' is not allowed on object_method, function", line += 3,
5);
validateError(compileResult, index, "annotation 'v15' is not allowed on object_method, function", line + 3, 5);
}
@Test
public void testInvalidAttachmentOnAnnotation() {
int index = 123;
int line = 490;
validateError(compileResult, index++, "annotation 'v1' is not allowed on annotation", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on annotation", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on annotation", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on annotation", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnVar() {
int index = 136;
int line = 529;
validateError(compileResult, index++, "annotation 'v1' is not allowed on var", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on var", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on var", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on var", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on var", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnLetVar() {
int index = 149;
int line = 568;
validateError(compileResult, index++, "annotation 'v1' is not allowed on var", line, 13);
validateError(compileResult, index++, "annotation 'v2' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v3' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v4' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v5' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v6' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v7' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v8' is not allowed on var", ++line, 13);
validateError(compileResult, index++, "annotation 'v9' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v10' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v12' is not allowed on var", line += 3, 13);
validateError(compileResult, index++, "annotation 'v13' is not allowed on var", line += 3, 13);
validateError(compileResult, index, "annotation 'v15' is not allowed on var", line + 3, 13);
}
@Test
public void testInvalidAttachmentOnConst() {
int index = 162;
int line = 606;
validateError(compileResult, index++, "annotation 'v1' is not allowed on const", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on const", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on const", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on const", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on const", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnExternal() {
int index = 175;
int line = 645;
validateError(compileResult, index++, "annotation 'v1' is not allowed on external", line, 62);
validateError(compileResult, index++, "annotation 'v2' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v3' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v4' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v5' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v6' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v7' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v8' is not allowed on external", ++line, 61);
validateError(compileResult, index++, "annotation 'v9' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v10' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v11' is not allowed on external", line += 3, 61);
validateError(compileResult, index++, "annotation 'v12' is not allowed on external", line += 3, 61);
validateError(compileResult, index, "annotation 'v15' is not allowed on external", line + 3, 61);
}
@Test
public void testInvalidAttachmentOnServiceVariable() {
int index = 188;
int line = 683;
validateError(compileResult, index++, "annotation 'v8' is not allowed on var", line, 1);
validateError(compileResult, index++, "annotation 'v1' is not allowed on service", line += 4, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on service", ++line, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on service", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on service", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on service", line + 3, 1);
}
@Test
public void testInvalidAttachmentOnWorker() {
int index = 202;
int line = 733;
validateError(compileResult, index++, "annotation 'v1' is not allowed on worker", line, 5);
validateError(compileResult, index++, "annotation 'v2' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v3' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v4' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v5' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v6' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v7' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v8' is not allowed on worker", ++line, 5);
validateError(compileResult, index++, "annotation 'v9' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v10' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v11' is not allowed on worker", line += 3, 5);
validateError(compileResult, index++, "annotation 'v12' is not allowed on worker", line += 3, 5);
validateError(compileResult, index, "annotation 'v13' is not allowed on worker", line + 3, 5);
}
@Test
public void testInvalidAttachmentOnStart() {
int index = 215;
int line = 776;
validateError(compileResult, index++, "action invocation as an expression not allowed here", line, 1);
validateError(compileResult, index++, "annotation 'v1' is not allowed on worker", line, 1);
validateError(compileResult, index++, "annotation 'v2' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on worker", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on worker", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on worker", line += 3, 1);
validateError(compileResult, index, "annotation 'v13' is not allowed on worker", line + 3, 1);
}
@Test
public void testInvalidAttachmentForField() {
int index = 229;
validateError(compileResult, index++, "annotation 'v16' is not allowed on var", 819, 1);
validateError(compileResult, index++, "annotation 'v16' is not allowed on function", 821, 1);
validateError(compileResult, index++, "annotation 'v17' is not allowed on function", 822, 1);
validateError(compileResult, index++, "annotation 'v18' is not allowed on function", 823, 1);
validateError(compileResult, index++, "annotation 'v16' is not allowed on type", 828, 1);
validateError(compileResult, index++, "annotation 'v17' is not allowed on type", 829, 1);
validateError(compileResult, index++, "annotation 'v18' is not allowed on type", 830, 1);
validateError(compileResult, index++, "annotation 'v17' is not allowed on record_field, field", 832, 5);
validateError(compileResult, index++, "annotation 'v16' is not allowed on class", 835, 1);
validateError(compileResult, index++, "annotation 'v17' is not allowed on class", 836, 1);
validateError(compileResult, index++, "annotation 'v18' is not allowed on class", 837, 1);
validateError(compileResult, index, "annotation 'v18' is not allowed on object_field, field", 839, 5);
}
@Test
public void testInvalidAttachmentForTypeConversionExpr() {
int index = 241;
validateError(compileResult, index++, "annotation 'v16' is not allowed on type", 847, 17);
}
@Test
public void testInvalidAttachmentForClass() {
int index = 242;
validateError(compileResult, index++, "annotation 'v19' is not allowed on class", 852, 6);
}
@Test
public void testQualifiedNameInInvalidAttachmentError() {
validateError(compileResult, 243,
"annotation 'ballerina/lang.annotations:1.0.0:tainted' is not allowed on class", 859, 1);
}
@Test
public void testInvalidAttachmentWithValue() {
validateError(compileResult, 244,
"no annotation value expected for annotation 'ballerina/lang.annotations:1.0.0:tainted'",
864, 10);
validateError(compileResult, 245, "no annotation value expected for annotation 'v7'",
869, 35);
}
@Test
public void testInvalidAttachmentWithoutValue() {
validateError(compileResult, 246, "annotation value expected for annotation of " +
"record type 'Annot' with required fields", 871, 1);
validateError(compileResult, 247, "annotation value expected for annotation of " +
"record type 'Annot' with required fields", 874, 1);
validateError(compileResult, 248, "annotation value expected for annotation of " +
"record type 'Annot' with required fields", 875, 22);
validateError(compileResult, 249, "annotation value expected for annotation of " +
"record type 'Annot' with required fields", 881, 1);
validateError(compileResult, 250, "annotation value expected for annotation of " +
"record type 'Annot' with required fields", 882, 1);
}
@Test
public void testInvalidAttachmentCount() {
validateError(compileResult, 251, "cannot specify more than one annotation value for " +
"annotation 'ballerina/lang.annotations:1.0.0:tainted'", 886, 1);
validateError(compileResult, 252,
"cannot specify more than one annotation value for annotation 'v1'", 888, 1);
}
@Test
public void testInvalidAttachmentOnServiceClass() {
int index = 253;
int line = 892;
validateError(compileResult, index++, "annotation 'v1' is not allowed on class", line, 1);
validateError(compileResult, index++, "annotation 'v3' is not allowed on class", line += 6, 1);
validateError(compileResult, index++, "annotation 'v4' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v5' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v6' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v7' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v8' is not allowed on class", ++line, 1);
validateError(compileResult, index++, "annotation 'v9' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v10' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v11' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v12' is not allowed on class", line += 3, 1);
validateError(compileResult, index++, "annotation 'v13' is not allowed on class", line += 3, 1);
validateError(compileResult, index, "annotation 'v15' is not allowed on class", line + 3, 1);
}
}
|
I think this is no longer valid.
|
private ClassLoader getClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = getClass().getClassLoader();
}
if (cl == null) {
cl = Object.class.getClassLoader();
}
return cl;
}
|
private ClassLoader getClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = getClass().getClassLoader();
}
if (cl == null) {
cl = Object.class.getClassLoader();
}
return cl;
}
|
class DevClasspathStaticHandler implements Handler<RoutingContext> {
private static final Logger LOG = Logger.getLogger(DevClasspathStaticHandler.class);
private static final Set<HttpMethod> ALLOWED_HTTP_METHODS = Set.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS);
private static final int HTTP_STATUS_OK = 200;
private static final int HTTP_STATUS_NO_CONTENT = 204;
private static final String ALLOW_HEADER = "Allow";
private static final String ALLOW_HEADER_VALUE = "HEAD,GET,OPTIONS";
private final Set<String> generatedResources;
private final Set<String> compressedMediaTypes;
private final ClassLoader currentClassLoader;
private final boolean enableCompression;
private final String indexPage;
private final Charset defaultEncoding;
public DevClasspathStaticHandler(Set<String> generatedResources, DevClasspathStaticHandlerOptions options) {
this.generatedResources = generatedResources;
this.compressedMediaTypes = options.getCompressMediaTypes();
this.currentClassLoader = Thread.currentThread().getContextClassLoader();
this.enableCompression = options.isEnableCompression();
this.indexPage = options.getIndexPage();
this.defaultEncoding = options.getDefaultEncoding();
}
@Override
public void handle(RoutingContext context) {
if (!ALLOWED_HTTP_METHODS.contains(context.request().method())) {
LOG.debugf("HTTP method '%s' not allowed, this static handler accepts only GET, OPTIONS and HEAD",
context.request().method().name());
beforeNextHandler(this.currentClassLoader, context);
} else {
doHandle(context);
}
}
private String removeStartSlashes(String value) {
return value.replaceAll("^/+", "");
}
private void doHandle(RoutingContext context) {
String resolvedPath = resolvePath(context);
String path = resolvedPath.endsWith("/") ? resolvedPath.concat(this.indexPage) : resolvedPath;
if (LOG.isDebugEnabled()) {
LOG.debugf("Handling request for path '%s'", path);
}
boolean containsGeneratedResource = this.generatedResources.contains(removeStartSlashes(path));
if (!containsGeneratedResource) {
beforeNextHandler(this.currentClassLoader, context);
return;
}
if (context.request().method().equals(HttpMethod.OPTIONS)) {
context.response().putHeader(ALLOW_HEADER, ALLOW_HEADER_VALUE).setStatusCode(HTTP_STATUS_NO_CONTENT)
.send();
return;
}
compressIfNeeded(context, path);
byte[] content = getClasspathResourceContent(path);
if (content != null) {
if (context.request().method().equals(HttpMethod.HEAD)) {
handleHeadMethod(context, path, content);
} else {
context.response().setStatusCode(HTTP_STATUS_OK).send(Buffer.buffer(content));
}
} else {
LOG.warnf("The '%s' file does not contain any content. Proceeding to the next handler if it exists", path);
beforeNextHandler(this.currentClassLoader, context);
}
}
private void handleHeadMethod(RoutingContext context, String path, byte[] content) {
String contentType = MimeMapping.getMimeTypeForFilename(path);
if (contentType != null) {
if (contentType.startsWith("text")) {
context.response().putHeader(HttpHeaders.CONTENT_TYPE, contentType + ";charset=" + defaultEncoding);
} else {
context.response().putHeader(HttpHeaders.CONTENT_TYPE, contentType);
}
}
context.response().putHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(content.length));
context.response().setStatusCode(HTTP_STATUS_OK).end();
}
private byte[] getClasspathResourceContent(String name) {
String resourceName = GeneratedStaticResourcesRecorder.META_INF_RESOURCES + name;
URL resource = getClassLoader().getResource(resourceName);
if (resource == null) {
LOG.warnf("The resource '%s' does not exist on classpath", resourceName);
return null;
}
try {
try (InputStream inputStream = resource.openStream()) {
return inputStream.readAllBytes();
}
} catch (IOException e) {
LOG.error("Error while reading file from Classpath for path " + resourceName, e);
return null;
}
}
private static String resolvePath(RoutingContext ctx) {
return (ctx.mountPoint() == null) ? ctx.normalizedPath()
: ctx.normalizedPath().substring(
ctx.mountPoint().endsWith("/") ? ctx.mountPoint().length() - 1 : ctx.mountPoint().length());
}
private static void beforeNextHandler(ClassLoader cl, RoutingContext ctx) {
Thread.currentThread().setContextClassLoader(cl);
ctx.next();
}
private void compressIfNeeded(RoutingContext ctx, String path) {
if (enableCompression && isCompressed(path)) {
ctx.response().headers().remove(HttpHeaders.CONTENT_ENCODING);
}
}
private boolean isCompressed(String path) {
if (this.compressedMediaTypes.isEmpty()) {
return false;
}
final String resourcePath = path.endsWith("/") ? path + this.indexPage : path;
String contentType = MimeMapping.getMimeTypeForFilename(resourcePath);
return contentType != null && this.compressedMediaTypes.contains(contentType);
}
}
|
class DevClasspathStaticHandler implements Handler<RoutingContext> {
private static final Logger LOG = Logger.getLogger(DevClasspathStaticHandler.class);
private static final int HTTP_STATUS_OK = 200;
private static final int HTTP_STATUS_NO_CONTENT = 204;
private static final String ALLOW_HEADER = "Allow";
private static final String ALLOW_HEADER_VALUE = "HEAD,GET,OPTIONS";
private final Set<String> generatedResources;
private final Set<String> compressedMediaTypes;
private final ClassLoader currentClassLoader;
private final boolean enableCompression;
private final String indexPage;
private final Charset defaultEncoding;
public DevClasspathStaticHandler(Set<String> generatedResources, DevClasspathStaticHandlerOptions options) {
this.generatedResources = generatedResources;
this.compressedMediaTypes = options.getCompressMediaTypes();
this.currentClassLoader = Thread.currentThread().getContextClassLoader();
this.enableCompression = options.isEnableCompression();
this.indexPage = options.getIndexPage();
this.defaultEncoding = options.getDefaultEncoding();
}
@Override
public void handle(RoutingContext context) {
String resolvedPath = resolvePath(context);
String path = resolvedPath.endsWith("/") ? resolvedPath.concat(this.indexPage) : resolvedPath;
if (LOG.isDebugEnabled()) {
LOG.debugf("Handling request for path '%s'", path);
}
boolean containsGeneratedResource = this.generatedResources.contains(path);
if (!containsGeneratedResource) {
beforeNextHandler(this.currentClassLoader, context);
return;
}
if (context.request().method().equals(HttpMethod.OPTIONS)) {
context.response().putHeader(ALLOW_HEADER, ALLOW_HEADER_VALUE).setStatusCode(HTTP_STATUS_NO_CONTENT)
.send();
return;
}
compressIfNeeded(context, path);
context.vertx().executeBlocking(future -> {
try {
byte[] content = getClasspathResourceContent(path);
future.complete(content);
} catch (Exception e) {
future.fail(e);
}
}, asyncResult -> {
if (asyncResult.succeeded()) {
byte[] result = (byte[]) asyncResult.result();
handleAsyncResultSucceeded(context, result, path);
} else {
context.fail(asyncResult.cause());
}
});
}
private void handleAsyncResultSucceeded(RoutingContext context, byte[] result, String path) {
if (result == null) {
LOG.warnf("The '%s' file does not contain any content. Proceeding to the next handler if it exists", path);
beforeNextHandler(this.currentClassLoader, context);
return;
}
String contentType = MimeMapping.getMimeTypeForFilename(path);
if (contentType != null) {
if (contentType.startsWith("text")) {
context.response().putHeader(HttpHeaders.CONTENT_TYPE, contentType + ";charset=" + defaultEncoding);
} else {
context.response().putHeader(HttpHeaders.CONTENT_TYPE, contentType);
}
}
if (context.request().method().equals(HttpMethod.HEAD)) {
handleHeadMethod(context, result);
} else {
context.response().send(Buffer.buffer(result));
}
}
private void handleHeadMethod(RoutingContext context, byte[] content) {
context.response().putHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(content.length));
context.response().setStatusCode(HTTP_STATUS_OK).end();
}
private byte[] getClasspathResourceContent(String name) {
String resourceName = GeneratedStaticResourcesRecorder.META_INF_RESOURCES + name;
URL resource = getClassLoader().getResource(resourceName);
if (resource == null) {
LOG.warnf("The resource '%s' does not exist on classpath", resourceName);
return null;
}
try {
try (InputStream inputStream = resource.openStream()) {
return inputStream.readAllBytes();
}
} catch (IOException e) {
LOG.error("Error while reading file from Classpath for path " + resourceName, e);
return null;
}
}
private static String resolvePath(RoutingContext ctx) {
return (ctx.mountPoint() == null) ? ctx.normalizedPath()
: ctx.normalizedPath().substring(
ctx.mountPoint().endsWith("/") ? ctx.mountPoint().length() - 1 : ctx.mountPoint().length());
}
private static void beforeNextHandler(ClassLoader cl, RoutingContext ctx) {
Thread.currentThread().setContextClassLoader(cl);
ctx.next();
}
private void compressIfNeeded(RoutingContext ctx, String path) {
if (enableCompression && isCompressed(path)) {
ctx.response().headers().remove(HttpHeaders.CONTENT_ENCODING);
}
}
private boolean isCompressed(String path) {
if (this.compressedMediaTypes.isEmpty()) {
return false;
}
final String resourcePath = path.endsWith("/") ? path + this.indexPage : path;
String contentType = MimeMapping.getMimeTypeForFilename(resourcePath);
return contentType != null && this.compressedMediaTypes.contains(contentType);
}
}
|
|
Okay got it :) So we can remove the check for the os and have only the check for the file name
|
private static boolean isDirEmpty(final Path directory) throws IOException {
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) {
Iterator pathIterator = dirStream.iterator();
if (pathIterator.hasNext()) {
Path path = (Path) pathIterator.next();
Path filePath = path.getFileName();
if (filePath != null && filePath.toString().equals(ProjectDirConstants.MAC_OS_DS_STORE_FILE)) {
return System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("mac") &&
!pathIterator.hasNext();
} else {
return false;
}
} else {
return true;
}
}
}
|
!pathIterator.hasNext();
|
private static boolean isDirEmpty(final Path directory) throws IOException {
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) {
Iterator pathIterator = dirStream.iterator();
if (!pathIterator.hasNext()) {
return true;
}
Path path = (Path) pathIterator.next();
Path fileName = path.getFileName();
return fileName != null && fileName.toString().equals(ProjectDirConstants.DS_STORE_FILE) &&
!pathIterator.hasNext();
}
}
|
class InitCommand implements BLauncherCmd {
public static final String DEFAULT_VERSION = "0.0.1";
private static final String USER_DIR = "user.dir";
private static final PrintStream errStream = System.err;
private final Path homePath = RepoUtils.createAndGetHomeReposPath();
private boolean alreadyInitializedProject = false;
private boolean manifestExistInProject = false;
private PrintStream out = System.out;
@CommandLine.Option(names = {"--interactive", "-i"})
private boolean interactiveFlag;
@CommandLine.Option(names = {"--help", "-h"}, hidden = true)
private boolean helpFlag;
@Override
public void execute() {
Path projectPath = Paths.get(System.getProperty(USER_DIR));
try {
boolean isProject = Files.exists(projectPath.resolve(ProjectDirConstants.DOT_BALLERINA_DIR_NAME));
if (isProject) {
alreadyInitializedProject = true;
manifestExistInProject = Files.exists(projectPath.resolve(ProjectDirConstants.MANIFEST_FILE_NAME));
}
if (!alreadyInitializedProject) {
Optional<Path> childDotBallerina = Files.walk(projectPath)
.filter(path -> Files.isDirectory(path) &&
path.toFile().getName().equals(ProjectDirConstants.DOT_BALLERINA_DIR_NAME))
.findFirst();
if (childDotBallerina.isPresent()) {
errStream.println("A ballerina project is already initialized in " +
childDotBallerina.get().toFile().getParent());
return;
}
Path projectRoot = findProjectRoot(projectPath);
if (projectRoot != null) {
errStream.println("Directory is already within a ballerina project :" + projectRoot.toString());
return;
}
}
} catch (IOException ignore) {
}
Scanner scanner = new Scanner(System.in, Charset.defaultCharset().name());
try {
Manifest manifest = null;
if (helpFlag) {
String commandUsageInfo = BLauncherCmd.getCommandUsageInfo(INIT_COMMAND);
errStream.println(commandUsageInfo);
return;
}
List<SrcFile> sourceFiles = new ArrayList<>();
List<ModuleMdFile> moduleMdFiles = new ArrayList<>();
boolean validInput = false;
boolean firstPrompt = true;
if (interactiveFlag) {
if (!manifestExistInProject) {
out.print("Create Ballerina.toml [yes/y, no/n]: (y) ");
String createToml = scanner.nextLine().trim();
manifest = createManifest(scanner, createToml);
}
if (alreadyInitializedProject) {
out.print("Create modules [yes/y, no/n]: (y) ");
firstPrompt = false;
String input = scanner.nextLine().trim();
if (input.equalsIgnoreCase("n")) {
out.println("Ballerina project not reinitialized");
return;
}
}
String srcInput;
do {
if (firstPrompt) {
out.print("Ballerina source [service/s, main/m, finish/f]: (s) ");
} else {
out.print("Ballerina source [service/s, main/m, finish/f]: (f) ");
}
srcInput = scanner.nextLine().trim();
if (srcInput.equalsIgnoreCase("service") || srcInput.equalsIgnoreCase("s")
|| (srcInput.isEmpty() && firstPrompt)) {
String packageName;
do {
out.print("Module for the service: (no module) ");
packageName = scanner.nextLine().trim();
} while (!validatePkgName(projectPath, packageName));
SrcFile srcFile = new SrcFile(packageName, FileType.SERVICE);
sourceFiles.add(srcFile);
SrcFile srcTestFile = new SrcFile(packageName, FileType.SERVICE_TEST);
sourceFiles.add(srcTestFile);
if (!packageName.isEmpty()) {
ModuleMdFile moduleMdFile = new ModuleMdFile(packageName, FileType.SERVICE);
moduleMdFiles.add(moduleMdFile);
}
firstPrompt = false;
} else if (srcInput.equalsIgnoreCase("main") || srcInput.equalsIgnoreCase("m")) {
String packageName;
do {
out.print("Module for the main: (no module) ");
packageName = scanner.nextLine().trim();
} while (!validatePkgName(projectPath, packageName));
SrcFile srcFile = new SrcFile(packageName, FileType.MAIN);
sourceFiles.add(srcFile);
SrcFile srcTestFile = new SrcFile(packageName, FileType.MAIN_TEST);
sourceFiles.add(srcTestFile);
if (!packageName.isEmpty()) {
ModuleMdFile moduleMdFile = new ModuleMdFile(packageName, FileType.MAIN);
moduleMdFiles.add(moduleMdFile);
}
firstPrompt = false;
} else if (srcInput.isEmpty() || srcInput.equalsIgnoreCase("f") ||
srcInput.equalsIgnoreCase("finish")) {
validInput = true;
firstPrompt = false;
} else {
out.println("Invalid input");
}
} while (!validInput);
out.print("\n");
} else {
manifest = new Manifest();
manifest.setName(guessOrgName());
manifest.setVersion(DEFAULT_VERSION);
if (isDirEmpty(projectPath)) {
SrcFile srcFile = new SrcFile("", FileType.SERVICE);
sourceFiles.add(srcFile);
}
}
InitHandler.initialize(projectPath, manifest, sourceFiles, moduleMdFiles);
if (!alreadyInitializedProject) {
out.println("Ballerina project initialized");
} else {
out.println("Ballerina project reinitialized");
}
} catch (IOException e) {
out.println("Error occurred while creating project: " + e.getMessage());
}
}
/**
* Create a manifest object.
*
* @param scanner scanner object
* @param createToml create toml or not
* @return manifest object
*/
private Manifest createManifest(Scanner scanner, String createToml) {
Manifest manifest = new Manifest();
if (createToml.equalsIgnoreCase("yes") || createToml.equalsIgnoreCase("y")
|| createToml.isEmpty()) {
String defaultOrg = guessOrgName();
String orgName;
do {
out.print("Organization name: (" + defaultOrg + ") ");
orgName = scanner.nextLine().trim();
}
while (!validateOrgName(orgName));
manifest.setName(orgName.isEmpty() ? defaultOrg : orgName);
String version;
do {
out.print("Version: (" + DEFAULT_VERSION + ") ");
version = scanner.nextLine().trim();
version = version.isEmpty() ? DEFAULT_VERSION : version;
}
while (!validateVersion(out, version));
manifest.setVersion(version);
}
return manifest;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return INIT_COMMAND;
}
/**
* {@inheritDoc}
*/
@Override
public void printLongDesc(StringBuilder out) {
out.append("Initializes a Ballerina Project. \n");
out.append("\n");
out.append("Use --interactive or -i to create a ballerina project in interactive mode.\n");
}
/**
* {@inheritDoc}
*/
@Override
public void printUsage(StringBuilder out) {
out.append(" ballerina init [-i] \n");
}
/**
* {@inheritDoc}
*/
@Override
public void setParentCmdParser(CommandLine parentCmdParser) {
}
/**
* {@inheritDoc}
*/
@Override
public void setSelfCmdParser(CommandLine selfCmdParser) {
}
/**
* Validates the version is a semver version.
*
* @param versionAsString The version.
* @return True if valid version, else false.
*/
private boolean validateVersion(PrintStream out, String versionAsString) {
String semverRegex = "((?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*))";
boolean matches = Pattern.matches(semverRegex, versionAsString);
if (!matches) {
out.println("--Invalid version: \"" + versionAsString + "\"");
}
return matches;
}
private String guessOrgName() {
String guessOrgName = System.getProperty("user.name");
if (guessOrgName == null) {
guessOrgName = "my_org";
} else {
guessOrgName = guessOrgName.toLowerCase(Locale.getDefault());
}
return guessOrgName;
}
/**
* Validates the org-name.
*
* @param orgName The org-name.
* @return True if valid org-name, else false.
*/
private boolean validateOrgName(String orgName) {
if (RepoUtils.isReservedOrgName(orgName)) {
out.println("--Invalid organization name: \'" + orgName + "\'. 'ballerina' and 'ballerinax' are reserved " +
"organization names that are used by Ballerina");
return false;
}
boolean matches = RepoUtils.validateOrg(orgName);
if (!matches) {
out.println("--Invalid organization name: \'" + orgName + "\'. Organization name can only contain " +
"lowercase alphanumerics and underscores and the maximum length is 256 characters");
}
return matches;
}
/**
* Validates the module name.
*
* @param projectPath
* @param pkgName The module name.
* @return True if valid module name, else false.
*/
private boolean validatePkgName(Path projectPath, String pkgName) {
if (validateExistingModules(projectPath, pkgName)) {
return false;
}
if (pkgName.isEmpty()) {
return true;
}
boolean matches = RepoUtils.validatePkg(pkgName);
if (!matches) {
out.println("--Invalid module name: \'" + pkgName + "\'. Module name can only contain " +
"alphanumerics, underscores and periods and the maximum length is 256 characters");
}
return matches;
}
/**
* Find the project root by recursively up to the root.
*
* @param projectDir project path
* @return project root
*/
private Path findProjectRoot(Path projectDir) {
Path path = projectDir.resolve(ProjectDirConstants.DOT_BALLERINA_DIR_NAME);
if (!path.equals(homePath) && java.nio.file.Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
return projectDir;
}
Path parentsParent = projectDir.getParent();
if (null != parentsParent) {
return findProjectRoot(parentsParent);
}
return null;
}
/**
* Validate existing modules.
*
* @param projectPath project path
* @param moduleNames modules name
* @return if the module name already exists
*/
private boolean validateExistingModules(Path projectPath, String moduleNames) {
if (alreadyInitializedProject) {
List<Path> modules = new ArrayList<>();
try {
modules = Files.list(projectPath).map(Path::getFileName).collect(Collectors.toList());
} catch (IOException ignore) {
}
if (modules.contains(Paths.get(moduleNames))) {
out.println("Module already exists");
return true;
}
}
return false;
}
}
|
class InitCommand implements BLauncherCmd {
public static final String DEFAULT_VERSION = "0.0.1";
private static final String USER_DIR = "user.dir";
private static final PrintStream errStream = System.err;
private final Path homePath = RepoUtils.createAndGetHomeReposPath();
private boolean alreadyInitializedProject = false;
private boolean manifestExistInProject = false;
private PrintStream out = System.out;
@CommandLine.Option(names = {"--interactive", "-i"})
private boolean interactiveFlag;
@CommandLine.Option(names = {"--help", "-h"}, hidden = true)
private boolean helpFlag;
@Override
public void execute() {
Path projectPath = Paths.get(System.getProperty(USER_DIR));
try {
boolean isProject = Files.exists(projectPath.resolve(ProjectDirConstants.DOT_BALLERINA_DIR_NAME));
if (isProject) {
alreadyInitializedProject = true;
manifestExistInProject = Files.exists(projectPath.resolve(ProjectDirConstants.MANIFEST_FILE_NAME));
}
if (!alreadyInitializedProject) {
Optional<Path> childDotBallerina = Files.walk(projectPath)
.filter(path -> Files.isDirectory(path) &&
path.toFile().getName().equals(ProjectDirConstants.DOT_BALLERINA_DIR_NAME))
.findFirst();
if (childDotBallerina.isPresent()) {
errStream.println("A ballerina project is already initialized in " +
childDotBallerina.get().toFile().getParent());
return;
}
Path projectRoot = findProjectRoot(projectPath);
if (projectRoot != null) {
errStream.println("Directory is already within a ballerina project :" + projectRoot.toString());
return;
}
}
} catch (IOException ignore) {
}
Scanner scanner = new Scanner(System.in, Charset.defaultCharset().name());
try {
Manifest manifest = null;
if (helpFlag) {
String commandUsageInfo = BLauncherCmd.getCommandUsageInfo(INIT_COMMAND);
errStream.println(commandUsageInfo);
return;
}
List<SrcFile> sourceFiles = new ArrayList<>();
List<ModuleMdFile> moduleMdFiles = new ArrayList<>();
boolean validInput = false;
boolean firstPrompt = true;
if (interactiveFlag) {
if (!manifestExistInProject) {
out.print("Create Ballerina.toml [yes/y, no/n]: (y) ");
String createToml = scanner.nextLine().trim();
manifest = createManifest(scanner, createToml);
}
if (alreadyInitializedProject) {
out.print("Create modules [yes/y, no/n]: (y) ");
firstPrompt = false;
String input = scanner.nextLine().trim();
if (input.equalsIgnoreCase("n")) {
out.println("Ballerina project not reinitialized");
return;
}
}
String srcInput;
do {
if (firstPrompt) {
out.print("Ballerina source [service/s, main/m, finish/f]: (s) ");
} else {
out.print("Ballerina source [service/s, main/m, finish/f]: (f) ");
}
srcInput = scanner.nextLine().trim();
if (srcInput.equalsIgnoreCase("service") || srcInput.equalsIgnoreCase("s")
|| (srcInput.isEmpty() && firstPrompt)) {
String packageName;
do {
out.print("Module for the service: (no module) ");
packageName = scanner.nextLine().trim();
} while (!validatePkgName(projectPath, packageName));
SrcFile srcFile = new SrcFile(packageName, FileType.SERVICE);
sourceFiles.add(srcFile);
SrcFile srcTestFile = new SrcFile(packageName, FileType.SERVICE_TEST);
sourceFiles.add(srcTestFile);
if (!packageName.isEmpty()) {
ModuleMdFile moduleMdFile = new ModuleMdFile(packageName, FileType.SERVICE);
moduleMdFiles.add(moduleMdFile);
}
firstPrompt = false;
} else if (srcInput.equalsIgnoreCase("main") || srcInput.equalsIgnoreCase("m")) {
String packageName;
do {
out.print("Module for the main: (no module) ");
packageName = scanner.nextLine().trim();
} while (!validatePkgName(projectPath, packageName));
SrcFile srcFile = new SrcFile(packageName, FileType.MAIN);
sourceFiles.add(srcFile);
SrcFile srcTestFile = new SrcFile(packageName, FileType.MAIN_TEST);
sourceFiles.add(srcTestFile);
if (!packageName.isEmpty()) {
ModuleMdFile moduleMdFile = new ModuleMdFile(packageName, FileType.MAIN);
moduleMdFiles.add(moduleMdFile);
}
firstPrompt = false;
} else if (srcInput.isEmpty() || srcInput.equalsIgnoreCase("f") ||
srcInput.equalsIgnoreCase("finish")) {
validInput = true;
firstPrompt = false;
} else {
out.println("Invalid input");
}
} while (!validInput);
out.print("\n");
} else {
manifest = new Manifest();
manifest.setName(guessOrgName());
manifest.setVersion(DEFAULT_VERSION);
if (isDirEmpty(projectPath)) {
SrcFile srcFile = new SrcFile("", FileType.SERVICE);
sourceFiles.add(srcFile);
}
}
InitHandler.initialize(projectPath, manifest, sourceFiles, moduleMdFiles);
if (!alreadyInitializedProject) {
out.println("Ballerina project initialized");
} else {
out.println("Ballerina project reinitialized");
}
} catch (IOException e) {
out.println("Error occurred while creating project: " + e.getMessage());
}
}
/**
* Create a manifest object.
*
* @param scanner scanner object
* @param createToml create toml or not
* @return manifest object
*/
private Manifest createManifest(Scanner scanner, String createToml) {
Manifest manifest = new Manifest();
if (createToml.equalsIgnoreCase("yes") || createToml.equalsIgnoreCase("y")
|| createToml.isEmpty()) {
String defaultOrg = guessOrgName();
String orgName;
do {
out.print("Organization name: (" + defaultOrg + ") ");
orgName = scanner.nextLine().trim();
} while (!validateOrgName(orgName));
manifest.setName(orgName.isEmpty() ? defaultOrg : orgName);
String version;
do {
out.print("Version: (" + DEFAULT_VERSION + ") ");
version = scanner.nextLine().trim();
version = version.isEmpty() ? DEFAULT_VERSION : version;
} while (!validateVersion(out, version));
manifest.setVersion(version);
}
return manifest;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return INIT_COMMAND;
}
/**
* {@inheritDoc}
*/
@Override
public void printLongDesc(StringBuilder out) {
out.append("Initializes a Ballerina Project. \n");
out.append("\n");
out.append("Use --interactive or -i to create a ballerina project in interactive mode.\n");
}
/**
* {@inheritDoc}
*/
@Override
public void printUsage(StringBuilder out) {
out.append(" ballerina init [-i] \n");
}
/**
* {@inheritDoc}
*/
@Override
public void setParentCmdParser(CommandLine parentCmdParser) {
}
/**
* {@inheritDoc}
*/
@Override
public void setSelfCmdParser(CommandLine selfCmdParser) {
}
/**
* Validates the version is a semver version.
*
* @param versionAsString The version.
* @return True if valid version, else false.
*/
private boolean validateVersion(PrintStream out, String versionAsString) {
String semverRegex = "((?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*))";
boolean matches = Pattern.matches(semverRegex, versionAsString);
if (!matches) {
out.println("--Invalid version: \"" + versionAsString + "\"");
}
return matches;
}
private String guessOrgName() {
String guessOrgName = System.getProperty("user.name");
if (guessOrgName == null) {
guessOrgName = "my_org";
} else {
guessOrgName = guessOrgName.toLowerCase(Locale.getDefault());
}
return guessOrgName;
}
/**
* Validates the org-name.
*
* @param orgName The org-name.
* @return True if valid org-name, else false.
*/
private boolean validateOrgName(String orgName) {
if (RepoUtils.isReservedOrgName(orgName)) {
out.println("--Invalid organization name: \'" + orgName + "\'. 'ballerina' and 'ballerinax' are reserved " +
"organization names that are used by Ballerina");
return false;
}
boolean matches = RepoUtils.validateOrg(orgName);
if (!matches) {
out.println("--Invalid organization name: \'" + orgName + "\'. Organization name can only contain " +
"lowercase alphanumerics and underscores and the maximum length is 256 characters");
}
return matches;
}
/**
* Validates the module name.
*
* @param projectPath
* @param pkgName The module name.
* @return True if valid module name, else false.
*/
private boolean validatePkgName(Path projectPath, String pkgName) {
if (validateExistingModules(projectPath, pkgName)) {
return false;
}
if (pkgName.isEmpty()) {
return true;
}
boolean matches = RepoUtils.validatePkg(pkgName);
if (!matches) {
out.println("--Invalid module name: \'" + pkgName + "\'. Module name can only contain " +
"alphanumerics, underscores and periods and the maximum length is 256 characters");
}
return matches;
}
/**
* Find the project root by recursively up to the root.
*
* @param projectDir project path
* @return project root
*/
private Path findProjectRoot(Path projectDir) {
Path path = projectDir.resolve(ProjectDirConstants.DOT_BALLERINA_DIR_NAME);
if (!path.equals(homePath) && java.nio.file.Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
return projectDir;
}
Path parentsParent = projectDir.getParent();
if (null != parentsParent) {
return findProjectRoot(parentsParent);
}
return null;
}
/**
* Validate existing modules.
*
* @param projectPath project path
* @param moduleNames modules name
* @return if the module name already exists
*/
private boolean validateExistingModules(Path projectPath, String moduleNames) {
if (alreadyInitializedProject) {
List<Path> modules = new ArrayList<>();
try {
modules = Files.list(projectPath).map(Path::getFileName).collect(Collectors.toList());
} catch (IOException ignore) {
}
if (modules.contains(Paths.get(moduleNames))) {
out.println("Module already exists");
return true;
}
}
return false;
}
}
|
If you need to support functions not in the form of xx(), but fun(A, B) in the future, how do you need to be compatible?
|
public Expr obtainExpr() {
if (SUPPORTED_DEFAULT_FNS.contains(expr)) {
String functionName = expr.replace("()", "");
FunctionCallExpr functionCallExpr = new FunctionCallExpr(new FunctionName(functionName), Lists.newArrayList());
Function fn = Expr.getBuiltinFunction(functionName, new Type[] {}, Function.CompareMode.IS_IDENTICAL);
functionCallExpr.setFn(fn);
functionCallExpr.setType(fn.getReturnType());
return functionCallExpr;
}
return null;
}
|
String functionName = expr.replace("()", "");
|
public Expr obtainExpr() {
if (SUPPORTED_DEFAULT_FNS.contains(expr)) {
String functionName = expr.replace("()", "");
FunctionCallExpr functionCallExpr = new FunctionCallExpr(new FunctionName(functionName), Lists.newArrayList());
Function fn = Expr.getBuiltinFunction(functionName, new Type[] {}, Function.CompareMode.IS_IDENTICAL);
functionCallExpr.setFn(fn);
functionCallExpr.setType(fn.getReturnType());
return functionCallExpr;
}
return null;
}
|
class DefaultExpr {
public static final Set<String> SUPPORTED_DEFAULT_FNS = ImmutableSet.of("uuid()", "uuid_numeric()");
@SerializedName("expr")
private String expr;
public DefaultExpr(String expr) {
this.expr = expr;
}
public String getExpr() {
return expr;
}
public void setExpr(String expr) {
this.expr = expr;
}
}
|
class DefaultExpr {
public static final Set<String> SUPPORTED_DEFAULT_FNS = ImmutableSet.of("uuid()", "uuid_numeric()");
@SerializedName("expr")
private String expr;
public DefaultExpr(String expr) {
this.expr = expr;
}
public String getExpr() {
return expr;
}
public void setExpr(String expr) {
this.expr = expr;
}
}
|
Why are we setting a default page size here? Shouldn't this be handled by the creator of this type?
|
public ContinuablePagedIterable(ContinuablePagedFlux<C, T, P> pagedFlux, int batchSize) {
super(pagedFlux);
this.pagedFlux = pagedFlux;
this.batchSize = batchSize;
this.defaultPageSize = 1;
this.continuationPredicate = null;
this.syncPageRetrieverProvider = null;
}
|
this.defaultPageSize = 1;
|
public ContinuablePagedIterable(ContinuablePagedFlux<C, T, P> pagedFlux, int batchSize) {
super(pagedFlux);
this.pagedFlux = pagedFlux;
this.batchSize = batchSize;
this.defaultPageSize = null;
this.continuationPredicate = null;
this.pageRetrieverSyncProvider = null;
}
|
class ContinuablePagedIterable<C, T, P extends ContinuablePage<C, T>> extends IterableStream<T> {
private static final ClientLogger LOGGER = new ClientLogger(ContinuablePagedIterable.class);
private final ContinuablePagedFlux<C, T, P> pagedFlux;
private final int batchSize;
private final Supplier<SyncPageRetriever<C, P>> syncPageRetrieverProvider;
final Integer defaultPageSize;
private final Predicate<C> continuationPredicate;
/**
* Creates instance with the given {@link ContinuablePagedFlux}.
*
* @param pagedFlux the paged flux use as iterable
*/
public ContinuablePagedIterable(ContinuablePagedFlux<C, T, P> pagedFlux) {
this(pagedFlux, 1);
}
/**
* Creates instance with the given {@link ContinuablePagedFlux}.
*
* @param pagedFlux the paged flux use as iterable
* @param batchSize the bounded capacity to prefetch from the {@link ContinuablePagedFlux}
*/
/**
* Creates instance with the given {@link SyncPageRetriever provider}.
*
* @param syncPageRetrieverProvider A provider that returns {@link SyncPageRetriever}.
* @param pageSize The preferred page size.
* @param continuationPredicate A predicate which determines if paging should continue.
* @throws NullPointerException If {@code syncPageRetrieverProvider} is null.
* @throws IllegalArgumentException If {@code pageSize} is not null and is less than or equal to zero.
*/
public ContinuablePagedIterable(Supplier<SyncPageRetriever<C, P>> syncPageRetrieverProvider, Integer pageSize,
Predicate<C> continuationPredicate) {
super(new ContinuablePagedByItemIterable<>(syncPageRetrieverProvider.get(), null,
continuationPredicate, pageSize));
this.syncPageRetrieverProvider = Objects.requireNonNull(syncPageRetrieverProvider,
"'syncPageRetrieverProvider' function cannot be null.");
if (pageSize != null && pageSize <= 0) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'pageSize' must be greater than 0 required but provided: " + pageSize));
}
this.continuationPredicate = continuationPredicate;
this.defaultPageSize = pageSize;
this.pagedFlux = null;
this.batchSize = 1;
}
@Override
public Stream<T> stream() {
return StreamSupport.stream(iterableByItemInternal().spliterator(), false);
}
/**
* Retrieve the {@link Stream}, one page at a time. It will provide same {@link Stream} of T values from starting if
* called multiple times.
*
* @return {@link Stream} of a pages
*/
public Stream<P> streamByPage() {
return streamByPageInternal(null, null, () -> this.pagedFlux.byPage().toStream(batchSize));
}
/**
* Retrieve the {@link Stream}, one page at a time, starting from the next page associated with the given
* continuation token. To start from first page, use {@link
*
* @param continuationToken The continuation token used to fetch the next page
* @return {@link Stream} of a pages
*/
public Stream<P> streamByPage(C continuationToken) {
return streamByPageInternal(continuationToken, null,
() -> this.pagedFlux.byPage(continuationToken).toStream(batchSize));
}
/**
* Retrieve the {@link Stream}, one page at a time, with each page containing {@code preferredPageSize} items.
*
* It will provide same {@link Stream} of T values from starting if called multiple times.
*
* @param preferredPageSize the preferred page size, service may or may not honor the page size preference hence
* client MUST be prepared to handle pages with different page size.
* @return {@link Stream} of a pages
*/
public Stream<P> streamByPage(int preferredPageSize) {
return streamByPageInternal(null, preferredPageSize,
() -> this.pagedFlux.byPage(preferredPageSize).toStream(batchSize));
}
/**
* Retrieve the {@link Stream}, one page at a time, with each page containing {@code preferredPageSize} items,
* starting from the next page associated with the given continuation token. To start from first page, use {@link
*
*
* @param preferredPageSize the preferred page size, service may or may not honor the page size preference hence
* client MUST be prepared to handle pages with different page size.
* @param continuationToken The continuation token used to fetch the next page
* @return {@link Stream} of a pages
*/
public Stream<P> streamByPage(C continuationToken, int preferredPageSize) {
return streamByPageInternal(continuationToken, preferredPageSize,
() -> this.pagedFlux.byPage(continuationToken, preferredPageSize).toStream(batchSize));
}
@Override
public Iterator<T> iterator() {
return iterableByItemInternal().iterator();
}
/**
* Retrieve the {@link Iterable}, one page at a time. It will provide same {@link Iterable} of T values from
* starting if called multiple times.
*
* @return {@link Stream} of a pages
*/
public Iterable<P> iterableByPage() {
return iterableByPageInternal(null, null, () -> this.pagedFlux.byPage().toIterable(batchSize));
}
/**
* Retrieve the {@link Iterable}, one page at a time, starting from the next page associated with the given
* continuation token. To start from first page, use {@link
*
* @param continuationToken The continuation token used to fetch the next page
* @return {@link Iterable} of a pages
*/
public Iterable<P> iterableByPage(C continuationToken) {
return iterableByPageInternal(continuationToken, null,
() -> this.pagedFlux.byPage(continuationToken).toIterable(batchSize));
}
/**
* Retrieve the {@link Iterable}, one page at a time, with each page containing {@code preferredPageSize} items.
*
* It will provide same {@link Iterable} of T values from starting if called multiple times.
*
* @param preferredPageSize the preferred page size, service may or may not honor the page size preference hence
* client MUST be prepared to handle pages with different page size.
* @return {@link Iterable} of a pages
*/
public Iterable<P> iterableByPage(int preferredPageSize) {
return iterableByPageInternal(null, preferredPageSize,
() -> this.pagedFlux.byPage(preferredPageSize).toIterable(batchSize));
}
/**
* Retrieve the {@link Iterable}, one page at a time, with each page containing {@code preferredPageSize} items,
* starting from the next page associated with the given continuation token. To start from first page, use {@link
*
*
* @param preferredPageSize the preferred page size, service may or may not honor the page size preference hence
* client MUST be prepared to handle pages with different page size.
* @param continuationToken The continuation token used to fetch the next page
* @return {@link Iterable} of a pages
*/
public Iterable<P> iterableByPage(C continuationToken, int preferredPageSize) {
return iterableByPageInternal(continuationToken, preferredPageSize,
() -> this.pagedFlux.byPage(continuationToken, preferredPageSize).toIterable(batchSize));
}
private Stream<P> streamByPageInternal(C continuationToken, Integer preferredPageSize,
Supplier<Stream<P>> nonPagedFluxCoreIterableSupplier) {
if (pagedFlux == null) {
return StreamSupport.stream(iterableByPageInternal(continuationToken, preferredPageSize, null)
.spliterator(), false);
}
if (pagedFlux instanceof ContinuablePagedFluxCore) {
return StreamSupport.stream(iterableByPageInternal(continuationToken, preferredPageSize, null)
.spliterator(), false);
} else {
return nonPagedFluxCoreIterableSupplier.get();
}
}
private Iterable<P> iterableByPageInternal(C continuationToken, Integer preferredPageSize,
Supplier<Iterable<P>> nonPagedFluxCoreIterableSupplier) {
if (pagedFlux == null) {
return new ContinuablePagedByPageIterable<>(syncPageRetrieverProvider.get(), continuationToken,
this.continuationPredicate, preferredPageSize);
}
if (pagedFlux instanceof ContinuablePagedFluxCore) {
ContinuablePagedFluxCore<C, T, P> pagedFluxCore = (ContinuablePagedFluxCore<C, T, P>) pagedFlux;
return new ContinuablePagedByPageIterable<>(pagedFluxCore.pageRetrieverProvider.get(), continuationToken,
pagedFluxCore.getContinuationPredicate(), preferredPageSize);
} else {
return nonPagedFluxCoreIterableSupplier.get();
}
}
private Iterable<T> iterableByItemInternal() {
if (pagedFlux == null) {
return new ContinuablePagedByItemIterable<>(this.syncPageRetrieverProvider.get(), null,
this.continuationPredicate, null);
}
if (pagedFlux instanceof ContinuablePagedFluxCore) {
ContinuablePagedFluxCore<C, T, P> pagedFluxCore = (ContinuablePagedFluxCore<C, T, P>) pagedFlux;
return new ContinuablePagedByItemIterable<>(pagedFluxCore.pageRetrieverProvider.get(), null,
pagedFluxCore.getContinuationPredicate(), null);
} else {
return this.pagedFlux.toIterable(this.batchSize);
}
}
}
|
class ContinuablePagedIterable<C, T, P extends ContinuablePage<C, T>> extends IterableStream<T> {
private static final ClientLogger LOGGER = new ClientLogger(ContinuablePagedIterable.class);
private final ContinuablePagedFlux<C, T, P> pagedFlux;
private final int batchSize;
private final Supplier<PageRetrieverSync<C, P>> pageRetrieverSyncProvider;
final Integer defaultPageSize;
private final Predicate<C> continuationPredicate;
/**
* Creates instance with the given {@link ContinuablePagedFlux}.
*
* @param pagedFlux the paged flux use as iterable
*/
public ContinuablePagedIterable(ContinuablePagedFlux<C, T, P> pagedFlux) {
this(pagedFlux, 1);
}
/**
* Creates instance with the given {@link ContinuablePagedFlux}.
*
* @param pagedFlux the paged flux use as iterable
* @param batchSize the bounded capacity to prefetch from the {@link ContinuablePagedFlux}
*/
/**
* Creates instance with the given {@link PageRetrieverSync provider}.
*
* @param pageRetrieverSyncProvider A provider that returns {@link PageRetrieverSync}.
* @param pageSize The preferred page size.
* @param continuationPredicate A predicate which determines if paging should continue.
* @throws NullPointerException If {@code pageRetrieverSyncProvider} is null.
* @throws IllegalArgumentException If {@code pageSize} is not null and is less than or equal to zero.
*/
public ContinuablePagedIterable(Supplier<PageRetrieverSync<C, P>> pageRetrieverSyncProvider, Integer pageSize,
Predicate<C> continuationPredicate) {
super(new ContinuablePagedByItemIterable<>(pageRetrieverSyncProvider.get(), null,
continuationPredicate, pageSize));
this.pageRetrieverSyncProvider = Objects.requireNonNull(pageRetrieverSyncProvider,
"'pageRetrieverSyncProvider' function cannot be null.");
if (pageSize != null && pageSize <= 0) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'pageSize' must be greater than 0 required but provided: " + pageSize));
}
this.continuationPredicate = (continuationPredicate == null) ? Objects::nonNull : continuationPredicate;
this.defaultPageSize = pageSize;
this.batchSize = 1;
this.pagedFlux = null;
}
@Override
public Stream<T> stream() {
return StreamSupport.stream(iterableByItemInternal().spliterator(), false);
}
/**
* Retrieve the {@link Stream}, one page at a time. It will provide same {@link Stream} of T values from starting if
* called multiple times.
*
* @return {@link Stream} of a pages
*/
public Stream<P> streamByPage() {
return streamByPageInternal(null, null, () -> this.pagedFlux.byPage().toStream(batchSize));
}
/**
* Retrieve the {@link Stream}, one page at a time, starting from the next page associated with the given
* continuation token. To start from first page, use {@link
*
* @param continuationToken The continuation token used to fetch the next page
* @return {@link Stream} of a pages
*/
public Stream<P> streamByPage(C continuationToken) {
return streamByPageInternal(continuationToken, null,
() -> this.pagedFlux.byPage(continuationToken).toStream(batchSize));
}
/**
* Retrieve the {@link Stream}, one page at a time, with each page containing {@code preferredPageSize} items.
*
* It will provide same {@link Stream} of T values from starting if called multiple times.
*
* @param preferredPageSize the preferred page size, service may or may not honor the page size preference hence
* client MUST be prepared to handle pages with different page size.
* @return {@link Stream} of a pages
*/
public Stream<P> streamByPage(int preferredPageSize) {
return streamByPageInternal(null, preferredPageSize,
() -> this.pagedFlux.byPage(preferredPageSize).toStream(batchSize));
}
/**
* Retrieve the {@link Stream}, one page at a time, with each page containing {@code preferredPageSize} items,
* starting from the next page associated with the given continuation token. To start from first page, use {@link
*
*
* @param preferredPageSize the preferred page size, service may or may not honor the page size preference hence
* client MUST be prepared to handle pages with different page size.
* @param continuationToken The continuation token used to fetch the next page
* @return {@link Stream} of a pages
*/
public Stream<P> streamByPage(C continuationToken, int preferredPageSize) {
return streamByPageInternal(continuationToken, preferredPageSize,
() -> this.pagedFlux.byPage(continuationToken, preferredPageSize).toStream(batchSize));
}
@Override
public Iterator<T> iterator() {
return iterableByItemInternal().iterator();
}
/**
* Retrieve the {@link Iterable}, one page at a time. It will provide same {@link Iterable} of T values from
* starting if called multiple times.
*
* @return {@link Stream} of a pages
*/
public Iterable<P> iterableByPage() {
return iterableByPageInternal(null, null, () -> this.pagedFlux.byPage().toIterable(batchSize));
}
/**
* Retrieve the {@link Iterable}, one page at a time, starting from the next page associated with the given
* continuation token. To start from first page, use {@link
*
* @param continuationToken The continuation token used to fetch the next page
* @return {@link Iterable} of a pages
*/
public Iterable<P> iterableByPage(C continuationToken) {
return iterableByPageInternal(continuationToken, null,
() -> this.pagedFlux.byPage(continuationToken).toIterable(batchSize));
}
/**
* Retrieve the {@link Iterable}, one page at a time, with each page containing {@code preferredPageSize} items.
*
* It will provide same {@link Iterable} of T values from starting if called multiple times.
*
* @param preferredPageSize the preferred page size, service may or may not honor the page size preference hence
* client MUST be prepared to handle pages with different page size.
* @return {@link Iterable} of a pages
*/
public Iterable<P> iterableByPage(int preferredPageSize) {
return iterableByPageInternal(null, preferredPageSize,
() -> this.pagedFlux.byPage(preferredPageSize).toIterable(batchSize));
}
/**
* Retrieve the {@link Iterable}, one page at a time, with each page containing {@code preferredPageSize} items,
* starting from the next page associated with the given continuation token. To start from first page, use {@link
*
*
* @param preferredPageSize the preferred page size, service may or may not honor the page size preference hence
* client MUST be prepared to handle pages with different page size.
* @param continuationToken The continuation token used to fetch the next page
* @return {@link Iterable} of a pages
*/
public Iterable<P> iterableByPage(C continuationToken, int preferredPageSize) {
return iterableByPageInternal(continuationToken, preferredPageSize,
() -> this.pagedFlux.byPage(continuationToken, preferredPageSize).toIterable(batchSize));
}
private Stream<P> streamByPageInternal(C continuationToken, Integer preferredPageSize,
Supplier<Stream<P>> nonPagedFluxCoreIterableSupplier) {
if (pagedFlux == null) {
return StreamSupport.stream(iterableByPageInternal(continuationToken, preferredPageSize, null)
.spliterator(), false);
}
if (pagedFlux instanceof ContinuablePagedFluxCore) {
return StreamSupport.stream(iterableByPageInternal(continuationToken, preferredPageSize, null)
.spliterator(), false);
} else {
return nonPagedFluxCoreIterableSupplier.get();
}
}
private Iterable<P> iterableByPageInternal(C continuationToken, Integer preferredPageSize,
Supplier<Iterable<P>> nonPagedFluxCoreIterableSupplier) {
if (pagedFlux == null) {
return new ContinuablePagedByPageIterable<>(pageRetrieverSyncProvider.get(), continuationToken,
this.continuationPredicate, preferredPageSize);
}
if (pagedFlux instanceof ContinuablePagedFluxCore) {
ContinuablePagedFluxCore<C, T, P> pagedFluxCore = (ContinuablePagedFluxCore<C, T, P>) pagedFlux;
return new ContinuablePagedByPageIterable<>(pagedFluxCore.pageRetrieverProvider.get(), continuationToken,
pagedFluxCore.getContinuationPredicate(), preferredPageSize);
} else {
return nonPagedFluxCoreIterableSupplier.get();
}
}
private Iterable<T> iterableByItemInternal() {
if (pagedFlux == null) {
return new ContinuablePagedByItemIterable<>(this.pageRetrieverSyncProvider.get(), null,
this.continuationPredicate, null);
}
if (pagedFlux instanceof ContinuablePagedFluxCore) {
ContinuablePagedFluxCore<C, T, P> pagedFluxCore = (ContinuablePagedFluxCore<C, T, P>) pagedFlux;
return new ContinuablePagedByItemIterable<>(pagedFluxCore.pageRetrieverProvider.get(), null,
pagedFluxCore.getContinuationPredicate(), null);
} else {
return this.pagedFlux.toIterable(this.batchSize);
}
}
}
|
@pubudu538 ATM T1 values are all capital. eg: `ARRAY`. Shall we make it like `Array`?
|
private String getTypeErrorMessage(Type found) {
Map<String, String> message = this.schema.message();
String typeCustomMessage = message.get(SchemaDeserializer.TYPE);
if (typeCustomMessage == null) {
return String.format("key '%s' expects %s . found %s", this.key, schema.type(), found);
}
return typeCustomMessage;
}
|
return String.format("key '%s' expects %s . found %s", this.key, schema.type(), found);
|
private String getTypeErrorMessage(Type found) {
Map<String, String> message = this.schema.message();
String typeCustomMessage = message.get(SchemaDeserializer.TYPE);
if (typeCustomMessage == null) {
return String.format("incompatible type for key '%s': expected '%s', found '%s'", this.key, schema.type(),
found);
}
return typeCustomMessage;
}
|
class SchemaValidator extends TomlNodeVisitor {
private static final String PROPERTY_HOLDER = "${property}";
private AbstractSchema schema;
private String key;
public SchemaValidator(Schema schema) {
this.schema = schema;
}
@Override
public void visit(TomlTableNode tomlTableNode) {
if (schema.type() != Type.OBJECT) {
TomlDiagnostic diagnostic = getTomlDiagnostic(tomlTableNode.location(), "TVE0002", "error.invalid.type",
DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.OBJECT));
tomlTableNode.addDiagnostic(diagnostic);
return;
}
Schema objectSchema = (Schema) schema;
Map<String, AbstractSchema> properties = objectSchema.properties();
List<String> requiredFields = getRequiredFields(objectSchema);
Map<String, TopLevelNode> tableEntries = tomlTableNode.entries();
for (Map.Entry<String, TopLevelNode> tableEntry : tableEntries.entrySet()) {
String key = tableEntry.getKey();
requiredFields.remove(key);
TopLevelNode value = tableEntry.getValue();
AbstractSchema schema = properties.get(key);
if (schema != null) {
visitNode(value, schema, key);
continue;
}
if (!objectSchema.hasAdditionalProperties()) {
DiagnosticInfo diagnosticInfo = new DiagnosticInfo("TVE0001", "error.unexpected.property",
DiagnosticSeverity.ERROR);
TomlDiagnostic diagnostic = new TomlDiagnostic(value.location(), diagnosticInfo,
getUnexpectedPropertyErrorMessage(key));
tomlTableNode.addDiagnostic(diagnostic);
}
}
for (String field : requiredFields) {
DiagnosticInfo diagnosticInfo = new DiagnosticInfo("TVE0006", "error.required.field.missing",
DiagnosticSeverity.ERROR);
TomlDiagnostic diagnostic = new TomlDiagnostic(tomlTableNode.location(), diagnosticInfo,
getRequiredErrorMessage(field));
tomlTableNode.addDiagnostic(diagnostic);
}
}
private String getRequiredErrorMessage(String field) {
Map<String, String> message = this.schema.message();
String typeCustomMessage = message.get(SchemaDeserializer.REQUIRED);
if (typeCustomMessage == null) {
return "missing required field '" + field + "'";
}
return typeCustomMessage.replace(PROPERTY_HOLDER, field);
}
private String getUnexpectedPropertyErrorMessage(String key) {
Map<String, String> message = this.schema.message();
String typeCustomMessage = message.get(SchemaDeserializer.ADDITIONAL_PROPERTIES);
if (typeCustomMessage == null) {
return "unexpected property '" + key + "'";
}
return typeCustomMessage.replace(PROPERTY_HOLDER, key);
}
@Override
public void visit(TomlTableArrayNode tomlTableArrayNode) {
if (schema.type() != Type.ARRAY) {
TomlDiagnostic diagnostic =
getTomlDiagnostic(tomlTableArrayNode.location(), "TVE0002", "error.invalid.type",
DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.ARRAY));
tomlTableArrayNode.addDiagnostic(diagnostic);
return;
}
ArraySchema arraySchema = (ArraySchema) schema;
AbstractSchema memberSchema = arraySchema.items();
List<TomlTableNode> children = tomlTableArrayNode.children();
for (TomlTableNode child : children) {
visitNode(child, memberSchema);
}
}
@Override
public void visit(TomlKeyValueNode keyValue) {
TomlValueNode value = keyValue.value();
visitNode(value);
}
@Override
public void visit(TomlValueNode tomlValue) {
visitNode(tomlValue);
}
private String getPatternErrorMessage(String pattern) {
Map<String, String> message = this.schema.message();
String typeCustomMessage = message.get(SchemaDeserializer.PATTERN);
if (typeCustomMessage == null) {
return String.format("key '%s' value does not match the regex provided in schema %s", this.key,
pattern);
}
return typeCustomMessage;
}
@Override
public void visit(TomlStringValueNode tomlStringValueNode) {
if (schema.type() != Type.STRING) {
TomlDiagnostic diagnostic =
getTomlDiagnostic(tomlStringValueNode.location(), "TVE0002", "error.invalid.type",
DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.STRING));
tomlStringValueNode.addDiagnostic(diagnostic);
return;
}
StringSchema stringSchema = (StringSchema) this.schema;
if (stringSchema.pattern().isPresent()) {
String pattern = stringSchema.pattern().get();
if (!Pattern.compile(pattern).matcher(tomlStringValueNode.getValue()).matches()) {
TomlDiagnostic diagnostic = getTomlDiagnostic(tomlStringValueNode.location(), "TVE0003",
"error.regex.mismatch", DiagnosticSeverity.ERROR, getPatternErrorMessage(pattern));
tomlStringValueNode.addDiagnostic(diagnostic);
}
}
}
@Override
public void visit(TomlDoubleValueNodeNode tomlDoubleValueNodeNode) {
if (schema.type() != Type.NUMBER) {
TomlDiagnostic diagnostic = getTomlDiagnostic(tomlDoubleValueNodeNode.location(), "TVE0002",
"error.invalid.type", DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.NUMBER));
tomlDoubleValueNodeNode.addDiagnostic(diagnostic);
return;
}
List<Diagnostic> diagnostics = validateMinMaxValues((NumericSchema) schema, tomlDoubleValueNodeNode.getValue(),
tomlDoubleValueNodeNode.location());
tomlDoubleValueNodeNode.addDiagnostics(diagnostics);
}
@Override
public void visit(TomlLongValueNode tomlLongValueNode) {
if (schema.type() != Type.INTEGER) {
TomlDiagnostic diagnostic = getTomlDiagnostic(tomlLongValueNode.location(), "TVE0002",
"error.invalid.type", DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.INTEGER));
tomlLongValueNode.addDiagnostic(diagnostic);
return;
}
List<Diagnostic> diagnostics =
validateMinMaxValues((NumericSchema) schema, Double.valueOf(tomlLongValueNode.getValue()),
tomlLongValueNode.location());
for (Diagnostic diagnostic : diagnostics) {
tomlLongValueNode.addDiagnostic(diagnostic);
}
}
@Override
public void visit(TomlArrayValueNode tomlArrayValueNode) {
if (schema.type() != Type.ARRAY) {
TomlDiagnostic diagnostic =
getTomlDiagnostic(tomlArrayValueNode.location(), "TVE0002", "error.invalid.type",
DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.ARRAY));
tomlArrayValueNode.addDiagnostic(diagnostic);
return;
}
ArraySchema arraySchema = (ArraySchema) schema;
AbstractSchema items = arraySchema.items();
for (TomlValueNode valueNode : tomlArrayValueNode.elements()) {
visitNode(valueNode, items);
}
}
private String getMaxValueExceedErrorMessage(Double max) {
Map<String, String> message = this.schema.message();
String maxCustomMessage = message.get(SchemaDeserializer.MAXIMUM);
if (maxCustomMessage == null) {
return String.format("key '%s' value can't be higher than %f", this.key,
max);
}
return maxCustomMessage;
}
private String getMinValueDeceedErrorMessage(Double min) {
Map<String, String> message = this.schema.message();
String minCustomMessage = message.get(SchemaDeserializer.MINIMUM);
if (minCustomMessage == null) {
return String.format("key '%s' value can't be lower than %f", this.key,
min);
}
return minCustomMessage;
}
private List<Diagnostic> validateMinMaxValues(NumericSchema numericSchema, Double value,
TomlNodeLocation location) {
List<Diagnostic> diagnostics = new ArrayList<>();
if (numericSchema.maximum().isPresent()) {
Double max = numericSchema.maximum().get();
if (value > max) {
TomlDiagnostic diagnostic = getTomlDiagnostic(location, "TVE0005", "error" +
".maximum.value.exceed", DiagnosticSeverity.ERROR, getMaxValueExceedErrorMessage(max));
diagnostics.add(diagnostic);
}
}
if (numericSchema.minimum().isPresent()) {
Double min = numericSchema.minimum().get();
if (value < min) {
TomlDiagnostic diagnostic = getTomlDiagnostic(location, "TVE0004", "error.minimum.value.deceed",
DiagnosticSeverity.ERROR, getMinValueDeceedErrorMessage(min));
diagnostics.add(diagnostic);
}
}
return diagnostics;
}
@Override
public void visit(TomlBooleanValueNode tomlBooleanValueNode) {
if (schema.type() != Type.BOOLEAN) {
TomlDiagnostic diagnostic = getTomlDiagnostic(tomlBooleanValueNode.location(), "TVE0002",
"error.invalid.type", DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.BOOLEAN));
tomlBooleanValueNode.addDiagnostic(diagnostic);
}
}
private void visitNode(TomlNode node) {
AbstractSchema previousSchema = this.schema;
String previousKey = this.key;
node.accept(this);
this.schema = previousSchema;
this.key = previousKey;
}
private void visitNode(TomlNode node, AbstractSchema schema) {
AbstractSchema previousSchema = this.schema;
this.schema = schema;
node.accept(this);
this.schema = previousSchema;
}
private void visitNode(TomlNode node, AbstractSchema schema, String key) {
AbstractSchema previousSchema = this.schema;
String previousKey = this.key;
this.schema = schema;
this.key = key;
node.accept(this);
this.schema = previousSchema;
this.key = previousKey;
}
private TomlDiagnostic getTomlDiagnostic(TomlNodeLocation location, String code, String template,
DiagnosticSeverity severity, String message) {
DiagnosticInfo diagnosticInfo = new DiagnosticInfo(code, template, severity);
return new TomlDiagnostic(location, diagnosticInfo, message);
}
private List<String> getRequiredFields(Schema objectSchema) {
if (objectSchema.required() == null) {
return new ArrayList<>();
}
return objectSchema.required();
}
}
|
class SchemaValidator extends TomlNodeVisitor {
private static final String PROPERTY_HOLDER = "${property}";
private AbstractSchema schema;
private String key;
private String schemaTitle;
public SchemaValidator(Schema schema) {
this.schema = schema;
this.schemaTitle = schema.title();
}
@Override
public void visit(TomlTableNode tomlTableNode) {
if (schema.type() != Type.OBJECT) {
TomlDiagnostic diagnostic = getTomlDiagnostic(tomlTableNode.location(), "TVE0002", "error.invalid.type",
DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.OBJECT));
tomlTableNode.addDiagnostic(diagnostic);
return;
}
Schema objectSchema = (Schema) schema;
Map<String, AbstractSchema> properties = objectSchema.properties();
List<String> requiredFields = getRequiredFields(objectSchema);
Map<String, TopLevelNode> tableEntries = tomlTableNode.entries();
for (Map.Entry<String, TopLevelNode> tableEntry : tableEntries.entrySet()) {
String key = tableEntry.getKey();
requiredFields.remove(key);
TopLevelNode value = tableEntry.getValue();
AbstractSchema schema = properties.get(key);
if (schema != null) {
visitNode(value, schema, key);
continue;
}
if (!objectSchema.hasAdditionalProperties()) {
DiagnosticInfo diagnosticInfo = new DiagnosticInfo("TVE0001", "error.unexpected.property",
DiagnosticSeverity.ERROR);
TomlDiagnostic diagnostic = new TomlDiagnostic(value.location(), diagnosticInfo,
getUnexpectedPropertyErrorMessage(key));
tomlTableNode.addDiagnostic(diagnostic);
}
}
for (String field : requiredFields) {
DiagnosticInfo diagnosticInfo = new DiagnosticInfo("TVE0006", "error.required.field.missing",
DiagnosticSeverity.ERROR);
TomlDiagnostic diagnostic = new TomlDiagnostic(tomlTableNode.location(), diagnosticInfo,
getRequiredErrorMessage(field));
tomlTableNode.addDiagnostic(diagnostic);
}
}
private String getRequiredErrorMessage(String field) {
Map<String, String> message = this.schema.message();
String typeCustomMessage = message.get(SchemaDeserializer.REQUIRED);
if (typeCustomMessage == null) {
return "missing required field '" + field + "'";
}
return typeCustomMessage.replace(PROPERTY_HOLDER, field);
}
private String getUnexpectedPropertyErrorMessage(String key) {
Map<String, String> message = this.schema.message();
String typeCustomMessage = message.get(SchemaDeserializer.ADDITIONAL_PROPERTIES);
if (typeCustomMessage == null) {
return String.format("key '%s' not supported in schema '%s'", key, schemaTitle);
}
return typeCustomMessage.replace(PROPERTY_HOLDER, key);
}
@Override
public void visit(TomlTableArrayNode tomlTableArrayNode) {
if (schema.type() != Type.ARRAY) {
TomlDiagnostic diagnostic =
getTomlDiagnostic(tomlTableArrayNode.location(), "TVE0002", "error.invalid.type",
DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.ARRAY));
tomlTableArrayNode.addDiagnostic(diagnostic);
return;
}
ArraySchema arraySchema = (ArraySchema) schema;
AbstractSchema memberSchema = arraySchema.items();
List<TomlTableNode> children = tomlTableArrayNode.children();
for (TomlTableNode child : children) {
visitNode(child, memberSchema);
}
}
@Override
public void visit(TomlKeyValueNode keyValue) {
TomlValueNode value = keyValue.value();
visitNode(value);
}
@Override
public void visit(TomlValueNode tomlValue) {
visitNode(tomlValue);
}
private String getPatternErrorMessage(String pattern) {
Map<String, String> message = this.schema.message();
String typeCustomMessage = message.get(SchemaDeserializer.PATTERN);
if (typeCustomMessage == null) {
return String.format("value for key '%s' expected to match the regex: %s", this.key, pattern);
}
return typeCustomMessage;
}
@Override
public void visit(TomlStringValueNode tomlStringValueNode) {
if (schema.type() != Type.STRING) {
TomlDiagnostic diagnostic =
getTomlDiagnostic(tomlStringValueNode.location(), "TVE0002", "error.invalid.type",
DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.STRING));
tomlStringValueNode.addDiagnostic(diagnostic);
return;
}
StringSchema stringSchema = (StringSchema) this.schema;
if (stringSchema.pattern().isPresent()) {
String pattern = stringSchema.pattern().get();
if (!Pattern.compile(pattern).matcher(tomlStringValueNode.getValue()).matches()) {
TomlDiagnostic diagnostic = getTomlDiagnostic(tomlStringValueNode.location(), "TVE0003",
"error.regex.mismatch", DiagnosticSeverity.ERROR, getPatternErrorMessage(pattern));
tomlStringValueNode.addDiagnostic(diagnostic);
}
}
}
@Override
public void visit(TomlDoubleValueNodeNode tomlDoubleValueNodeNode) {
if (schema.type() != Type.NUMBER) {
TomlDiagnostic diagnostic = getTomlDiagnostic(tomlDoubleValueNodeNode.location(), "TVE0002",
"error.invalid.type", DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.NUMBER));
tomlDoubleValueNodeNode.addDiagnostic(diagnostic);
return;
}
List<Diagnostic> diagnostics = validateMinMaxValues((NumericSchema) schema, tomlDoubleValueNodeNode.getValue(),
tomlDoubleValueNodeNode.location());
tomlDoubleValueNodeNode.addDiagnostics(diagnostics);
}
@Override
public void visit(TomlLongValueNode tomlLongValueNode) {
if (schema.type() != Type.INTEGER) {
TomlDiagnostic diagnostic = getTomlDiagnostic(tomlLongValueNode.location(), "TVE0002",
"error.invalid.type", DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.INTEGER));
tomlLongValueNode.addDiagnostic(diagnostic);
return;
}
List<Diagnostic> diagnostics =
validateMinMaxValues((NumericSchema) schema, Double.valueOf(tomlLongValueNode.getValue()),
tomlLongValueNode.location());
for (Diagnostic diagnostic : diagnostics) {
tomlLongValueNode.addDiagnostic(diagnostic);
}
}
@Override
public void visit(TomlArrayValueNode tomlArrayValueNode) {
if (schema.type() != Type.ARRAY) {
TomlDiagnostic diagnostic =
getTomlDiagnostic(tomlArrayValueNode.location(), "TVE0002", "error.invalid.type",
DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.ARRAY));
tomlArrayValueNode.addDiagnostic(diagnostic);
return;
}
ArraySchema arraySchema = (ArraySchema) schema;
AbstractSchema items = arraySchema.items();
for (TomlValueNode valueNode : tomlArrayValueNode.elements()) {
visitNode(valueNode, items);
}
}
private String getMaxValueExceedErrorMessage(Double max) {
Map<String, String> message = this.schema.message();
String maxCustomMessage = message.get(SchemaDeserializer.MAXIMUM);
if (maxCustomMessage == null) {
return String.format("value for key '%s' can't be higher than %f", this.key,
max);
}
return maxCustomMessage;
}
private String getMinValueDeceedErrorMessage(Double min) {
Map<String, String> message = this.schema.message();
String minCustomMessage = message.get(SchemaDeserializer.MINIMUM);
if (minCustomMessage == null) {
return String.format("value for key '%s' can't be lower than %f", this.key,
min);
}
return minCustomMessage;
}
private List<Diagnostic> validateMinMaxValues(NumericSchema numericSchema, Double value,
TomlNodeLocation location) {
List<Diagnostic> diagnostics = new ArrayList<>();
if (numericSchema.maximum().isPresent()) {
Double max = numericSchema.maximum().get();
if (value > max) {
TomlDiagnostic diagnostic = getTomlDiagnostic(location, "TVE0005", "error" +
".maximum.value.exceed", DiagnosticSeverity.ERROR, getMaxValueExceedErrorMessage(max));
diagnostics.add(diagnostic);
}
}
if (numericSchema.minimum().isPresent()) {
Double min = numericSchema.minimum().get();
if (value < min) {
TomlDiagnostic diagnostic = getTomlDiagnostic(location, "TVE0004", "error.minimum.value.deceed",
DiagnosticSeverity.ERROR, getMinValueDeceedErrorMessage(min));
diagnostics.add(diagnostic);
}
}
return diagnostics;
}
@Override
public void visit(TomlBooleanValueNode tomlBooleanValueNode) {
if (schema.type() != Type.BOOLEAN) {
TomlDiagnostic diagnostic = getTomlDiagnostic(tomlBooleanValueNode.location(), "TVE0002",
"error.invalid.type", DiagnosticSeverity.ERROR, getTypeErrorMessage(Type.BOOLEAN));
tomlBooleanValueNode.addDiagnostic(diagnostic);
}
}
private void visitNode(TomlNode node) {
AbstractSchema previousSchema = this.schema;
String previousKey = this.key;
node.accept(this);
this.schema = previousSchema;
this.key = previousKey;
}
private void visitNode(TomlNode node, AbstractSchema schema) {
AbstractSchema previousSchema = this.schema;
this.schema = schema;
node.accept(this);
this.schema = previousSchema;
}
private void visitNode(TomlNode node, AbstractSchema schema, String key) {
AbstractSchema previousSchema = this.schema;
String previousKey = this.key;
this.schema = schema;
this.key = key;
node.accept(this);
this.schema = previousSchema;
this.key = previousKey;
}
private TomlDiagnostic getTomlDiagnostic(TomlNodeLocation location, String code, String template,
DiagnosticSeverity severity, String message) {
DiagnosticInfo diagnosticInfo = new DiagnosticInfo(code, template, severity);
return new TomlDiagnostic(location, diagnosticInfo, message);
}
private List<String> getRequiredFields(Schema objectSchema) {
if (objectSchema.required() == null) {
return new ArrayList<>();
}
return objectSchema.required();
}
}
|
`totalCount` has been removed from accumulator in the latest commit, and will be calculated in `getValue()` once needed.
|
public Double[] getValue() {
List<Pair<Double, Integer>> sortedPercentages = new ArrayList<>();
for (int index = 0; index < percentages.length; index++) {
sortedPercentages.add(new Pair<>(percentages[index] * (totalCount - 1) + 1, index));
}
sortedPercentages.sort(Comparator.comparing(Pair::getKey));
List<Map.Entry<Double, Long>> sortedList = new ArrayList<>();
try {
for (Map.Entry<Double, Long> entry : valueCount.entries()) {
sortedList.add(entry);
}
} catch (Exception e) {
throw new FlinkRuntimeException(e);
}
sortedList.sort(Map.Entry.comparingByKey());
Double[] percentiles = new Double[percentages.length];
long preCnt = sortedList.get(0).getValue();
for (int i = 0, j = 0; i < sortedPercentages.size(); i++) {
Pair<Double, Integer> entry = sortedPercentages.get(i);
double position = entry.getKey();
long lower = (long) Math.floor(position);
long higher = (long) Math.ceil(position);
while (preCnt < lower) {
j++;
preCnt += sortedList.get(j).getValue();
}
percentiles[entry.getValue()] =
preCnt >= higher
? sortedList.get(j).getKey()
: (higher - position) * sortedList.get(j).getKey()
+ (position - lower) * sortedList.get(j + 1).getKey();
}
return percentiles;
}
|
public Double[] getValue() {
long totalCount = 0L;
List<Map.Entry<Double, Long>> sortedList = new ArrayList<>();
try {
for (Map.Entry<Double, Long> entry : valueCount.entries()) {
sortedList.add(entry);
totalCount += entry.getValue();
}
} catch (Exception e) {
throw new FlinkRuntimeException(e);
}
if (totalCount <= 0) {
return null;
}
sortedList.sort(Map.Entry.comparingByKey());
List<Pair<Double, Integer>> sortedPercentages = new ArrayList<>();
for (int index = 0; index < percentages.length; index++) {
sortedPercentages.add(new Pair<>(percentages[index] * (totalCount - 1) + 1, index));
}
sortedPercentages.sort(Comparator.comparing(Pair::getKey));
Double[] percentiles = new Double[percentages.length];
long preCnt = sortedList.get(0).getValue();
for (int i = 0, j = 0; i < sortedPercentages.size(); i++) {
Pair<Double, Integer> entry = sortedPercentages.get(i);
double position = entry.getKey();
long lower = (long) Math.floor(position);
long higher = (long) Math.ceil(position);
while (preCnt < lower) {
j++;
preCnt += sortedList.get(j).getValue();
}
percentiles[entry.getValue()] =
preCnt >= higher
? sortedList.get(j).getKey()
: (higher - position) * sortedList.get(j).getKey()
+ (position - lower) * sortedList.get(j + 1).getKey();
}
return percentiles;
}
|
class PercentileAccumulator {
public double[] percentages;
public long totalCount;
public MapView<Double, Long> valueCount;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PercentileAccumulator that = (PercentileAccumulator) o;
return Arrays.equals(percentages, that.percentages)
&& totalCount == that.totalCount
&& Objects.equals(valueCount, that.valueCount);
}
@Override
public int hashCode() {
return Objects.hash(Arrays.hashCode(percentages), totalCount, valueCount.hashCode());
}
public void setPercentages(Double percentage) {
if (percentage < 0.0 || percentage > 1.0) {
throw new IllegalArgumentException(
String.format(
"Percentage of PERCENTILE should be between [0.0, 1.0], but was '%s'.",
percentage));
}
percentages = new double[] {percentage};
}
public void setPercentages(Double[] percentage) {
percentages = new double[percentage.length];
for (int i = 0; i < percentages.length; i++) {
if (percentage[i] < 0.0 || percentage[i] > 1.0) {
throw new IllegalArgumentException(
String.format(
"Percentage of PERCENTILE should be between [0.0, 1.0], but was '%s'.",
percentage[i]));
}
percentages[i] = percentage[i];
}
}
}
|
class PercentileAccumulator {
public double[] percentages;
public MapView<Double, Long> valueCount;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PercentileAccumulator that = (PercentileAccumulator) o;
return Arrays.equals(percentages, that.percentages)
&& Objects.equals(valueCount, that.valueCount);
}
@Override
public int hashCode() {
return Objects.hash(Arrays.hashCode(percentages), valueCount.hashCode());
}
public void setPercentages(Double percentage) {
if (percentage < 0.0 || percentage > 1.0) {
throw new IllegalArgumentException(
String.format(
"Percentage of PERCENTILE should be between [0.0, 1.0], but was '%s'.",
percentage));
}
percentages = new double[] {percentage};
}
public void setPercentages(Double[] percentage) {
percentages = new double[percentage.length];
for (int i = 0; i < percentages.length; i++) {
if (percentage[i] < 0.0 || percentage[i] > 1.0) {
throw new IllegalArgumentException(
String.format(
"Percentage of PERCENTILE should be between [0.0, 1.0], but was '%s'.",
percentage[i]));
}
percentages[i] = percentage[i];
}
}
}
|
|
Imo it just shouldnt print anythiNg unless debug. Why would we want those behind firewalls to get annoying message on every build?
|
public void close() {
try {
CompletableFuture.allOf(postFutures.toArray(new CompletableFuture[0])).get(
PropertyUtils.getProperty("quarkus.analytics.timeout", DEFAULT_TIMEOUT),
TimeUnit.MILLISECONDS);
if (log.isDebugEnabled() && !postFutures.isEmpty()) {
log.debug("[Quarkus build analytics] Build analytics sent successfully. Sent event can be seen at .../target/" +
fileLocations.lastTrackFileName());
}
} catch (ExecutionException | TimeoutException e) {
if (log.isDebugEnabled()) {
log.debug("[Quarkus build analytics] Failed to send build analytics to Segment: " +
e.getClass().getName() + ": " +
(e.getMessage() == null ? "(no message)" : e.getMessage()));
}
log.info("[Quarkus build analytics] Failed to send build analytics to Segment. " +
"Connection might not be available or is too slow.");
} catch (Exception e) {
log.warn("[Quarkus build analytics] Failed to send build analytics to Segment: " +
e.getClass().getName() + ": " +
(e.getMessage() == null ? "(no message)" : e.getMessage()));
}
}
|
log.info("[Quarkus build analytics] Failed to send build analytics to Segment. " +
|
public void close() {
try {
CompletableFuture.allOf(postFutures.toArray(new CompletableFuture[0])).get(
PropertyUtils.getProperty("quarkus.analytics.timeout", DEFAULT_TIMEOUT),
TimeUnit.MILLISECONDS);
if (log.isDebugEnabled() && !postFutures.isEmpty()) {
log.debug("[Quarkus build analytics] Build analytics sent successfully. Sent event can be seen at .../target/" +
fileLocations.lastTrackFileName());
}
} catch (ExecutionException | TimeoutException e) {
if (log.isDebugEnabled()) {
log.debug("[Quarkus build analytics] Failed to send build analytics to Segment. " +
"Connection might not be available or is too slow: " +
e.getClass().getName() + ": " +
(e.getMessage() == null ? "(no message)" : e.getMessage()));
}
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("[Quarkus build analytics] Failed to send build analytics to Segment: " +
e.getClass().getName() + ": " +
(e.getMessage() == null ? "(no message)" : e.getMessage()));
}
}
}
|
class AnalyticsService implements AutoCloseable {
private final Queue<CompletableFuture<HttpResponse<String>>> postFutures;
final private RestClient restClient;
final private ConfigService config;
final private AnonymousUserId userId;
final private MessageWriter log;
final FileLocations fileLocations;
public AnalyticsService(final FileLocations fileLocations, MessageWriter log) {
this.fileLocations = fileLocations;
this.log = log;
this.postFutures = new ConcurrentLinkedQueue<>();
this.restClient = new RestClient(log);
this.userId = AnonymousUserId.getInstance(fileLocations, log);
this.config = new ConfigService(this.restClient, this.userId, fileLocations, log);
}
public void buildAnalyticsUserInput(Function<String, String> analyticsEnabledSupplier) {
this.config.userAcceptance(analyticsEnabledSupplier);
}
public void sendAnalytics(final TrackEventType trackEventType,
ApplicationModel applicationModel,
final Map<String, Object> buildInfo,
final File localBuildDir) {
if (this.config.isActive() &&
this.config.isArtifactActive(
applicationModel.getAppArtifact().getGroupId(),
getQuarkusVersion(applicationModel))) {
final Map<String, Object> context = createContextMap(applicationModel, buildInfo);
sendIdentity(context);
Track trackEvent = Track.builder()
.userId(userId.getUuid())
.context(context)
.event(trackEventType)
.properties(TrackProperties.builder()
.appExtensions(createExtensionsPropertyValue(applicationModel))
.build())
.timestamp(Instant.now())
.build();
postFutures.add(this.restClient.postTrack(trackEvent));
try {
FileUtils.overwrite(trackEvent,
Path.of(localBuildDir.getAbsolutePath(), fileLocations.lastTrackFileName()));
} catch (IOException e) {
log.warn("[Quarkus build analytics] Failed to write the last analytics file. " + e.getMessage());
}
}
}
@Override
List<TrackProperties.AppExtension> createExtensionsPropertyValue(ApplicationModel applicationModel) {
return applicationModel.getDependencies().stream()
.filter(dep -> dep.isResolved() &&
dep.isFlagSet(TOP_LEVEL_RUNTIME_EXTENSION_ARTIFACT) &&
onlyPublic(dep.getGroupId(), log))
.map(dep -> TrackProperties.AppExtension.builder()
.groupId(dep.getGroupId())
.artifactId(dep.getArtifactId())
.version(dep.getVersion())
.build())
.collect(Collectors.toList());
}
void sendIdentity(final Map<String, Object> context) {
if (this.userId.isNew()) {
this.restClient.postIdentity(Identity.builder()
.userId(this.userId.getUuid())
.context(context)
.timestamp(Instant.now())
.build());
}
}
Map<String, Object> createContextMap(ApplicationModel applicationModel,
Map<String, Object> buildInfo) {
ArtifactCoords moduleId = applicationModel.getAppArtifact();
return new ContextBuilder()
.mapPair(PROP_APP)
.pair(PROP_NAME, hashSHA256(moduleId.getGroupId() + ":" + moduleId.getArtifactId()))
.pair(PROP_VERSION, hashSHA256(moduleId.getArtifactId() + ":" + moduleId.getVersion()))
.build()
.mapPair(PROP_JAVA)
.pair(PROP_VENDOR, getProperty("java.vendor", "N/A"))
.pair(PROP_VERSION, getProperty("java.version", "N/A"))
.build()
.mapPair(PROP_GRAALVM)
.pair(PROP_VENDOR, ofNullable(buildInfo.get(GRAALVM_VERSION_DISTRIBUTION)).orElse("N/A"))
.pair(PROP_VERSION, ofNullable(buildInfo.get(GRAALVM_VERSION_VERSION)).orElse("N/A"))
.pair(PROP_JAVA_VERSION, ofNullable(buildInfo.get(GRAALVM_VERSION_JAVA)).orElse("N/A"))
.build()
.mapPair(PROP_BUILD)
.pair(PROP_MAVEN_VERSION, ofNullable(buildInfo.get(MAVEN_VERSION)).orElse("N/A"))
.pair(PROP_GRADLE_VERSION, ofNullable(buildInfo.get(GRADLE_VERSION)).orElse("N/A"))
.build()
.mapPair(PROP_QUARKUS)
.pair(PROP_VERSION, getQuarkusVersion(applicationModel))
.build()
.pair(PROP_IP, VALUE_NULL_IP)
.mapPair(PROP_LOCATION)
.pair(PROP_LOCALE_COUNTRY, Locale.getDefault().getCountry())
.build()
.mapPair(PROP_OS)
.pair(PROP_NAME, getProperty("os.name", "N/A"))
.pair(PROP_VERSION, getProperty("os.version", "N/A"))
.pair(PROP_OS_ARCH, getProperty("os.arch", "N/A"))
.build()
.mapPair(PROP_CI)
.pair(PROP_CI_NAME, getBuildSystemName())
.build()
.mapPair(PROP_KUBERNETES)
.pair(PROP_DETECTED, isKubernetesDetected())
.build()
.pair(PROP_TIMEZONE, ZoneId.systemDefault().getDisplayName(TextStyle.NARROW, Locale.ENGLISH))
.build();
}
private String isKubernetesDetected() {
return Boolean.toString(allEnvSet(
"KUBERNETES_SERVICE_HOST",
"KUBERNETES_SERVICE_PORT"));
}
private String getBuildSystemName() {
String travis = getenv("TRAVIS");
String user = getenv("USER");
if ("true".equals(travis) && "travis".equals(user)) {
return "travis";
}
if (allEnvSet("JENKINS_URL", "JENKINS_HOME", "WORKSPACE")) {
return "jenkins";
}
if (allEnvSet("GITHUB_WORKFLOW", "GITHUB_WORKSPACE", "GITHUB_RUN_ID")) {
return "github-actions";
}
if (allEnvSet("BUILD_REASON", "AGENT_JOBSTATUS")) {
return "azure-pipelines";
}
return "unknown";
}
private boolean allEnvSet(String... names) {
for (String name : names) {
if (getenv(name) == null) {
return false;
}
}
return true;
}
private String getQuarkusVersion(ApplicationModel applicationModel) {
return applicationModel.getPlatforms().getImportedPlatformBoms().stream()
.filter(artifactCoords -> artifactCoords.getArtifactId().equals("quarkus-bom"))
.map(ArtifactCoords::getVersion)
.findFirst()
.orElse("N/A");
}
}
|
class AnalyticsService implements AutoCloseable {
private final Queue<CompletableFuture<HttpResponse<String>>> postFutures;
final private RestClient restClient;
final private ConfigService config;
final private AnonymousUserId userId;
final private MessageWriter log;
final FileLocations fileLocations;
public AnalyticsService(final FileLocations fileLocations, MessageWriter log) {
this.fileLocations = fileLocations;
this.log = log;
this.postFutures = new ConcurrentLinkedQueue<>();
this.restClient = new RestClient(log);
this.userId = AnonymousUserId.getInstance(fileLocations, log);
this.config = new ConfigService(this.restClient, this.userId, fileLocations, log);
}
public void buildAnalyticsUserInput(Function<String, String> analyticsEnabledSupplier) {
this.config.userAcceptance(analyticsEnabledSupplier);
}
public void sendAnalytics(final TrackEventType trackEventType,
ApplicationModel applicationModel,
final Map<String, Object> buildInfo,
final File localBuildDir) {
if (this.config.isActive() &&
this.config.isArtifactActive(
applicationModel.getAppArtifact().getGroupId(),
getQuarkusVersion(applicationModel))) {
final Map<String, Object> context = createContextMap(applicationModel, buildInfo);
sendIdentity(context);
Track trackEvent = Track.builder()
.userId(userId.getUuid())
.context(context)
.event(trackEventType)
.properties(TrackProperties.builder()
.appExtensions(createExtensionsPropertyValue(applicationModel))
.build())
.timestamp(Instant.now())
.build();
postFutures.add(this.restClient.postTrack(trackEvent));
try {
FileUtils.overwrite(trackEvent,
Path.of(localBuildDir.getAbsolutePath(), fileLocations.lastTrackFileName()));
} catch (IOException e) {
log.warn("[Quarkus build analytics] Failed to write the last analytics file. " + e.getMessage());
}
}
}
@Override
List<TrackProperties.AppExtension> createExtensionsPropertyValue(ApplicationModel applicationModel) {
return applicationModel.getDependencies().stream()
.filter(dep -> dep.isResolved() &&
dep.isFlagSet(TOP_LEVEL_RUNTIME_EXTENSION_ARTIFACT) &&
onlyPublic(dep.getGroupId(), log))
.map(dep -> TrackProperties.AppExtension.builder()
.groupId(dep.getGroupId())
.artifactId(dep.getArtifactId())
.version(dep.getVersion())
.build())
.collect(Collectors.toList());
}
void sendIdentity(final Map<String, Object> context) {
if (this.userId.isNew()) {
this.restClient.postIdentity(Identity.builder()
.userId(this.userId.getUuid())
.context(context)
.timestamp(Instant.now())
.build());
}
}
Map<String, Object> createContextMap(ApplicationModel applicationModel,
Map<String, Object> buildInfo) {
ArtifactCoords moduleId = applicationModel.getAppArtifact();
return new ContextBuilder()
.mapPair(PROP_APP)
.pair(PROP_NAME, hashSHA256(moduleId.getGroupId() + ":" + moduleId.getArtifactId()))
.pair(PROP_VERSION, hashSHA256(moduleId.getArtifactId() + ":" + moduleId.getVersion()))
.build()
.mapPair(PROP_JAVA)
.pair(PROP_VENDOR, getProperty("java.vendor", "N/A"))
.pair(PROP_VERSION, getProperty("java.version", "N/A"))
.build()
.mapPair(PROP_GRAALVM)
.pair(PROP_VENDOR, ofNullable(buildInfo.get(GRAALVM_VERSION_DISTRIBUTION)).orElse("N/A"))
.pair(PROP_VERSION, ofNullable(buildInfo.get(GRAALVM_VERSION_VERSION)).orElse("N/A"))
.pair(PROP_JAVA_VERSION, ofNullable(buildInfo.get(GRAALVM_VERSION_JAVA)).orElse("N/A"))
.build()
.mapPair(PROP_BUILD)
.pair(PROP_MAVEN_VERSION, ofNullable(buildInfo.get(MAVEN_VERSION)).orElse("N/A"))
.pair(PROP_GRADLE_VERSION, ofNullable(buildInfo.get(GRADLE_VERSION)).orElse("N/A"))
.build()
.mapPair(PROP_QUARKUS)
.pair(PROP_VERSION, getQuarkusVersion(applicationModel))
.build()
.pair(PROP_IP, VALUE_NULL_IP)
.mapPair(PROP_LOCATION)
.pair(PROP_LOCALE_COUNTRY, Locale.getDefault().getCountry())
.build()
.mapPair(PROP_OS)
.pair(PROP_NAME, getProperty("os.name", "N/A"))
.pair(PROP_VERSION, getProperty("os.version", "N/A"))
.pair(PROP_OS_ARCH, getProperty("os.arch", "N/A"))
.build()
.mapPair(PROP_CI)
.pair(PROP_CI_NAME, getBuildSystemName())
.build()
.mapPair(PROP_KUBERNETES)
.pair(PROP_DETECTED, isKubernetesDetected())
.build()
.pair(PROP_TIMEZONE, ZoneId.systemDefault().getDisplayName(TextStyle.NARROW, Locale.ENGLISH))
.build();
}
private String isKubernetesDetected() {
return Boolean.toString(allEnvSet(
"KUBERNETES_SERVICE_HOST",
"KUBERNETES_SERVICE_PORT"));
}
private String getBuildSystemName() {
String travis = getenv("TRAVIS");
String user = getenv("USER");
if ("true".equals(travis) && "travis".equals(user)) {
return "travis";
}
if (allEnvSet("JENKINS_URL", "JENKINS_HOME", "WORKSPACE")) {
return "jenkins";
}
if (allEnvSet("GITHUB_WORKFLOW", "GITHUB_WORKSPACE", "GITHUB_RUN_ID")) {
return "github-actions";
}
if (allEnvSet("BUILD_REASON", "AGENT_JOBSTATUS")) {
return "azure-pipelines";
}
return "unknown";
}
private boolean allEnvSet(String... names) {
for (String name : names) {
if (getenv(name) == null) {
return false;
}
}
return true;
}
private String getQuarkusVersion(ApplicationModel applicationModel) {
return applicationModel.getPlatforms().getImportedPlatformBoms().stream()
.filter(artifactCoords -> artifactCoords.getArtifactId().equals("quarkus-bom"))
.map(ArtifactCoords::getVersion)
.findFirst()
.orElse("N/A");
}
}
|
Should we also add this change to the changelog?
| "Mono<PiiEntityCollection> recognizePiiEntities(String document, String language) {\n try {\n(...TRUNCATED)
|
throw logger.logExceptionAsError(toTextAnalyticsException(entitiesResult.getError()));
| "Mono<PiiEntityCollection> recognizePiiEntities(String document, String language) {\n try {\n(...TRUNCATED)
| "class RecognizePiiEntityAsyncClient {\n private final ClientLogger logger = new ClientLogger(Rec(...TRUNCATED)
| "class RecognizePiiEntityAsyncClient {\n private final ClientLogger logger = new ClientLogger(Rec(...TRUNCATED)
|
Let's open a separate issue for that, it's a bigger piece of work
| "public String getId() {\n String id = this.title.toLowerCase().replaceAll(SPACE, DASH);\n (...TRUNCATED)
|
id = URLEncoder.encode(id, StandardCharsets.UTF_8.toString());
| "public String getId() {\n String id = this.title.toLowerCase().replaceAll(SPACE, DASH);\n (...TRUNCATED)
| "class Page {\n private final String icon; \n private final String title; \n private final (...TRUNCATED)
| "class Page {\n private final String icon; \n private final String title; \n private final (...TRUNCATED)
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 1