1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.neo4j.server.webadmin.rest;
21
22 import java.util.Map;
23
24 import javax.servlet.http.HttpServletRequest;
25 import javax.ws.rs.GET;
26 import javax.ws.rs.POST;
27 import javax.ws.rs.Path;
28 import javax.ws.rs.core.Context;
29 import javax.ws.rs.core.Response;
30 import javax.ws.rs.core.Response.Status;
31
32 import org.apache.log4j.Logger;
33 import org.neo4j.server.database.Database;
34 import org.neo4j.server.rest.repr.BadInputException;
35 import org.neo4j.server.rest.repr.InputFormat;
36 import org.neo4j.server.rest.repr.OutputFormat;
37 import org.neo4j.server.rest.repr.ValueRepresentation;
38 import org.neo4j.server.webadmin.console.ScriptSession;
39 import org.neo4j.server.webadmin.rest.representations.ServiceDefinitionRepresentation;
40
41 @Path( ConsoleService.SERVICE_PATH )
42 public class ConsoleService implements AdvertisableService
43 {
44 private static final String SERVICE_NAME = "console";
45 static final String SERVICE_PATH = "server/console";
46 private final SessionFactory sessionFactory;
47 private final Database database;
48 private final OutputFormat output;
49
50 public ConsoleService( SessionFactory sessionFactory, Database database,
51 OutputFormat output )
52 {
53 this.sessionFactory = sessionFactory;
54 this.database = database;
55 this.output = output;
56 }
57
58 public ConsoleService( @Context Database database,
59 @Context HttpServletRequest req,
60 @Context OutputFormat output )
61 {
62 this( new SessionFactoryImpl( req.getSession( true ) ), database, output );
63 }
64
65 Logger log = Logger.getLogger( ConsoleService.class );
66
67 public String getName()
68 {
69 return SERVICE_NAME;
70 }
71
72 public String getServerPath()
73 {
74 return SERVICE_PATH;
75 }
76
77 @GET
78 public Response getServiceDefinition()
79 {
80 ServiceDefinitionRepresentation result = new ServiceDefinitionRepresentation( SERVICE_PATH );
81 result.resourceUri( "exec", "" );
82
83 return output.ok( result );
84 }
85
86 @POST
87 public Response exec( @Context InputFormat input, String data )
88 {
89 Map<String, Object> args;
90 try
91 {
92 args = input.readMap( data );
93 }
94 catch ( BadInputException e )
95 {
96 return output.badRequest( e );
97 }
98
99 if ( !args.containsKey( "command" ) )
100 {
101 return Response.status( Status.BAD_REQUEST ).entity(
102 "Expected command argument not present." ).build();
103 }
104
105 ScriptSession scriptSession = getSession( args );
106 log.info( scriptSession.toString() );
107
108 String result = scriptSession.evaluate( (String)args.get( "command" ) );
109
110 return output.ok( ValueRepresentation.string( result ) );
111 }
112
113 private ScriptSession getSession( Map<String, Object> args )
114 {
115 return sessionFactory.createSession( (String)args.get( "engine" ), database );
116 }
117 }