Home

Results 1 to 2 of 2

Thread: An example Vibe/Filr REST client written in Java.

Hybrid View

  1. #1
    Join Date
    Apr 2016
    Posts
    1

    An example Vibe/Filr REST client written in Java.

    I needed to create users in Vibe/Filr using the REST API.
    I just got it working and wanted to share my code with the community.

    It's far from perfect but here you go, maybe it helps someone else:

    Code:
    import java.io.*;
    import java.net.*;
    import java.nio.charset.Charset;
    import java.util.*;
    
    import javax.xml.bind.DatatypeConverter;
    
    import net.raysforge.commons.HttpsUtils;
    import net.raysforge.commons.Json;
    
    public class FilrRestClient {
    
    	private String baseURL;
    	private String user;
    	private String pass;
    
    	public FilrRestClient(String baseURL, String user, String pass) {
    		if (!baseURL.endsWith("/rest/")) {
    			System.out.println("unsupported base URL format: " + baseURL);
    		}
    		this.baseURL = baseURL;
    		this.user = user;
    		this.pass = pass;
    		HttpsUtils.trustEveryone(); // accept self signed SSL certificates, you can find the code also on Stackoverflow
    	}
    
    	@SuppressWarnings({ "unchecked" })
    	private Map<String, Object> getDataAsMap(String path) throws IOException {
    		Object data = getData(path);
    		if( data == null) {
    			return null;
    		} else if (data instanceof Map<?, ?>) {
    			return (Map<String, Object>) data;
    		} else {
    			throw new RuntimeException("data != instance of Map");
    		}
    	}
    
    	private Object getData(String path) throws IOException {
    		URL url = new URL(baseURL + path);
    		HttpURLConnection con = (HttpURLConnection) url.openConnection();
    
    		String b64 = DatatypeConverter.printBase64Binary((user + ":" + pass).getBytes());
    		con.setRequestProperty("Authorization", "Basic " + b64);
    
    		int responseCode = con.getResponseCode();
    		if( responseCode == 404) {
    			System.out.println("404 for " + path);
    			return null;
    		}
    		else if (responseCode < 200 || responseCode >= 300) {
    			throw new RuntimeException("HTTP RESPONSE CODE:" + responseCode);
    		}
    
    		//Stream
    		Reader r = new InputStreamReader(con.getInputStream());
    
    		Json json = new Json();
    
    		return json.parse(r);
    	}
    
    	private Object postData(String path, String data) throws IOException {
    		URL url = new URL(baseURL + path);
    		HttpURLConnection con = (HttpURLConnection) url.openConnection();
    		con.setDoOutput(true);
    		con.setRequestMethod("POST");
    		con.setRequestProperty("Content-Type", "application/json");
    		con.setRequestProperty("charset", "utf-8");
    		con.setRequestProperty("Content-Length", Integer.toString(data.getBytes(Charset.forName("UTF-8")).length));
    		con.setUseCaches(false);
    
    		String b64 = DatatypeConverter.printBase64Binary((user + ":" + pass).getBytes());
    		con.setRequestProperty("Authorization", "Basic " + b64);
    
    		try (OutputStream os = con.getOutputStream();) {
    			os.write(data.getBytes(Charset.forName("UTF-8")));
    		}
    
    		con.getResponseCode();
    		//System.out.println(responseCode);
    
    		//Stream
    		try (Reader r = new InputStreamReader(con.getInputStream())) {
    			Json json = new Json();
    			return json.parse(r);
    		}
    	}
    
    	@SuppressWarnings("unchecked")
    	List<FilrUser> getUsers() throws IOException {
    		Map<String, Object> users = getDataAsMap("users/");
    		List<FilrUser> fuser = new ArrayList<FilrUser>();
    		List<Object> items = (List<Object>) users.get("items");
    		for (Object item : items) {
    			fuser.add(new FilrUser((Map<String, Object>) item));
    		}
    		return fuser;
    	}
    
    	@SuppressWarnings("unchecked")
    	FilrUser searchUser(String username) throws IOException {
    		Map<String, Object> users = getDataAsMap("principals?keyword=" + username);
    
    		List<Object> items = (List<Object>) users.get("items");
    		for (Object item : items) {
    			FilrUser fuser = new FilrUser((Map<String, Object>) item);
    			return fuser;
    		}
    		return null;
    	}
    
    	FilrUser getUser(String username) throws IOException {
    		Map<String, Object> user = getDataAsMap("users/name/" + username);
    		if (user != null && "user".equals(user.get("entity_type"))) {
    			FilrUser fuser = new FilrUser(user);
    			if (fuser.title.equals(username)) {
    				return fuser;
    			}
    		}
    		return null;
    	}
    
    	void createUserIfAbsent(String username, String passwd) throws IOException {
    
    		HashMap<String, Object> map = new HashMap<String, Object>();
    		map.put("name", username);
    		//map.put("title", username); // NOT_SUPPORTED:Cannot set title directly
    		//map.put("password", passwd); // BAD_INPUT:Unrecognized field password
    		map.put("entity_type", "user");
    		map.put("doc_type", "entry");
    
    		if (getUser(username) == null) {
    			System.out.println(Json.toJsonString(map));
    			postData("users/?password="+passwd, Json.toJsonString(map));
    		}
    
    	}
    
    }
    Code:
    import java.util.Map;
    
    public class FilrUser {
    
    	public Double id;
    	public String title;
    	public String email;
    
    	public FilrUser(Map<String, Object> userMap) {
    		if(!"user".equals( userMap.get("entity_type")))
    			throw new RuntimeException("!'user'.equals( userMap.get('entity_type'))");
    		id = (Double) userMap.get("id");
    		title = (String) userMap.get("title");
    		email = (String) userMap.get("email_address");
    	}
    
    	@Override
    	public String toString() {
    		return "FilrUser [id=" + id + ", title=" + title + ", email=" + email + "]";
    	}
    }
    Use like this:
    Code:
    	 final static String FilrURL = "http://localhost:8080/rest/"; 
    	 final static String FilrUser = "Admin"; 
    	 final static String FilrPass = "admin"; 
    
    	public static void main(String[] args) throws IOException {
    		
    		FilrRestClient frc = new FilrRestClient(FilrURL, FilrUser, FilrPass);
    		
    		List<FilrUser> users = frc.getUsers();
    		for (FilrUser filrUser : users) {
    			System.out.println(filrUser.title);
    		}
    		
    		
    		FilrUser user = frc.getUser("admin");
    		System.out.println(user);
    
    		//frc.createUserIfAbsent("ray", "ray");

  2. #2
    Automatic reply NNTP User

    Re: An example Vibe/Filr REST client written in Java.

    rhulha,

    It appears that in the past few days you have not received a response to your
    posting. That concerns us, and has triggered this automated reply.

    These forums are peer-to-peer, best effort, volunteer run and that if your issue
    is urgent or not getting a response, you might try one of the following options:

    - Visit http://www.novell.com/support and search the knowledgebase and/or check
    all the other self support options and support programs available.
    - Open a service request: https://www.novell.com/support
    - You could also try posting your message again. Make sure it is posted in the
    correct newsgroup. (http://forums.novell.com)
    - You might consider hiring a local partner to assist you.
    https://www.partnernetprogram.com/pa...nder/find.html

    Be sure to read the forum FAQ about what to expect in the way of responses:
    http://forums.novell.com/faq.php

    Sometimes this automatic posting will alert someone that can respond.

    If this is a reply to a duplicate posting or otherwise posted in error, please
    ignore and accept our apologies and rest assured we will issue a stern reprimand
    to our posting bot.

    Good luck!

    Your Novell Forums Team
    http://forums.novell.com



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •