DavException.kt 5.52 KB
Newer Older
1
/*
Ricki Hirner's avatar
Ricki Hirner committed
2 3 4
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 6
 */

7
package at.bitfire.dav4android.exception
Ricki Hirner's avatar
Ricki Hirner committed
8

Ricki Hirner's avatar
Ricki Hirner committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
import at.bitfire.dav4android.Constants
import at.bitfire.dav4android.Property
import at.bitfire.dav4android.XmlUtils
import okhttp3.MediaType
import okhttp3.Response
import okio.Buffer
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.Serializable
import java.util.logging.Level

/**
 * Signals that an error occurred during a WebDAV-related operation.
 *
 * This could be a logical error like when a required ETag has not been
 * received, but also an explicit HTTP error.
 */
28 29
open class DavException @JvmOverloads constructor(
        message: String,
Ricki Hirner's avatar
Ricki Hirner committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
        ex: Throwable? = null,

        /**
         * An associated HTTP [Response]. Will be closed after evaluation.
         */
        httpResponse: Response? = null
): Exception(message, ex), Serializable {

    companion object {

        const val MAX_EXCERPT_SIZE = 10*1024   // don't dump more than 20 kB

        fun isPlainText(type: MediaType) =
                type.type() == "text" ||
                (type.type() == "application" && type.subtype() in arrayOf("html", "xml"))

    }

48
    var request: String? = null
Ricki Hirner's avatar
Ricki Hirner committed
49 50

    /**
51 52
     * Body excerpt of [request] (up to [MAX_EXCERPT_SIZE] characters). Only available
     * if the HTTP request body was textual content and could be read again.
Ricki Hirner's avatar
Ricki Hirner committed
53
     */
54 55 56 57
    var requestBody: String? = null
        private set

    val response: String?
Ricki Hirner's avatar
Ricki Hirner committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

    /**
     * Body excerpt of [response] (up to [MAX_EXCERPT_SIZE] characters). Only available
     * if the HTTP response body was textual content.
     */
    var responseBody: String? = null
        private set

    /**
     * Precondition/postcondition XML elements which have been found in the XML response.
     */
    var errors: Set<Property.Name> = setOf()
        private set


    init {
        if (httpResponse != null) {
75
            response = httpResponse.toString()
Ricki Hirner's avatar
Ricki Hirner committed
76 77

            try {
78
                request = httpResponse.request().toString()
Ricki Hirner's avatar
Ricki Hirner committed
79

80
                httpResponse.request().body()?.let { body ->
Ricki Hirner's avatar
Ricki Hirner committed
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
                    body.contentType()?.let {
                        if (isPlainText(it)) {
                            val buffer = Buffer()
                            body.writeTo(buffer)
                            val baos = ByteArrayOutputStream()
                            buffer.writeTo(baos)
                            requestBody = baos.toString(it.charset(Charsets.UTF_8)!!.name())
                        }
                    }
                }
            } catch (e: Exception) {
                Constants.log.log(Level.WARNING, "Couldn't read HTTP request", e)
                requestBody = "Couldn't read HTTP request: ${e.message}"
            }

            try {
                // save response body excerpt
                if (httpResponse.body()?.source() != null) {
                    // response body has a source

                    httpResponse.peekBody(MAX_EXCERPT_SIZE.toLong())?.use { body ->
                        body.contentType()?.let {
                            if (isPlainText(it))
                                responseBody = body.string()
                        }
                    }

                    httpResponse.body()?.use { body ->
                        body.contentType()?.let {
                            if (it.type() in arrayOf("application", "text") && it.subtype() == "xml") {
                                // look for precondition/postcondition XML elements
                                try {
                                    val parser = XmlUtils.newPullParser()
                                    parser.setInput(body.charStream())

                                    var eventType = parser.eventType
                                    while (eventType != XmlPullParser.END_DOCUMENT) {
                                        if (eventType == XmlPullParser.START_TAG && parser.depth == 1)
                                            if (parser.namespace == XmlUtils.NS_WEBDAV && parser.name == "error")
                                                errors = parseXmlErrors(parser)
                                        eventType = parser.next()
                                    }
                                } catch (e: XmlPullParserException) {
                                    Constants.log.log(Level.WARNING, "Couldn't parse XML response", e)
                                }
                            }
                        }
                    }
                }
            } catch (e: IOException) {
                Constants.log.log(Level.WARNING, "Couldn't read HTTP response", e)
                responseBody = "Couldn't read HTTP response: ${e.message}"
            } finally {
                httpResponse.body()?.close()
            }
        } else
            response = null
    }


    private fun parseXmlErrors(parser: XmlPullParser): Set<Property.Name> {
        val names = mutableSetOf<Property.Name>()

        val depth = parser.depth
        var eventType = parser.eventType
        while (!(eventType == XmlPullParser.END_TAG && parser.depth == depth)) {
            if (eventType == XmlPullParser.START_TAG && parser.depth == depth + 1)
                names += Property.Name(parser.namespace, parser.name)
            eventType = parser.next()
        }

        return names
    }

}