Rational Developer para System z


Lição 2: Desenvolver o Código para a Classe BrowseMemberAction

Essa lição fornecerá orientação sobre as etapas para desenvolver o código necessário para a classe BrowseMemberAction.

Para desenvolver o código para a classe BrowseMemberAction:

  1. Abra a classe BrowseMemberAction no editor se já não estiver aberta. No Package Explorer, expanda com.ibm.carma.plugin.browse > src > browse, e dê um clique duplo na classe BrowseMemberAction.
  2. O primeiro método gravado será selectionChanged. Esse método é usado para controlar os itens para os quais a ação de navegação é ativada. No código de exemplo a seguir, a ação do membro de navegação é ativada somente nos membros do CARMA e somente para um membro por vez. Em razão disso, as verificações devem ser executadas antes de ativar a ação do navegador. O pseudocódigo a seguir demonstra isso:
    if (more than one item is selected)
       disable action;
    
    if (item selected is CARMA member)
       enable action
    else
       disable action
    Use o código de amostra a seguir para implementar esse método:
    public void selectionChanged(IAction action, ISelection selection) {		
       Iterator i = ((IStructuredSelection) selection).iterator();
    
       // by default assume false
       action.setEnabled(false);
    
       if( ((IStructuredSelection) selection).size() != 1){
          return;
       }
    		
       while (i.hasNext()) {
          Object next = i.next();
          if (next instanceof CARMAMember) { // the element is a member
             //remember the item selected so if the action is run it knows
             //which item to run the action against
             this.itemSelected = (CARMAMember) next;
          } else {
             this.itemSelected = null;
             return;
          }
       }		
    
       // if we passed the test...then enable the action
       action.setEnabled(true);
    }
  3. O segundo método a ser gravado é o método run. Esse método é chamado quando você deseja chamar o BrowserMemberAction. Para abrir o CARMAMember somente no modo de navegação, o ambiente de trabalho precisa fazer o download do conteúdo do arquivo do RAM para o IFile, um tipo de arquivo no Eclipse, configurar as propriedades IFile como somente leitura e então abrir o IFile. O pseudocódigo a seguir demonstra isso:
    Get the CARMAMember the user wants to browse;
    Create an IFile that represents the CARMAMember;
    Download contents of the CARMAMember into the IFile;
    Set the properties of the IFile to read-only;
    Call Eclipse to open the IFile;
    Use o código de amostra a seguir para implementar esse método:
    public void run(IAction action) {	
       //if itemSelected is null then the browse action was run
       //on something that is not a CARMA Member, this should never happen
       if (this.itemSelected != null) {
          //Get the name of the CARMA Member
          String memberName = itemSelected.getFileName();
    			
          //Create a temporary location on the workstation to hold the
          //local cache of the file
          IWorkspace myWorkspace = ResourcesPlugin.getWorkspace();
          IWorkspaceRoot myRoot = myWorkspace.getRoot();
    			
          IProject myResource = myRoot.getProject("/BootCampTemp");
    			
          //If the temporary directory that holds the temporary files
          //does not exist create it
          if( !myResource.exists() ){
             try{
                myResource.create(new NullProgressMonitor());
             } catch(Exception e){
                e.printStackTrace();
             }
          }
    			
          //If the temp location which is a project is not open
          //open it
          if( !myResource.isOpen()){
             try{
                myResource.open(new NullProgressMonitor());
             } catch(Exception e){
                e.printStackTrace();
             }
          }
    			
          //Make sure the temporary space is of the right type and exists
          if (myResource instanceof IContainer && myResource.exists()) {
             IContainer myContainer = (IContainer) myResource;
    	
          //Create the IFile in the temporary location 
          final IFile myFile = myContainer.getFile(new Path(memberName));
    				
          //Create the job that will get the contents of the file
          GetContentsJob myJob = new GetContentsJob("CRAJOB1", itemSelected);
    				
          //Run the Job
          myJob.schedule();
    
          try{
             InputStream myStream = null;
             while( (myStream = myJob.getStream()) == null){}
             
             //Copy the contents into the IFile
             if(!myFile.exists())
                myFile.create(myStream, true, new NullProgressMonitor());
             } catch(Exception e){
                e.printStackTrace();
             }			
    				
             //Set the file's attributes to read-only and open the file
             Display display = Display.getDefault();
             display.syncExec(new Runnable() {
             public void run() {
                IWorkbenchPage page = 
                   PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                
                try {
                   ResourceAttributes myAttributes = myFile.getResourceAttributes();
                   if(myAttributes == null){
                      myAttributes = new ResourceAttributes();
                   }
                   //setting the attributes to readonly
                   myAttributes.setReadOnly(true);
                   try{
                      myFile.setResourceAttributes(myAttributes);
                   } catch(Exception e){
                      e.printStackTrace();
                   }
                   //opening the file in browse mode
                   IDE.openEditor(page, myFile, true);
                } catch (PartInitException e) {
                   //TODO handle exception
                   System.out.println(e);
                }
             }
          });
          }
       }
    }
  4. Verifique se todos os pacotes que a classe precisará serão importados. Inclua qualquer um que esteja na lista abaixo, mas que ainda não esteja incluído nas instruções de importação:
    import java.io.InputStream;
    import java.util.Iterator;
    
    import org.eclipse.core.resources.IContainer;
    import org.eclipse.core.resources.IFile;
    import org.eclipse.core.resources.IProject;
    import org.eclipse.core.resources.IWorkspace;
    import org.eclipse.core.resources.IWorkspaceRoot;
    import org.eclipse.core.resources.ResourceAttributes;
    import org.eclipse.core.resources.ResourcesPlugin;
    import org.eclipse.core.runtime.NullProgressMonitor;
    import org.eclipse.core.runtime.Path;
    import org.eclipse.jface.action.IAction;
    import org.eclipse.jface.viewers.ISelection;
    import org.eclipse.jface.viewers.IStructuredSelection;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.ui.IViewActionDelegate;
    import org.eclipse.ui.IViewPart;
    import org.eclipse.ui.IWorkbenchPage;
    import org.eclipse.ui.PartInitException;
    import org.eclipse.ui.PlatformUI;
    import org.eclipse.ui.ide.IDE;
    
    import com.ibm.carma.model.CARMAMember;
    import com.ibm.carma.ui.job.GetContentsJob;
  5. Salve a origem e depure qualquer erro.

Termos de Uso | Feedback



Este centro de informações foi desenvolvido com a tecnologia Eclipse. (http://www.eclipse.org)