Skip to content

Commit 5fdec96

Browse files
committed
More code clean up of AddRef dialog for IDEA plugin
1 parent ae56bba commit 5fdec96

File tree

6 files changed

+484
-430
lines changed

6 files changed

+484
-430
lines changed

src/ServiceStackIDEA/.idea/workspace.xml

Lines changed: 171 additions & 142 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 19 additions & 284 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,22 @@
11
package net.servicestack.idea;
22

33
import com.intellij.ide.util.PackageChooserDialog;
4-
import com.intellij.notification.Notification;
5-
import com.intellij.notification.NotificationType;
6-
import com.intellij.notification.Notifications;
7-
import com.intellij.openapi.editor.Document;
8-
import com.intellij.openapi.editor.Editor;
9-
import com.intellij.openapi.fileChooser.ex.FileTextFieldImpl;
10-
import com.intellij.openapi.fileEditor.FileDocumentManager;
11-
import com.intellij.openapi.fileEditor.FileEditorManager;
124
import com.intellij.openapi.module.Module;
135
import com.intellij.openapi.project.Project;
14-
import com.intellij.openapi.roots.ModuleRootManager;
156
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
16-
import com.intellij.openapi.vfs.LocalFileSystem;
17-
import com.intellij.openapi.vfs.VirtualFile;
18-
import com.intellij.openapi.vfs.VirtualFileManager;
19-
import com.intellij.psi.*;
20-
import com.intellij.psi.search.FilenameIndex;
21-
import com.intellij.psi.search.GlobalSearchScope;
7+
import com.intellij.psi.PsiPackage;
228
import com.intellij.ui.JBColor;
23-
import org.apache.http.client.utils.URIBuilder;
24-
import org.apache.maven.model.Dependency;
25-
import org.apache.maven.model.Model;
26-
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
27-
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
28-
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
9+
import com.intellij.uiDesigner.core.GridConstraints;
10+
import com.intellij.uiDesigner.core.GridLayoutManager;
11+
import com.intellij.uiDesigner.core.Spacer;
2912
import org.jetbrains.annotations.NotNull;
30-
import org.jetbrains.idea.maven.project.MavenProjectsManager;
3113

3214
import javax.swing.*;
3315
import javax.swing.event.DocumentEvent;
3416
import javax.swing.event.DocumentListener;
17+
import java.awt.*;
3518
import java.awt.event.*;
36-
import java.io.*;
37-
import java.net.MalformedURLException;
38-
import java.net.URISyntaxException;
3919
import java.net.URL;
40-
import java.net.URLConnection;
41-
import java.util.ArrayList;
42-
import java.util.List;
43-
import java.util.Objects;
4420

