/*------------------------------------------------------------------*/
/* Web Development with SAS by Example, Second Edition */
/* by Frederick E. Pratter */
/* Copyright(c) 2006 by SAS Institute Inc., Cary, NC, USA */
/* ISBN: 978-1-59047-501-0 */
/* ISBN-10: 1-59047-501-1 */
/* */
/*-------------------------------------------------------------------/
/* */
/* This material is provided "as is" by SAS Institute Inc. There */
/* are no warranties, expressed or implied, as to merchantability or*/
/* fitness for a particular purpose regarding the materials or code */
/* contained herein. The Institute is not responsible for errors */
/* in this material as it now exists or will exist, nor does the */
/* Institute provide technical support for it. */
/* */
/*-------------------------------------------------------------------/
/* Questions or problem reports concerning this material may be */
/* addressed to the author: */
/* */
/* SAS Institute Inc. */
/* SAS Publishing */
/* Attn: Frederick E. Pratter */
/* SAS Campus Drive */
/* Cary, NC 27513 */
/* */
/* */
/* If you prefer, you can send email to: */
/* */
/* saspress@sas.com */
/* */
/* Use this for subject field: */
/* */
/* Comments for Frederick Pratter */
/* */
/*------------------------------------------------------------------*/
/* Date Last Updated: September 25, 2006 */
/*------------------------------------------------------------------*/
Chapter 2
Example 2.1 Sample HTML Page Source
Eastern Oregon University Computer Science &
Multimedia Studies Program
Chapter 3
Example 3.1 Sample PROC TABULATE Program
options noovp nodate nonumber nocenter ls=80;
proc tabulate data=SASHELP.RETAIL
formchar="|----|+|---+=|-/\<>*";
title "Retail Sales In Millions Of $";
class YEAR/descending;
var SALES;
table YEAR="" all="Total", SALES="" *
(sum="Total Sales"*f=dollar8.
pctsum="Overall Percent"*f=8.2
n="Number of Sales"*f=8.
mean="Average Sale"*f=dollar8.2
min="Smallest Sale"*f=dollar8.
max="Largest Sale"*f=dollar8.)/
box="Year" rts=8;
run;
Example 3.2 Using HTML Pre-formatting
Retail Sales Table
Example 3.3 Using PUT statements to Write HTML
filename temp 'Example 3-3.lst';
filename out 'Example 3-3.html';
*** redirect procedure output ***;
proc printto new file=temp;
*** create table ***;
proc tabulate data=SASHELP.RETAIL
formchar='|----|+|---+=|-/\<>*';
title 'Retail Sales In Millions Of $';
class YEAR/descending;
var SALES;
table YEAR='' all='Total', SALES='' *
(sum='Total Sales'*f=dollar8.
pctsum='Overall Percent'*f=8.2
n='Number of Sales'*f=8.
mean='Average Sale'*f=dollar8.2
min='Smallest Sale'*f=dollar8.
max='Largest Sale'*f=dollar8.)/
box='Year' rts=8;
run;
*** turn off redirection ****;
proc printto;
*** generate HTML output ***;
data _null_;
infile temp end=eof;
input;
file out;
if (_n_ eq 1) then /* write header and title */
put ''/
''/
'' _infile_ ''/
''/
'
' _infile_ '
'/
'
';
else put _infile_;
if (eof) then /* write closing tags */
put '
'/ ''/' ';
run;
Example 3.4 HTML Output Formatter Macro
filename OUT '../public_html/example3-4.html';
%OUT2HTM(capture=on);
*** create table ***;
proc means data=SASHELP.RETAIL
n mean min max
nonobs fw=8 maxdec=2;
class YEAR/descending;
var SALES;
title;
run;
%OUT2HTM(capture=off, htmlfref=OUT);
Example 3.5 %OUT2HTM Macro HTML Source
The MEANS Procedure
Analysis Variable : SALES Retail sales in millions of $
YEAR N Mean Minimum Maximum
--------------------------------------------------
Example 3.6 Data Set Formatter Macro
filename OUT '../public_html/example3-6.html';
title Sales Total by Month;
%ds2htm (
data = SASHELP.RETAIL,
where = YEAR gt 1990,
var = YEAR MONTH SALES,
htmlfref = out);
Example 3.7 %DS2HTM Macro HTML Source
Sales Total by Month
YEAR
MONTH
Retail sales in millions of
$
1991
1
$703
1991
4
$709
1991
7
$728
1991
10
$807
[... repeated lines omitted ...]
1994
1
$876
1994
4
$998
Example 3.8 Tabulate Formatter Macro
options noovp nodate nonumber nocenter ls=80
formchar='82838485868788898a8b8c'x;
filename OUT '../public_html/example3-8.html';
%TAB2HTM(capture=on);
*** create table ***;
proc tabulate data=SASHELP.RETAIL;
title 'Retail Sales In Millions Of $';
class YEAR/descending;
var SALES;
table YEAR='' all='Total', SALES='' *
(sum='Total Sales'*f=dollar8.
pctsum='Overall Percent'*f=8.2
n='Number of Sales'*f=8.
mean='Average Sale'*f=dollar8.2
min='Smallest Sale'*f=dollar8.
max='Largest Sale'*f=dollar8.)/
box='Year' rts=8;
run;
%TAB2HTM(capture=off, htmlfref=OUT, center=Y);
Example 3.9 Tabulate Formatter Macro HTML Source
Retail Sales In Millions Of $
Year
Total Sales
Overall Percent
Number of Sales
Average Sale
Smallest Sale
Largest Sale
1994
$1,874
5.97
2
$937.00
$876
$998
1993
$3,578
11.40
4
$894.50
$758
$991
[... repeated lines omitted ...]
1980
$1,030
3.28
4
$257.50
$220
$295
Total
$31,374
100.00
58
$540.93
$220
$998
Example 3.10 SAS Display Manager HTML Source
SAS Output
Retail Sales In Millions Of
$
Year
Total Sales
Overall Percent
Number of Sales
Average Sale
Smallest Sale
Largest Sale
1994
$1,874
5.97
2
$937.00
$876
$998
[... repeated lines omitted ...]
Total
$31,374
100.00
58
$540.93
$220
$998
Example 3.11 Using the ODS HTML Statement
filename OUT "Example 3-11.html";
ods listing close;
ods html body=OUT;
proc tabulate data=SASHELP.RETAIL;
title "Retail Sales In Millions of $";
class YEAR/descending;
var SALES;
table YEAR="" all="Total", SALES="" *
(sum="Total Sales"*f=dollar8.
pctsum="Overall Percent"*f=8.2
n="Number of Sales"*f=8.
mean="Average Sale"*f=dollar8.2
min="Smallest Sale"*f=dollar8.
max="Largest Sale"*f=dollar8.)/
box="Year" rts=8;
run;
ods html close;
ods listing;
Example 3.12 Creating Multiple Web Pages
ods listing close;
ods html body="../public_html/example3-12.html" newfile=proc;
***** Step #1 ****;
proc print data=SASHELP.RETAIL;
title "1994 Sales Total by Month";
where YEAR gt 1990;
var MONTH SALES;
id YEAR;
run;
***** Step #2 ****;
proc means data=SASHELP.RETAIL
n mean min max
nonobs fw=8 maxdec=2;
title 'Retail Sales In Millions Of $';
class YEAR/descending;
var SALES;
run;
***** Step #3 ****;
proc tabulate data=SASHELP.RETAIL;
class YEAR/descending;
var SALES;
table YEAR='' all='Total', SALES='' *
(sum='Total Sales'*f=dollar8.
pctsum='Overall Percent'*f=8.2
n='Number of Sales'*f=8.
mean='Average Sale'*f=dollar8.2
min='Smallest Sale'*f=dollar8.
max='Largest Sale'*f=dollar8.)/
box='Year' rts=8;
run;
ods html close;
ods listing;
Example 3.13 Creating Frames with ODS
ods listing close;
ods html path="../public_html" (url="http://hygelac/BBU/")
body = "body3-13.html"
contents = "contents3-13.html"
frame = "frame3-13.html";
***** Step #1 ****;
proc print data=SASHELP.RETAIL;
title "1994 Sales Total by Month";
where YEAR gt 1990;
var MONTH SALES;
id YEAR;
run;
***** Step #2 ****;
proc means data=SASHELP.RETAIL
n mean min max
nonobs fw=8 maxdec=2;
title 'Retail Sales In Millions Of $';
class YEAR/descending;
var SALES;
run;
***** Step #3 ****;
proc tabulate data=SASHELP.RETAIL;
class YEAR/descending;
var SALES;
table YEAR='' all='Total', SALES='' *
(sum='Total Sales'*f=dollar8.
pctsum='Overall Percent'*f=8.2
n='Number of Sales'*f=8.
mean='Average Sale'*f=dollar8.2
min='Smallest Sale'*f=dollar8.
max='Largest Sale'*f=dollar8.)/
box='Year' rts=8;
run;
ods html close;
ods listing;
Example 3.14 ODS HTML Data Set Listing
filename OUT "../public_html/example3-14.html";
title "Sales Total by Month 1991-1994";
ods listing close;
ods html body=OUT;
data _null_;
set SASHELP.RETAIL;
where (YEAR gt 1990);
file print ods=(variables=(YEAR MONTH SALES));
put _ods_;
run;
ods html close;
ods listing;
Example 3.15 Default Style Template
proc template;
define style Styles.Default;
style fonts
"Fonts used in the default style" /
'TitleFont2' = ("Arial, Helvetica, sans-serif",4,Bold Italic)
'TitleFont' = ("Arial, Helvetica, sans-serif",5,Bold Italic)
'StrongFont' = ("Arial, Helvetica, sans-serif",4,Bold)
'EmphasisFont' = ("Arial, Helvetica, sans-serif",3,Italic)
'FixedEmphasisFont' = ("Courier New, Courier,
monospace",2,Italic)
'FixedStrongFont' = ("Courier New, Courier,
monospace",2,Bold)
'FixedHeadingFont' = ("Courier New, Courier, monospace",2)
'BatchFixedFont' = ("SAS Monospace, Courier New, Courier,
monospace",2)
'FixedFont' = ("Courier",2)
'headingEmphasisFont' = ("Arial, Helvetica, sansserif",
4,Bold Italic)
'headingFont' = ("Arial, Helvetica, sans-serif",4,Bold)
'docFont' = ("Arial, Helvetica, sans-serif",3);
[ ... many more styles omitted ... ]
end;
run;
Example 3.16 ODS Sasweb Style Data Set Listing
filename OUT "../public_html/example3-16.html";
title "Sales Total by Month 1991-1994";
ods listing close;
ods html body=OUT style=sasweb;
data _null_;
set SASHELP.RETAIL;
where (YEAR gt 1990);
file print ods=(variables=(YEAR MONTH SALES));
put _ods_;
run;
ods html close;
ods listing;
Example 3.17 ODS Markup: XHTML
filename OUT "../public_html/example3-17.html";
ods listing close;
ods markup body=OUT tagset=XHTML;
proc tabulate data=SASHELP.RETAIL;
title "Retail Sales In Millions Of $";
class YEAR/descending;
var SALES;
table YEAR="" all="Total", SALES="" *
(sum="Total Sales"*f=dollar8.
pctsum="Overall Percent"*f=8.2
n="Number of Sales"*f=8.
mean="Average Sale"*f=dollar8.2
min="Smallest Sale"*f=dollar8.
max="Largest Sale"*f=dollar8.)/
box="Year" rts=8;
run;
ods markup close;
ods listing;
Example 3.18 XHTML Source
SAS Output
Retail Sales In Millions Of $
Year
Total Sales
Overall Percent
Number of Sales
Average Sale
Smallest Sale
Largest Sale
1994
$1,874
5.97
2
$937.00
$876
$998
[... repeated lines omitted ...]
1980
$1,030
3.28
4
$257.50
$220
$295
Total
$31,374
100.00
58
$540.93
$220
$998
Example 3.19 XHTML Template
proc template;
define tagset Tagsets.xhtml / store = SASUSER.TEMPLAT;
define event cell_is_empty;
put %nrstr(" ");
end;
define event doc;
start:
put "" NL;
put "" NL;
put "" NL;
ndent;
finish:
xdent;
put "" NL;
end;
define event doc_head;
start:
put "" NL;
ndent;
finish:
xdent;
put "" NL;
end;
define event doc_body;
start:
put "" NL;
put TITLE;
finish:
/* add W3C logo to page */
put '
' NL;
put '' NL;
end;
define event doc_title;
put "";
put "SAS Output" / if !exists(VALUE);
put VALUE;
put "" NL;
end;
define event proc_title;
put "
" VALUE "
" CR;
end;
define event system_title;
put "
" VALUE "
" CR;
end;
define event system_footer;
put "
" VALUE "
" CR;
end;
define event byline;
put "
" VALUE "
" CR;
end;
define event note;
put "
" VALUE "
" CR;
end;
define event fatal;
put "
" VALUE "
" CR;
end;
define event error;
put "
" VALUE "
" CR;
end;
define event warning;
put "
" VALUE "
" CR;
end;
define event table;
start:
put "
" NL;
ndent;
finish:
xdent;
put "
" NL;
end;
define event row;
start:
put "
" NL;
ndent;
finish:
xdent;
put "
" NL;
end;
define event table_head;
start:
put "" NL;
ndent;
finish:
xdent;
put "" NL;
end;
define event table_body;
start:
put "" NL;
ndent;
finish:
xdent;
put "" NL;
end;
define event table_foot;
start:
put "" NL;
ndent;
finish:
xdent;
put "" NL;
end;
define event rowcol;
putq " rowspan=" ROWSPAN;
putq " colspan=" COLSPAN;
end;
define event header;
start:
put "
";
put VALUE;
finish:
put "
";
end;
define event data;
start:
put "
";
put VALUE;
finish:
put "
" NL / if cmp( section , "head" );
put "" NL / if !cmp( section , "head" );
end;
mapsub = %nrstr("/</>/&/"/");
map = %nrstr("<>&""");
split = " ";
output_type = "xml";
indent = 3;
end; /* define tagset */
Chapter 4
Example 4.1 Sample Program to Start the SAS/SHARE Server
*****************************************************;
***** start SAS/SHARE server on local host *****;
***** system administrator password: system *****;
***** user pasword: user *****;
***** authentication is on *****;
*****************************************************;
proc server
id=shr1
oapw=system
uapw=user
authenticate=required;
run;
Example 4.2 Stop the SAS/SHARE Server
*****************************************************;
***** stop SAS/SHARE server on local host *****;
*****************************************************;
proc operate serverid=shr1 sapw=system uid=_prompt_;
stop server;
run;
Example 4.4 Remote Library Services
libname SHARED slibref=SASHELP server=hygelac.shr1 sapw=user passwd=_prompt_;
proc print data=SHARED.RETAIL;
title "Retail Sales Total by Month: 1991-1994";
where YEAR gt 1990;
var MONTH SALES;
id YEAR;
run;
Example 4.5 Remote SQL Pass-Through
proc sql;
connect to remote (server=hygelac.shr1 sapw=user user=frederick password=_prompt_);
select * from connection to remote
(select YEAR, MONTH, sum(SALES)
format=dollar12. label='Total Sales'
from SASHELP.RETAIL
group by YEAR, MONTH);
quit;
Example 4.6 Remote Compute Services
rsubmit;
proc tabulate data=SASHELP.RETAIL;
title "Retail Sales In Millions Of $";
class YEAR/descending;
var SALES;
table YEAR="" all="Total", SALES="" *
(sum="Total Sales"*f=dollar8.
pctsum="Overall Percent"*f=8.2
n="Number of Sales"*f=8.
mean="Average Sale"*f=dollar8.2
min="Smallest Sale"*f=dollar8.
max="Largest Sale"*f=dollar8.)/
box="Year" rts=8;
run;
endrsubmit;
Chapter 5
Example 5.1 Hello World CGI Program
#!/usr/bin/perl
##
## HelloWorld.pl ? My first Perl program
##
use CGI ':standard'; # include CGI module
print header; # generate MIME content line
print start_html "CGI Examples"; # generate starting HTML tags
# print "Hello World"
print h1( { -style=>'color: blue; '}, 'Hello World!');
# generate date/time field
( $s, $m, $h, $d, $mm, $y ) = localtime(time);
$y+=1900; # convert 2-digit year to 4
$mm++; # months start with 0
print p( {-style=>'font-weight: bold; font-size: 24;'},
"The time now: $h:$m on $mm/$d/$y:");
print end_html; # generate ending HTML tags
Example 5.2 Perl-Generated HTML Source
Content-Type: text/html; charset=ISO-8859-1
CGI Examples
Hello World!
The time now is 10:44 on 12/22/2005.
Example 5.3 Perl Temperature Conversion Calculator
#!/usr/bin/perl
##
## Sample Perl program for temperature conversion
##
use CGI ':standard';
print header;
print start_html "Perl Temperature Conversion Examples";
# get input parameters and calculate result
$temp = param("input");
$type = param("convert");
if ( $type == 1 ) # convert F to C
{
$result = 5*($temp - 32)/9;
}
elsif ( $type == 2 )# convert C to F
{
$result = 9*$temp/5 + 32;
}
print '
';
print end_html;
Chapter 6
Example 6.1 SAS/IntrNet: Hello World
/*simply write out a web page that says "Hello World!"*/
data _null_;
file _webout;
put '';
put 'Hello World!';
put '';
put '
Hello World!
';
put '';
put '';
run;
Example 6.2 SAS/IntrNet: Temperature Conversion Program
/* SAS/IntrNet program to convert F to C and vice versa */
data _null_;
file _webout;
***** write generic XHTML header *****;
put ''/
''/
'';
***** write top of page *****;
put ''/
'SAS/IntrNet Temperature Conversion
Calculator'/
''/
''/
'
'/
'
Temperature Conversion Calculator
';
**** create HTML form * with hidden text fields ***;
put ''/
'
'/
''/
'';
run;
Example 6.3 PROC APPSRV
proc appsrv unsafe='&";%''' &sysparm;
allocate file sample '!SASROOT\IntrNet\sample';
allocate library samplib '!SASROOT\IntrNet\sample' access=readonly;
allocate library sampdat '!SASROOT\IntrNet\sample' access=readonly;
allocate library tmplib 'C:\Program Files\SAS\IntrNet\default\temp';
allocate file logfile
'C:\Program Files\SAS\IntrNet\default\logs\%a_%p.log';
/* allocate new program library */
allocate file examples 'c:\Inetpub\scripts\examples';
proglibs examples;
proglibs sample samplib %ifcexist(sashelp.webeis) sashelp.webprog;
proglibs sashelp.websdk1;
adminlibs sashelp.webadmn;
datalibs sampdat tmplib;
log file=logfile;
quit;
Example 6.4 Using ODS to Display Procedure Output
%* Sales report Example - Display Product by Region;
%macro salesrpt;
%global region;
proc report data=sashelp.shoes;
by region;
%if (®ion ne ) %then %do;
where region="®ion";
%end;
title "Sales by Product";
footnote "Data are current as of &systime &sysdate9";
column product sales;
define product / group;
define sales / analysis sum;
quit;
%mend salesrpt;
/* redirect output to client */
ods html3 body=_webout;
%salesrpt
Example 6.5 Using ODS MARKUP to Customize Procedure Output
/* prepend XHTML template */
libname userlib
"c:\Documents and Settings\frederick\My Documents\My SAS Files\9.1";
ods path (prepend) userlib.templat;
/* redirect output to client */
ods markup body=_webout tagset=xhtml;
Chapter 7
Example 7.1 Summarizing Data with htmSQL
SAS IntrNet Examples: htmSQL
{query server="hygelac:5011" sapw="user" userid="sas" password="sasuser" }
{sql}
select product,
sum(sales) as total label="Total Sales" format=dollar8.
from sashelp.shoes
where region='{®ion}'
group by product
{/sql}
Shoe Sales by Product
{norows}
No rows selected. Check that the region parameter has been specified correctly.
{/norows}
Region: {®ion}
{label var="{&sys.colname[*]}"
before="
"
between="
"
after="
"}
{eachrow}
{ &{&sys.colname[*]}
before="
"
between="
"
after="
" }
{/eachrow}
{/query}
Data are current as of {&sys.time}{&sys.ampm}
{&sys.month} {&sys.monthday}, {&sys.year}
Example 7.2 htmSQL Code to Generate Form Control Values
SAS IntrNet Examples: htmSQL
{query server="hygelac:5011"
sapw="user" userid="sas" password="sasuser" }
{sql} select distinct region from sashelp.shoes{/sql}
{/query}
Chapter 8
Example 8.1 The Basic JavaBean
// A simple Bean
import java.io.Serializable;
public class TestBean
implements Serializable
{
private int num;
public void setValue(int n)
{
num = n;
}
public int getValue()
{
return num;
}
}
Example 8.2 Hello World Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out;
String title = "Simple Servlet Output";
response.setContentType("text/html");
out = response.getWriter();
out.println("");
out.println(title);
out.println("");
out.println("
" + title + "
");
out.println("
Hello World!");
out.println("");
out.close();
}
public void doPost (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
Example 8.3 Servlet Configuration File web.xml
BBU Examples
Hello World servlet example
HelloWorldHelloWorldHelloWorld/HelloWorld
Example 8.4 Simple JSP Example
JSP Examples
Simple JavaServer Page
<% out.print("Hello World!"); %>
The time now is <%= new java.util.Date() %>
Example 8.5 Custom Tag Handler
import java.util.Date;import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class SimpleTag extends TagSupport
{
public int doStartTag() throws JspException
{
try
{
pageContext.getOut().print
("Hello World." + "The time now is " + new Date());
}
catch (Exception ex)
{
throw new JspTagException
("SimpleTag: " + ex.getMessage());
}
return SKIP_BODY;
}
public int doEndTag()
{
return EVAL_PAGE;
}
}
Example 8.6 Tag Library Description
1.01.2Sample tag libraryLibrary for simple tag exampleSayHello SimpleTagEMPTYHello world example
Example 8.7 JSP Using Custom Tags
<%@ taglib URL="simple.tld" prefix="test" %>
JSP Examples ? Custom Tag Library
JavaServer Page Custom Tag Example
Example 8.8 JDBC Example
import java.sql.*;
/* connection test to a remote SAS/SHARE server using JDBC */
public class JDBCTest
{
public static void main(String[] args)
{
Connection con = null;
try // open connection to database
{
Class.forName(
"com.sas.net.sharenet.ShareNetDriver");
con = DriverManager.getConnection(
"jdbc:sharenet://hunding:8551?
user=sasdemo&password=sasuser");
// print connection information
DatabaseMetaData dma = con.getMetaData();
System.out.println("Connected to " + dma.getURL());
System.out.println("Driver " + dma.getDriverName());
System.out.println("Version " + dma.getDriverVersion());
}
catch(Exception e) { e.printStackTrace(); }
finally // make sure connection gets closed properly
{
Try { if (null != con) con.close(); }
catch (SQLException e) {}
}
}
}
Example 8.9 Using JDBC with JSTL Custom Tags
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
JSP Examples - JDBC
SASHELP.CLASS
SAS Share JDBC Driver
<%-- open a database connection --%>
<%-- execute the database query --%>
select * from sashelp.class
<%-- Print the column names for the header of the table --%>
Name
Age
Sex
Height
Weight
<%-- loop through the rows of the query --%>
Example 8.10 HTML Data Entry Form
JSP Examples: JSTL Demo
Demo Entry Form
Example 8.11 Updating a Database with JSTL and JDBC
<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
JSP Examples: JSTL Demo
<%-- update data --%>
<% /* SQL code to append parameters to CLASS table */
String strSQL="INSERT INTO sashelp.class SET " +
"name=\""+request.getParameter("name")+"\","+
"sex=\""+request.getParameter("sex")+"\","+
"age="+request.getParameter("age")+","+
"height="+request.getParameter("height")+","+
"weight="+request.getParameter("weight");
%>
<%=strSQL %>
[Java scriptlet comes next]
[HTML form code follows]
Example 9.2 Java Temperature Conversion Scriptlet
<% // Java scriptlet to calculate temperature conversion
String temp = request.getParameter("input");
String type = request.getParameter("convert");
String result = new String();
// make sure that we have values for the parameters
if (null != temp && null != type)
{
double dt = new Double(temp).doubleValue();
if (type.charAt(0) == 'F')
result = String.valueOf(5.0 * (dt - 32.0)/9.0);
else if (type.charAt(0) == 'C')
result = String.valueOf((9.0 * dt) / 5.0d + 32.0);
}
%>
Example 9.3 JSP Temperature Conversion Calculator
<%-- JSP Temperature Conversion Calculator --%>
<%@ include file="header.html" %>
<% // Java scriptlet to calculate temperature
String temp = request.getParameter("input");
String type = request.getParameter("convert");
String result = new String();
// make sure that we have values for the parameters
if (null != temp && null != type)
{
double dt = new Double(temp).doubleValue();
if (type.charAt(0) == 'F')
result = String.valueOf(5d * (dt - 32d)/9d);
else if (type.charAt(0) == 'C')
result = String.valueOf((9d * dt) / 5d + 32d);
}
%>
Temperature Conversion Calculator
Fahrenheit to Centigrade
Centigrade to Fahrenheit
Example 9.4 Scriptlet with pageContext Attributes
<%@ page import="com.sas.collection.OrderedCollection" %>
<% // Java scriptlet to calculate temperature
String temp = request.getParameter("input");
String type = request.getParameter("convert");
String result = new String();
// default is 1st radio button
int checked = 0;
// add the labels for the radio buttons to the page context
pageContext.setAttribute
( "values", new OrderedCollection("F,C") );
pageContext.setAttribute
( "labels", new OrderedCollection
("Fahrenheit to Centigrade, Centigrade to Fahrenheit"));
if (null != temp && null != type)
{
double dt = new Double(temp).doubleValue();
if (type.charAt(0) == 'F')
{
result = String.valueOf(5.0 * (dt - 32.0)/9.0);
}
else if (type.charAt(0) == 'C')
{
result = String.valueOf((9.0 * dt) / 5.0 + 32.0);
checked = 1;
}
}
%>
Fahrenheit to Centigrade
Centigrade to Fahrenheit
<%@ include file="footer.html" %>
Example 9.5 Sample PROC REPORT Macro
options nodate nonumber noovp nocenter pagesize=20;
/* Sample Program: shoes.sas */
%macro salesrpt(region);
proc report data=sashelp.shoes;
by region;
%if ( ®ion ne null ) %then %do;
where region="®ion";
%end;
title "
Shoe Sales by Region x Product
";
footnote "Data are current as of &systime &sysdate9";
column product sales;
define product / group;
define sales / analysis sum;
quit;
%mend salesrpt;
%salesrpt(<%= request.getParameter("region") %>)
Example 9.6 JavaServer Page Using SubmitInterface
<%@ taglib uri=http://www.sas.com/taglib/sasads prefix="sasads" %>
<%@ include file="header.html" %>
SubmitInterface Example
<%@ include file="shoes.sas" %>
Example 9.7 Using the SAS Appdev Studio 2.0 DataSetInfo Interface
<%@ taglib uri="http://www.sas.com/taglib/sasads"
prefix="sasads"%>
<%@ page import="com.sas.sasserver.datasetinfo.DataSetInfoInterface" %>
<%@ page import="com.sas.collection.OrderedCollection" %>
<%@ include file="header.html" %>
<% // Java scriptlet to add choicebox values to page context
DataSetInfoInterface dsinfo = (DataSetInfoInterface)
com.sas.servlet.util.Util.newInstance
(connection1.getClassFactory(),
connection1,
DataSetInfoInterface.class);
dsinfo.setDataSet("SASHELP.SHOES");
// display unique values of region
int index = dsinfo.getVariableIndex("REGION");
pageContext.setAttribute("values",
new OrderedCollection
(dsinfo.getVariableUniqueValues(index)));
%>
International Shoe Sales Data
Chapter 10
Example 10.1 Visual Basic Code to Test a DCOM Workspace Connection
Option Explicit
' define a global workspace
Dim obSAS As SAS.Workspace
Dim obWSMgr As New SASWorkspaceManager.WorkspaceManager
Private Sub Form_Load()
Dim xmlInfo As String
' create Workspace server
Dim obServer As New SASWorkspaceManager.ServerDef
obServer.MachineDNSName = "hunding"
Set obSAS = obWSMgr.Workspaces.CreateWorkspaceByServer _
("", VisibilityProcess, obServer, "", "", xmlInfo)
End Sub
Private Sub cmdTest1_Click()
' use LanguageService to submit code
obSAS.LanguageService.Submit _
"%include 'c:\temp\IOMTest.sas'; run;"
MsgBox obSAS.LanguageService.FlushLog(100000)
MsgBox obSAS.LanguageService.FlushList(100000)
End Sub
Private Sub cmdTest2_Click()
'run the stored SAS program
Dim obStoredProcessService As SAS.StoredProcessService
Set obStoredProcessService = _
obSAS.LanguageService.StoredProcessService
obStoredProcessService.Repository = "file:c:\temp"
obStoredProcessService.Execute "IOMtest", _
"cond='sex eq ""M""'"
MsgBox obSAS.LanguageService.FlushLog(100000)
MsgBox obSAS.LanguageService.FlushList(1000000)
End Sub
Private Sub Form_Unload(Cancel As Integer)
obWSMgr.Workspaces.RemoveWorkspaceByUUID obSAS.UniqueIdentifier
obSAS.Close
End Sub
Example 10.2 Visual Basic Code to Open an IOM Bridge Workspace Connection
' create Workspace server using IOM Bridge for COM
Dim obServer As New SASWorkspaceManager.ServerDef
obServer.MachineDNSName = "hygelac"
obServer.Protocol = ProtocolBridge
obServer.Port = 8591
Set obSAS = obWSMgr.Workspaces.CreateWorkspaceByServer _
("", VisibilityProcess, obServer, "sassrv", "sasuser", xmlInfo)
Example 10.3 Sample SAS Program
%let cond=;
*ProcessBody;
proc print data=sashelp.class;
title "Test IOM Connection";
where &cond;
run;
Example 10.4 C++ Code to Test a DCOM Workspace Connection
#include
#include
#include
using namespace std;
#import "C:\Program Files\SAS Institute\Shared Files\Integration
Technologies\sas.tlb"
#import "C:\Program Files\SAS Institute\Shared Files\Integration
Technologies\SASWMan.dll"
int main()
{
SASWorkspaceManager::IWorkspaceManager2Ptr pIWorkspaceManager;
SASWorkspaceManager::IServerDef2Ptr pIServerDef = NULL;
SAS::IWorkspacePtr pIWorkspace;
BSTR xmlInfo;
HRESULT hr = CoInitialize(NULL);
hr = pIWorkspaceManager.CreateInstance(
"SASWorkspaceManager.WorkspaceManager.1");
pIServerDef.CreateInstance("SASWorkspaceManager.ServerDef");
pIServerDef->PutMachineDNSName("hygelac");
pIServerDef->Protocol = SASWorkspaceManager::ProtocolBridge;
pIServerDef->put_Port(8591);
pIWorkspace = pIWorkspaceManager->Workspaces->CreateWorkspaceByServer(
_bstr_t(""), //workspace name
SASWorkspaceManager::VisibilityProcess,
pIServerDef, // server
_bstr_t("sassrv"), // login
_bstr_t("sasuser"), // password
&xmlInfo // connection log
);
pIWorkspace->LanguageService->Submit(
"%include '/home/sasadm/IOMTest.sas'; run;");
MessageBox(NULL,
pIWorkspace->LanguageService->FlushLog(10000),
"SAS Log",
MB_OK
);
MessageBox(NULL,
pIWorkspace->LanguageService->FlushList(10000),
"List Output",
MB_OK
);
pIWorkspace->Close();
return(0);
}
Example 10.5 Java Code to Test an IOM Bridge Workspace Connection
import com.sas.services.connection.Server;
import com.sas.services.connection.BridgeServer;
import com.sas.services.connection.ConnectionFactoryConfiguration;
import com.sas.services.connection.ConnectionFactoryManager;
import com.sas.services.connection.ConnectionFactoryInterface;
import com.sas.services.connection.ConnectionFactoryException;
import com.sas.services.connection.ConnectionInterface;
import com.sas.services.connection.ManualConnectionFactoryConfiguration;
import com.sas.iom.SAS.IWorkspace;
import com.sas.iom.SAS.IWorkspaceHelper;
import com.sas.iom.SAS.ILanguageService;
import com.sas.iom.SAS.ILanguageServicePackage.CarriageControlSeqHolder;
import com.sas.iom.SAS.ILanguageServicePackage.LineTypeSeqHolder;
import com.sas.iom.SASIOMDefs.GenericError;
import com.sas.iom.SASIOMDefs.StringSeqHolder;
import javax.swing.JOptionPane;
public class IOMTest{
public IOMTest() throws ConnectionFactoryException, GenericError
{
// connection parameters
String classID = Server.CLSID_SAS;
String host = "hunding";
int port = 8591;
String userName = "sassrv";
String password = "sasuser";
// identify the IOM Bridge server (the Workspace server)
Server server = new BridgeServer(classID,host,port);
// make a manual connection factory configuration
ConnectionFactoryConfiguration cxfConfig =
new ManualConnectionFactoryConfiguration(server);
// get a connection factory manager
ConnectionFactoryManager cxfManager =
new ConnectionFactoryManager();
// get a connection factory interface from the manager
ConnectionFactoryInterface cxf = cxfManager.getFactory(cxfConfig);
// get a connection from the interface
ConnectionInterface cx = cxf.getConnection(userName,password);
// create a workspace by "narrowing" connection to the ORB
IWorkspace iWorkspace = IWorkspaceHelper.narrow(cx.getObject());
// Submit batch SAS code
ILanguageService sasLanguage = iWorkspace.LanguageService();
sasLanguage.Submit("%include 'c:\\temp\\IOMtest.sas'; run;");
// flush log file to string array
StringSeqHolder logHldr = new StringSeqHolder();
sasLanguage.FlushLogLines(
Integer.MAX_VALUE,
new CarriageControlSeqHolder(),
new LineTypeSeqHolder(),
logHldr);
// display log file
String[] logLines = logHldr.value;
JOptionPane.showMessageDialog(null, logLines);
// flush list file to string array
StringSeqHolder listHldr = new StringSeqHolder();
sasLanguage.FlushListLines(
Integer.MAX_VALUE,
new CarriageControlSeqHolder(),
new LineTypeSeqHolder(),
listHldr);
// display list file
String[] listLines = listHldr.value;
JOptionPane.showMessageDialog(null, listLines);
iWorkspace.Close();
cx.close();
}
public static void main(String args[]) {
try {
new IOMTest();
System.exit(0);
}
catch(Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
}
Chapter 11
Example 11.1 Tomcat Installation Batch File
set JAVA_HOME=C:\j2sdk1.4.2_05
set CATALINA_HOME=C:\Tomcat4.1
set CATALINA_OPTS=-Xms512m -Xmx1024m
-server XX:-UseOnStackReplacement -Djava.awt.headless=true
rem The following command should be on a single line
%CATALINA_HOME%/bin/tomcat.exe
install Apache-Catalina %JAVA_HOME%/jre/bin/server/jvm.dll -
Djava.security.manager
Djava.security.policy=%CATALINA_HOME%/conf/catalina.policy -
Djava.class.path=%CATALINA_HOME%/bin/bootstrap.jar;
%JAVA_HOME%/lib/tools.jar
Dcatalina.home=%CATALINA_HOME% %CATALINA_OPTS% -Xrs
start org.apache.catalina.startup.BootstrapService
params start
stop org.apache.catalina.startup.BootstrapService
params stop
out %CATALINA_HOME%/logs/stdout.log
err %CATALINA_HOME%/logs/stderr.log\
Example 11.2 Sample Program to Generate Dynamic Output
%* Sales report Example ? Display Product by Region;
%macro salesrpt;
%global region;
proc report data=sashelp.shoes;
by region;
%if (®ion ne ) %then %do;
where region="®ion";
%end;
title "Sales by Product by Region";
footnote "Data are current as of &systime &sysdate9";
column product sales;
define product / group;
define sales / analysis sum;
quit;
%mend salesrpt;
%salesrpt
Example 11.3 Sample Stored Process Service Application3
package servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.sas.services.discovery.LocalDiscoveryServiceInterface;
import com.sas.services.discovery.DiscoveryService;
import com.sas.services.discovery.ServiceTemplate;
import com.sas.services.user.UserServiceInterface;
import com.sas.services.user.UserContextInterface;
import com.sas.services.session.SessionServiceInterface;
import com.sas.services.session.SessionContextInterface;
import com.sas.services.storedprocess.StoredProcessServiceFactory;
import com.sas.services.storedprocess.StoredProcessServiceInterface;
import com.sas.services.storedprocess.StoredProcessInterface;
import com.sas.services.storedprocess.ExecutionInterface;
import com.sas.services.connection.BridgeServer;
import com.sas.services.connection.Server;
import com.sas.services.connection.ConnectionFactoryInterface;
import com.sas.services.connection.ConnectionFactoryManager;
import com.sas.services.connection.ConnectionInterface;
import com.sas.services.connection.ConnectionFactoryConfiguration;
import
com.sas.services.connection.ManualConnectionFactoryConfiguration;
import com.sas.services.deployment.MetadataSourceInterface;
import com.sas.services.deployment.OMRMetadataSource;
import com.sas.services.deployment.ServiceLoader;
public class SimpleServlet extends HttpServlet
{
public void doPost (HttpServletRequest request,
HttpServletResponse response) throws IOException
{
PrintWriter out=response.getWriter();
response.setContentType("text/html");
// run-time values for Metadata server connection parameters
String host="hunding";
String port = "8561";
String userName = "sasdemo";
String password = "password";
String repository = "Foundation";
String softwareComponent = "Remote Services";
String serviceComponent = "BIP Remote Services OMR";
// run-time values for Stored Process server connection
int bridgeport = 8611;
String file="c:\\Documents and Settings\\sas\\My Documents";
String pgm="shoes.sas";
try
{
// connect to Metadata server on port 8561 to discover Services
LocalDiscoveryServiceInterface discoveryService =
DiscoveryService.defaultInstance();
MetadataSourceInterface metadataSource =
new OMRMetadataSource(host,port,userName,password,
repository,softwareComponent,serviceComponent);
ServiceLoader.lookupRemoteDiscoveryServices(
metadataSource, discoveryService);
// create user context
ServiceTemplate stp = new ServiceTemplate(
new Class[] {UserServiceInterface.class} );
UserServiceInterface userService = (UserServiceInterface)
discoveryService.findService(stp);
UserContextInterface user =
userService.newUser(userName,password,"DefaultAuth");
// create session context
stp = new ServiceTemplate( new Class[]
{SessionServiceInterface.class} );
SessionServiceInterface sessionService =
( SessionServiceInterface)
discoveryService.findService(stp);
SessionContextInterface sessionContext =
sessionService.newSessionContext(user);
// create stored process service
StoredProcessServiceFactory spFactory =
new StoredProcessServiceFactory();
StoredProcessServiceInterface spServiceInterface =
spFactory.getStoredProcessService();
StoredProcessInterface spi =
spServiceInterface.newStoredProcess(
sessionContext,
StoredProcessInterface.SERVER_TYPE_STOREDPROCESS,
StoredProcessInterface.RESULT_TYPE_STREAM);
// send messages to stored process
spi.setSourceFromFile(file,pgm);
spi.setParameterValue("region","Canada");
spi.addInputStream("_WEBOUT");
// connect to Stored Process Server on
// load balancing port 8611
BridgeServer server = new BridgeServer(
Server.CLSID_SASSTP,host,bridgeport);
ConnectionFactoryConfiguration cxfConfig =
new ManualConnectionFactoryConfiguration(server);
ConnectionFactoryInterface cxf = ConnectionFactoryManager.
getConnectionFactory(cxfConfig);
ConnectionInterface ci =
cxf.getConnection(userName,password);
// run stored process
ExecutionInterface ei = spi.execute(false,null,false,ci);
// display results
InputStream is = ei.getInputStream("_WEBOUT");
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String temp = "";
while((temp = br.readLine()) != null)
{
out.println(temp);
}
}
catch (Exception ex) {
out.println("" + "SAS encountered an error: " +
ex.getLocalizedMessage() + "");
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
}
Appendix A
Example A.1 JavaScript Date Example
Display Date Using JavaScript
Example A.2 JavaScript Temperature Conversion Calculator
JavaScript Temperature Conversion Calculator
Temperature Conversion Calculator
Appendix B
Example B.1 Java Temperature Conversion Applet
Java Temperature Conversion Applet
Temperature Conversion Calculator
Example B.2 Temperature Conversion Applet
// Java Temperature Conversion Applet
import java.applet.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class calculator extends Applet implements ActionListener
{
private TextField tfInput, tfResult;
private Button btF2C, btC2F;
private final String F2C =
new String("Fahrenheit to Centigrade");
private final String C2F =
new String("Centigrade to Fahrenheit");
//initialize user interface
public void init()
{
//set layout and foreground colors
setLayout(new BorderLayout());
setBackground(Color.white);
setFont(new Font("Times New Roman", Font.PLAIN,14));
//create text fields
tfInput = new TextField(6);
tfResult = new TextField(6);
//set result field read only
tfResult.setEditable(false);
//create buttons
btF2C = new Button(F2C);
btC2F = new Button(C2F);
//register listeners
btF2C.addActionListener(this);
btC2F.addActionListener(this);
//create 3 panels
Panel p1 = new Panel();
p1.add(new Label(
"Enter a temperature and select conversion type:"));
p1.add(tfInput);
Panel p2 = new Panel();
p2.add(new Label("Result:"));
p2.add(tfResult);
Panel p3 = new Panel();
p3.add(btF2C);
p3.add(btC2F);
// add panels to frame
add(BorderLayout.NORTH, p1);
add(BorderLayout.CENTER, p2);
add(BorderLayout.SOUTH, p3);
}
//event handler for buttons
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
double t1, t2;
// get input temp
t1 = (Double.valueOf(tfInput.getText())).doubleValue();
// compute result
t2 = actionCommand.equals(F2C) ? 5.0*(t1-32.0)/9.0 : 9.0*t1/5.0 + 32.0;
// display result
tfResult.setText(String.valueOf(t2));
}
}
Example B.3 Temperature Conversion Applet (Swing)
import javax.swing.*;
import java.awt.*; // include font, colors, layouts
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Jcalculator extends Japplet implements ActionListener
{
private JTextField tfInput, tfResult;
private JButton btF2C, btC2F;
private final String F2C = new String("Fahrenheit to Centigrade");
private final String C2F = new String("Centigrade to Fahrenheit");
//initialize user interface
public void init()
{
//format the applet's content pane
getContentPane().setLayout(new BorderLayout());
getContentPane().setBackground(Color.white);
getContentPane().setFont
(new Font("Times New Roman", Font.PLAIN, 14));
//create text fields
tfInput = new JTextField(6);
tfResult = new JTextField(12);
//set result field read only
tfResult.setEditable(false);
//create buttons
btF2C = new JButton(F2C);
btC2F = new JButton(C2F);
//register listeners
btF2C.addActionListener(this);
btC2F.addActionListener(this);
//create 3 panels
JPanel p1 = new JPanel();
p1.add(new JLabel(
"Enter a temperature and select conversion type:"));
p1.add(tfInput);
JPanel p2 = new JPanel();
p2.add(new JLabel("Result:"));
p2.add(tfResult);
JPanel p3 = new JPanel();
p3.add(btF2C);
p3.add(btC2F);
// add panels to content pane
getContentPane().add(BorderLayout.NORTH, p1);
getContentPane().add(BorderLayout.CENTER, p2);
getContentPane().add(BorderLayout.SOUTH, p3);
}
}
Example B.4 HTML Source for Locating and Downloading the Java Plug-in
Java Temperature Conversion Applet
Temperature Conversion Calculator
Example B.5 HelloWorld Applet
import java.awt.Graphics;
public class HelloWorld extends java.applet.Applet
{
public void paint( Graphics g )
{
g.drawString( "Hello, World!", 60, 30 );
}
}
Example B.6 HelloWorld HTML
Hello World Example
Example B.7 webAFCalculator.html
webAFCalculator
Appendix C
Example C.1 Generated HTML Source Code
SAS Design Time Controls Example
DTC Table Control: SASHELP.RETAIL
Retail sales in millions of $
DATE
YEAR
MONTH
DAY
$876
9 4Q1
1994
1
1
$998
94Q2
1994
4
1
Example C.2 DTC Table Control: JavaServer Page Code
<%
{
appserver.AppServer IappServer = new appserver.AppServer();
IappServer.setURL(null);
IappServer.setURL("http://hygelac/cgi-bin/broker");
String queryString =
"_service=default&_debug=0&
_program=sashelp.websdk1.ds2htm2.scl&data=SASHELP.RETAIL&
pagepart=body&sqlview=Y&where=year%20eq%201994&
twidth=0&twunits=Percent&border=Y&formats=Y&labels=Y&
obsnum=N&talign=default&vface=Arial,Helvetica,sansserif&
sface=Arial,Helvetica,sansserif&
clface=Arial,Helvetica,sansserif&
iface=Arial,Helvetica,sansserif&
oface=Arial,Helvetica,sansserif&
cface=Arial,Helvetica,sansserif&
bface=Arial,Helvetica,sans-serif";
java.io.OutputStream os = IappServer.getOutputStream();
os.write(queryString.getBytes());
os.close();
String HTML = IappServer.getHTML();
int responseCode = IappServer.getResponseCode();
if (responseCode >= 200 && responseCode < 300)
out.println(HTML);
else if (responseCode == 401) {
HTML = "
ERROR: Authenticated sites are not supported.
" + HTML;
IappServer.printDTCError(
new java.io.PrintWriter(out,true),responseCode, HTML);
}
else
IappServer.printDTCError(new java.io.PrintWriter(out, true),
responseCode, HTML);
}
%>
Example C.3 SAS DTC: Table Control: Active Server Page Code
<%
sub displayURL(URL)
Dim AppServer, HTML
Set AppServer = CreateObject("SAS.AppServerPostURL")
AppServer.webServer = "hunding"
AppServer.URL = "/scripts/broker.exe"
AppServer.queryString = URL
HTML = AppServer.openURL()
Response.Write HTML
End sub
displayURL("_service=default&_debug=0&_program=sashelp.websdk1.ds2htm2.scl&
data=SASHELP.RETAIL&pagepart=body&twidth=0&twunits=Percent&border=Y&
formats=Y&labels=Y&obsnum=N&talign=default&vface=Arial,Helvetica,sansserif&
sface=Arial,Helvetica,sansserif&clface=Arial,Helvetica,sansserif&
iface=Arial,Helvetica,sansserif&oface=Arial,Helvetica,sansserif&
cface=Arial,Helvetica,sansserif&bface=Arial,Helvetica,sans-serif")
%>
Appendix D
Example D.1 HTML Code for webEIS Applet