REST api

Wednesday, 12 May 2010 · 2 messages
RP
Robby Pelssers12 May 2010 16:49 #
Hi all, I took a go at implementing my own api for inserting/deleting/querying through the REST API. For the ones interested here is my code which is also available at http://robbypelssers.blogspot.com/2010/05/exist-db-how-to-use-rest.html If you find errors or have remarks how-to improve.... drop me a mail. Cheers, Robby Pelssers
----------------------------------------------------------------------------------------
public interface RestCommand {
    void setConnection(HttpURLConnection conn);
    HttpURLConnection getConnection();
    void setInputStream(InputStream is);
    InputStream getInputStream();
    void execute() throws IOException;
    String getRequestMethod();
    String getURI();
    void onSuccess();
    void onFailure(Exception e);
}
----------------------------------------------------------------------------------------
public abstract class AbstractRestCommand implements RestCommand {

    private HttpURLConnection connection;
    private InputStream inputStream;
    private String URI;

    public AbstractRestCommand(String URI) {
	this.URI = URI;
    }

    public HttpURLConnection getConnection() {
	return this.connection;
    }

    public InputStream getInputStream() {
 	return this.inputStream;
    }

    public void setConnection(HttpURLConnection conn) {
        this.connection = conn;
    }

    public void setInputStream(InputStream in) {
        this.inputStream = in;
    }

    public String getURI() {
	return this.URI;
    }

    public void onSuccess() {}
    public void onFailure(Exception e) {}
}
----------------------------------------------------------------------------------------
public class PutCommand extends AbstractRestCommand {

    public PutCommand(String URI) {
	super(URI);
    }

    public void execute() throws IOException {
	// Set an output connection.
	getConnection().setDoOutput(true);
	OutputStream out = getConnection().getOutputStream();
	for (int c = getInputStream().read(); c != -1; c = getInputStream().read()) {
	    out.write(c);
	}
	out.flush();
	getInputStream().close();
	out.close();

	int responseCode = getConnection().getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_CREATED) {
            onSuccess();
        }
        else {
            onFailure(new InvalidResponseCodeException(responseCode));
        }
    }

    public final String getRequestMethod() {
	return "PUT";
    }
}
----------------------------------------------------------------------------------------
public class PostCommand extends AbstractRestCommand {

    public PostCommand(String URI) {
	super(URI);
    }

    public void execute() throws IOException {
        getConnection().setRequestProperty("Content-Type", "application/query+xml");
	// Set an output connection.
	getConnection().setDoOutput(true);
	OutputStream out = getConnection().getOutputStream();
	for (int c = getInputStream().read(); c != -1; c = getInputStream().read()) {
	    out.write(c);
	}
	out.flush();
	getInputStream().close();
	out.close();

	int responseCode = getConnection().getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK) {
            onSuccess();
        }
        else {
            onFailure(new InvalidResponseCodeException(responseCode));
        }
    }

    public final String getRequestMethod() {
	return "POST";
    }
}
----------------------------------------------------------------------------------------
public class DeleteCommand extends AbstractRestCommand {

    public DeleteCommand(String URI) {
	super(URI);
    }

    public final String getRequestMethod() {
	return "DELETE";
    }

    public void execute() throws IOException {
	int responseCode = getConnection().getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK) {
            onSuccess();
        }
        else {
            onFailure(new InvalidResponseCodeException(responseCode));
        }
    }
}
----------------------------------------------------------------------------------------
public class XmlDBAuthenticator extends Authenticator {

    private String username;
    private String password;

