⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tomcatproject.java

📁 一个学习eclipse插件开发的绝好入门程序
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
		this.addTomcatJarToProjectClasspath();
		this.addWEBINFLibJarFilesToProjectClasspath();
				
		this.clearDefaultSourceEntries();
		this.setClassesAsOutputFolder();
		if(classesContainsJavaFiles()) {
			this.setClassesAsSourceFolder();
		}
		
		this.setSrcAsSourceFolder();
		this.setWEBINFSrcAsSourceFolder();
		this.setWorkAsSourceFolder();
	
		this.updateContext();
	}

	public void clearDefaultSourceEntries()  throws CoreException {
		IClasspathEntry[] entries = javaProject.getRawClasspath();
		List cp= new ArrayList(entries.length + 1);
		for(int i=0; i<entries.length; i++) {
			if(entries[i].getEntryKind() != IClasspathEntry.CPE_SOURCE) {
				cp.add(entries[i]);
			}
		}
		javaProject.setRawClasspath((IClasspathEntry[])cp.toArray(new IClasspathEntry[cp.size()]), null);
	}

	/*
	 * Add servlet.jar and jasper.jar to project classpath
	 */	
	public void addTomcatJarToProjectClasspath()  throws CoreException {
		TomcatBootstrap tb = TomcatLauncherPlugin.getDefault().getTomcatBootstrap();
		
		IClasspathEntry[] entries = javaProject.getRawClasspath();
		List cp = new ArrayList(entries.length + 1);
		
		for (int i = 0; i < entries.length; i++) {
			IClasspathEntry entry = entries[i];
			if(!((entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) && 
				(entry.getPath().toOSString().startsWith(TomcatLauncherPlugin.getDefault().getTomcatIPath().toOSString())))) {
				cp.add(entry);
			}		
		}

		cp.addAll(tb.getTomcatJars());
							
		javaProject.setRawClasspath((IClasspathEntry[])cp.toArray(new IClasspathEntry[cp.size()]), null);
	}
	

	/*
	 * Add all jar in WEB-INF/lib to project classpath
	 */
	public void addWEBINFLibJarFilesToProjectClasspath()  throws CoreException {
		IFolder libFolder = this.getWebInfFolder().getFolder("lib");
		IResource[] libFiles = libFolder.members();

		IClasspathEntry[] entries = javaProject.getRawClasspath();
		List cp= new ArrayList(entries.length + 1);
		cp.addAll(Arrays.asList(entries));
		
		for(int i=0; i<libFiles.length; i++) {
			if((libFiles[i].getType() == IResource.FILE) && (libFiles[i].getFileExtension().equalsIgnoreCase("jar"))) {
				cp.add(JavaCore.newLibraryEntry(libFiles[i].getFullPath(), null, null));
			}				
		}

		javaProject.setRawClasspath((IClasspathEntry[])cp.toArray(new IClasspathEntry[cp.size()]), null);
	}
	
	public IFolder getWebInfFolder() {
		if (getRootDirFolder() == null) {
			return project.getFolder("WEB-INF");
		} else {
			return getRootDirFolder().getFolder("WEB-INF");
		}
	}

	public IFolder getWorkFolder() {
//		if (getRootDirFolder() == null) {
//			return project.getFolder("work");
//		} else {
//			return getRootDirFolder().getFolder("work");
//		}

		return project.getFolder("work");
		
	}

	public IFolder getRootDirFolder() {
		if (rootDirFolder == null) {
			this.initRootDirFolder(false);
		}
		return rootDirFolder;
	}

	private void initRootDirFolder(boolean create) {
		StringTokenizer tokenizer = new StringTokenizer(this.getRootDir(), "/\\:");
		IFolder folder = null;
		try {
			while (tokenizer.hasMoreTokens()) {
				String each = tokenizer.nextToken();
				if (folder == null) {
					folder = project.getFolder(each);
				} else {
					folder = folder.getFolder(each);
				}
				if (create) {
					this.createFolder(folder);
				}
			}
		} catch (CoreException ex) {
			TomcatLauncherPlugin.log(ex);
			folder = null;
			setRootDir("/");
		}
		this.rootDirFolder = folder;

	}


	public void createWEBINFFolder()  throws CoreException {
		IFolder webinfFolder = this.getWebInfFolder();	
		this.createFolder(webinfFolder);
		this.createFolder(webinfFolder.getFolder("classes"));
		this.createFolder(webinfFolder.getFolder("lib"));
	    
		// Create .cvsignore for classes
		this.createFile(webinfFolder.getFile(".cvsignore"), "classes");     
	}

	public void createWEBINFSrcFolder()  throws CoreException {
		this.createFolder(this.getWebInfFolder().getFolder("src"));
	}

	public void createWorkFolder()  throws CoreException {
		IFolder folderHandle = this.getWorkFolder();
		this.createFolder(folderHandle);
		
		String tomcatVersion = TomcatLauncherPlugin.getDefault().getTomcatVersion();
		if(tomcatVersion.equals(TomcatLauncherPlugin.TOMCAT_VERSION4) 
				|| tomcatVersion.equals(TomcatLauncherPlugin.TOMCAT_VERSION41)) { 	
			folderHandle = folderHandle.getFolder("org");
			this.createFolder(folderHandle);
			folderHandle = folderHandle.getFolder("apache");
			this.createFolder(folderHandle);
			folderHandle = folderHandle.getFolder("jsp");
			this.createFolder(folderHandle);
		}
		
		// Add a .cvsignore file in work directory
		this.createFile(project.getFile(".cvsignore") , "work");     
					
	}

	public void setSrcAsSourceFolder()  throws CoreException {
//		this.setFolderAsSourceEntry(project.getFolder("src"));
	}

	public void setWEBINFSrcAsSourceFolder()  throws CoreException {
		this.setFolderAsSourceEntry(this.getWebInfFolder().getFolder("src"), null);
	}


	public void setClassesAsOutputFolder()  throws CoreException {
		IFolder classesFolder = this.getWebInfFolder().getFolder("classes");
		javaProject.setOutputLocation(classesFolder.getFullPath(),null);
	}

	public void setClassesAsSourceFolder()  throws CoreException {	
		IFolder classesFolder = this.getWebInfFolder().getFolder("classes");
		this.setFolderAsSourceEntry(classesFolder, null);
	}
	
	public void setWorkAsSourceFolder()  throws CoreException {
		this.setFolderAsSourceEntry(this.getWorkFolder(), this.getWorkFolder());
	}


	private void createFolder(IFolder folderHandle)  throws CoreException {		
		try {
			// Create the folder resource in the workspace
			folderHandle.create(false, true, null); //new SubProgressMonitor(monitor, 500));
		}
		catch (CoreException e) {
			// If the folder already existed locally, just refresh to get contents
			if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
				folderHandle.refreshLocal(IResource.DEPTH_INFINITE, null); //new SubProgressMonitor(monitor, 500));
			else
				throw e;
		}
	}

	private void createFile(IFile fileHandle, String content)  throws CoreException {     
		try {
			fileHandle.create(new ByteArrayInputStream(content.getBytes()), 0, null);
		}
		catch (CoreException e) {
			// If the file already existed locally, just refresh to get contents
			if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
				fileHandle.refreshLocal(IResource.DEPTH_INFINITE, null); //new SubProgressMonitor(monitor, 500));
			else
				throw e;
		}
	}
		
		
	/*
	 * ouput could be null (project default output will be used)
	 */
	private void setFolderAsSourceEntry(IFolder folderHandle, IFolder output) throws CoreException {
		IClasspathEntry[] entries= javaProject.getRawClasspath();
		IClasspathEntry[] newEntries= new IClasspathEntry[entries.length + 1];
		System.arraycopy(entries,0, newEntries,0, entries.length);
		IPath outputPath = null;
		if(output != null) outputPath = output.getFullPath();
		
		IPath[] emptyPath = {};
		newEntries[entries.length] = JavaCore.newSourceEntry(folderHandle.getFullPath(), emptyPath, outputPath);

		javaProject.setRawClasspath(newEntries, null);	
	}

	 
	/**
	 * Add or update a Context definition
	 */
	public void updateContext() throws CoreException, IOException {
		if(TomcatLauncherPlugin.getDefault().getConfigMode().equals(TomcatLauncherPlugin.SERVERXML_MODE)) {
			this.updateServerXML();
		} else {
			this.updateContextFile();
		}
	}
	
	/*
	 * Add or update a Context entry on Tomcat server.xml file
	 */
	private void updateServerXML() throws CoreException, IOException {

		if(getUpdateXml()) {		
			this.backupServerXML();

			String xml = FileUtil.readTextFile(getServerXML());
			if(!contextExistsInXML(xml)) {
				this.addContextToServerXML();	
			} else {
				this.updateContextDefinitionInFile(getServerXML());		
			}
		}
	}	

	/*
	 * create or update a Context file
	 */
	private void updateContextFile() throws CoreException, IOException {

		if(getUpdateXml()) {
			File contextFile = this.getContextFile();
			if(!contextFile.exists()) {
				FileUtil.toTextFile(contextFile, this.createContextDefinition());	
			} else {
				updateContextDefinitionInFile(contextFile);
			}
		}
	}


	private File getContextFile() {
		File contextFile = new File(TomcatLauncherPlugin.getDefault().getContextsDir() +
			File.separator + getContextFileName());
		return contextFile;
	}
	
	private String getContextFileName() {
		String contextFileName = this.getWebPath();
		if(contextFileName.startsWith("/")) {
			contextFileName = contextFileName.substring(1);
		}
		
		// Tomcat 5 converts / to # in context file name
		contextFileName = contextFileName.replace('/', '#');
		
		return contextFileName + ".xml";	
	}
	
	
	
	public void removeContext() throws CoreException, IOException {
		// Always call removeContext file because Tomcat create it automatically when using server.xml
		this.removeContextFile();
		
		if(TomcatLauncherPlugin.getDefault().getConfigMode().equals(TomcatLauncherPlugin.SERVERXML_MODE)) {
			this.removeContextInServerXML();
		}
	}

	private void removeContextFile() {
		this.getContextFile().delete();	
	}
	
	private void removeContextInServerXML() throws CoreException, IOException {
		this.backupServerXML();

		String xml = FileUtil.readTextFile(getServerXML());
		if(contextExistsInXML(xml)) {			
			int contextTagIdx = this.getContextTagIndex(xml);			
			int endTagIndex = xml.indexOf("</Context>", contextTagIdx);
			boolean hasNoBody = false;
			if (endTagIndex < 0) {
				endTagIndex = xml.indexOf('>', contextTagIdx);
				hasNoBody = true;
			}
			else
				endTagIndex+= "</Context>".length();
			

			StringBuffer out = null;

			out = new StringBuffer(xml.substring(0, contextTagIdx));
			out.append(xml.substring(endTagIndex+1, xml.length()));				

			if (out != null) FileUtil.toTextFile(getServerXML(), out.toString());				
				
		}
	}


	/**
	 * Backup Tomcat server.xml file using the following algorithm :
	 * - Initial server.xml is backuped to server.xml.backup
	 * - Before updating server.xml create a copy named server.xml.old
	 */
	public void backupServerXML() throws CoreException, IOException {
		String backup =  getServerXMLLocation() + ".backup";
		String old =  getServerXMLLocation() + ".old";
			
		if(!getServerXML().exists()) {
			String msg = "Tomcat server.xml file is not found in " + getServerXML().getAbsolutePath();
			Status status = new Status(IStatus.ERROR, TomcatLauncherPlugin.getDefault().getDescriptor().getUniqueIdentifier(), IStatus.ERROR, msg, null);
			throw new CoreException(status);
		}
			
		File backupFile = new File(backup);
		if(!backupFile.exists()) {
			FileUtil.copy(getServerXML(), backupFile);	
		}
		
		FileUtil.copy(getServerXML(), new File(old));			
	}
	

	
	private File getServerXML() {
		return new File(getServerXMLLocation());		
	}
	
	private String getServerXMLLocation() {
		return TomcatLauncherPlugin.getDefault().getConfigFile();
	}


	/**
	 * Quick and dirty implementations : using an XML Parser would be better
	 */
	private boolean contextExistsInXML(String xml) throws IOException {
		return (getContextTagIndex(xml) != -1);
	}
	
	private int getContextTagIndex(String xml) throws IOException {
		int pathIndex = xml.indexOf(getContextPath());
		
		if(pathIndex == -1)
			return -1;		
		
		int tagIndex = (xml.substring(0, pathIndex)).lastIndexOf('<');
		String tag = xml.substring(tagIndex, tagIndex + 8);	
		if(!tag.equalsIgnoreCase(getContextStartTag()))
			return -1;
			
		return tagIndex;
	}
	
	private void addContextToServerXML() throws IOException {
		String xml = FileUtil.readTextFile(getServerXML());
		String tag = TomcatLauncherPlugin.getDefault().getTomcatBootstrap().getXMLTagAfterContextDefinition();
			
		int tagIndex = xml.indexOf(tag);
		int insertIndex = (xml.substring(0, tagIndex)).lastIndexOf('\n');
			
		StringBuffer out = new StringBuffer(xml.substring(0, insertIndex));
		out.append(this.createContextDefinition());
		out.append(xml.substring(insertIndex, xml.length()));
		
		FileUtil.toTextFile(getServerXML(), out.toString());	
	}
	
	private String createContextDefinition() {
		StringBuffer contextBuffer = new StringBuffer();
		contextBuffer.append(getContextStartTag());
		contextBuffer.append(' ');
		contextBuffer.append(getContextPath());
		contextBuffer.append(' ');
		contextBuffer.append(getContextReloadable());	
		contextBuffer.append(' ');		
		contextBuffer.append(getContextDocBase());
		contextBuffer.append(' ');
		contextBuffer.append(getContextWorkDir());
		contextBuffer.append(" />\n");

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -