All pastes #896455 Raw Edit

Miscellany

public text v1 · immutable
·published 2008-02-08 17:43 UTC
rendered paste body
/*
 * Created on 05.02.2008
 * emonic.test emonic.test MBelIntoFile.java
 */

package emonic.test;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.*;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.emonic.base.EMonoPlugin;
import org.emonic.base.codehierarchy.AssemblyParser;
import org.emonic.base.codehierarchy.IAssembly;
import org.emonic.base.codehierarchy.IDotNetElement;
import org.emonic.base.codehierarchy.IField;
import org.emonic.base.codehierarchy.IMethod;
import org.emonic.base.codehierarchy.INamespace;
import org.emonic.base.codehierarchy.IType;
import org.emonic.base.filemanipulators.FileDocument;

import edu.arizona.cs.mbel2.parse.MSILParseException;

import junit.framework.TestCase;

public class MBelIntoFile extends TestCase {

	//FIXME dynamic path introduction
	private static final String dllPathOne = "/home/dertl/ViMEM.dll";
	//private static final String dllPathOne = "/home/dertl/vimem/mono/lib/mono/2.0/mscorlib.dll";	
	private static final String dllDirPath = "/home/dertl/vimem/mono/lib/mono/1.0/";
	private static final String dllDirPath2 = "/home/dertl/vimem/mono/lib/mono/2.0/"; //NOT 2.0!
	private static final String assemblyFilePath ="/home/dertl/vimem/assembly.txt";
			
	private StringBuffer text;
	
	
	public MBelIntoFile(){
		super();
	}
	
	public void testCreation() throws Throwable{
		
		Job job = new Job("Parsing...") {
			public IStatus run(IProgressMonitor monitor) {
				try {
					monitor.beginTask("Analyzing " , 10);
					//Call AssemblyParser of MBel => use dllPathOne

					Vector fileVec = addAssembliesToArray();							

					monitor.worked(5);			
					ByteArrayOutputStream bos = iterateAssembliesToBB(fileVec);

					writeBBToFile(bos);					
					
					//grep for elements														
					//GREP WITH BYTE BUFFER					
			        /*long start = System.currentTimeMillis();
			        Grep.compile("ViMEM> IParaFrame.KeyRegistry.KEY_8");
					ByteBuffer bb = ByteBuffer.wrap(bos.toByteArray());
					Grep.grep(bb);
			        long end = System.currentTimeMillis();
			        System.out.println("[GREP with ByteBuffer] Time: "+(end-start)+"ms");*/			        

			        //GREP WITH FILE					
			        /*start = System.currentTimeMillis();
			        Grep.compile("ViMEM> IParaFrame.KeyRegistry.KEY_8");
			        Grep.grep(new File(assemblyFilePath));
			        end = System.currentTimeMillis();
			        System.out.println("[GREP with File] Time: "+(end-start)+"ms");*/			        
   
			        //alternative grep
					long start = System.currentTimeMillis(); 
					grepElements( "ViMEM> IParaFrame.KeyRegistry.KEY_8");	
					long end = System.currentTimeMillis();
					System.out.println("[Alternative GREP self written with file] Time: " + (end-start) + "ms");
														        
					//grep delete and add incremental => comparable to save of file
			        //delete only lines from ViMEM assembly!
			        //Grep.compile("ViMEM> IParaFrame.KeyRegistry");
					//Grep.grepDelete(bb);
			        
					//Grep.grep(bb);
														
					//grep delete => remove dll, delete file
					
					//grep add => new file, add dll
			      
					return Status.OK_STATUS;
					
				}catch (Exception e) {
					e.printStackTrace();
					return Status.CANCEL_STATUS;
				} finally {
					monitor.done();
				}
			}
		};
		job.schedule();
		while(true){
		 if(job.getState() == job.NONE)
			 break;
		}
		
			
	}	
	
	//alternative grep
    private void grepElements(String toGrep) {
              //Search file via java-grep => accords to string
              //bei this => create
              
              String line;
              BufferedReader input = null;
              Matcher matcher;
              Pattern pattern;
             
              try {
                input = new BufferedReader(new FileReader(assemblyFilePath));

              } catch (FileNotFoundException e1) {
                 e1.printStackTrace();
              }
             
              pattern = Pattern.compile(".*"+toGrep+".*");
              try{
            	  while((line = input.readLine()) != null){
                    matcher = pattern.matcher(line);
                      if(matcher.matches()){
                        System.out.println(line);
                      }
                  }
              }catch(IOException e){
                      e.printStackTrace();
              }                     
      }	

