Skip to main content
summaryrefslogtreecommitdiffstats
blob: 6ee2dd804f7068c6034e21e1134464ff224433a8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/*******************************************************************************
 * Copyright (c) 2003, 2005 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * IBM Corporation - initial API and implementation
 *******************************************************************************/
/*
 * Created on Mar 25, 2004
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package org.eclipse.jst.common.jdt.internal.integration.ui;

import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.jdom.IDOMField;
import org.eclipse.jdt.core.jdom.IDOMMethod;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jst.common.jdt.internal.integration.JavaInsertionHelper;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.ui.IEditorInput;
import org.eclipse.wst.common.frameworks.internal.operations.IHeadlessRunnableWithProgress;

/**
 * @author DABERG
 * 
 * To change the template for this generated type comment go to Window>Preferences>Java>Code
 * Generation>Code and Comments
 */
public class JavaInsertionOperation implements IHeadlessRunnableWithProgress {
	private static final String NEW_LINE = System.getProperty("line.separator"); //$NON-NLS-1$
	protected JavaInsertionHelper insertionHelper;
	protected IEditorInput editorInput;
	protected IDocument document;
	protected ITextSelection textSelection;
	protected IProgressMonitor monitor;

	/**
	 *  
	 */
	public JavaInsertionOperation(JavaInsertionHelper insertionHelper, IEditorInput editorInput, IDocument document, ITextSelection textSelection) {
		super();
		this.insertionHelper = insertionHelper;
		this.editorInput = editorInput;
		this.document = document;
		this.textSelection = textSelection;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.wst.common.frameworks.internal.operation.IHeadlessRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
	 */
	public void run(IProgressMonitor monitorArg) throws InvocationTargetException, InterruptedException {
		this.monitor = monitorArg;
		insertCodeSnippet();
		processJavaHelper();
	}

	/**
	 *  
	 */
	protected void insertCodeSnippet() throws InvocationTargetException {
		String replacementString = insertionHelper.getInsertionString();
		if (replacementString == null || replacementString.length() == 0)
			return;
		if (textSelection == null)
			throw new RuntimeException("No text selection for inserting text."); //$NON-NLS-1$
		try {
			document.replace(textSelection.getOffset(), textSelection.getLength(), replacementString);
		} catch (BadLocationException e) {
			throw new InvocationTargetException(e);
		}
		int start = textSelection.getStartLine();
		int lines = document.computeNumberOfLines(replacementString) + 1;
		format(document, start, lines, 0);
	}

	protected void processJavaHelper() {
		ICompilationUnit cu = JavaUI.getWorkingCopyManager().getWorkingCopy(editorInput);
		if (cu != null) {
			IType type = null;
			try {
				type = cu.getTypes()[0];
			} catch (JavaModelException e) {
				//Ignore
			}
			if (type != null) {
				if (insertionHelper.hasFields())
					createFields(type, insertionHelper.getFields());
				if (insertionHelper.hasMethods())
					createMethods(type, insertionHelper.getMethods());
				if (insertionHelper.hasImports())
					createImports(cu, insertionHelper.getImportStatements());
				executeExtendedOperations();
			}
		}
	}

	/**
	 *  
	 */
	private void executeExtendedOperations() {
		List ops = insertionHelper.getExtendedOperations();
		if (ops != null) {
			for (int i = 0; i < ops.size(); i++)
				executedExtendedOperation((IHeadlessRunnableWithProgress) ops.get(i));
		}
	}

	/**
	 * @param operation
	 */
	private void executedExtendedOperation(IHeadlessRunnableWithProgress operation) {
		try {
			operation.run(null);
		} catch (Exception e) {
			Logger log = Logger.getLogger();
			log.log("Executing extended operation failed:  " + operation); //$NON-NLS-1$
			log.log(e);
		}
	}

	protected void createFields(IType aType, List fields) {
		IDOMField field;
		for (int i = 0; i < fields.size(); i++) {
			field = (IDOMField) fields.get(i);
			if (!aType.getField(field.getName()).exists()) {
				try {
					aType.createField(format(field.getContents(), 1, true), null, true, null);
				} catch (JavaModelException e) {
					Logger.getLogger().logError(e);
				}
			}
		}
	}

	/**
	 * @param wc
	 */
	protected void createMethods(IType aType, List methods) {
		IDOMMethod method;
		for (int i = 0; i < methods.size(); i++) {
			method = (IDOMMethod) methods.get(i);
			if (!aType.getMethod(method.getName(), getParamaterTypeSignatures(method)).exists()) {
				try {
					aType.createMethod(format(method.getContents(), 1, true), null, true, null);
				} catch (JavaModelException e) {
					Logger.getLogger().logError(e);
				}
			}
		}
	}

	protected void createImports(ICompilationUnit cu, List imports) {
		String importStmt;
		for (int i = 0; i < imports.size(); i++) {
			importStmt = (String) imports.get(i);
			if (!cu.getImport(importStmt).exists() && !importStmt.startsWith("java.lang")) { //$NON-NLS-1$
				try {
					cu.createImport(importStmt, null, null);
				} catch (JavaModelException e) {
					Logger.getLogger().logError(e);
				}
			}
		}
	}

	protected String format(String contents, int indent, boolean ensureEndLineReturn) {
		Document doc = new Document(contents);
		int lines = doc.getNumberOfLines();
		format(doc, 0, lines - 1, indent);
		String result = doc.get();
		if (ensureEndLineReturn)
			result = ensureLineReturn(result);
		return result;
	}

	protected void format(IDocument documentArg, int startLine, int lines, int indent) {
		try {
			int end = documentArg.getLineOffset(startLine + lines);
			int length = end - startLine;
			CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
			TextEdit edit = formatter.format(CodeFormatter.K_UNKNOWN, documentArg.get(), startLine, length, indent, null);
			if (edit != null) {
				try {
					edit.apply(documentArg);
				} catch (MalformedTreeException e) {
					//Ignore
				}
			}
		} catch (BadLocationException e) {
			Logger log = Logger.getLogger();
			log.log("Failed to format text."); //$NON-NLS-1$
			log.log(e);
		}
	}

	protected String formatString(String pattern, String[] arguments) {
		return MessageFormat.format(pattern, arguments);
	}

	/**
	 * @param result
	 * @return
	 */
	protected String ensureLineReturn(String aString) {
		if (!aString.endsWith(NEW_LINE))
			return aString + NEW_LINE;
		return aString;
	}

	protected String[] getParamaterTypeSignatures(IDOMMethod aMethod) {
		String[] result = null;
		String[] parms = aMethod.getParameterTypes();
		if (parms != null) {
			if (parms.length == 0)
				result = parms;
			else
				result = new String[parms.length];
			boolean isResolved = false;
			String parm;
			for (int i = 0; i < parms.length; i++) {
				parm = parms[i];
				isResolved = parm.indexOf('.') > 0;
				result[i] = Signature.createTypeSignature(parm, isResolved);
			}
		}
		return result;
	}
}

Back to the top