Skip to content

Commit

Permalink
feat: Replace gson and jsoup with IntelliJ code style for JSON/XML/HT…
Browse files Browse the repository at this point in the history
…ML formatting (#1119)
  • Loading branch information
tangcent committed Apr 3, 2024
1 parent e83c940 commit 6e89e5b
Show file tree
Hide file tree
Showing 16 changed files with 276 additions and 100 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ package com.itangcent.http
import com.itangcent.annotation.script.ScriptIgnore
import com.itangcent.annotation.script.ScriptTypeName
import com.itangcent.common.kit.toJson
import com.itangcent.common.logger.ILogger
import com.itangcent.common.spi.SpiUtils
import com.itangcent.common.logger.Log
import com.itangcent.common.utils.notNullOrEmpty
import org.apache.http.HttpEntity
import org.apache.http.NameValuePair
Expand Down Expand Up @@ -36,7 +35,7 @@ import javax.net.ssl.SSLContext

@ScriptTypeName("httpClient")
open class ApacheHttpClient : HttpClient {
companion object {
companion object : Log() {
private fun String.createContentType(charset: String = "UTF-8"): ContentType {
val contentType = ContentType.parse(this)
return if (contentType.charset == null) {
Expand Down Expand Up @@ -155,8 +154,7 @@ open class ApacheHttpClient : HttpClient {
val body = request.body()
if (body != null) {
if (requestEntity != null) {
SpiUtils.loadService(ILogger::class)
?.warn("The request with a body should not set content-type:${request.contentType()}")
LOG.warn("The request with a body should not set content-type:${request.contentType()}")
}
requestEntity = when (body) {
is HttpEntity -> {
Expand Down
3 changes: 0 additions & 3 deletions idea-plugin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,6 @@ dependencies {

implementation("org.jetbrains.kotlin:kotlin-reflect:1.8.0")

// https://mvnrepository.com/artifact/org.jsoup/jsoup
implementation("org.jsoup:jsoup:1.12.1")

// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
implementation("com.fasterxml.jackson.core:jackson-databind:2.12.2")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import com.itangcent.http.HttpRequest
import com.itangcent.http.HttpResponse
import com.itangcent.http.contentType
import com.itangcent.idea.plugin.settings.helper.PostmanSettingsHelper
import com.itangcent.idea.utils.resolveGsonLazily
import com.itangcent.idea.utils.GsonExUtils
import com.itangcent.intellij.context.ActionContext
import com.itangcent.intellij.extend.acquireGreedy
import com.itangcent.intellij.extend.asJsonElement
Expand Down Expand Up @@ -208,7 +208,7 @@ open class DefaultPostmanApiHelper : PostmanApiHelper {
val request = getHttpClient().put("$COLLECTION/$collectionId")
.contentType(ContentType.APPLICATION_JSON)
.header("x-api-key", postmanSettingsHelper.getPrivateToken())
.body(GsonUtils.toJson(linkedMapOf("collection" to apiInfo)).resolveGsonLazily())
.body(GsonUtils.toJson(linkedMapOf("collection" to apiInfo)).apply { GsonExUtils.resolveGsonLazily(this) })

try {
beforeRequest(request)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ import com.itangcent.common.utils.*
import com.itangcent.idea.plugin.api.export.*
import com.itangcent.idea.plugin.api.export.core.*
import com.itangcent.idea.psi.resource
import com.itangcent.utils.setExts
import com.itangcent.intellij.context.ActionContext
import com.itangcent.intellij.extend.logger
import com.itangcent.intellij.jvm.DuckTypeHelper
import com.itangcent.intellij.jvm.JsonOption
import com.itangcent.intellij.jvm.PsiClassHelper
import com.itangcent.intellij.logger.Logger
import com.itangcent.utils.setExts
import java.util.*

class RequestRuleWrap(private val methodExportContext: MethodExportContext?, private val request: Request) {
Expand Down Expand Up @@ -102,7 +102,7 @@ class RequestRuleWrap(private val methodExportContext: MethodExportContext?, pri
val context = ActionContext.getContext()!!
val resource = request.resource()
if (resource == null) {
context.instance(Logger::class).warn("no resource be related with:${request}")
context.logger().warn("no resource be related with:${request}")
return
}
val responseType = context.instance(DuckTypeHelper::class).findType(bodyClass, resource) ?: return
Expand All @@ -126,7 +126,7 @@ class RequestRuleWrap(private val methodExportContext: MethodExportContext?, pri
val context = ActionContext.getContext()!!
val resource = request.resource()
if (resource == null) {
context.instance(Logger::class).warn("no resource be related with:${request}")
context.logger().warn("no resource be related with:${request}")
return
}
val responseType = context.instance(DuckTypeHelper::class).findType(modelClass, resource)
Expand All @@ -141,7 +141,7 @@ class RequestRuleWrap(private val methodExportContext: MethodExportContext?, pri
val context = ActionContext.getContext()!!
val resource = request.resource()
if (resource == null) {
context.instance(Logger::class).warn("no resource be related with:${request}")
context.logger().warn("no resource be related with:${request}")
return
}
val responseType = context.instance(DuckTypeHelper::class).findType(modelClass, resource)
Expand All @@ -155,7 +155,7 @@ class RequestRuleWrap(private val methodExportContext: MethodExportContext?, pri
)
fun addModelClass(modelClass: String?) {
ActionContext.getContext()
?.instance(Logger::class)
?.logger()
?.warn("addModelClass is deprecated, please use addModelClassAsFormParam instead of addModelClass")
addModelClassAsFormParam(modelClass)
}
Expand Down Expand Up @@ -348,7 +348,7 @@ class RequestRuleWrap(private val methodExportContext: MethodExportContext?, pri
val context = ActionContext.getContext()!!
val resource = request.resource()
if (resource == null) {
context.instance(Logger::class).warn("no resource be related with:${request}")
context.logger().warn("no resource be related with:${request}")
return
}
val responseType = context.instance(DuckTypeHelper::class).findType(bodyClass, resource)
Expand All @@ -363,7 +363,7 @@ class RequestRuleWrap(private val methodExportContext: MethodExportContext?, pri
val context = ActionContext.getContext()!!
val resource = request.resource()
if (resource == null) {
context.instance(Logger::class).warn("no resource be related with:${request}")
context.logger().warn("no resource be related with:${request}")
return
}
val responseType = context.instance(DuckTypeHelper::class).findType(bodyClass, resource)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import com.itangcent.intellij.context.ActionContext
import com.itangcent.intellij.extend.findCurrentMethod
import com.itangcent.intellij.extend.guice.singleton
import com.itangcent.intellij.extend.guice.with
import com.itangcent.intellij.extend.logger
import com.itangcent.intellij.extend.withBoundary
import com.itangcent.intellij.file.DefaultLocalFileRepository
import com.itangcent.intellij.file.LocalFileRepository
Expand Down Expand Up @@ -171,7 +172,7 @@ open class SuvApiExporter {

fun exportApisFromMethod(actionContext: ActionContext, requests: List<DocWrapper>) {

this.logger = actionContext.instance(Logger::class)
this.logger = actionContext.logger()

val actionContextBuilder = ActionContext.builder()
actionContextBuilder.setParentContext(actionContext)
Expand Down Expand Up @@ -240,7 +241,7 @@ open class SuvApiExporter {

builder.inheritFrom(actionContext, TipsHelper::class)

// builder.bindInstance(Logger::class, BeanWrapperProxies.wrap(Logger::class, actionContext.instance(Logger::class)))
// builder.bindInstance(Logger::class, BeanWrapperProxies.wrap(Logger::class, actionContext.logger()))

// builder.bind(Logger::class) { it.with(ConfigurableLogger::class).singleton() }
// builder.bind(Logger::class, "delegate.logger") { it.with(ConsoleRunnerLogger::class).singleton() }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import com.google.inject.ImplementedBy
import com.itangcent.common.logger.traceError
import com.itangcent.idea.plugin.api.export.core.Folder
import com.itangcent.intellij.context.ActionContext
import com.itangcent.intellij.extend.logger
import com.itangcent.intellij.extend.sub
import com.itangcent.intellij.logger.Logger


@ImplementedBy(DefaultYapiApiHelper::class)
Expand Down Expand Up @@ -84,7 +84,7 @@ fun YapiApiHelper.getCartForFolder(folder: Folder, privateToken: String): CartIn
try {
cartId = findCart(privateToken, name)
} catch (e: Exception) {
ActionContext.getContext()?.instance(Logger::class)
ActionContext.getContext()?.logger()
?.traceError("error to find cart [$name]", e)
return null
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ import com.itangcent.common.logger.traceError
import com.itangcent.common.model.FormParam
import com.itangcent.common.model.Request
import com.itangcent.common.model.hasBodyOrForm
import com.itangcent.common.utils.*
import com.itangcent.common.utils.appendlnIfNotEmpty
import com.itangcent.common.utils.notNullOrBlank
import com.itangcent.common.utils.notNullOrEmpty
import com.itangcent.common.utils.safe
import com.itangcent.http.*
import com.itangcent.idea.binder.DbBeanBinderFactory
import com.itangcent.idea.icons.EasyIcons
Expand All @@ -32,6 +35,7 @@ import com.itangcent.idea.psi.resourceMethod
import com.itangcent.idea.swing.onSelect
import com.itangcent.idea.swing.onTextChange
import com.itangcent.idea.utils.*
import com.itangcent.intellij.context.ActionContext
import com.itangcent.intellij.extend.rx.ThrottleHelper
import com.itangcent.intellij.extend.withBoundary
import com.itangcent.intellij.file.LocalFileRepository
Expand All @@ -40,8 +44,6 @@ import com.itangcent.suv.http.HttpClientProvider
import org.apache.commons.lang3.RandomUtils
import org.apache.commons.lang3.exception.ExceptionUtils
import org.apache.http.entity.ContentType
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.GridBagConstraints
Expand Down Expand Up @@ -1320,7 +1322,10 @@ class ApiCallDialog : ContextDialog(), ApiCallUI {
super.onDispose()
}

class ResponseStatus(var response: HttpResponse) {
class ResponseStatus(
var response: HttpResponse,
val actionContext: ActionContext = ActionContext.getContext()!!
) {

//auto format
var isFormat: Boolean = true
Expand All @@ -1344,14 +1349,17 @@ class ApiCallDialog : ContextDialog(), ApiCallUI {
return try {
val contentType = safe { response.contentType()?.let { ContentType.parse(it) } }
if (contentType != null) {
if (contentType.mimeType.startsWith("text/html") || contentType.mimeType.startsWith("text/xml")) {
val doc: Document = Jsoup.parse(getRawResult())
doc.outputSettings().prettyPrint(true)
return doc.outerHtml()
if (contentType.mimeType.startsWith("text/html")) {
return getRawResult()?.let { actionContext.instance(FormatterHelper::class).formatHtml(it) }
}
if (contentType.mimeType.startsWith("text/xml")) {
return getRawResult()?.let { actionContext.instance(FormatterHelper::class).formatXml(it) }
}
if (contentType.mimeType.startsWith("application/json")) {
return getRawResult()?.let { actionContext.instance(FormatterHelper::class).formatJson(it) }
}
}

getRawResult()?.let { GsonUtils.prettyJsonStr(it) }
getRawResult()
} catch (e: Exception) {
getRawResult()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import com.itangcent.intellij.config.rule.RuleParser
import com.itangcent.intellij.config.rule.StringRule
import com.itangcent.intellij.config.rule.parseStringRule
import com.itangcent.intellij.context.ActionContext
import com.itangcent.intellij.extend.logger
import com.itangcent.intellij.extend.rx.AutoComputer
import com.itangcent.intellij.extend.rx.mutual
import com.itangcent.intellij.jvm.DuckTypeHelper
Expand Down Expand Up @@ -618,7 +619,7 @@ class ScriptExecutorDialog : ContextDialog() {
try {
delay = task()
} catch (e: Throwable) {
actionContext.instance(Logger::class)
actionContext.logger()
.traceError("error to eval script", e)
} finally {
schedule(delay ?: 3000)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import com.itangcent.idea.plugin.settings.helper.RecommendConfigSettingsHelper
import com.itangcent.idea.swing.MessagesHelper
import com.itangcent.idea.swing.showChooseWithTipDialog
import com.itangcent.intellij.context.ActionContext
import com.itangcent.intellij.extend.logger
import com.itangcent.intellij.logger.Logger

class EnumProcessInitializer : Initializer {
Expand All @@ -34,7 +35,7 @@ class EnumProcessInitializer : Initializer {
propertiesComponent.setValue(ENUM_RECOMMEND_ITEMS_CONFIRMED_KEY, true)
}
} catch (e: Exception) {
actionContext.instance(Logger::class).traceError("error in enumRecommendItemsConfirmed.", e)
actionContext.logger().traceError("error in enumRecommendItemsConfirmed.", e)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import com.google.inject.name.Named
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.util.io.FileUtil
import com.itangcent.intellij.context.ActionContext
import com.itangcent.intellij.logger.Logger
import com.itangcent.intellij.extend.logger
import com.itangcent.intellij.util.FileUtils
import com.itangcent.intellij.util.ToolUtils
import com.itangcent.utils.localPath
Expand All @@ -27,7 +27,7 @@ class DefaultFileSaveHelper : FileSaveHelper {
private val lastImportedLocation: String? = null

@Inject
private val actionContext: ActionContext? = null
private lateinit var actionContext: ActionContext

override fun saveOrCopy(
content: String?,
Expand Down Expand Up @@ -62,11 +62,13 @@ class DefaultFileSaveHelper : FileSaveHelper {
) {
if (content == null) return

IdeaFileChooserHelper.create(actionContext!!, FileChooserDescriptorFactory
.createSingleFileOrFolderDescriptor()
.withTitle("Export Location")
.withDescription("Choose directory to export api to")
.withHideIgnored(false))
IdeaFileChooserHelper.create(
actionContext, FileChooserDescriptorFactory
.createSingleFileOrFolderDescriptor()
.withTitle("Export Location")
.withDescription("Choose directory to export api to")
.withHideIgnored(false)
)
.lastSelectedLocation(getLastImportedLocation())
.selectFile({ file ->
if (file.isDirectory) {
Expand Down Expand Up @@ -107,11 +109,13 @@ class DefaultFileSaveHelper : FileSaveHelper {
onSaveFailed: (String?) -> Unit,
onSaveCancel: () -> Unit,
) {
IdeaFileChooserHelper.create(actionContext!!, FileChooserDescriptorFactory
.createSingleFileOrFolderDescriptor()
.withTitle("Select Location")
.withDescription("Choose folder/file to save")
.withHideIgnored(false))
IdeaFileChooserHelper.create(
actionContext, FileChooserDescriptorFactory
.createSingleFileOrFolderDescriptor()
.withTitle("Select Location")
.withDescription("Choose folder/file to save")
.withHideIgnored(false)
)
.lastSelectedLocation(getLastImportedLocation())
.selectFile({ file ->
if (file.isDirectory) {
Expand Down Expand Up @@ -171,16 +175,15 @@ class DefaultFileSaveHelper : FileSaveHelper {
}

private fun copyAndLog(info: String, onCopy: () -> Unit) {
val logger: Logger = ActionContext.getContext()!!.instance(Logger::class)
try {
ToolUtils.copy2Clipboard(info)
} catch (e: HeadlessException) {
} catch (_: HeadlessException) {
}
onCopy()
if (info.length > 10000) {
logger.info("Api data is too lager to show in console!")
actionContext.logger().info("Api data is too lager to show in console!")
} else {
logger.log(info)
actionContext.logger().log(info)
}
}

Expand Down

0 comments on commit 6e89e5b

Please sign in to comment.