-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
ReflectiveProcedureCompiler.java
296 lines (269 loc) · 11.7 KB
/
ReflectiveProcedureCompiler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*
* Copyright (c) 2002-2016 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.impl.proc;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.neo4j.collection.RawIterator;
import org.neo4j.kernel.api.exceptions.KernelException;
import org.neo4j.kernel.api.exceptions.ProcedureException;
import org.neo4j.kernel.api.exceptions.Status;
import org.neo4j.kernel.api.proc.CallableProcedure;
import org.neo4j.kernel.api.proc.ProcedureSignature;
import org.neo4j.kernel.api.proc.ProcedureSignature.FieldSignature;
import org.neo4j.kernel.api.proc.ProcedureSignature.ProcedureName;
import org.neo4j.kernel.impl.proc.OutputMappers.OutputMapper;
import org.neo4j.procedure.PerformsWrites;
import org.neo4j.procedure.Procedure;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyIterator;
import static java.util.Collections.emptyList;
import static org.neo4j.helpers.collection.Iterators.asRawIterator;
/**
* Handles converting a class into one or more callable {@link CallableProcedure}.
*/
public class ReflectiveProcedureCompiler
{
private final MethodHandles.Lookup lookup = MethodHandles.lookup();
private final OutputMappers outputMappers;
private final MethodSignatureCompiler inputSignatureDeterminer;
private final FieldInjections fieldInjections;
public ReflectiveProcedureCompiler( TypeMappers typeMappers, ComponentRegistry components )
{
inputSignatureDeterminer = new MethodSignatureCompiler(typeMappers);
outputMappers = new OutputMappers( typeMappers );
this.fieldInjections = new FieldInjections( components );
}
public List<CallableProcedure> compile( Class<?> procDefinition ) throws KernelException
{
try
{
List<Method> procedureMethods = asList( procDefinition.getDeclaredMethods() ).stream()
.filter( m -> m.isAnnotationPresent( Procedure.class ) )
.collect( Collectors.toList() );
if( procedureMethods.isEmpty() )
{
return emptyList();
}
MethodHandle constructor = constructor( procDefinition );
ArrayList<CallableProcedure> out = new ArrayList<>( procedureMethods.size() );
for ( Method method : procedureMethods )
{
out.add( compileProcedure( procDefinition, constructor, method ) );
}
out.sort( (a,b) -> a.signature().name().toString().compareTo( b.signature().name().toString() ) );
return out;
}
catch( KernelException e )
{
throw e;
}
catch ( Exception e )
{
throw new ProcedureException( Status.Procedure.ProcedureRegistrationFailed, e,
"Failed to compile procedure defined in `%s`: %s", procDefinition.getSimpleName(), e.getMessage() );
}
}
private ReflectiveProcedure compileProcedure( Class<?> procDefinition, MethodHandle constructor, Method method )
throws ProcedureException, IllegalAccessException
{
ProcedureName procName = extractName( procDefinition, method );
List<FieldSignature> inputSignature = inputSignatureDeterminer.signatureFor( method );
OutputMapper outputMapper = outputMappers.mapper( method );
MethodHandle procedureMethod = lookup.unreflect( method );
List<FieldInjections.FieldSetter> setters = fieldInjections.setters( procDefinition );
ProcedureSignature.Mode mode = ProcedureSignature.Mode.READ_ONLY;
Procedure procedure = method.getAnnotation( Procedure.class );
if ( procedure.mode().equals( Procedure.Mode.DBMS ) )
{
mode = ProcedureSignature.Mode.DBMS;
}
else if ( procedure.mode().equals( Procedure.Mode.SCHEMA ) )
{
mode = ProcedureSignature.Mode.SCHEMA_WRITE;
}
else if ( procedure.mode().equals( Procedure.Mode.WRITE ) )
{
mode = ProcedureSignature.Mode.READ_WRITE;
}
if ( method.isAnnotationPresent( PerformsWrites.class ) )
{
if ( !procedure.mode().equals( Procedure.Mode.DEFAULT ) )
{
throw new ProcedureException( Status.Procedure.ProcedureRegistrationFailed,
"Conflicting procedure annotation, cannot use PerformsWrites and mode" );
}
else
{
mode = ProcedureSignature.Mode.READ_WRITE;
}
}
ProcedureSignature signature = new ProcedureSignature( procName, inputSignature, outputMapper.signature(), mode );
return new ReflectiveProcedure( signature, constructor, procedureMethod, outputMapper, setters );
}
private MethodHandle constructor( Class<?> procDefinition ) throws ProcedureException
{
try
{
return lookup.unreflectConstructor( procDefinition.getConstructor() );
}
catch ( IllegalAccessException | NoSuchMethodException e )
{
throw new ProcedureException( Status.Procedure.ProcedureRegistrationFailed, e,
"Unable to find a usable public no-argument constructor in the class `%s`. " +
"Please add a valid, public constructor, recompile the class and try again.",
procDefinition.getSimpleName() );
}
}
private ProcedureName extractName( Class<?> procDefinition, Method m )
{
String valueName = m.getAnnotation( Procedure.class ).value();
String definedName = m.getAnnotation( Procedure.class ).name();
String procName = (definedName.trim().isEmpty() ? valueName : definedName);
if( procName.trim().length() > 0 )
{
String[] split = procName.split( "\\." );
if( split.length == 1)
{
return new ProcedureName( new String[0], split[0] );
}
else
{
int lastElement = split.length - 1;
return new ProcedureName( Arrays.copyOf(split, lastElement ), split[lastElement] );
}
}
Package pkg = procDefinition.getPackage();
// Package is null if class is in root package
String[] namespace = pkg == null ? new String[0] : pkg.getName().split( "\\." );
String name = m.getName();
return new ProcedureName( namespace, name );
}
private static class ReflectiveProcedure implements CallableProcedure
{
private final ProcedureSignature signature;
private final MethodHandle constructor;
private final MethodHandle procedureMethod;
private final OutputMapper outputMapper;
private final List<FieldInjections.FieldSetter> fieldSetters;
public ReflectiveProcedure( ProcedureSignature signature, MethodHandle constructor,
MethodHandle procedureMethod, OutputMapper outputMapper,
List<FieldInjections.FieldSetter> fieldSetters )
{
this.signature = signature;
this.constructor = constructor;
this.procedureMethod = procedureMethod;
this.outputMapper = outputMapper;
this.fieldSetters = fieldSetters;
}
@Override
public ProcedureSignature signature()
{
return signature;
}
@Override
public RawIterator<Object[], ProcedureException> apply( Context ctx, Object[] input ) throws ProcedureException
{
// For now, create a new instance of the class for each invocation. In the future, we'd like to keep instances local to
// at least the executing session, but we don't yet have good interfaces to the kernel to model that with.
try
{
int numberOfDeclaredArguments = signature.inputSignature().size();
if (numberOfDeclaredArguments != input.length) {
throw new ProcedureException( Status.Procedure.ProcedureCallFailed,
"Procedure `%s` takes %d arguments but %d was provided.",
signature.name(),
numberOfDeclaredArguments, input.length );
}
Object cls = constructor.invoke();
//API injection
for ( FieldInjections.FieldSetter setter : fieldSetters )
{
setter.apply( ctx, cls );
}
Object[] args = new Object[numberOfDeclaredArguments + 1];
args[0] = cls;
System.arraycopy( input, 0, args, 1, numberOfDeclaredArguments );
Object rs = procedureMethod.invokeWithArguments( args );
// This also handles VOID
if ( rs == null )
{
return asRawIterator( emptyIterator() );
}
else
{
return new MappingIterator( ((Stream<?>) rs).iterator() );
}
}
catch ( Throwable throwable )
{
String message = throwable.getMessage();
if( message == null )
{
message = String.format("`%s` was thrown when invoking the procedure.",
throwable.getClass().getName());
}
throw new ProcedureException( Status.Procedure.ProcedureCallFailed, throwable,
"Failed to invoke procedure `%s`: %s", signature.name(), "Caused by: " + throwable );
}
}
private class MappingIterator implements RawIterator<Object[],ProcedureException>
{
private final Iterator<?> out;
public MappingIterator( Iterator<?> out )
{
this.out = out;
}
@Override
public boolean hasNext() throws ProcedureException
{
try
{
return out.hasNext();
}
catch( RuntimeException e )
{
throw new ProcedureException( Status.Procedure.ProcedureCallFailed, e,
"Failed to call procedure `%s`: %s", signature, e.getMessage() );
}
}
@Override
public Object[] next() throws ProcedureException
{
try
{
Object record = out.next();
return outputMapper.apply( record );
}
catch( RuntimeException e )
{
throw new ProcedureException( Status.Procedure.ProcedureCallFailed, e,
"Failed to call procedure `%s`: %s", signature, e.getMessage() );
}
}
}
}
}