    public XmlDBAuthenticator(String username, String password) {
	this.username = username;
	this.password = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password.toCharArray());
    }
}
----------------------------------------------------------------------------------------
public interface XmlDBClient {
Authenticator getAuthenticator(); /** * @param command: PutCommand * @param path: the absolute path of the resource to insert * @throws FileNotFoundException */ void put(PutCommand command, String path) throws FileNotFoundException; /** * @param command: PutCommand * @param is: input stream of the resource to insert */ void put(PutCommand command, InputStream is); /** * @param command: DeleteCommand */ void delete(DeleteCommand command); /** * @param command: PostCommand * @param path: the absolute path of the xquery to be executed * @throws FileNotFoundException */ void post(PostCommand command, String path) throws FileNotFoundException; /** * @param command: PostCommand * @param is: input stream of the xquery to be executed */ void post(PostCommand command, InputStream is); } ---------------------------------------------------------------------------------------- public class XmlDBClientImpl implements XmlDBClient {
    private Authenticator authenticator;

    public XmlDBClientImpl(Authenticator authenticator) {
	this.authenticator = authenticator;
    }

    public Authenticator getAuthenticator() {
	return this.authenticator;
    }

    protected void executeCommand(RestCommand command, InputStream is) {
	URL url = null;
	HttpURLConnection conn = null;
	try {
            Authenticator.setDefault(getAuthenticator());
	    url = new URL(command.getURI());
	    conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(command.getRequestMethod());

            command.setConnection(conn);
	    command.setInputStream(is);
	    command.execute();
	}  catch (IOException e) {
            command.onFailure(e);
	}  finally {
	    // Close connection.
	    if (conn != null) {
		conn.disconnect();
	    }
	}
    }

    public void put(PutCommand command, InputStream is) {
        executeCommand(command, is);
    }

    public void put(PutCommand command, String path) throws FileNotFoundException  {
        put(command, new FileInputStream(path));
    }

    public void delete(DeleteCommand command) {
        executeCommand(command, null);
    }

    public void post(PostCommand command, String path) throws FileNotFoundException {
	post(command, new FileInputStream(path));
    }

    public  void post(PostCommand command, InputStream is) {
        executeCommand(command, is);
    }
}
----------------------------------------------------------------------------------------
public class XmlDBClientTest {

  private XmlDBClient client;

  @Before
  public void setup() {
    client = new XmlDBClientImpl(new XmlDBAuthenticator("robby", "pelssers"));
  }

  @After
  public void tearDown() {
    client = null;
  }

  @Test
  public void testInsertDocument() throws FileNotFoundException {
    String URI = "http://localhost:8080/exist/rest/db/released/products/TESTPRODUCT.xml";
    String path = "D:/nxp/repository/released/products/TESTPRODUCT.xml";
    client.put(
        new PutCommand(URI) {
          @Override
          public void onSuccess() {
    	    System.out.println("TESTPRODUCT.xml was succesfully inserted");
    	  }
    	  @Override
    	  public void onFailure(Exception e) {
    	    System.out.println("TESTPRODUCT.xml was NOT succesfully inserted: " + e.getMessage());
    	  }
    	},
    	path
    );
  }

  @Test
  public void testDeleteDocument() {
    String URI = "http://localhost:8080/exist/rest/db/released/products/TESTPRODUCT.xml";
    client.delete(
        new DeleteCommand(URI) {
          @Override
       	  public void onSuccess() {
    	    System.out.println("TESTPRODUCT.xml was succesfully deleted");
    	  }
    	  @Override
    	  public void onFailure(Exception e) {
    	    System.out.println("TESTPRODUCT.xml was NOT succesfully deleted: " + e.getMessage());
    	  }
    	}
    );
  }

  @Test
  public void testQueryProductsByAuthor() {
    String queryURI = "http://localhost:8080/exist/rest/db";
    client.post(
      new PostCommand (queryURI) {
        @Override
        public void onSuccess() {
          System.out.println("Query was executed succesfully");
	  try {
	    BufferedReader br = new BufferedReader(new InputStreamReader(getConnection().getInputStream(), "UTF-8"));
	    // Print all lines of the result.
	    String line;
	    while((line = br.readLine()) != null) {
	      System.out.println(line);
	    }
	    br.close();
	  } catch (Exception e) {
	    e.printStackTrace();
	  }
        }
        @Override
        public void onFailure(Exception e) {
        				System.out.println("Query was NOT executed succesfully: " + e.getMessage());
        }
      },
      getClass().getClassLoader().getResourceAsStream("productsByAuthor.xquery")
     );
  }
}
----------------------------------------------------------------------------------------
CG
Christian Grün12 May 2010 18:14 #
Dear Robby Pelssers, thanks a lot for your efforts – your work is more than welcome! We planned already to add an implementation for eXist for our own JAX-RX REST API. Ideally, we can merge our future efforts; feel free what you think of it. All the best, Christian
Quoted text · Robby Pelssers · 336 lines
On Wed, May 12, 2010 at 4:49 PM, Robby Pelssers <robby.pelssers at ciber.com> wrote: > Hi all, > > I took a go at implementing my own api for inserting/deleting/querying through the REST API. > > For the ones interested here is my code which is also available at > http://robbypelssers.blogspot.com/2010/05/exist-db-how-to-use-rest.html > > If you find errors or have remarks how-to improve.... drop me a mail. > > Cheers, > Robby Pelssers > > ---------------------------------------------------------------------------------------- > public interface RestCommand { > void setConnection(HttpURLConnection conn); > HttpURLConnection getConnection(); > void setInputStream(InputStream is); > InputStream getInputStream(); > void execute() throws IOException; > String getRequestMethod(); > String getURI(); > void onSuccess(); > void onFailure(Exception e); > } > ---------------------------------------------------------------------------------------- > public abstract class AbstractRestCommand implements RestCommand { > > private HttpURLConnection connection; > private InputStream inputStream; > private String URI; > > public AbstractRestCommand(String URI) { > this.URI = URI; > } > > public HttpURLConnection getConnection() { > return this.connection; > } > > public InputStream getInputStream() { > return this.inputStream; > } > > public void setConnection(HttpURLConnection conn) { > this.connection = conn; > } > > public void setInputStream(InputStream in) { > this.inputStream = in; > } > > public String getURI() { > return this.URI; > } > > public void onSuccess() {} > public void onFailure(Exception e) {} > } > ---------------------------------------------------------------------------------------- > public class PutCommand extends AbstractRestCommand { > > public PutCommand(String URI) { > super(URI); > } > > public void execute() throws IOException { > // Set an output connection. > getConnection().setDoOutput(true); > OutputStream out = getConnection().getOutputStream(); > for (int c = getInputStream().read(); c != -1; c = getInputStream().read()) { > out.write(c); > } > out.flush(); > getInputStream().close(); > out.close(); > > int responseCode = getConnection().getResponseCode(); > if(responseCode == HttpURLConnection.HTTP_CREATED) { > onSuccess(); > } > else { > onFailure(new InvalidResponseCodeException(responseCode)); > } > } > > public final String getRequestMethod() { > return "PUT"; > } > } > ---------------------------------------------------------------------------------------- > public class PostCommand extends AbstractRestCommand { > > public PostCommand(String URI) { > super(URI); > } > > public void execute() throws IOException { > getConnection().setRequestProperty("Content-Type", "application/query+xml"); > // Set an output connection. > getConnection().setDoOutput(true); > OutputStream out = getConnection().getOutputStream(); > for (int c = getInputStream().read(); c != -1; c = getInputStream().read()) { > out.write(c); > } > out.flush(); > getInputStream().close(); > out.close(); > > int responseCode = getConnection().getResponseCode(); > if(responseCode == HttpURLConnection.HTTP_OK) { > onSuccess(); > } > else { > onFailure(new InvalidResponseCodeException(responseCode)); > } > } > > public final String getRequestMethod() { > return "POST"; > } > } > ---------------------------------------------------------------------------------------- > public class DeleteCommand extends AbstractRestCommand { > > public DeleteCommand(String URI) { > super(URI); > } > > public final String getRequestMethod() { > return "DELETE"; > } > > public void execute() throws IOException { > int responseCode = getConnection().getResponseCode(); > if(responseCode == HttpURLConnection.HTTP_OK) { > onSuccess(); > } > else { > onFailure(new InvalidResponseCodeException(responseCode)); > } > } > } > ---------------------------------------------------------------------------------------- > public class XmlDBAuthenticator extends Authenticator { > > private String username; > private String password; > > public XmlDBAuthenticator(String username, String password) { > this.username = username; > this.password = password; > } > > protected PasswordAuthentication getPasswordAuthentication() { > return new PasswordAuthentication(username, password.toCharArray()); > } > } > ---------------------------------------------------------------------------------------- > public interface XmlDBClient { > > Authenticator getAuthenticator(); > > /** > * @param command: PutCommand > * @param path: the absolute path of the resource to insert > * @throws FileNotFoundException > */ > void put(PutCommand command, String path) throws FileNotFoundException; > > /** > * @param command: PutCommand > * @param is: input stream of the resource to insert > */ > void put(PutCommand command, InputStream is); > > /** > * @param command: DeleteCommand > */ > void delete(DeleteCommand command); > > /** > * @param command: PostCommand > * @param path: the absolute path of the xquery to be executed > * @throws FileNotFoundException > */ > void post(PostCommand command, String path) throws FileNotFoundException; > > /** > * @param command: PostCommand > * @param is: input stream of the xquery to be executed > */ > void post(PostCommand command, InputStream is); > } > ---------------------------------------------------------------------------------------- > public class XmlDBClientImpl implements XmlDBClient { > > private Authenticator authenticator; > > public XmlDBClientImpl(Authenticator authenticator) { > this.authenticator = authenticator; > } > > public Authenticator getAuthenticator() { > return this.authenticator; > } > > protected void executeCommand(RestCommand command, InputStream is) { > URL url = null; > HttpURLConnection conn = null; > try { > Authenticator.setDefault(getAuthenticator()); > url = new URL(command.getURI()); > conn = (HttpURLConnection) url.openConnection(); > conn.setRequestMethod(command.getRequestMethod()); > > command.setConnection(conn); > command.setInputStream(is); > command.execute(); > } catch (IOException e) { > command.onFailure(e); > } finally { > // Close connection. > if (conn != null) { > conn.disconnect(); > } > } > } > > public void put(PutCommand command, InputStream is) { > executeCommand(command, is); > } > > public void put(PutCommand command, String path) throws FileNotFoundException { > put(command, new FileInputStream(path)); > } > > public void delete(DeleteCommand command) { > executeCommand(command, null); > } > > public void post(PostCommand command, String path) throws FileNotFoundException { > post(command, new FileInputStream(path)); > } > > public void post(PostCommand command, InputStream is) { > executeCommand(command, is); > } > } > ---------------------------------------------------------------------------------------- > public class XmlDBClientTest { > > private XmlDBClient client; > > @Before > public void setup() { > client = new XmlDBClientImpl(new XmlDBAuthenticator("robby", "pelssers")); > } > > @After > public void tearDown() { > client = null; > } > > @Test > public void testInsertDocument() throws FileNotFoundException { > String URI = "http://localhost:8080/exist/rest/db/released/products/TESTPRODUCT.xml"; > String path = "D:/nxp/repository/released/products/TESTPRODUCT.xml"; > client.put( > new PutCommand(URI) { > @Override > public void onSuccess() { > System.out.println("TESTPRODUCT.xml was succesfully inserted"); > } > @Override > public void onFailure(Exception e) { > System.out.println("TESTPRODUCT.xml was NOT succesfully inserted: " + e.getMessage()); > } > }, > path > ); > } > > @Test > public void testDeleteDocument() { > String URI = "http://localhost:8080/exist/rest/db/released/products/TESTPRODUCT.xml"; > client.delete( > new DeleteCommand(URI) { > @Override > public void onSuccess() { > System.out.println("TESTPRODUCT.xml was succesfully deleted"); > } > @Override > public void onFailure(Exception e) { > System.out.println("TESTPRODUCT.xml was NOT succesfully deleted: " + e.getMessage()); > } > } > ); > } > > @Test > public void testQueryProductsByAuthor() { > String queryURI = "http://localhost:8080/exist/rest/db"; > client.post( > new PostCommand (queryURI) { > @Override > public void onSuccess() { > System.out.println("Query was executed succesfully"); > try { > BufferedReader br = new BufferedReader(new InputStreamReader(getConnection().getInputStream(), "UTF-8")); > // Print all lines of the result. > String line; > while((line = br.readLine()) != null) { > System.out.println(line); > } > br.close(); > } catch (Exception e) { > e.printStackTrace(); > } > } > @Override > public void onFailure(Exception e) { > System.out.println("Query was NOT executed succesfully: " + e.getMessage()); > } > }, > getClass().getClassLoader().getResourceAsStream("productsByAuthor.xquery") > ); > } > } > ---------------------------------------------------------------------------------------- > _______________________________________________ > BaseX-Talk mailing list > BaseX-Talk at mailman.uni-konstanz.de > https://mailman.uni-konstanz.de/mailman/listinfo/basex-talk >

⚡Generated with XQuery