Thanks for the sample code! I have managed to convert it to  Java and
successfully
execute  factor(2006) in sage from Java.

Shing

public class SageSession {


        public String getSession(String hostname, String port, String
password) {

                String session = null;
                String httpStr = "http://"; + hostname + ":" + port
                                + "/simple/login?username=admin&password=" + 
password;
                try {

                        URL url = new URL(httpStr);
                        HttpURLConnection connection = (HttpURLConnection) url
                                        .openConnection();
                        InputStream is = connection.getInputStream();
                        BufferedReader br = new BufferedReader(new 
InputStreamReader(is));
                        String line;
                        while ((line = br.readLine()) != null) {
                                //System.out.println("OUT> " + line);
                                if (line.indexOf("session") > 0) {
                                        StringTokenizer tokenizer = new 
StringTokenizer(line,
                                                        "\": ");
                                        tokenizer.nextElement();
                                        session = (String) 
tokenizer.nextElement();
                                        break;
                                }
                        }
                        br.close();
                        is.close();
                        connection.disconnect();
                }

                catch (MalformedURLException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }

                return session;
        }

        /**
         * Execute expression in sage and return the result as a String.
         */
        public String sage(String hostname, String port, String session,
String expression) {

                StringBuffer result = new StringBuffer();
                try {
                        String httpStr = "http://"; + hostname + ":" + port + 
"/simple/
compute?session="
            + session + "&code=" +
URLEncoder.encode(expression,"UTF-8");
                        URL url = new URL(httpStr);
                        HttpURLConnection connection = (HttpURLConnection) url
                                        .openConnection();
                        InputStream is = connection.getInputStream();
                        BufferedReader br = new BufferedReader(new 
InputStreamReader(is));
                        String line;
                        while ((line = br.readLine()) != null) {
                                //System.out.println("OUT> " + line);
                            result.append(line +"\n");

                        }
                        br.close();
                        is.close();
                        connection.disconnect();
                }

                catch (MalformedURLException e) {
                         e.printStackTrace( );
                } catch (IOException e) {
                        e.printStackTrace();
                }


                return result.toString();
        }

        public static void main(String[] str) throws Exception {
                String host = "localhost";
                String port = "8000";
                String password = "xxx";

                SageSession connection = new SageSession();
                String session = connection.getSession(host, port, password);
                System.out.println("session =" + session);
                String expression ="factor(2^12 -1)";
                String result = connection.sage(host, port, session, 
expression);
                System.out.println("expression =" + result );

        }
}




On Jul 19, 8:34 pm, "Mike Hansen" <[EMAIL PROTECTED]> wrote:
> Hi Shing,
>
> You can actually make HTTP calls to the Sage notebook using Robert
> Bradshaw's simple API.  For example, the following is a (condensed)
> Python script which authenticates with a running Sage notebook.
>
> import urllib, re
> def get_url(url):
>     h = urllib.urlopen(url); data = h.read(); h.close(); return data
> session = None
> def sage(expression, host="localhost", passwd = "passwd", port = 8000):
>     global session
>     if session is None:
>         login_page =
> get_url('http://%s:%s/simple/login?username=admin&password=%s' %
> (host, port, passwd))
>         session = re.match(r'.*"session": "([^"]*)"', login_page,
> re.DOTALL).groups()[0] #extract the sessionid from the result
>     expression = urllib.quote(expression)
>     res = get_url('http://%s:%s/simple/compute?session=%s&code=%s' %
> (host, port, session, expression))
>     return res
> def test_equality(expr1, expr2):
>     res = sage("bool( %s == %s)"%(expr1, expr2))
>     dictionary, res = res.split("___S_A_G_E___")
>     res = res.strip()
>     return True if res == "True" else False
>
> The function 'sage' takes in a Sage expression and returns the result
> as a string.  You can look at sage/server/simple/twist.py for more
> examples of how this is used.  Doing the same thing from Java wouldn't
> be difficult.
>
> --Mike
>
> On Sat, Jul 19, 2008 at 2:24 PM, Shing <[EMAIL PROTECTED]> wrote:
>
> > I have upgraded to 3.0.5. Now the time taken to run the factor script
> > is down to 2s (with 3.0.3 it was 12s)
> > I am trying to call Sage from a Java web application. So far the only
> > way I know is to do it indirectly by running
> > a sage script from Java.  Is there a more directly way of calling Sage
> > from Java ?
> > The factor script is just a test. In general, my sage script would do
> > different computation.
>
> > Thanks!
> > Shing
>
> > On Jul 19, 1:45 pm, "William Stein" <[EMAIL PROTECTED]> wrote:
> >> On Sat, Jul 19, 2008 at 1:53 PM, Shing <[EMAIL PROTECTED]> wrote:
>
> >> > Hi,
> >> >   I have tried the standalone Python/Script at
> >> >http://www.sagemath.org/doc/html/tut/node55.html
>
> >> > to factorize a number.
>
> >> > #!/usr/bin/env sage
>
> >> > import sys
> >> > from sage.all import *
>
> >> > if len(sys.argv) != 2:
> >> >    print "Usage: %s <n>"%sys.argv[0]
> >> >    print "Outputs the prime factorization of n."
> >> >    sys.exit(1)
>
> >> > print factor(sage_eval(sys.argv[1]))
>
> >> > The script takes about 12s to factories 2006. But in the notebook,
> >> > it takes  less than 1 second.
> >> > I would like to use a standalone script from command line to do some
> >> > computation. Is there a way to speed it up ?
>
> >> > I am using Sage 3.0.3 on a Athlon 3200 64bit PC, running OpenSuse 11.
>
> >> > Thanks in advance for any assistance!
>
> >> The Sage startup time in sage-3.0.5 is better than in 3.0.3, so you might
> >> want to try upgrading.   Are you *just* factoring integers are do you plan
> >> to do much more?  This is fast:
>
> >> teragon-2:~ was$ time echo "factor(2006)" | sage -gp
> >>                   GP/PARI CALCULATOR Version 2.3.3 (released)
> >>            i386 running darwin (ix86/GMP-4.2.1 kernel) 32-bit version
> >>             compiled: May  4 2008, gcc-4.0.1 (Apple Inc. build 5465)
> >>                 (readline v5.2 enabled, extended help available)
>
> >>                      Copyright (C) 2000-2006 The PARI Group
>
> >> PARI/GP is free software, covered by the GNU General Public License, and
> >> comes WITHOUT ANY WARRANTY WHATSOEVER.
>
> >> Type ? for help, \q to quit.
> >> Type ?12 for how to get moral (and possibly technical) support.
>
> >> parisize = 4000000, primelimit = 500000
> >> %1 =
> >> [2 1]
>
> >> [17 1]
>
> >> [59 1]
>
> >> Goodbye!
>
> >> real    0m0.388s
> >> user    0m0.033s
> >> sys     0m0.051s
>
> >>  -- William
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sage-support
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---

Reply via email to