package servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import listeners.ExamplesSessionBindingListener;
import com.sas.actionprovider.HttpActionProvider;
import com.sas.iquery.dataretrieval.QueryConnector;
import com.sas.iquery.metadata.MetadataException;
import com.sas.iquery.metadata.business.BusinessModel;
import com.sas.iquery.metadata.business.BusinessQuery;
import com.sas.iquery.metadata.business.DataItem;
import com.sas.iquery.metadata.business.DataItemReference;
import com.sas.iquery.metadata.business.DataSelection;
import com.sas.iquery.metadata.business.InformationMap;
import com.sas.iquery.metadata.business.Role;
import com.sas.iquery.metadata.business.SelectedItem;
import com.sas.iquery.metadata.business.step.StepInterface;
import com.sas.services.discovery.DiscoveryService;
import com.sas.services.discovery.DiscoveryServiceInterface;
import com.sas.services.discovery.ServiceTemplate;
import com.sas.services.session.SessionContextInterface;
import com.sas.services.session.SessionServiceInterface;
import com.sas.services.user.UserContextInterface;
import com.sas.services.user.UserServiceInterface;
import com.sas.servlet.tbeans.dataexplorer.html.DataViewer;
import com.sas.servlet.tbeans.dataexplorer.html.VisualDataExplorer;
import com.sas.servlet.tbeans.olaptableview.html.OLAPTableView;
import com.sas.servlet.tbeans.olaptableview.html.OLAPTableViewComposite;
import com.sas.servlet.util.BaseUtil;
import com.sas.web.keys.ComponentKeys;
public class InfoMapViewerExampleControllerServlet extends
javax.servlet.http.HttpServlet {
// Declare a default version ID since parent class implements
// java.io.Serializable
private static final long serialVersionUID = 1L;
private static final String ACTION_PROVIDER = "sas_actionProvider_InfoMapViewerExample";
private static final String VISUAL_DATA_EXPLORER = "vde";
// Edit this path to point to an information map
private static final String MAP_NAME = "SBIP://Foundation/BIP Tree/ReportStudio/Maps/OrionStar Map";
/*
* doPost() Respond to the Post message.
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Note: Calling doGet to provide same behavior to POST and GET HTTP
// methods.
doGet(request, response);
}
/*
* doGet() Respond to the Get message.
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Note: Add User DO_GET code here
HttpSession session = request.getSession();
// Ensure character set is specified before calling
// response.getWriter().
String charset = BaseUtil.getOutputCharacterEncoding(request);
response.setContentType("text/html; charset=" + charset);
// Setup the ActionProvider
HttpActionProvider sas_actionProvider = null;
synchronized (session) {
if (session != null) {
sas_actionProvider = (HttpActionProvider) session
.getAttribute(ACTION_PROVIDER);
}
// if ActionProvider is null, create one and put it on the session
if (sas_actionProvider == null) {
sas_actionProvider = new HttpActionProvider();
sas_actionProvider.setLocale(request.getLocale());
sas_actionProvider.setControllerURL(request.getContextPath()
+ "/InfoMapViewerExample");
sas_actionProvider.setName(ACTION_PROVIDER);
// store object in its scope
if (session != null)
session.setAttribute(ACTION_PROVIDER, sas_actionProvider);
}
// else execute the ActionProvider command
else {
sas_actionProvider.executeCommand(request, response, response
.getWriter());
}
}
synchronized (session) {
// Setup the InformationServicesSelector
VisualDataExplorer vde = null;
if (session != null) {
vde = (VisualDataExplorer) session
.getAttribute(VISUAL_DATA_EXPLORER);
}
if (vde == null) {
try {
// Obtain the local discovery service
DiscoveryServiceInterface discoveryService = DiscoveryService
.defaultInstance();
// Use the discovery services to find a user service.
UserServiceInterface userService = (UserServiceInterface) discoveryService
.findService(new ServiceTemplate(
new Class[] { UserServiceInterface.class }));
// Get a user context from the user service by logging in.
// The initial parameters are obtained from the web.xml
// file.
// Note: A password must be set in the web.xml file.
ServletConfig sc = getServletConfig();
String domain = sc.getInitParameter("metadata-domain");
String username = sc.getInitParameter("metadata-userid");
String password = sc.getInitParameter("metadata-password");
UserContextInterface userContext = userService.newUser(
username, password, domain);
if (session != null) {
ExamplesSessionBindingListener.getInstance(session)
.addUserContext(userContext);
}
// Use the discovery services to find a session service.
SessionServiceInterface sessionService = (SessionServiceInterface) discoveryService
.findService(new ServiceTemplate(
new Class[] { SessionServiceInterface.class }));
// Create a session for this user and bind it to the user
// context.
SessionContextInterface sessionContext = sessionService
.newSessionContext(userContext);
userContext.setSessionContext(sessionContext);
if (session != null) {
ExamplesSessionBindingListener.getInstance(session)
.addSessionContext(sessionContext,
"InfoMapViewerExample_lock");
}
// Create the Visual Data Explorer, and add it to the
// session. Change the value of the MAP_NAME constant to
// instantiate the Visual Data Explorer with data
vde = new VisualDataExplorer(sessionContext, MAP_NAME);
// Retrieve the VDE data model
DataSelection dataSelection = (DataSelection) vde
.getDataModel();
// Define the data items that should exist on the query. The
// value should match the item name in the information map
List rows = new ArrayList();
List columns = new ArrayList();
List slicers = new ArrayList();
Hashtable filters = new Hashtable();
// Add items to row, column or slicer. Rows and columns must
// have one or more items. Slicer can have zero or more
// items
rows.add("Global");
rows.add("Demographics");
columns.add("Year-quarter-month");
columns.add("Sum of Quantity");
columns.add("Sum of Total Cost");
slicers.add("Customers");
// Initialize the model with the values specified
initializeBusinessQuery(dataSelection, true, rows, columns,
slicers, filters);
// Print the mdx query to the log
printQuery(dataSelection);
// Refresh the DataViewer, after the model is changed
DataViewer dv = (DataViewer) vde
.getComponent(VisualDataExplorer.VISUALDATAEXPLORER_DATAVIEWER);
// Set the number of rows/columns
if (null != dv.getOLAPBusinessQueryAdapter()) {
OLAPTableViewComposite olapTableComposite = (OLAPTableViewComposite) dv
.getTable();
OLAPTableView olapTable = (OLAPTableView) olapTableComposite
.getComponent(OLAPTableViewComposite.OLAPTABLEVIEW_TABLEDATA);
olapTable.setColumnPageSize(10);
olapTable.setRowPageSize(20);
}
dv.setDataModelNeedsRefreshed();
dv.reinitialize(false);
vde.setActionProvider(sas_actionProvider);
vde.setId(VISUAL_DATA_EXPLORER);
if (session != null) {
session.setAttribute(VISUAL_DATA_EXPLORER, vde);
}
} catch (Exception e) {
throw new ServletException(e);
}
}
}
// Forward the request to the JSP for display
String sas_forwardLocation = request
.getParameter(ComponentKeys.FORWARD_LOCATION);
if (sas_forwardLocation == null) {
sas_forwardLocation = "/InfoMapViewerExampleViewer.jsp";
}
RequestDispatcher rd = getServletContext().getRequestDispatcher(
sas_forwardLocation);
rd.forward(request, response);
}
/* Print the mdx equivalent of a BusinessQuery */
private void printQuery(BusinessQuery ds) {
QueryConnector qc = new QueryConnector();
try {
String mdxQuery = qc.getPhysicalQuery(ds);
System.out.println(mdxQuery);
} catch (Exception e) {
e.printStackTrace();
}
}
/* Remove all items from a BusinessQuery */
public void clearQuery(BusinessQuery businessQuery) {
List initiallySelected = businessQuery.getSelectedItems();
for (int i = 0; i < initiallySelected.size(); i++) {
SelectedItem selected = (SelectedItem) initiallySelected.get(i);
try {
businessQuery.removeSelectedItem(selected);
} catch (MetadataException e) {
e.printStackTrace();
}
}
}
public void initializeBusinessQuery(BusinessQuery businessQuery,
boolean clearQuery, List rows, List columns, List slicers,
Hashtable filters) {
if (clearQuery) {
clearQuery(businessQuery);
}
BusinessModel bmodel = businessQuery.getBusinessModel();
// make sure we are the root business model
while (!(bmodel instanceof InformationMap)) {
bmodel = bmodel.getParentBusinessModel();
}
// get all items in this model
List dataItemList = bmodel.getObjects(false, DataItem.class);
// add items to rows, columns, and filters
addItemsToRole(businessQuery, dataItemList, rows, Role.ROW, filters);
addItemsToRole(businessQuery, dataItemList, columns, Role.COLUMN,
filters);
addItemsToRole(businessQuery, dataItemList, slicers, Role.BACKGROUND,
filters);
}
/*
* Iterate through a list of items. If the item is found in the business
* model, add it to the query, on the role specified
*/
private void addItemsToRole(BusinessQuery businessQuery, List dataItemList,
List items, Role role, Hashtable filters) {
BusinessModel businessModel = businessQuery.getBusinessModel();
Iterator i = items.iterator();
for (; i.hasNext();) {
String itemName = (String) i.next();
for (Iterator iter = dataItemList.iterator(); iter.hasNext();) {
DataItem dataItem = (DataItem) iter.next();
if (dataItem.getLabel().equalsIgnoreCase(itemName)) {
try {
// See if the item already exists in the query
DataItem newDataItem = lookForDataItemInExistingQuery(
dataItem, businessQuery);
// If it does not exist in query, check for an existing
// reference
if (null == newDataItem) {
newDataItem = lookForExistingDataItemReference(
businessModel, dataItem);
// if a reference doesn't exist, create it, and add
// it to the model
if (null == newDataItem) {
newDataItem = businessModel
.newDataItemReference(dataItem);
businessModel.addBusinessItem(newDataItem);
}
}
// Finally, add the item to the query on the proper role
businessQuery.addResultItem(newDataItem, role);
// If the filters HashTable contains a value that
// matches the item name, apply the filter
if (filters.keySet().contains(itemName)) {
StepInterface filter = (StepInterface) filters
.get(itemName);
for (; newDataItem.getSteps().size() > 0;) {
newDataItem.removeStep(0);
}
newDataItem.addStep(filter);
}
} catch (MetadataException e) {
e.printStackTrace();
}
}
}
}
}
/*
* Search through a BusinessQuery, to see if a data item already exists in
* that query
*/
private DataItem lookForDataItemInExistingQuery(DataItem dataItem,
BusinessQuery businessQuery) throws MetadataException {
DataItem retval = null;
java.util.List queryItems = businessQuery.getResultItems();
Iterator qi = queryItems.iterator();
boolean foundItemInQueryItems = false;
while (qi.hasNext() && !foundItemInQueryItems) {
DataItem queryItem = (DataItem) qi.next();
if (queryItem.getLabel().equalsIgnoreCase(dataItem.getLabel())) {
retval = queryItem;
foundItemInQueryItems = true;
}
}
return retval;
}
/*
* Search through a BusinessQuery, to see if a DataItemReference already
* exists in that query
*/
private DataItemReference lookForExistingDataItemReference(
BusinessModel businessModel, DataItem dataItem) {
DataItemReference retval = null;
List dataItemList = businessModel.getObjects(false,
DataItemReference.class);
String label = dataItem.getLabel();
for (Iterator iter = dataItemList.iterator(); iter.hasNext();) {
DataItemReference dataItemRef = (DataItemReference) iter.next();
if (dataItemRef.getLabel().equalsIgnoreCase(label)) {
retval = dataItemRef;
break;
}
}
return retval;
}
private void turnOnAllTotals(BusinessQuery ds) {
try {
ds.setTotalType(BusinessQuery.ALLTOTAL, Role.ROW);
ds.setTotalType(BusinessQuery.GRANDTOTAL, Role.ROW);
ds.setTotalType(BusinessQuery.GRANDTOTAL, Role.COLUMN);
ds.setTotalType(BusinessQuery.ALLTOTAL, Role.COLUMN);
} catch (MetadataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|