package websample.crtest;

import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.representation.InputRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

public class Fetch extends ServerResource {
    
    
    @Get
    public Representation fetch(){
        Form f = this.getReference().getQueryAsForm();
        String url = f.getFirstValue("url");
        if(url == null){
            url = "https://www.yahoo.com";
        }
        else{
            if(!url.startsWith("http"))
                url = "http://"+url;
        }
        this.getLogger().info("Retrieving: "+url);
        ClientResource cr = new ClientResource(url);
        Representation toRet = null;
        
        try{
            Representation r = cr.get();
            String text = r.getText();
            //System.out.println(text);
            MediaType mt = r.getMediaType();
            toRet = new StringRepresentation(text, mt);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        if(cr != null) cr.release();
        return toRet;
    }

}
