Resources

SAS® AppDev Studio 3.0 Developer's Site

OLAPTableview: Displaying a Swing Table with OLAP Data   About It Build It  

Data Source: OLAP Information Map

Step 1: Create a project in webAF and set up access to data source

  1. Create a new project named OLAPTableView. Select Application Project from the webAF Projects list. You can use all other default new project settings.
  2. Add the components and arrange them as seen on the About It page.
    Component Name Icon Icon Tab Location
     JButton  JButton image  Swing > Selector
     JLabel  JLabel image  Swing > Text
     JLabel  JLabel image  Swing > Text
     com.sas.swing.visuals.olaptableview.OLAPTableView  <no icon> <select from class list>
  3. Set the property values.
    Component Name Property Name Property Value
    JButton1 text Select Table
    JLabel1 text Status:
  4. Add the following import statements before the main class declaration near the beginning of the Java source:
    import java.net.URL;
    import com.sas.services.deployment.MetadataSourceInterface;
    import com.sas.services.deployment.OMRMetadataSource;
    import com.sas.services.deployment.URLMetadataSource;
    import com.sas.services.deployment.ServiceLoader;
    import com.sas.services.discovery.DiscoveryServiceInterface;
    import com.sas.services.discovery.DiscoveryService;
    import com.sas.services.discovery.ServiceTemplate;
    import com.sas.services.information.metadata.PathUrl;
    import com.sas.services.session.SessionServiceInterface;
    import com.sas.services.session.SessionContextInterface;
    import com.sas.services.user.UserServiceInterface;
    import com.sas.services.user.UserContextInterface;
    import com.sas.iquery.metadata.IntelligentQueryMetadataServiceFactory;
    import com.sas.iquery.metadata.IntelligentQueryMetadataServiceInterface;
    import com.sas.iquery.metadata.business.InformationMap;
    import com.sas.iquery.metadata.business.DataSelection;
    import com.sas.iquery.metadata.business.DataSelectionFactory;
    import com.sas.storage.iquery.BusinessQueryToOLAPDataSetAdapter;
    import com.sas.swing.models.OLAPTableModelAdapter;
    import com.sas.util.SasPasswordString;
    import com.sas.swing.visuals.util.Util;
    import com.sas.swing.visuals.remotefileselector.RemoteFileSelectorDialog;
    import com.sas.swing.visuals.remotefileselector.InformationServicesSelectorPanel;
    
  5. Add the following member variable declarations before the class constructor near the beginning of the Java source:
    // Handles to services in SAS Foundation Services.
    private DiscoveryServiceInterface discoveryService;
    private SessionServiceInterface sessionService;
    private UserServiceInterface userService;
    
    // Handles to contexts in SAS Foundation Services.
    private SessionContextInterface sessionContext;
    private UserContextInterface userContext;
    
    // Our internal BusinessQuery dataSelection.
    private DataSelection dataSelection;
    
  6. Right click JButton1 (the Select Table button) and select Handle Event.
  7. For Which type of handler do you want to create? select "Write your own code".
  8. Under the Interaction Description, click the hyperlink "the <event> occurs...", select "Action Performed" for JButton1 and click OK.
  9. Click the Source button to go to the Java source to add your code.
  10. Insert the following code in place of the line that reads "NOTE: Add new code here". Also insert your repository name in the specified location.
    String selection = populateList("<your repository name>");
       if( selection.endsWith("(BriefInformationMap)") ){
               LoadInformationMap(selection);
       }
       else{
               m_container.JLabel2.setText("");
       }
    
  11. To disconnect from SAS Foundation Services when done, add the following code to the destroy() method:
    try
       {
          FSDisconnect();
       }
       catch (Exception e)
       {
          showException(e);
       }
    
  12. To define the methods that work with SAS Foundation Services, BusinessQuery service, and OLAPTableView, add the following code near the end of the Java source. Note that you will need to supply OMR server and SAS Foundation Services settings that are specific to your environment. Specifically, you will need to provide your host name, port number, domain name, user ID, password, and repository in the appropriate locations below. For detailed information on deploying and connecting to services, see SAS Foundation Services.
    /**
        * Deploys SAS Foundation Services using either a specified XML deployment file or by
        * identifying a location in the SAS Metadata Server.
        * @param xmlDeploymentFile The name of the XML deployment file to use (optional).
        * If null, the services will be deployed using information in the SAS Metadata Server.
        * @exception Exception
        */
       public void FSDeploy(String xmlDeploymentFile) throws Exception
       {
    	     if ( discoveryService != null )
    	     {
    		     return;
    	     }
    
          //Set JVM env variables to enable authentication via Platform Services;
          com.sas.net.ClassResourceLocator policy =
             new com.sas.net.ClassResourceLocator("java.app.policy", this.getClass());
          com.sas.net.ClassResourceLocator login =
             new com.sas.net.ClassResourceLocator("login.config", this.getClass());
          try {
             java.lang.System.setProperty("java.security.auth.login.config",
                login.getResource().toString());
          } catch (Exception e) {
             throw new Exception
              ("Cannot load the login.config file. Make sure it exists in the same directory as the application.");
          }
          try {
             java.lang.System.setProperty("java.security.policy",
                policy.getResource().toString());
          } catch (Exception e) {
             throw new Exception
              ("Cannot load the policy file. Make sure it exists in the same directory as the application.");
          }
    
          final String applicationDeploymentName = "ADS Local Services";
          final String serviceDeploymentGroupName = "BIP Core Services";
    
          MetadataSourceInterface metadataSource = null;
    
          // If an XML deployment file was specified...
          if (xmlDeploymentFile != null)
          {
             // Create a metadata source from the XML deployment file.
             com.sas.net.ClassResourceLocator crl =
                new com.sas.net.ClassResourceLocator(xmlDeploymentFile, this.getClass());
             metadataSource = new URLMetadataSource(crl.getResource(),
                applicationDeploymentName, serviceDeploymentGroupName);
          }
          else
          {
             // Create a metadata source for an Open Metadata Repository
             final String serverHost             = "server";
             final String serverPort             = "9999";
             final String serverIdentityId       = "username";
             final String serverIdentityPassword = SasPasswordString.
                encode(SasPasswordString.SAS001_ENCODING, "password");
             final String serverRepositoryName   = "Repository Name";
    
             metadataSource = new OMRMetadataSource(serverHost, serverPort,
                serverIdentityId, serverIdentityPassword, serverRepositoryName,
                applicationDeploymentName, serviceDeploymentGroupName);
          }
    
          // Obtain the local discovery service
          discoveryService = DiscoveryService.defaultInstance();
    
          // Deploy the services using the created metadata source.
          ServiceLoader.deployServices(metadataSource, discoveryService);
       }
    
       /**
        * Logs into the SAS Foundation Services that were obtained
        * via the FSConnect method.
        * @exception Exception
        */
       public void FSLogin() throws Exception
       {
          // Use the remote discovery services to find a user service.
          userService = (UserServiceInterface)discoveryService.findService(
             new ServiceTemplate(
                new Class[] {com.sas.services.user.UserServiceInterface.class}
             ));
    
          // Get a user context from the user service by logging in.
          final String domain    = "DOMAIN";
          final String username   = "username";
          final String password    = SasPasswordString.encode
             (SasPasswordString.SAS001_ENCODING, "password");
          userContext = userService.newUser(username, password, domain);
    
          // Use the remote discovery services to find a session service.
          sessionService = (SessionServiceInterface)discoveryService.findService(
             new ServiceTemplate(
                new Class[] {com.sas.services.session.SessionServiceInterface.class}
             ));
    
          // Create a session for this user and bind it to the user context.
          sessionContext = sessionService.newSessionContext(userContext);
          userContext.setSessionContext(sessionContext);
       }
    
       /**
        * Loads the BusinessQuery Information Map identified by the mapName parameter,
        * and creates and populates a BQ data selection object based on the contents
        * of the InformationMap.
        * @param mapName The name of the InformationMap to load.
        * @exception Exception
        * @return A boolean value representing whether or not the map was loaded.
        */
       public boolean BQGetDataSelection(String mapName) throws Exception
       {
          // Get a BusinessQuery metadata service object.
          IntelligentQueryMetadataServiceInterface IQMetadataService =
             IntelligentQueryMetadataServiceFactory.newService();
    
          // Get a specific InformationMap from the metadata service object.
          PathUrl pathURL = new PathUrl(mapName);
          InformationMap informationMap =
             IQMetadataService.getInformationMap(sessionContext, pathURL);
          if (informationMap != null)
          {
             // Determine the structure of the data in the InformationMap.
             if (!informationMap.getStructure().isOLAP())
             {
                javax.swing.JOptionPane.showMessageDialog(this,
                   "The selected map doesn't represent OLAP data.",
                   "Error", javax.swing.JOptionPane.ERROR_MESSAGE);
                return false;
             }
    
             // Create a dataSelection from the InformationMap and add ResultItems to it
             // to create a sample. Since we're passing in null for the maxElements parameter,
             // only 2 Hierarchies and 2 Measures will be used.
             dataSelection = DataSelectionFactory.newSampleDataSelection(informationMap, null);
          }
    
          return true;
       }
    
       /**
        * Disconnects from the SAS Foundation Services and releases any used resources.
        * @exception Exception
        */
       public void FSDisconnect() throws Exception
       {
          // Release the remote discovery service
          if (discoveryService != null)
             discoveryService.destroy();
       }
    
       /**
        * This is the primary entry point for this example. It connects and logs into
        * the SAS Foundation Services, then obtains a BusinessQuery data selection from
        * the requested InformationMap.
        *
        * The data selection is then adapted to fit into the OLAPTableView object, where
        * it is then appropriately rendered.
        * @param mapName The name of the InformationMap to load.
        */
       public void LoadInformationMap(String mapName)
       {
          try
          {
             JLabel2.setText("Building DataSelection from requested InformationMap...");
             if (BQGetDataSelection(mapName))
             {
                JLabel2.setText("Building BusinessQuery/OLAP dataset adapter...");
                BusinessQueryToOLAPDataSetAdapter businessQueryToOLAPDataSetAdapter =
                   new BusinessQueryToOLAPDataSetAdapter(dataSelection);
    
                JLabel2.setText("Building OLAP table model adapter...");
                final OLAPTableModelAdapter olapTableModelAdapter =
                   new OLAPTableModelAdapter(businessQueryToOLAPDataSetAdapter);
    
                JLabel2.setText("Setting model for OLAPTableView...");
                // Note that setting the model needs to be performed back in
                // the original event queue thread.
                java.awt.EventQueue.invokeLater( new Runnable() {
                   public void run()
                   {
                      OLAPTableView1.setModel(olapTableModelAdapter);
                      JLabel2.setText("Done.");
                   }
                });
             }
          }
          catch (Exception e)
          {
             showException(e);
          }
       }
       public String populateList(String mapPath)
       {
    	   try{
             JLabel2.setText("Deploying SAS Foundation Services...");
             FSDeploy(null);
    
             JLabel2.setText("Logging in to SAS Foundation Services...");
             FSLogin();
    
    		java.util.List repos = userContext.getRepositories();
    		com.sas.services.information.RepositoryInterface reposInt =
    			(com.sas.services.information.RepositoryInterface)repos.get(0);
    		String startDir = "";
    		if (mapPath != null)
    		{
    			int index = mapPath.lastIndexOf("/");
    			if (index != -1)
    			{
    				startDir = mapPath.substring(0, index);
    			}
    		}
    		java.util.Map fileTypes = new java.util.HashMap();
    		fileTypes.put("Information Maps", "InformationMap");
    
    		InformationServicesSelectorPanel panel =
    			new InformationServicesSelectorPanel(startDir, reposInt, fileTypes, false);
    		RemoteFileSelectorDialog dialog =
    			new RemoteFileSelectorDialog(Util.getParentAWTFrame(this),
    			"Select an Information Map", true, 2, panel);
    		dialog.setVisible(true);
    		java.util.List items = new java.util.ArrayList();
    		//if (!panel.wasCancelled())
    			items =  panel.getReturnedInformation(true);
    		if (items != null && items.size() > 0)
    		{
    			mapPath = items.get(0).toString();
    		}
    		return mapPath;
    	}catch (Exception e)
    	   {
    		   showException(e);
    		   return "";
    	   }
       }
    

Step 2: Finish the project

  1. Build the project.
  2. Copy the required files (login.config and app.policy) into the project directory. These files are available from your webAF\resources directory, which is located in the directory where you installed SAS AppDev Studio. For more information on these files, see SAS Foundation Services.
  3. Build the project.
  4. Start the IOM Spawner by selecting Start Menu [arrow] SAS AppDev Studio [arrow] Services [arrow] SAS V9.1 [arrow] Start SAS V9.1 IOM Spawner.
  5. Start the Java Web server.
  6. Execute in browser.
  7. Using the JComboBox, select the name of the OLAP Information Map to have it displayed in the OLAPTableView.