use of io.github.kings1990.plugin.fastrequest.model.MethodType in project fast-request by dromara.
the class FastRequestToolWindow method sendRequestEvent.
public void sendRequestEvent(boolean fileMode) {
if (!sendButtonFlag) {
return;
}
sendButtonFlag = false;
try {
FastRequestConfiguration config = FastRequestComponent.getInstance().getState();
assert config != null;
NameGroup defaultNameGroup = new NameGroup(StringUtils.EMPTY, new ArrayList<>());
HostGroup defaultHostGroup = new HostGroup(StringUtils.EMPTY, StringUtils.EMPTY);
String domain = config.getDataList().stream().filter(n -> n.getName().equals(projectComboBox.getSelectedItem())).findFirst().orElse(defaultNameGroup).getHostGroup().stream().filter(h -> h.getEnv().equals(envComboBox.getSelectedItem())).findFirst().orElse(defaultHostGroup).getUrl();
String sendUrl = urlTextField.getText();
if (StringUtils.isBlank(domain) || !UrlUtil.isURL(domain + sendUrl)) {
ApplicationManager.getApplication().invokeLater(() -> {
((MyLanguageTextField) responseTextAreaPanel).setText("Correct url required");
});
tabbedPane.setSelectedIndex(4);
responseTabbedPanel.setSelectedIndex(2);
sendButtonFlag = true;
((MyLanguageTextField) prettyJsonEditorPanel).setText("");
return;
}
String methodType = (String) methodTypeComboBox.getSelectedItem();
HttpRequest request = HttpUtil.createRequest(Method.valueOf(methodType), domain + sendUrl);
request.setMaxRedirectCount(10);
headerParamsKeyValueList = headerParamsKeyValueList == null ? new ArrayList<>() : headerParamsKeyValueList;
List<DataMapping> globalHeaderList = config.getGlobalHeaderList();
globalHeaderList = globalHeaderList == null ? new ArrayList<>() : globalHeaderList;
Map<String, List<String>> globalHeaderMap = globalHeaderList.stream().filter(DataMapping::getEnabled).collect(Collectors.toMap(DataMapping::getType, p -> Lists.newArrayList(p.getValue()), (existing, replacement) -> existing));
Map<String, List<String>> headerMap = headerParamsKeyValueList.stream().filter(DataMapping::getEnabled).collect(Collectors.toMap(DataMapping::getType, p -> Lists.newArrayList(p.getValue()), (existing, replacement) -> existing));
globalHeaderMap.putAll(headerMap);
request.header(globalHeaderMap);
Map<String, Object> multipartFormParam = multipartKeyValueList.stream().filter(ParamKeyValue::getEnabled).collect(HashMap::new, (m, v) -> {
Object value = v.getValue();
String key = v.getKey();
if (TypeUtil.Type.File.name().equals(v.getType())) {
if (value != null && !StringUtils.isBlank(value.toString())) {
m.put(key, new File(value.toString()));
} else {
m.put(key, null);
}
} else {
m.put(key, value);
}
}, HashMap::putAll);
Map<String, Object> urlParam = urlParamsKeyValueList.stream().filter(ParamKeyValue::getEnabled).collect(Collectors.toMap(ParamKeyValue::getKey, ParamKeyValue::getValue, (existing, replacement) -> existing));
String jsonParam = ((LanguageTextField) jsonParamsTextArea).getText();
Map<String, Object> formMap = new HashMap<>();
urlEncodedKeyValueList.stream().filter(ParamKeyValue::getEnabled).forEach(q -> {
formMap.put(q.getKey(), q.getValue());
});
boolean formFlag = true;
// json优先
if (!formMap.isEmpty()) {
request.form(formMap);
formFlag = false;
}
if (StringUtils.isNotEmpty(jsonParam)) {
request.body(JSON.toJSONString(JSON.parse(jsonParam)));
formFlag = false;
}
if (!urlParam.isEmpty()) {
String queryParam = UrlQuery.of(urlParam).build(StandardCharsets.UTF_8);
request.setUrl(request.getUrl() + "?" + queryParam);
}
if (!multipartFormParam.isEmpty() && formFlag) {
request.form(multipartFormParam);
}
FileSaverDialog fd = null;
if (fileMode) {
fd = FileChooserFactory.getInstance().createSaveFileDialog(new FileSaverDescriptor("Save As", ""), myProject);
}
FileSaverDialog finalFd = fd;
requestProgressBar.setVisible(true);
requestProgressBar.setForeground(ColorProgressBar.GREEN);
Future<?> future = ThreadUtil.execAsync(() -> {
try {
long start = System.currentTimeMillis();
HttpResponse response = request.execute();
long end = System.currentTimeMillis();
ApplicationManager.getApplication().invokeLater(() -> {
tabbedPane.setSelectedIndex(4);
String duration = String.valueOf(end - start);
requestProgressBar.setVisible(false);
int status = response.getStatus();
// download file
if (fileMode && status >= 200 && status < 300) {
((MyLanguageTextField) prettyJsonEditorPanel).setText("");
((MyLanguageTextField) responseTextAreaPanel).setText("");
Task.Backgroundable task = new Task.Backgroundable(myProject, "Saving file...") {
@Override
public void run(@NotNull ProgressIndicator indicator) {
ApplicationManager.getApplication().invokeLater(() -> {
sendButtonFlag = false;
try {
File f = new File(myProject.getBasePath());
File finalFile = response.completeFileNameFromHeader(f);
response.writeBody(finalFile);
VirtualFileWrapper fileWrapper = finalFd.save(finalFile.getName());
if (fileWrapper != null) {
File file = fileWrapper.getFile();
FileUtil.move(finalFile, file, true);
NotificationGroupManager.getInstance().getNotificationGroup("toolWindowNotificationGroup").createNotification("Success", MessageType.INFO).addAction(new GotoFile(file)).notify(myProject);
}
finalFile.delete();
} catch (Exception ignored) {
}
sendButtonFlag = true;
});
}
};
ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, new BackgroundableProcessIndicator(task));
}
if (!fileMode) {
String body = response.body();
int bodyLength = StrUtil.byteLength(body, StandardCharsets.UTF_8);
if (bodyLength > MAX_DATA_LENGTH) {
((MyLanguageTextField) responseTextAreaPanel).setText(body);
((MyLanguageTextField) prettyJsonEditorPanel).setText(body);
refreshResponseTable("");
} else {
if (JSONUtil.isJson(body)) {
responseTabbedPanel.setSelectedIndex(1);
((MyLanguageTextField) prettyJsonEditorPanel).setText(body.isBlank() ? "" : body);
((MyLanguageTextField) responseTextAreaPanel).setText(body);
refreshResponseTable(body);
} else {
responseTabbedPanel.setSelectedIndex(2);
String subBody = body.substring(0, Math.min(body.length(), 32768));
if (body.length() > 32768) {
subBody += "\n\ntext too large only show 32768 characters\n.............";
}
String finalSubBody = subBody;
((MyLanguageTextField) prettyJsonEditorPanel).setText(finalSubBody);
((MyLanguageTextField) responseTextAreaPanel).setText(subBody);
refreshResponseTable("");
}
}
}
responseInfoParamsKeyValueList = Lists.newArrayList(new ParamKeyValue("Url", request.getUrl(), 2, TypeUtil.Type.String.name()), new ParamKeyValue("Cost", duration + " ms", 2, TypeUtil.Type.String.name()), new ParamKeyValue("Response status", status + " " + Constant.HttpStatusDesc.STATUS_MAP.get(status)), new ParamKeyValue("Date", DateUtil.formatDateTime(new Date())));
// refreshTable(responseInfoTable);
responseInfoTable.setModel(new ListTableModel<>(getColumns(Lists.newArrayList("Name", "Value")), responseInfoParamsKeyValueList));
responseInfoTable.getColumnModel().getColumn(0).setPreferredWidth(150);
responseInfoTable.getColumnModel().getColumn(0).setMaxWidth(150);
responseStatusComboBox.setSelectedItem(status);
responseStatusComboBox.setBackground((status >= 200 && status < 300) ? MyColor.green : MyColor.red);
}, ModalityState.NON_MODAL);
} catch (Exception ee) {
sendButtonFlag = true;
requestProgressBar.setVisible(false);
tabbedPane.setSelectedIndex(4);
responseTabbedPanel.setSelectedIndex(2);
responseStatusComboBox.setSelectedItem(0);
String errorMsg = ee.getMessage();
ApplicationManager.getApplication().invokeLater(() -> {
((MyLanguageTextField) responseTextAreaPanel).setText(errorMsg);
((MyLanguageTextField) prettyJsonEditorPanel).setText("");
});
responseStatusComboBox.setBackground(MyColor.red);
responseInfoParamsKeyValueList = Lists.newArrayList(new ParamKeyValue("Url", request.getUrl(), 2, TypeUtil.Type.String.name()), new ParamKeyValue("Error", errorMsg));
// refreshTable(responseInfoTable);
responseInfoTable.setModel(new ListTableModel<>(getColumns(Lists.newArrayList("Name", "Value")), responseInfoParamsKeyValueList));
responseInfoTable.getColumnModel().getColumn(0).setPreferredWidth(150);
responseInfoTable.getColumnModel().getColumn(0).setMaxWidth(150);
CustomNode root = new CustomNode("Root", "");
((DefaultTreeModel) responseTable.getTableModel()).setRoot(root);
}
sendButtonFlag = true;
});
} catch (Exception exception) {
sendButtonFlag = true;
requestProgressBar.setVisible(false);
String errorMsg = exception.getMessage();
ApplicationManager.getApplication().invokeLater(() -> {
((MyLanguageTextField) responseTextAreaPanel).setText(errorMsg);
((MyLanguageTextField) prettyJsonEditorPanel).setText("");
});
responseStatusComboBox.setSelectedItem(0);
responseStatusComboBox.setBackground(MyColor.red);
responseInfoParamsKeyValueList = Lists.newArrayList(new ParamKeyValue("Error", errorMsg));
// refreshTable(responseInfoTable);
responseInfoTable.setModel(new ListTableModel<>(getColumns(Lists.newArrayList("Name", "Value")), responseInfoParamsKeyValueList));
responseInfoTable.getColumnModel().getColumn(0).setPreferredWidth(150);
responseInfoTable.getColumnModel().getColumn(0).setMaxWidth(150);
CustomNode root = new CustomNode("Root", "");
((DefaultTreeModel) responseTable.getTableModel()).setRoot(root);
tabbedPane.setSelectedIndex(4);
responseTabbedPanel.setSelectedIndex(2);
}
}
use of io.github.kings1990.plugin.fastrequest.model.MethodType in project fast-request by dromara.
the class FastRequestCollectionToolWindow method filterNode.
private boolean filterNode(CollectionCustomNode node, String search, String rule) {
if (node.isRoot()) {
ArrayList<CollectionCustomNode> nodeList = (ArrayList<CollectionCustomNode>) IteratorUtils.toList(node.children().asIterator());
for (CollectionCustomNode n : nodeList) {
filterNode(n, search, rule);
}
} else {
if (node.getChildCount() == 0) {
boolean methodTypeSearchFlag = rule.contains(SearchTypeEnum.get.name()) || rule.contains(SearchTypeEnum.post.name()) || rule.contains(SearchTypeEnum.put.name()) || rule.contains(SearchTypeEnum.delete.name()) || rule.contains(SearchTypeEnum.patch.name());
String targetText = "";
if (rule.contains(SearchTypeEnum.name.name())) {
String name = node.getName();
targetText += name == null ? "" : name;
}
if (rule.contains(SearchTypeEnum.url.name())) {
String url = node.getUrl();
targetText += url == null ? "" : url;
}
if (methodTypeSearchFlag) {
String methodType = node.getDetail().getParamGroup().getMethodType();
if (methodType == null || !rule.contains(methodType.toLowerCase())) {
node.removeFromParent();
return true;
}
}
if (rule.isBlank() || (targetText.isBlank() && methodTypeSearchFlag)) {
targetText = node.getSearchText();
}
if (!targetText.toLowerCase().contains(search.toLowerCase())) {
node.removeFromParent();
return true;
} else {
return false;
}
} else {
ArrayList<CollectionCustomNode> nodeList = (ArrayList<CollectionCustomNode>) IteratorUtils.toList(node.children().asIterator());
boolean removeGroup = true;
for (CollectionCustomNode n : nodeList) {
removeGroup &= filterNode(n, search, rule);
}
if (removeGroup) {
node.removeFromParent();
}
}
}
return false;
}
use of io.github.kings1990.plugin.fastrequest.model.MethodType in project fast-request by dromara.
the class RequestMappingByNameContributor method mapItems.
private RequestMappingItem mapItems(PsiAnnotation psiAnnotation) {
PsiMethod method = (PsiMethod) fetchAnnotatedPsiElement(psiAnnotation);
Constant.FrameworkType frameworkType = FrPsiUtil.calcFrameworkType(method);
FastUrlGenerator generator;
if (frameworkType.equals(Constant.FrameworkType.SPRING)) {
generator = springMethodUrlGenerator;
} else {
generator = jaxRsGenerator;
}
String methodUrl = generator.getMethodRequestMappingUrl(method);
String classUrl = generator.getClassRequestMappingUrl(method);
String originUrl = classUrl + "/" + methodUrl;
originUrl = (originUrl.startsWith("/") ? "" : "/") + originUrl.replace("//", "/");
String methodType = generator.getMethodType(method);
return new RequestMappingItem(method, originUrl, methodType);
}
use of io.github.kings1990.plugin.fastrequest.model.MethodType in project fast-request by dromara.
the class JaxRsGenerator method generate.
@Override
public String generate(PsiElement psiElement) {
ParamGroup paramGroup = config.getParamGroup();
if (!(psiElement instanceof PsiMethod)) {
return StringUtils.EMPTY;
}
PsiMethod psiMethod = (PsiMethod) psiElement;
String methodUrl = getMethodRequestMappingUrl(psiMethod);
String classUrl = getClassRequestMappingUrl(psiMethod);
String originUrl = classUrl + "/" + methodUrl;
originUrl = originUrl.replace("//", "/");
paramGroup.setOriginUrl(originUrl);
List<ParamNameType> methodUrlParamList = getMethodUrlParamList(psiMethod);
List<ParamNameType> methodBodyParamList = getMethodBodyParamList(psiMethod);
// pathParam
LinkedHashMap<String, Object> pathParamMap = pathValueParamParse.parseParam(config, methodUrlParamList);
// requestParam
LinkedHashMap<String, Object> requestParamMap = requestParamParse.parseParam(config, methodUrlParamList);
// bodyParam
LinkedHashMap<String, Object> bodyParamMap = bodyParamParse.parseParam(config, methodBodyParamList);
// methodType
String methodType = getMethodType(psiMethod);
String methodDescription = getMethodDescription(psiMethod);
paramGroup.setPathParamMap(pathParamMap);
paramGroup.setRequestParamMap(requestParamMap);
paramGroup.setBodyParamMap(bodyParamMap);
paramGroup.setMethodType(methodType);
paramGroup.setMethodDescription(methodDescription);
paramGroup.setClassName(((PsiMethodImpl) psiElement).getContainingClass().getQualifiedName());
paramGroup.setMethod(psiMethod.getName());
Module moduleForFile = ModuleUtil.findModuleForPsiElement(psiElement);
if (moduleForFile != null) {
String name = moduleForFile.getName();
paramGroup.setModule(name);
}
return null;
}
use of io.github.kings1990.plugin.fastrequest.model.MethodType in project fast-request by dromara.
the class SpringMethodUrlGenerator method generate.
@Override
public String generate(PsiElement psiElement) {
ParamGroup paramGroup = config.getParamGroup();
if (!(psiElement instanceof PsiMethod)) {
return StringUtils.EMPTY;
}
PsiMethod psiMethod = (PsiMethod) psiElement;
String methodUrl = getMethodRequestMappingUrl(psiMethod);
String classUrl = getClassRequestMappingUrl(psiMethod);
String originUrl = classUrl + "/" + methodUrl;
originUrl = originUrl.replace("//", "/");
paramGroup.setOriginUrl(originUrl);
List<ParamNameType> methodUrlParamList = getMethodUrlParamList(psiMethod);
List<ParamNameType> methodBodyParamList = getMethodBodyParamList(psiMethod);
// pathParam
LinkedHashMap<String, Object> pathParamMap = pathValueParamParse.parseParam(config, methodUrlParamList);
// requestParam
LinkedHashMap<String, Object> requestParamMap = requestParamParse.parseParam(config, methodUrlParamList);
// bodyParam
LinkedHashMap<String, Object> bodyParamMap = bodyParamParse.parseParam(config, methodBodyParamList);
// methodType
String methodType = getMethodType(psiMethod);
String methodDescription = getMethodDescription(psiMethod);
paramGroup.setPathParamMap(pathParamMap);
paramGroup.setRequestParamMap(requestParamMap);
paramGroup.setBodyParamMap(bodyParamMap);
paramGroup.setMethodType(methodType);
paramGroup.setMethodDescription(methodDescription);
paramGroup.setClassName(((PsiMethodImpl) psiElement).getContainingClass().getQualifiedName());
paramGroup.setMethod(psiMethod.getName());
Module moduleForFile = ModuleUtil.findModuleForPsiElement(psiElement);
if (moduleForFile != null) {
String name = moduleForFile.getName();
paramGroup.setModule(name);
}
return null;
}
Aggregations