Skip to content

Commit

Permalink
Introduce scalastyle, use it to clean up core
Browse files Browse the repository at this point in the history
  • Loading branch information
rossabaker committed Aug 3, 2016
1 parent fa05f71 commit 162962f
Show file tree
Hide file tree
Showing 93 changed files with 483 additions and 304 deletions.
Expand Up @@ -140,7 +140,7 @@ private final class Http1Connection(val requestKey: RequestKey,
val next: Task[StringWriter] =
if (!flushPrelude) Task.now(rr)
else Task.async[StringWriter] { cb =>
val bb = ByteBuffer.wrap(rr.result().getBytes(StandardCharsets.ISO_8859_1))
val bb = ByteBuffer.wrap(rr.result.getBytes(StandardCharsets.ISO_8859_1))
channelWrite(bb).onComplete {
case Success(_) => cb(\/-(new StringWriter))
case Failure(EOF) => stageState.get match {
Expand Down
4 changes: 2 additions & 2 deletions blaze-core/src/main/scala/org/http4s/blaze/Http1Stage.scala
Expand Up @@ -88,15 +88,15 @@ trait Http1Stage { self: TailStage[ByteBuffer] =>
// add KeepAlive to Http 1.0 responses if the header isn't already present
rr << (if (!closeOnFinish && minor == 0 && connectionHeader.isEmpty) "Connection: keep-alive\r\n\r\n" else "\r\n")

val b = ByteBuffer.wrap(rr.result().getBytes(StandardCharsets.ISO_8859_1))
val b = ByteBuffer.wrap(rr.result.getBytes(StandardCharsets.ISO_8859_1))
new IdentityWriter(b, h.length, this)

case _ => // No Length designated for body or Transfer-Encoding included for HTTP 1.1
if (minor == 0) { // we are replying to a HTTP 1.0 request see if the length is reasonable
if (closeOnFinish) { // HTTP 1.0 uses a static encoder
logger.trace("Using static encoder")
rr << "\r\n"
val b = ByteBuffer.wrap(rr.result().getBytes(StandardCharsets.ISO_8859_1))
val b = ByteBuffer.wrap(rr.result.getBytes(StandardCharsets.ISO_8859_1))
new IdentityWriter(b, -1, this)
}
else { // HTTP 1.0, but request was Keep-Alive.
Expand Down
Expand Up @@ -32,7 +32,7 @@ class CachingStaticWriter(writer: StringWriter, out: TailStage[ByteBuffer],

if (innerWriter == null) { // We haven't written anything yet
writer << "\r\n"
val b = ByteBuffer.wrap(writer.result().getBytes(StandardCharsets.ISO_8859_1))
val b = ByteBuffer.wrap(writer.result.getBytes(StandardCharsets.ISO_8859_1))
new InnerWriter(b).writeBodyChunk(c, flush = true)
}
else writeBodyChunk(c, flush = true) // we are already proceeding
Expand All @@ -44,7 +44,7 @@ class CachingStaticWriter(writer: StringWriter, out: TailStage[ByteBuffer],
val c = addChunk(chunk)
writer << "Content-Length: " << c.length << "\r\nConnection: keep-alive\r\n\r\n"

val b = ByteBuffer.wrap(writer.result().getBytes(StandardCharsets.ISO_8859_1))
val b = ByteBuffer.wrap(writer.result.getBytes(StandardCharsets.ISO_8859_1))

new InnerWriter(b).writeEnd(c).map(_ || _forceClose)
}
Expand All @@ -57,7 +57,7 @@ class CachingStaticWriter(writer: StringWriter, out: TailStage[ByteBuffer],
if (flush || c.length >= bufferSize) { // time to just abort and stream it
_forceClose = true
writer << "\r\n"
val b = ByteBuffer.wrap(writer.result().getBytes(StandardCharsets.ISO_8859_1))
val b = ByteBuffer.wrap(writer.result.getBytes(StandardCharsets.ISO_8859_1))
innerWriter = new InnerWriter(b)
innerWriter.writeBodyChunk(chunk, flush)
}
Expand Down
Expand Up @@ -34,7 +34,7 @@ class ChunkProcessWriter(private var headers: StringWriter,
rr << "0\r\n" // Last chunk
trailerHeaders.foreach( h => rr << h.name.toString << ": " << h << "\r\n") // trailers
rr << "\r\n" // end of chunks
ByteBuffer.wrap(rr.result().getBytes(ISO_8859_1))
ByteBuffer.wrap(rr.result.getBytes(ISO_8859_1))
}
else ChunkEndBuffer
}.runAsync {
Expand All @@ -53,12 +53,12 @@ class ChunkProcessWriter(private var headers: StringWriter,
h << s"Content-Length: ${body.remaining()}\r\n\r\n"

// Trailers are optional, so dropping because we have no body.
val hbuff = ByteBuffer.wrap(h.result().getBytes(ISO_8859_1))
val hbuff = ByteBuffer.wrap(h.result.getBytes(ISO_8859_1))
pipe.channelWrite(hbuff::body::Nil)
}
else {
h << s"Content-Length: 0\r\n\r\n"
val hbuff = ByteBuffer.wrap(h.result().getBytes(ISO_8859_1))
val hbuff = ByteBuffer.wrap(h.result.getBytes(ISO_8859_1))
pipe.channelWrite(hbuff)
}
} else {
Expand All @@ -80,7 +80,7 @@ class ChunkProcessWriter(private var headers: StringWriter,
val list = writeLength(chunk.length)::chunk.toByteBuffer::CRLF::last
if (headers != null) {
headers << "Transfer-Encoding: chunked\r\n\r\n"
val b = ByteBuffer.wrap(headers.result().getBytes(ISO_8859_1))
val b = ByteBuffer.wrap(headers.result.getBytes(ISO_8859_1))
headers = null
b::list
} else list
Expand Down
Expand Up @@ -155,7 +155,7 @@ private class Http1ServerStage(service: HttpService,
// add KeepAlive to Http 1.0 responses if the header isn't already present
rr << (if (!closeOnFinish && parser.minorVersion == 0 && respConn.isEmpty) "Connection: keep-alive\r\n\r\n" else "\r\n")

val b = ByteBuffer.wrap(rr.result().getBytes(StandardCharsets.ISO_8859_1))
val b = ByteBuffer.wrap(rr.result.getBytes(StandardCharsets.ISO_8859_1))
new BodylessWriter(b, this, closeOnFinish)(ec)
}
else getEncoder(respConn, respTransferCoding, lengthHeader, resp.trailerHeaders, rr, parser.minorVersion, closeOnFinish)
Expand Down
6 changes: 3 additions & 3 deletions core/src/main/scala/org/http4s/AttributeMap.scala
Expand Up @@ -14,7 +14,7 @@ package org.http4s
final class AttributeKey[T] private (val name: String) {
def apply(value: T): AttributeEntry[T] = AttributeEntry(this, value)

override def toString = name
override def toString: String = name
}

object AttributeKey {
Expand All @@ -26,7 +26,7 @@ object AttributeKey {
* Encourage greater consistency in internal keys by imposing a universal prefix.
*/
private[http4s] def http4s[T](name: String): AttributeKey[T] =
apply("org.http4s."+name)
apply(s"org.http4s.$name")
}

/** An immutable map where an [[AttributeKey]] for a fixed type `T` can only be associated with values of type `T`.
Expand Down Expand Up @@ -82,6 +82,6 @@ object AttributeMap
// type inference required less generality
/** A map entry where `key` is constrained to only be associated with a fixed value of type `T`. */
final case class AttributeEntry[T](key: AttributeKey[T], value: T) {
override def toString = key.name + ": " + value
override def toString: String = key.name + ": " + value
}

22 changes: 11 additions & 11 deletions core/src/main/scala/org/http4s/CacheDirective.scala
Expand Up @@ -26,7 +26,7 @@ import util.string._
sealed trait CacheDirective extends Product with Renderable {
val name = productPrefix.replace("$minus", "-").ci
def value: String = name.toString
override def toString = value
override def toString: String = value
def render(writer: Writer): writer.type = writer.append(value)
}

Expand All @@ -36,21 +36,21 @@ sealed trait CacheDirective extends Product with Renderable {
*/
object CacheDirective {
final case class `max-age`(deltaSeconds: Duration) extends CacheDirective {
override def value = name + "=" + deltaSeconds.toSeconds
override def value: String = name + "=" + deltaSeconds.toSeconds
}

final case class `max-stale`(deltaSeconds: Option[Duration] = None) extends CacheDirective {
override def value = name + deltaSeconds.fold("")("=" + _.toSeconds)
override def value: String = name + deltaSeconds.fold("")("=" + _.toSeconds)
}

final case class `min-fresh`(deltaSeconds: Duration) extends CacheDirective {
override def value = name + "=" + deltaSeconds.toSeconds
override def value: String = name + "=" + deltaSeconds.toSeconds
}

case object `must-revalidate` extends CacheDirective

final case class `no-cache`(fieldNames: Seq[CaseInsensitiveString] = Seq.empty) extends CacheDirective {
override def value = name + (if (fieldNames.isEmpty) "" else fieldNames.mkString("=\"", ",", "\""))
override def value: String = name + (if (fieldNames.isEmpty) "" else fieldNames.mkString("=\"", ",", "\""))
}

case object `no-store` extends CacheDirective
Expand All @@ -60,23 +60,23 @@ object CacheDirective {
case object `only-if-cached` extends CacheDirective

final case class `private`(fieldNames: Seq[CaseInsensitiveString] = Nil) extends CacheDirective {
override def value = name + (if (fieldNames.isEmpty) "" else fieldNames.mkString("=\"", ",", "\""))
override def value: String = name + (if (fieldNames.isEmpty) "" else fieldNames.mkString("=\"", ",", "\""))
}

case object `proxy-revalidate` extends CacheDirective

case object public extends CacheDirective

final case class `s-maxage`(deltaSeconds: Duration) extends CacheDirective {
override def value = name + "=" + deltaSeconds.toSeconds
override def value: String = name + "=" + deltaSeconds.toSeconds
}

final case class `stale-if-error`(deltaSeconds: Duration) extends CacheDirective {
override def value = name + "=" + deltaSeconds.toSeconds
override def value: String = name + "=" + deltaSeconds.toSeconds
}

final case class `stale-while-revalidate`(deltaSeconds: Duration) extends CacheDirective {
override def value = name + "=" + deltaSeconds.toSeconds
override def value: String = name + "=" + deltaSeconds.toSeconds
}

def apply(name: CaseInsensitiveString, argument: Option[String] = None): CacheDirective =
Expand All @@ -90,6 +90,6 @@ object CacheDirective {
private final case class CustomCacheDirective(override val name: CaseInsensitiveString, argument: Option[String] = None)
extends CacheDirective
{
override def value = name + argument.fold("")("=\"" + _ + '"')
override def value: String = name + argument.fold("")("=\"" + _ + '"')
}
}
}
4 changes: 2 additions & 2 deletions core/src/main/scala/org/http4s/Challenge.scala
Expand Up @@ -38,5 +38,5 @@ final case class Challenge(scheme: String,
b.append(',').append(k).append("=\"").append(v).append('"')
}

override def toString = value
}
override def toString: String = value
}
4 changes: 2 additions & 2 deletions core/src/main/scala/org/http4s/ContentCoding.scala
Expand Up @@ -23,8 +23,8 @@ import string._

final case class ContentCoding (coding: CaseInsensitiveString, qValue: QValue = QValue.One) extends HasQValue with Renderable {
def withQValue(q: QValue): ContentCoding = copy(coding, q)
def satisfies(encoding: ContentCoding) = encoding.satisfiedBy(this)
def satisfiedBy(encoding: ContentCoding) = {
def satisfies(encoding: ContentCoding): Boolean = encoding.satisfiedBy(this)
def satisfiedBy(encoding: ContentCoding): Boolean = {
(this.coding.toString == "*" || this.coding == encoding.coding) &&
qValue.isAcceptable && encoding.qValue.isAcceptable
}
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/scala/org/http4s/Cookie.scala
Expand Up @@ -25,7 +25,7 @@ import org.http4s.util.{Renderable, Writer}
import java.time.Instant

object RequestCookieJar {
def empty = new RequestCookieJar(Nil)
def empty: RequestCookieJar = new RequestCookieJar(Nil)

def apply(cookies: Cookie*): RequestCookieJar = (newBuilder ++= cookies).result()
/** The default builder for RequestCookieJar objects.
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/scala/org/http4s/Credentials.scala
Expand Up @@ -56,7 +56,7 @@ object BasicCredentials {
final case class OAuth2BearerToken(token: String) extends Credentials {
val authScheme = AuthScheme.Bearer

override def value = renderString
override def value: String = renderString

override def render(writer: Writer): writer.type = writer.append("Bearer ").append(token)
}
Expand Down
29 changes: 17 additions & 12 deletions core/src/main/scala/org/http4s/EntityDecoder.scala
Expand Up @@ -86,13 +86,16 @@ object EntityDecoder extends EntityDecoderInstances {
def decodeBy[T](r1: MediaRange, rs: MediaRange*)(f: Message => DecodeResult[T]): EntityDecoder[T] = new EntityDecoder[T] {
override def decode(msg: Message, strict: Boolean): DecodeResult[T] = {
try {
if (strict) msg.headers.get(`Content-Type`) match {
case Some(c) if matchesMediaType(c.mediaType) => f(msg)
case Some(c) => DecodeResult.failure(MediaTypeMismatch(c.mediaType, consumes))
case None if matchesMediaType(UndefinedMediaType) => f(msg)
case None => DecodeResult.failure(MediaTypeMissing(consumes))
if (strict) {
msg.headers.get(`Content-Type`) match {
case Some(c) if matchesMediaType(c.mediaType) => f(msg)
case Some(c) => DecodeResult.failure(MediaTypeMismatch(c.mediaType, consumes))
case None if matchesMediaType(UndefinedMediaType) => f(msg)
case None => DecodeResult.failure(MediaTypeMissing(consumes))
}
} else {
f(msg)
}
else f(msg)
}
catch {
case NonFatal(e) => DecodeResult.failure(MalformedMessageBodyFailure("Error decoding body", Some(e)))
Expand All @@ -106,16 +109,18 @@ object EntityDecoder extends EntityDecoderInstances {
override def decode(msg: Message, strict: Boolean): DecodeResult[T] = {
msg.headers.get(`Content-Type`) match {
case Some(contentType) =>
if (a.matchesMediaType(contentType.mediaType)) a.decode(msg, strict)
else b.decode(msg, strict).leftMap{
if (a.matchesMediaType(contentType.mediaType)) {
a.decode(msg, strict)
} else b.decode(msg, strict).leftMap{
case MediaTypeMismatch(actual, expected) =>
MediaTypeMismatch(actual, expected ++ a.consumes)
case other => other
}

case None =>
if (a.matchesMediaType(UndefinedMediaType)) a.decode(msg, strict)
else b.decode(msg, strict).leftMap{
if (a.matchesMediaType(UndefinedMediaType)) {
a.decode(msg, strict)
} else b.decode(msg, strict).leftMap{
case MediaTypeMissing(expected) =>
MediaTypeMissing(expected ++ a.consumes)
case other => other
Expand All @@ -142,7 +147,7 @@ trait EntityDecoderInstances {
/////////////////// Instances //////////////////////////////////////////////

/** Provides a mechanism to fail decoding */
def error[T](t: Throwable) = new EntityDecoder[T] {
def error[T](t: Throwable): EntityDecoder[T] = new EntityDecoder[T] {
override def decode(msg: Message, strict: Boolean): DecodeResult[T] = {
DecodeResult(msg.body.kill.run.flatMap(_ => Task.fail(t)))
}
Expand Down Expand Up @@ -171,6 +176,6 @@ trait EntityDecoderInstances {
DecodeResult.success(msg.body.to(p).run).map(_ => file)
}

implicit def multipart: EntityDecoder[Multipart] =
implicit def multipart: EntityDecoder[Multipart] =
MultipartDecoder.decoder
}
14 changes: 9 additions & 5 deletions core/src/main/scala/org/http4s/EntityEncoder.scala
Expand Up @@ -130,6 +130,8 @@ trait EntityEncoderInstances0 {
}

trait EntityEncoderInstances extends EntityEncoderInstances0 {
private val DefaultChunkSize = 4096

implicit def stringEncoder(implicit charset: Charset = DefaultCharset): EntityEncoder[String] = {
val hdr = `Content-Type`(MediaType.`text/plain`).withCharset(charset)
simple(hdr)(s => ByteVector.view(s.getBytes(charset.nioCharset)))
Expand Down Expand Up @@ -178,19 +180,21 @@ trait EntityEncoderInstances extends EntityEncoderInstances0 {
src => Task.delay(src.close())) { src =>
Task.now { buf: Array[Char] => Task.delay {
val m = src.read(buf)
if (m == buf.length) buf
else if (m == -1) throw Terminated(End)
else buf.slice(0, m)
m match {
case l if l == buf.length => buf
case -1 => throw Terminated(End)
case _ => buf.slice(0, m)
}
}}
}
val chunkR = unsafeChunkR.map(f => (n: Int) => {
val buf = new Array[Char](n)
f(buf)
})
Process.constant(4096).toSource.through(chunkR)
Process.constant(DefaultChunkSize).toSource.through(chunkR)
}

def chunkedEncoder[A](f: A => Channel[Task, Int, ByteVector], chunkSize: Int = 4096): EntityEncoder[A] =
def chunkedEncoder[A](f: A => Channel[Task, Int, ByteVector], chunkSize: Int = DefaultChunkSize): EntityEncoder[A] =
sourceEncoder[ByteVector].contramap { a => Process.constant(chunkSize).toSource.through(f(a)) }

implicit val multipartEncoder: EntityEncoder[Multipart] =
Expand Down
6 changes: 3 additions & 3 deletions core/src/main/scala/org/http4s/Header.scala
Expand Up @@ -40,14 +40,14 @@ sealed trait Header extends Renderable with Product {

def value: String = {
val w = new StringWriter
renderValue(w).result()
renderValue(w).result
}

def is(key: HeaderKey): Boolean = key.matchHeader(this).isDefined

def isNot(key: HeaderKey): Boolean = !is(key)

override def toString = name + ": " + value
override def toString: String = name + ": " + value

def toRaw: Raw = Raw(name, value)

Expand Down Expand Up @@ -89,7 +89,7 @@ object Header {
/** A Header that is already parsed from its String representation. */
trait Parsed extends Header {
def key: HeaderKey
def name = key.name
def name: CaseInsensitiveString = key.name
def parsed: this.type = this
}

Expand Down

0 comments on commit 162962f

Please sign in to comment.