	private void updateMetadataFile(IAssembly assembly, ByteArrayOutputStream bos) {
		text = new StringBuffer();		

		//get namespace[]
		INamespace[] namespaces =  assembly.getNamespaces();
		for(int i=0; i<namespaces.length;i++){
			String namespaceName = namespaces[i].getElementName();
			//namespace itself has to element of file + assemblies name for identification 
			text.append(assembly.getElementName() + "> " + namespaceName + "\n");
			
			//IDotNetElement[] dotnetelements = namespaces[i].getChildren();
			IType[] dotnetTypes = namespaces[i].getTypes();												
			
			//get dotnetelements of types like classes
			for(int j=0; j<dotnetTypes.length;j++){
				String dotnettext = assembly.getElementName() + "> " + namespaceName + "." + dotnetTypes[j].getElementName();
				//type itself has to be element of file
				text.append(dotnettext +"\n");
				
				
				IDotNetElement[] dotnetelements = dotnetTypes[j].getChildren();

				
				for(int k=0; k<dotnetelements.length;k++){
					int type = dotnetelements[k].getElementType();
					String additionaltext = "";
					
					/*
					 * TODO: if the following switch(type) block is used, the time for calculation
					 * of ViMEM.dll is doubled from 0,3-0,4 sec to 0,6-0,7sec!!!
					 */
					switch(type){
						case IDotNetElement.METHOD:
							additionaltext = " FLAGS:"+((IMethod)dotnetelements[k]).getFlags() + 
								" RETURN:"+((IMethod)dotnetelements[k]).getReturnType() +
								" SIGNATURE:" + ((IMethod)dotnetelements[k]).getSignature(); 
							break;
						case IDotNetElement.FIELD:
							additionaltext = " FLAGS:"+((IField)dotnetelements[k]).getFlags();
							break;

					}									
					text.append(dotnettext + "." + dotnetelements[k].getElementName() + additionaltext + "\n");
				}
			}
			
		}
		
		//get Types which are not in a namespace
		//FIXME
		
		int length = text.length();
		for (int i=0; i < length; i++){		      
		  bos.write((byte)text.charAt(i));			
		}
	}
	

	private ByteArrayOutputStream getOutputStreamForDlls() {
		//create file for output 
		//File assemblyText = new File(assemblyFilePath);
		ByteArrayOutputStream bos = null;
		bos = new ByteArrayOutputStream();

		return bos;
	}

	private ByteArrayOutputStream iterateAssembliesToBB(Vector fileVec)
			throws IOException, MSILParseException, FileNotFoundException {
		Map[] maps = new Map[]{ Collections.EMPTY_MAP,
				Collections.EMPTY_MAP };
		ByteArrayOutputStream bos = getOutputStreamForDlls();
		
		//create file with file input of MBel
		Iterator iter =  fileVec.iterator();
		while(iter.hasNext()){
			File actualFile = (File) iter.next();
			maps = new Map[]{ Collections.EMPTY_MAP,
					Collections.EMPTY_MAP };
			System.out.print(actualFile.getName());
			Date start = new Date();	
			IAssembly asse = AssemblyParser.parseAssembly(new FileInputStream(actualFile.getAbsolutePath()),
												 new Path(actualFile.getAbsolutePath()), maps);
			updateMetadataFile(asse, bos);
			Date end = new Date();
			System.out.println( " Time: "+(end.getTime()-start.getTime())+"ms");
		}
		return bos;
	}

	private Vector addAssembliesToArray() {
		Vector fileVec = new Vector();
		fileVec.add(new File(dllPathOne));
		
		File dllDir = new File(dllDirPath);
		if(dllDir.isDirectory()){
			String[] files = dllDir.list();
			for(int i=0; i< files.length;i++){
				//if file = dll
				if(files[i].endsWith(".dll"))
					fileVec.add(new File(dllDir, files[i]));
			}
		}		
		dllDir = new File(dllDirPath2);
		if(dllDir.isDirectory()){
			String[] files = dllDir.list();
			for(int i=0; i< files.length;i++){
				//if file = dll
				if(files[i].endsWith(".dll"))
					fileVec.add(new File(dllDir, files[i]));
			}
		}
		return fileVec;
	}

	private void writeBBToFile(ByteArrayOutputStream bos)
			throws FileNotFoundException, IOException {
		//Write to file
		long begin = System.currentTimeMillis();
		File assemblyText = new File(assemblyFilePath);
		FileOutputStream fos = new FileOutputStream(assemblyText);
		fos.write(bos.toByteArray());
		fos.close();
		long endit = System.currentTimeMillis();
		System.out.println(endit-begin);
	}
	
}