Skip to content

Commit 92ee709

Browse files
committed
Fix to work without selected package
1 parent 807175d commit 92ee709

File tree

2 files changed

+165
-66
lines changed

2 files changed

+165
-66
lines changed

src/ServiceStackEclipse/src/net/servicestack/eclipse/maven/EclipseMavenHelper.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,15 @@
1212
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
1313
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
1414
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
15+
import org.eclipse.core.resources.IFile;
1516

1617
public class EclipseMavenHelper {
17-
public boolean addMavenDependencyIfRequired(File pomFile, String groupId, String packageId, String version) throws Exception {
18+
public boolean addMavenDependencyIfRequired(IFile pomFile, String groupId, String packageId, String version) throws Exception {
1819
boolean noDependencyAdded = true;
1920
MavenXpp3Reader reader = new MavenXpp3Reader();
2021
Model pomModel;
2122
try {
22-
pomModel = reader.read(new FileReader(pomFile));
23+
pomModel = reader.read(new FileReader(new File(pomFile.getLocationURI())));
2324
final List<Dependency> dependencies= pomModel.getDependencies();
2425
boolean requiresPomDependency = true;
2526
for (Dependency dep : dependencies) {
@@ -33,7 +34,7 @@ public boolean addMavenDependencyIfRequired(File pomFile, String groupId, String
3334
dependency.setGroupId(groupId);
3435
dependency.setArtifactId(packageId);
3536
dependency.setVersion(version);
36-
FileWriter writer = new FileWriter(pomFile.getAbsolutePath());
37+
FileWriter writer = new FileWriter(pomFile.getLocationURI().getPath());
3738
pomModel.addDependency(dependency);
3839
new MavenXpp3Writer().write(writer, pomModel);
3940
noDependencyAdded = false;

src/ServiceStackEclipse/src/net/servicestack/eclipse/wizard/AddReferenceWizard.java

Lines changed: 161 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@
66
import java.io.IOException;
77
import java.io.InputStream;
88
import java.lang.reflect.InvocationTargetException;
9+
import java.util.ArrayList;
10+
import java.util.HashMap;
11+
import java.util.List;
12+
import java.util.Map;
913

1014
import net.servicestack.eclipse.maven.EclipseMavenHelper;
1115
import net.servicestack.eclipse.nativetypes.INativeTypesHandler;
@@ -14,19 +18,22 @@
1418
import org.eclipse.core.resources.IFile;
1519
import org.eclipse.core.resources.IFolder;
1620
import org.eclipse.core.resources.IProject;
17-
import org.eclipse.core.resources.ResourcesPlugin;
21+
import org.eclipse.core.resources.IResource;
1822
import org.eclipse.core.runtime.CoreException;
23+
import org.eclipse.core.runtime.IAdaptable;
1924
import org.eclipse.core.runtime.IPath;
2025
import org.eclipse.core.runtime.IProgressMonitor;
2126
import org.eclipse.core.runtime.Path;
27+
import org.eclipse.jdt.core.IJavaElement;
2228
import org.eclipse.jdt.core.IPackageFragment;
2329
import org.eclipse.jface.operation.IRunnableWithProgress;
24-
import org.eclipse.jface.resource.ImageDescriptor;
30+
import org.eclipse.jface.viewers.ISelection;
2531
import org.eclipse.jface.viewers.IStructuredSelection;
2632
import org.eclipse.jface.wizard.Wizard;
2733
import org.eclipse.ui.IEditorRegistry;
2834
import org.eclipse.ui.IWorkbench;
2935
import org.eclipse.ui.IWorkbenchPage;
36+
import org.eclipse.ui.IWorkbenchWindow;
3037
import org.eclipse.ui.PartInitException;
3138
import org.eclipse.ui.PlatformUI;
3239
import org.eclipse.ui.part.FileEditorInput;
@@ -39,117 +46,132 @@ public class AddReferenceWizard extends Wizard {
3946
private IPath _packagePath;
4047
private boolean _hasPomFile;
4148
private File _pomFile;
42-
43-
private String errorMessage;
49+
public String packageName;
50+
private IProject currentProject;
51+
boolean packageSelected = false;
4452

4553
private static final String dependencyGroupId = "net.servicestack";
4654
private static final String dependencyVersion = "1.0.10";
4755
private static final String clientPackageId = "client";
56+
boolean success = false;
4857

4958
public AddReferenceWizard(IFolder selection,
5059
IStructuredSelection packageSelection) {
60+
IResource selectedResource = extractSelection(packageSelection);
61+
currentProject = selectedResource.getProject();
5162
_selection = selection;
52-
Object firstElement = packageSelection.getFirstElement();
53-
if(firstElement instanceof IPackageFragment) {
54-
_packageFragment = (IPackageFragment)firstElement;
63+
if(packageSelection != null) {
64+
Object firstElement = packageSelection.getFirstElement();
65+
if (firstElement instanceof IPackageFragment) {
66+
_packageFragment = (IPackageFragment) firstElement;
67+
packageName = _packageFragment.toString().substring(0,_packageFragment.toString().indexOf("[")).trim();
68+
}
5569
}
56-
_projectPath = _packageFragment.getJavaProject().getPath();
57-
_packagePath = _packageFragment.getPath();
5870

59-
File lastPath = new File(_packagePath.toString());
60-
File projectPath = new File(_projectPath.toString());
61-
if (!lastPath.isDirectory() || !projectPath.isDirectory()) {
71+
72+
if(_packageFragment == null) {
73+
_projectPath = currentProject.getFullPath();
74+
discoverPom(selection.getProjectRelativePath().toString(),_projectPath.toString());
75+
} else {
76+
_projectPath = _packageFragment.getJavaProject().getPath();
77+
_packagePath = _packageFragment.getPath();
78+
packageSelected = true;
79+
discoverPom(_packagePath.toString(),_projectPath.toString());
80+
}
81+
}
82+
83+
private void discoverPom(String folderPath, String projectPath) {
84+
File lastPath = new File(folderPath);
85+
File projectPathFile = new File(projectPath);
86+
if (!lastPath.isDirectory() || !projectPathFile.isDirectory()) {
6287
_hasPomFile = false;
6388
}
64-
while (!lastPath.getAbsolutePath()
65-
.equals(projectPath.getAbsolutePath())) {
66-
if (!hasChildPomFile(lastPath)) {
67-
lastPath = lastPath.getParentFile();
68-
} else {
89+
while (!lastPath.toString().equals(File.separator)) {
90+
if (hasChildPomFile(lastPath.toString())) {
6991
// POM found
7092
_hasPomFile = true;
71-
_pomFile = new File(lastPath.getAbsolutePath() + "/pom.xml");
93+
String pomPath = stripFirstDirectoryFromPath(new Path(lastPath.toString() + File.separator + "pom.xml")).toString();
94+
_pomFile = new File(pomPath);
95+
break;
7296
}
97+
lastPath = lastPath.getParentFile();
7398
}
7499
}
100+
101+
IResource extractSelection(ISelection sel) {
102+
if (!(sel instanceof IStructuredSelection))
103+
return null;
104+
IStructuredSelection ss = (IStructuredSelection) sel;
105+
Object element = ss.getFirstElement();
106+
if (element instanceof IResource)
107+
return (IResource) element;
108+
if (!(element instanceof IAdaptable))
109+
return null;
110+
IAdaptable adaptable = (IAdaptable)element;
111+
Object adapter = adaptable.getAdapter(IResource.class);
112+
return (IResource) adapter;
113+
}
75114

76-
private boolean hasChildPomFile(File filePath) {
77-
File[] matchingFiles = filePath.listFiles(new FilenameFilter() {
78-
public boolean accept(File dir, String name) {
79-
return name.startsWith("pom") && name.endsWith("xml");
80-
}
81-
});
82-
return matchingFiles != null && matchingFiles.length > 0;
115+
private boolean hasChildPomFile(String filePath) {
116+
IProject project = currentProject;
117+
IPath pomPath = stripFirstDirectoryFromPath(new Path(filePath + File.separator + "pom.xml"));
118+
IFile file = project.getFile(pomPath);
119+
return file.exists();
83120
}
84121

85122
@Override
86123
public boolean performFinish() {
87-
// TODO Auto-generated method stub
88124
final String addressUrl = _page.getAddressUrl();
89125
final String fileName = _page.getFileName();
126+
success = false;
90127
try {
91128
getContainer().run(false, false, new IRunnableWithProgress() {
92129

93130
@Override
94131
public void run(IProgressMonitor monitor)
95132
throws InvocationTargetException, InterruptedException {
96133

134+
monitor.beginTask("Fetching ServiceStack Reference", 10);
135+
monitor.worked(2);
97136
String code = null;
98-
INativeTypesHandler nativeTypesHandler = new JavaNativeTypesHandler();
99137
try {
100-
code = nativeTypesHandler
101-
.getUpdatedCode(addressUrl, null);
138+
139+
code = fetchDto(addressUrl);
102140
if (code == null) {
103-
_page.setErrorMessage(errorMessage = "Invalid ServiceStack endpoint.");
141+
_page.setErrorMessage("Invalid ServiceStack endpoint.");
142+
return;
104143
}
105144
} catch (IOException e1) {
106-
// TODO Auto-generated catch block
107145
_page.setErrorMessage("Error occurred trying to validate the ServiceStack endpoint - "
108146
+ e1.getMessage());
109147
e1.printStackTrace();
110148
return;
111149
}
112150

113-
151+
monitor.worked(2);
114152
try {
115-
String workspacePath = ResourcesPlugin.getWorkspace().getRoot().getFullPath().toString();
116-
String constructedPath = "";
117-
//Skip first segment of project path as we want path relative to project.
118-
for(int i = 1; i < _packageFragment.getPath().segmentCount(); i++) {
119-
constructedPath += "/" + _packageFragment.getPath().segment(i);
120-
}
121-
String currentPackagePath = constructedPath;
122-
Path filePath = new Path(currentPackagePath + "/" + fileName);
123-
IProject project = _packageFragment.getResource().getProject();
124-
IFile dtoFile = project.getFile(filePath);
125-
String contents = code;
126-
InputStream source = new ByteArrayInputStream(contents
127-
.getBytes());
128-
dtoFile.create(source, false, null);
153+
addDtoFileWithCode(fileName, code);
129154
} catch (CoreException e) {
130-
// TODO Auto-generated catch block
131155
e.printStackTrace();
132156
_page.setErrorMessage("Error occurred when trying to create DTO file - "
133157
+ e.getMessage());
158+
monitor.done();
159+
return;
134160
}
161+
monitor.worked(2);
135162
if (_hasPomFile) {
136-
137-
EclipseMavenHelper mavenHelper = new EclipseMavenHelper();
138163
try {
139-
if (mavenHelper.addMavenDependencyIfRequired(
140-
_pomFile, dependencyGroupId,
141-
clientPackageId, dependencyVersion)) {
142-
// TODO Show pom file/prompt to import changes
143-
// of pom file/perform maven task to download
144-
// dependencies
145-
}
164+
updatePomFile();
146165
} catch (Exception e) {
147166
// TODO Warn maven dependency failed, continue as
148167
// DTOs were added.
149168
e.printStackTrace();
150169
}
170+
monitor.worked(2);
151171
}
152-
172+
monitor.worked(2);
173+
monitor.done();
174+
success = true;
153175
}
154176
});
155177
} catch (InvocationTargetException | InterruptedException e2) {
@@ -159,9 +181,90 @@ public void run(IProgressMonitor monitor)
159181
+ e2.getMessage());
160182
}
161183

162-
return true;
184+
return success;
163185
}
164186

187+
private void updatePomFile() throws Exception {
188+
EclipseMavenHelper mavenHelper = new EclipseMavenHelper();
189+
IProject project = currentProject;
190+
IPath pomPath = new Path(_pomFile.getPath());
191+
IFile file = project.getFile(pomPath);
192+
if (mavenHelper.addMavenDependencyIfRequired(file,
193+
dependencyGroupId, clientPackageId,
194+
dependencyVersion)) {
195+
// TODO Show pom file/prompt to import changes
196+
// of pom file/perform maven task to download
197+
// dependencies
198+
}
199+
}
200+
201+
private String fetchDto(final String addressUrl) throws IOException {
202+
String code = null;
203+
INativeTypesHandler nativeTypesHandler = new JavaNativeTypesHandler();
204+
Map<String, String> options = null;
205+
if(packageSelected) {
206+
options = new HashMap<String,String>();
207+
options.put("Package", packageName);
208+
}
209+
code = nativeTypesHandler.getUpdatedCode(addressUrl, options);
210+
return code;
211+
}
212+
213+
/**
214+
* The method returns the current Path information as List<String>.
215+
* <ol>
216+
* <li>0 - Project name</li>
217+
* <li>1 - SRC Folder name</li>
218+
* <li>2 - Package name</li>
219+
* </ol>
220+
*
221+
* @return List<Object>
222+
*/
223+
public static List<Object> getSelectedObjectPath() {
224+
// the current selection in the entire page
225+
final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
226+
final IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection("org.eclipse.jdt.ui.PackageExplorer");
227+
final Object o = selection.getFirstElement();
228+
final List<Object> a = new ArrayList<Object>(4);
229+
IJavaElement obj = (IJavaElement) o;
230+
if (o == null) {
231+
return null;
232+
}
233+
while (obj != null) {
234+
a.add(0, obj);
235+
obj = obj.getParent();
236+
}
237+
// remove JavaModel
238+
a.remove(0);
239+
return a;
240+
}
241+
242+
private void addDtoFileWithCode(final String fileName, String code)
243+
throws CoreException {
244+
String constructedPath = stripFirstDirectoryFromPath(_selection.getFullPath()).toString();
245+
String currentPackagePath = constructedPath;
246+
Path filePath = new Path(currentPackagePath + File.separator + fileName);
247+
IProject project = currentProject;
248+
IFile dtoFile = project.getFile(filePath);
249+
String contents = code;
250+
InputStream source = new ByteArrayInputStream(contents.getBytes());
251+
dtoFile.create(source, true, null);
252+
}
253+
254+
private IPath stripFirstDirectoryFromPath(IPath path) {
255+
String constructedPath = "";
256+
// Skip first segment of project path as we want path relative to
257+
// project.
258+
for (int i = 1; i < path.segmentCount(); i++) {
259+
constructedPath += "/" + path.segment(i);
260+
}
261+
if(constructedPath.equals("")) {
262+
constructedPath = "/";
263+
}
264+
Path result = new Path(constructedPath);
265+
return result;
266+
}
267+
165268
public boolean canFinish() {
166269
return _page.canFinish;
167270
}
@@ -181,7 +284,6 @@ protected void openEditor(IFile file, String editorID)
181284
}
182285

183286
private IWorkbench getWorkbench() {
184-
// TODO Auto-generated method stub
185287
return PlatformUI.getWorkbench();
186288
}
187289

@@ -190,10 +292,6 @@ public void addPages() {
190292
super.addPages();
191293

192294
_page = new AddReferencePage();
193-
String sessionName = _selection.getParent().getParent().getName()
194-
.toLowerCase();
195-
// _page.setPathToOutput(_outputFolder.getFolder(sessionName).getLocation().toOSString());
196-
// _page.setPathToInputFolder(_selection.getFolder(sessionName).getLocation().toOSString());
197295
addPage(_page);
198296
}
199297

0 commit comments

Comments
 (0)