4521
public class AddRef extends JDialog {
4622
private JPanel contentPane;
@@ -54,16 +30,7 @@ public class AddRef extends JDialog {
5430
private Module module;
5531

5632
private String errorMessage;
57-
private PsiPackage selectedPackage;
5833
private String selectedDirectory;
59-
private boolean packageIsDirectory = false;
60-
61-
private static final String dependencyGroupId = "net.servicestack";
62-
private static final String dependencyPackageId = "android";
63-
private static final String dependencyVersion = "1.0.10";
64-
private static final String clientPackageId = "client";
65-
66-
public IPomFileHelper pomFileHelper;
6734

6835
public AddRef(@NotNull Module module) {
6936
this.module = module;
@@ -206,7 +173,6 @@ public void actionPerformed(ActionEvent e) {
206173
}
207174

208175
public void setSelectedPackage(@NotNull PsiPackage selectedPackage) {
209-
this.selectedPackage = selectedPackage;
210176
setPackageBrowseText(selectedPackage.getQualifiedName());
211177
}
212178

@@ -245,7 +211,7 @@ private void setPackageBrowseText(String packageName) {
245211
}
246212

247213
private ImageIcon createImageIcon(String path, String description) {
248-
java.net.URL imgURL = getClass().getResource(path);
214+
URL imgURL = getClass().getResource(path);
249215
if (imgURL != null) {
250216
return new ImageIcon(imgURL, description);
251217
} else {
@@ -255,203 +221,21 @@ private ImageIcon createImageIcon(String path, String description) {
255221
}
256222

257223
private void onOK() {
258-
String url;
259-
List<String> javaCodeLines = new ArrayList<>();
260-
try {
261-
URIBuilder urlBuilder = createUrl(addressUrlTextField.getText());
262-
urlBuilder.addParameter("Package", packageBrowse.getText());
263-
String name = getDtpNameWithoutExtension().replaceAll("\\.", "_");
264-
urlBuilder.addParameter("GlobalNamespace", name);
265-
url = urlBuilder.build().toString();
266-
267-
URL serviceUrl = new URL(url);
268-
URLConnection javaResponseConnection = serviceUrl.openConnection();
269-
BufferedReader javaResponseReader = new BufferedReader(
270-
new InputStreamReader(
271-
javaResponseConnection.getInputStream()));
272-
String metadataInputLine;
273-
274-
while ((metadataInputLine = javaResponseReader.readLine()) != null)
275-
javaCodeLines.add(metadataInputLine);
276-
277-
javaResponseReader.close();
278-
279-
if(!javaCodeLines.get(0).startsWith("/* Options:")) {
280-
//Invalid endpoint
281-
errorMessage = "The address url is not a valid ServiceStack endpoint.";
282-
return;
283-
}
284-
285-
} catch (URISyntaxException | MalformedURLException e) {
286-
e.printStackTrace();
287-
errorMessage = e.getClass().getName() + " - Invalid ServiceStack endpoint provided - " + addressUrlTextField.getText();
288-
return;
289-
} catch (IOException e) {
290-
e.printStackTrace();
291-
errorMessage = e.getClass().getName() + " - Failed to read response - " + addressUrlTextField.getText();
292-
return;
293-
}
294-
295-
296-
GradleBuildFileHelper gradleBuildFileHelper = new GradleBuildFileHelper(this.module);
297-
boolean showDto;
298-
final MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(module.getProject());
299-
300-
boolean isMavenModule = mavenProjectsManager != null && mavenProjectsManager.isMavenizedModule(module);
301-
if(isMavenModule) {
302-
showDto = tryAddMavenDependency();
224+
StringBuilder errorMessage = new StringBuilder();
225+
AddServiceStackRefHandler.handleOk(
226+
addressUrlTextField.getText(),
227+
packageBrowse.getText(),
228+
nameTextField.getText(),
229+
selectedDirectory,
230+
module,
231+
errorMessage);
232+
233+
if (errorMessage.toString().length() > 0) {
234+
errorTextPane.setText(errorMessage.toString());
235+
errorTextPane.setVisible(true);
303236
} else {
304-
//Gradle
305-
showDto = addGradleDependencyIfRequired(gradleBuildFileHelper);
237+
dispose();
306238
}
307-
308-
String dtoPath;
309-
try {
310-
dtoPath = getDtoPath();
311-
} catch (Exception e) {
312-
return;
313-
}
314-
315-
if (!writeDtoFile(javaCodeLines, dtoPath)) {
316-
return;
317-
}
318-
refreshFile(dtoPath, showDto);
319-
VirtualFileManager.getInstance().syncRefresh();
320-
dispose();
321-
}
322-
323-
private boolean tryAddMavenDependency() {
324-
boolean showDto;
325-
String message = "Unable to locate module pom.xml file. Can't add required dependency '" +
326-
dependencyGroupId + ":" + clientPackageId + ":" + dependencyVersion +
327-
"'.";
328-
Notification notification = new Notification(
329-
"ServiceStackIDEA",
330-
"Warning Add ServiceStack Reference",
331-
message,
332-
NotificationType.WARNING);
333-
try {
334-
PsiFile[] pomLibFiles = FilenameIndex.getFilesByName(module.getProject(), "pom.xml", GlobalSearchScope.allScope(module.getProject()));
335-
String pomFilePath = null;
336-
for(PsiFile psiPom : pomLibFiles) {
337-
if(Objects.equals(psiPom.getParent().getVirtualFile().getPath(), module.getModuleFile().getParent().getPath())) {
338-
pomFilePath = psiPom.getVirtualFile().getPath();
339-
}
340-
}
341-
if(pomFilePath == null) {
342-
Notifications.Bus.notify(notification);
343-
return false;
344-
}
345-
File pomLibFile = new File(pomFilePath);
346-
showDto = pomFileHelper.addMavenDependencyIfRequired(pomLibFile, dependencyGroupId, clientPackageId, dependencyVersion);
347-
} catch(Exception e) {
348-
showDto = false;
349-
Notifications.Bus.notify(notification);
350-
}
351-
return showDto;
352-
}
353-
354-
private boolean addGradleDependencyIfRequired(GradleBuildFileHelper gradleBuildFileHelper) {
355-
boolean result = true;
356-
if(gradleBuildFileHelper.addDependency(dependencyGroupId, dependencyPackageId, dependencyVersion)) {
357-
result = false;
358-
refreshBuildFile();
359-
}
360-
return result;
361-
}
362-
363-
private boolean writeDtoFile(List<String> javaCode, String path) {
364-
BufferedWriter writer = null;
365-
boolean result = true;
366-
try {
367-
writer = new BufferedWriter(new OutputStreamWriter(
368-
new FileOutputStream(path), "utf-8"));
369-
for (String item : javaCode) {
370-
writer.write(item);
371-
writer.newLine();
372-
}
373-
} catch (IOException ex) {
374-
result = false;
375-
errorMessage = "Error writing DTOs to file - " + ex.getMessage();
376-
} finally {
377-
try {
378-
assert writer != null;
379-
writer.close();
380-
} catch (Exception ignored) {
381-
}
382-
}
383-
384-
return result;
385-
}
386-
387-
private String getDtoPath() throws FileNotFoundException {
388-
VirtualFile moduleFile = module.getModuleFile();
389-
if(moduleFile == null) {
390-
throw new FileNotFoundException("Module file not found. Unable to add DTO to project.");
391-
}
392-
String fullDtoPath;
393-
394-
PsiPackage mainPackage = JavaPsiFacade.getInstance(module.getProject()).findPackage(packageBrowse.getText());
395-
if(mainPackage != null && mainPackage.isValid() && mainPackage.getDirectories().length > 0) {
396-
File foo = new File(selectedDirectory);
397-
VirtualFile selectedFolder = LocalFileSystem.getInstance().findFileByIoFile(foo);
398-
if(selectedFolder == null) {
399-
errorMessage = "Unable to determine path for DTO file.";
400-
throw new FileNotFoundException();
401-
}
402-
PsiDirectory rootPackageDir = PsiManager.getInstance(module.getProject()).findDirectory(selectedFolder);
403-
if(rootPackageDir == null) {
404-
errorMessage = "Unable to determine path for DTO file.";
405-
throw new FileNotFoundException();
406-
}
407-
fullDtoPath = rootPackageDir.getVirtualFile().getPath() + "/" + getDtoFileName();
408-
} else {
409-
String moduleSourcePath;
410-
if(moduleFile.getParent() == null) {
411-
moduleSourcePath = moduleFile.getPath() + "/main/java";
412-
} else {
413-
moduleSourcePath = moduleFile.getParent().getPath() + "/src/main/java";
414-
}
415-
fullDtoPath = moduleSourcePath + "/" + getDtoFileName();
416-
}
417-
return fullDtoPath;
418-
}
419-
420-
private void refreshBuildFile() {
421-
VirtualFileManager.getInstance().syncRefresh();
422-
if(module.getModuleFile() == null) { return; }
423-
424-
VirtualFile fileByUrl = VirtualFileManager.getInstance().findFileByUrl(module.getModuleFile().getParent().getUrl() + "/build.gradle");
425-
426-
if(fileByUrl == null) { return; }
427-
428-
FileEditorManager.getInstance(module.getProject()).openFile(fileByUrl, false);
429-
Editor currentEditor = FileEditorManager.getInstance(module.getProject()).getSelectedTextEditor();
430-
if(currentEditor == null) { return; }
431-
Document document = currentEditor.getDocument();
432-
433-
FileDocumentManager.getInstance().reloadFromDisk(document);
434-
VirtualFileManager.getInstance().syncRefresh();
435-
}
436-
437-
private void refreshFile(String filePath, boolean openFile) {
438-
VirtualFileManager.getInstance().syncRefresh();
439-
File file = new File(filePath);
440-
VirtualFile fileByUrl = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
441-
442-
if (fileByUrl == null) {
443-
return;
444-
}
445-
446-
FileEditorManager.getInstance(module.getProject()).openFile(fileByUrl, false);
447-
Editor currentEditor = FileEditorManager.getInstance(module.getProject()).getSelectedTextEditor();
448-
if(currentEditor == null) { return; }
449-
Document document = currentEditor.getDocument();
450-
451-
if (!openFile) FileEditorManager.getInstance(module.getProject()).closeFile(fileByUrl);
452-
453-
FileDocumentManager.getInstance().reloadFromDisk(document);
454-
VirtualFileManager.getInstance().syncRefresh();
455239
}
456240

457241
private class BrowsePackageListener implements ActionListener {
@@ -473,60 +257,11 @@ public void actionPerformed(ActionEvent e) {
473257
if (dialog.getExitCode() == PackageChooserDialog.CANCEL_EXIT_CODE) {
474258
return;
475259
}
476-
selectedPackage = dialog.getSelectedPackage();
477260
_textField.setText(dialog.getSelectedPackage().getQualifiedName());
478261
}
479262
}
480263

481-
private URIBuilder createUrl(String text) throws MalformedURLException, URISyntaxException {
482-
String serverUrl = text.endsWith("/") ? text : (text + "/");
483-
serverUrl = (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) ? serverUrl : ("http://" + serverUrl);
484-
URL url = new URL(serverUrl);
485-
String path = url.getPath().contains("?") ? url.getPath().split("\\?", 2)[0] : url.getPath();
486-
if (!path.endsWith("types/java/")) {
487-
serverUrl += "types/java/";
488-
}
489-
URIBuilder builder;
490-
491-
try {
492-
builder = new URIBuilder(serverUrl);
493-
} catch (URISyntaxException e) {
494-
e.printStackTrace();
495-
throw e;
496-
}
497-
498-
499-
return builder;
500-
}
501-
502-
private String getDtoFileName() {
503-
String name = nameTextField.getText();
504-
int p = name.lastIndexOf(".");
505-
String e = name.substring(p + 1);
506-
if (p == -1 || !Objects.equals(e, "java")) {
507-
/* file has no extension */
508-
return name + ".java";
509-
} else {
510-
/* file has extension e */
511-
return name;
512-
}
513-
}
514-
515-
private String getDtpNameWithoutExtension() {
516-
String name = nameTextField.getText();
517-
int p = name.lastIndexOf(".");
518-
String e = name.substring(p + 1);
519-
if (p == -1 || !Objects.equals(e, "java")) {
520-
/* file has no extension */
521-
return name;
522-
} else {
523-
/* file has extension e */
524-
return name.substring(0, p);
525-
}
526-
}
527-
528264
private void onCancel() {
529-
// add your code here if necessary
530265
dispose();
531266
}
532267
}

0 commit comments

Comments
 (0)