![]() | ![]() | ![]() | ![]() | ![]() |
This sample uses the SAS® Foundation Services API in order to execute a stored process that is defined in metadata. The servlet streams back the results of the stored process to the browser. In this sample, SAS Foundation Services are deployed in the local Java Virtual Machine (JVM). The Web application defines a listener class that connects to the metadata server in order to deploy the foundation services.
Although SAS® AppDev Studio is not required for this sample, SAS AppDev Studio users can also integrate this example into their Web applications. SAS® Integration Technologies is required in order to use this code.
This sample assumes that you know how to create and deploy Web applications.
These sample files and code examples are provided by SAS Institute Inc. "as is" without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and fitness for a particular purpose. Recipients acknowledge and agree that SAS Institute shall not be liable for any damages whatsoever arising out of their use of this material. In addition, SAS Institute will provide no support for the materials contained herein.
To run this code with SAS AppDev Studio 3.3, follow the directions below. If you do not have a SAS AppDev Studio license, the Downloads tab lists some files that you can download, along with instructions on creating a Web application.
Tip: For help with building a Web application project and testing a Web application, see SAS Note 32218.
Edit the repository, storedProcess, username, password, and domain strings in the doPost method to match your environment.
String repository = "Foundation";
String storedProcess = "/Samples/Stored Processes/Sample: Shoe Sales by Region";
String username = "username";
String password = "password";
String domain = "DefaultAuth";
package servlets;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import com.sas.services.information.RepositoryInterface;
import com.sas.services.information.metadata.PathUrl;
import com.sas.services.session.SessionContextInterface;
import com.sas.services.session.SessionServiceInterface;
import com.sas.services.storedprocess.ExecutionException;
import com.sas.services.storedprocess.ExecutionInterface;
import com.sas.services.storedprocess.StoredProcessInterface;
import com.sas.services.storedprocess.StoredProcessServiceInterface;
import com.sas.services.user.UserContextInterface;
import com.sas.services.user.UserServiceInterface;
import com.sas.services.webapp.ServicesFacade;
public class StreamStoredProcess extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// first, check to see if we are attempting to replay an image
// if the stored process creates binary images, it will call back to
// this servlet again using a image link in the generated html output
String replayParam = request.getParameter("_program");
if (null != replayParam && replayParam.equals("replay")) {
replayImage(request, response);
} else {
// if not replaying, then we execute the stored process
// we hardcode the paramters here, you may set these values by
// any method you choose
String repository = "Foundation";
String storedProcess = "/Samples/Stored Processes/Sample: Shoe Sales by Region";
String username = "username";
String password = "password";
String domain = "DefaultAuth";
executeStoredProcess(request, response, repository, storedProcess,
username, password, domain);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
private void executeStoredProcess(HttpServletRequest request,
HttpServletResponse response, String repository, String program,
String username, String password, String domain)
throws ServletException, IOException {
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
response.setContentType("text/html");
ExecutionInterface spExecution = null;
try {
UserServiceInterface userService = ServicesFacade.getUserService();
UserContextInterface userContext = userService.newUser(username,
password, domain);
SessionServiceInterface sessionService = ServicesFacade
.getSessionService();
SessionContextInterface sessionContext = sessionService
.newSessionContext(userContext); // (6) Get repository
RepositoryInterface repos = userContext.getRepository("Foundation");
if (repos == null) {
out.println("Foundation repository not found.");
return;
}
// (7) Find program in repository (use metadata
// StoredProcessInterface)
PathUrl path = new PathUrl("sbip://" + repository + program
+ "(StoredProcess)");
com.sas.services.storedprocess.metadata.StoredProcessInterface metadata = (com.sas.services.storedprocess.metadata.StoredProcessInterface) repos
.getObjectByPath(path);
if (metadata == null) {
out.println("Program not found: " + program);
return;
}
// (8) Get stored process service
StoredProcessServiceInterface spService = ServicesFacade
.getStoredProcessService();
// (9) Make stored process object (use storedprocess
// StoredProcessInterface)
com.sas.services.storedprocess.StoredProcessInterface storedProcess = spService
.newStoredProcess(sessionContext, metadata);
session.setAttribute("SESSIONCONTEXT",
(SessionContextInterface) sessionContext);
session.setAttribute("SPSERVICE",
(StoredProcessServiceInterface) spService);
session.setAttribute("BINDER", new CustomBindingListener(
sessionContext));
HashMap paramMap = new HashMap();
// We must set the url value back to the location of this servlet so
// that the images may be replayed
paramMap.put("_URL", request.getRequestURI());
storedProcess.setParameterValues(paramMap);
// (10) Run stored process
spExecution = storedProcess.execute(false, null, false, null);
// (11) Display results
if (storedProcess.getResultType() == com.sas.services.storedprocess.StoredProcessInterface.RESULT_TYPE_STREAM) {
// Set up reader
String encoding = null;
BufferedReader spStream;
com.sas.io.InputStreamHeaderInterface header = spExecution
.getInputStreamHeader("_WEBOUT");
if (header != null)
encoding = header.getCharacterEncoding();
if (encoding != null) {
spStream = new BufferedReader(new InputStreamReader(
spExecution.getInputStream("_WEBOUT"), encoding));
} else {
spStream = new BufferedReader(new InputStreamReader(
spExecution.getInputStream("_WEBOUT")));
}
// Get data and copy to out
String line;
while ((line = spStream.readLine()) != null) {
out.println(line);
}
}
// (12) Wait for completion
int returnCode = spExecution.waitForCompletion();
// (13) See if execute had an error
if (returnCode == ExecutionInterface.STATUS_EXCEPTION_OCCURRED
|| returnCode == ExecutionInterface.STATUS_SAS_EXCEPTION_OCCURRED) {
ExecutionException[] errors = spExecution.getExceptions();
out.println("Error executing stored process. ");
for (int i = 0; i < errors.length; i++) {
out.println(errors[i].getLocalizedMessage());
}
return;
}
// (14) Check SAS return code
int sasrc = spExecution.getSASConditionCode();
if (sasrc != 0 && sasrc != 4) {
out.println("Error in SAS program. Return code:" + sasrc);
}
// (15) Print SAS log
String log = spExecution.readSASLog(
ExecutionInterface.LOG_FORMAT_HTML,
ExecutionInterface.LOG_ALL_LINES);
out.println(log);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (spExecution == null) {
System.out
.println("Unable to terminate stored process, spExecution = null");
return;
}
try {
spExecution.waitForCompletion();
spExecution.destroy();
} catch (Exception e) {
System.out
.println("Unable to destroy stored process execution");
e.printStackTrace();
return;
}
}
}
private void replayImage(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ExecutionInterface spExecution = null;
try {
HttpSession session = request.getSession();
// Get session context
SessionContextInterface sessionContext = (SessionContextInterface) session
.getAttribute("SESSIONCONTEXT");
// Get stored process service
StoredProcessServiceInterface spService = (StoredProcessServiceInterface) session
.getAttribute("SPSERVICE");
if (sessionContext == null || spService == null) {
System.out.println("Missing session values");
return;
}
// Create replay object
com.sas.services.storedprocess.StoredProcessInterface storedProcess = spService
.newStoredProcess(sessionContext,
StoredProcessInterface.SERVER_TYPE_STOREDPROCESS,
StoredProcessInterface.RESULT_TYPE_STREAM);
storedProcess.setSourceFromFile("", "replay");
storedProcess.setName("Replay");
storedProcess.addInputStream("_WEBOUT");
// Get URL parameters
String program = null;
String sessionval = null;
HashMap paramMap = new HashMap();
Enumeration params = request.getParameterNames();
while (params.hasMoreElements()) {
String key = (String) params.nextElement();
String values[] = (String[]) request.getParameterValues(key);
if (key.equalsIgnoreCase("_program"))
program = values[0];
if (key.equalsIgnoreCase("_sessionid"))
sessionval = values[0];
paramMap.put(key, values);
}
if (program == null || !program.equalsIgnoreCase("replay")) {
System.out
.println("The parameter _PROGRAM must be set to replay");
return;
}
// Set stored process parameters
storedProcess.setParameterValues(paramMap);
// Run stored process
try {
spExecution = storedProcess.execute(false, null, false,
sessionval);
} catch (Exception e) {
System.out.println("Error replaying images: "
+ e.getLocalizedMessage());
return;
}
// Handle results
if (storedProcess.getResultType() == StoredProcessInterface.RESULT_TYPE_STREAM) {
// Get header
com.sas.io.InputStreamHeaderInterface header = spExecution
.getInputStreamHeader("_WEBOUT");
if (header != null) {
Map headerlines = header.getHeaders();
if (headerlines != null) {
Iterator it = headerlines.keySet().iterator();
while (it.hasNext()) {
String key = it.next().toString();
response.addHeader(key, (String) headerlines
.get(key));
}
}
}
// Get data
BufferedInputStream inData = new BufferedInputStream(
spExecution.getInputStream("_WEBOUT"));
BufferedOutputStream outData = new BufferedOutputStream(
response.getOutputStream());
byte[] buffer = new byte[4096];
int n;
while ((n = inData.read(buffer, 0, buffer.length)) > 0) {
outData.write(buffer, 0, n);
}
outData.flush();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (spExecution == null) {
System.out
.println("Unable to terminate stored process, spExecution = null");
return;
}
try {
spExecution.waitForCompletion();
spExecution.destroy();
} catch (Exception e) {
System.out
.println("Unable to destroy stored process execution");
e.printStackTrace();
return;
}
}
}
// Used to save/delete the session
// this is necessary in order to call back and replay images
private class CustomBindingListener implements HttpSessionBindingListener {
private SessionContextInterface sessionContext = null;
private Object lock;
public CustomBindingListener(SessionContextInterface sessionContext) {
try {
this.sessionContext = sessionContext;
this.lock = sessionContext
.lock("com.sas.services.storedprocess.webapp");
} catch (Exception e) {
}
}
public void valueBound(HttpSessionBindingEvent event) {
}
public void valueUnbound(HttpSessionBindingEvent event) {
try {
if (sessionContext != null) {
sessionContext.unlock(lock);
sessionContext.destroy();
}
} catch (Exception e) {
}
}
}
}
|
These sample files and code examples are provided by SAS Institute Inc. "as is" without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and fitness for a particular purpose. Recipients acknowledge and agree that SAS Institute shall not be liable for any damages whatsoever arising out of their use of this material. In addition, SAS Institute will provide no support for the materials contained herein.
The download is not necessary if you have SAS AppDev Studio 3.3. If you have SAS AppDev Studio 3.3, the instructions on the Full Code tab will build the necessary Web application files. If you do not have a SAS AppDev Studio license, the instructions below will demonstrate how to build the Web application directory.
You will need to extract the contents of this zip file into your Web application directory before you run the JSP code on the Full Code tab. This zip file contains:
Edit the following strings in the WEB-INF\server.properties file with your information:
software_component=ID Portal Local Services
deployment_group_1=BIP Local Services OMR
deployment_group_2=BIP Stored Process Service
Edit the following strings in the WEB-INF\login.config file with your information:
Before you can run the servlet, you will need to do the following:
lib under the WEB-INF directory of your Web application.
http://[server]:[port]/[webapp name]/StreamStoredProcess| Type: | Sample |
| Date Modified: | 2008-03-11 14:36:53 |
| Date Created: | 2006-05-09 16:10:45 |
| Product Family | Product | Host | Product Release | SAS Release | ||
| Starting | Ending | Starting | Ending | |||
| SAS System | SAS AppDev Studio | Microsoft Windows 2000 Datacenter Server | 3.3 | 9.1 TS1M3 SP4 | ||
| Microsoft Windows 2000 Server | 3.3 | 9.1 TS1M3 SP4 | ||||
| Microsoft Windows 2000 Professional | 3.3 | 9.1 TS1M3 SP4 | ||||
| Microsoft® Windows® for x64 | 3.3 | 9.1 TS1M3 SP4 | ||||
| Microsoft Windows 2000 Advanced Server | 3.3 | 9.1 TS1M3 SP4 | ||||
| Microsoft Windows Server 2003 Datacenter Edition | 3.3 | 9.1 TS1M3 SP4 | ||||
| Microsoft Windows NT Workstation | 3.3 | 9.1 TS1M3 SP4 | ||||
| Microsoft Windows Server 2003 Enterprise Edition | 3.3 | 9.1 TS1M3 SP4 | ||||
| Microsoft Windows Server 2003 Standard Edition | 3.3 | 9.1 TS1M3 SP4 | ||||
| Microsoft Windows XP Professional | 3.3 | 9.1 TS1M3 SP4 | ||||
| Windows Vista | 3.3 | 9.1 TS1M3 SP4 | ||||
| SAS System | SAS Integration Technologies | HP-UX IPF | 9.1 TS1M3 SP4 | |||
| Linux | 9.1 TS1M3 SP4 | |||||
| Linux on Itanium | 9.1 TS1M3 SP4 | |||||
| OpenVMS Alpha | 9.1 TS1M3 SP4 | |||||
| Tru64 UNIX | 9.1 TS1M3 SP4 | |||||
| 64-bit Enabled Solaris | 9.1 TS1M3 SP4 | |||||
| z/OS | 9.1 TS1M3 SP4 | |||||
| Microsoft® Windows® for 64-Bit Itanium-based Systems | 9.1 TS1M3 SP4 | |||||
| Microsoft Windows Server 2003 Datacenter 64-bit Edition | 9.1 TS1M3 SP4 | |||||
| Microsoft Windows Server 2003 Enterprise 64-bit Edition | 9.1 TS1M3 SP4 | |||||
| Microsoft Windows XP 64-bit Edition | 9.1 TS1M3 SP4 | |||||
| Microsoft® Windows® for x64 | 9.1 TS1M3 SP4 | |||||
| Microsoft Windows 2000 Advanced Server | 9.1 TS1M3 SP4 | |||||
| Microsoft Windows 2000 Datacenter Server | 9.1 TS1M3 SP4 | |||||
| Microsoft Windows 2000 Server | 9.1 TS1M3 SP4 | |||||
| Microsoft Windows 2000 Professional | 9.1 TS1M3 SP4 | |||||
| Microsoft Windows NT Workstation | 9.1 TS1M3 SP4 | |||||
| Microsoft Windows Server 2003 Datacenter Edition | 9.1 TS1M3 SP4 | |||||
| Microsoft Windows Server 2003 Enterprise Edition | 9.1 TS1M3 SP4 | |||||
| Microsoft Windows Server 2003 Standard Edition | 9.1 TS1M3 SP4 | |||||
| Microsoft Windows XP Professional | 9.1 TS1M3 SP4 | |||||
| Windows Vista | 9.1 TS1M3 SP4 | |||||
| 64-bit Enabled AIX | 9.1 TS1M3 SP4 | |||||
| 64-bit Enabled HP-UX | 9.1 TS1M3 SP4 | |||||





