summaryrefslogtreecommitdiff
path: root/src/main/scala/org/xapek/influxdb/influxdb.scala
blob: 0aeb856fecf2fcfccbcb02285d20432208f5e249 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package org.xapek.influxdb

import java.util.Date
import java.net.URI
import scala.collection.JavaConversions._
import shapeless.Sized
import org.apache.http.client.utils.URLEncodedUtils
import org.apache.http.NameValuePair

import org.xapek.influxdb.types.{InfluxIdentifier, InfluxString, InfluxNumber, InfluxDate}


class InfluxdbError(val serverMessage: String)
  extends Exception(s"Server responded: $serverMessage")

case class InfluxDB(val host: String, val port: Int = 8086,
                    val db: String = "data", val path: String = "query",
                    val username: String = "", val password: String = "")

private case class UriNameValue(val name: String, val value: String) {
  def this(nvp: NameValuePair) = this(nvp.getName, nvp.getValue)
}

object InfluxDB {
  def SELECT(column: String) = {
    new QueryBuilderSelect(Sized[List](influxIdentifier(column)))
  }

  implicit def influxIdentifier(s: String): InfluxIdentifier = new InfluxIdentifier(s)

  implicit def influxString(s: String) = new InfluxString(s)

  implicit def influxNumber(n: Int) = new InfluxNumber(n)

  implicit def influxNumber(n: Double) = new InfluxNumber(n)

  implicit def influxDate(n: Date): InfluxDate = new InfluxDate(n)

  def fromUrl(url: String): InfluxDB = {
    val uri = new URI(url)
    var influxdb = new InfluxDB(uri.getHost)
    URLEncodedUtils.parse(uri, "UTF-8").toList
      .map(new UriNameValue(_)).foreach { x =>
        x match {
          case UriNameValue("db", db)             => influxdb = influxdb.copy(db = db)
          case UriNameValue("username", username) => influxdb = influxdb.copy(username = username)
          case UriNameValue("password", password) => influxdb = influxdb.copy(password = password)
          case _                                  =>
        }
      }
    if (uri.getPort != -1)
      influxdb = influxdb.copy(port = uri.getPort)

    if (uri.getPath.length() > 1)
      influxdb = influxdb.copy(path = uri.getPath)
    influxdb
  }

  def col(col: String) = new InfluxIdentifier(col)

  def time = new InfluxIdentifier("time")
}