java.lang.Long Scala Examples

The following examples show how to use java.lang.Long. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: SparkSolrAccumulator.scala    From spark-solr   with Apache License 2.0 5 votes vote down vote up
package com.lucidworks.spark

import java.lang.Long

import org.apache.spark.util.AccumulatorV2

class SparkSolrAccumulator extends AccumulatorV2[java.lang.Long, java.lang.Long] {
  private var _count = 0L

  override def isZero: Boolean = _count == 0

  override def copy(): SparkSolrAccumulator = {
    val newAcc = new SparkSolrAccumulator
    newAcc._count = this._count
    newAcc
  }

  override def reset(): Unit = {
    _count = 0L
  }

  override def add(v: Long): Unit = {
    _count += v
  }

  def count: Long = _count

  override def merge(other: AccumulatorV2[Long, Long]): Unit = other match {
    case o: SparkSolrAccumulator =>
      _count += o.count
    case _ =>
      throw new UnsupportedOperationException(
        s"Cannot merge ${this.getClass.getName} with ${other.getClass.getName}")
  }

  override def value: Long = _count

  def inc(): Unit = _count += 1
} 
Example 2
Source File: VariableServiceImpl.scala    From Linkis   with Apache License 2.0 5 votes vote down vote up
package com.webank.wedatasphere.linkis.variable.service

import java.lang.Long
import java.util

import com.webank.wedatasphere.linkis.common.utils.Logging
import com.webank.wedatasphere.linkis.protocol.variable.ResponseQueryVariable
import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper
import com.webank.wedatasphere.linkis.variable.dao.VarMapper
import com.webank.wedatasphere.linkis.variable.entity.{VarKey, VarKeyUser, VarKeyValueVO}
import com.webank.wedatasphere.linkis.variable.exception.VariableException
import org.apache.commons.lang.StringUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional




  private def insertGlobalVariable(saveVariable: VarKeyValueVO, userName: String): Unit = {
    val newKey = new VarKey
    newKey.setApplicationID(-1L)
    newKey.setKey(saveVariable.getKey)
    varMapper.insertKey(newKey)
    val newValue = new VarKeyUser
    newValue.setApplicationID(-1L)
    newValue.setKeyID(newKey.getId)
    newValue.setUserName(userName)
    newValue.setValue(saveVariable.getValue)
    varMapper.insertValue(newValue)
  }

  private def updateGlobalVariable(saveVariable: VarKeyValueVO, valueID: Long): Unit = {
    varMapper.updateValue(valueID, saveVariable.getValue)
  }

  @Transactional
  override def saveGlobalVaraibles(globalVariables: util.List[_], userVariables: util.List[VarKeyValueVO], userName: String): Unit = {
    import scala.collection.JavaConversions._
    import scala.util.control.Breaks._
    val saves = globalVariables.map(f => BDPJettyServerHelper.gson.fromJson(BDPJettyServerHelper.gson.toJson(f), classOf[VarKeyValueVO]))
    saves.foreach {
      f =>
        if (StringUtils.isBlank(f.getKey) || StringUtils.isBlank(f.getValue)) throw new VariableException("key或value不能为空")
        var flag = true
        breakable {
          for (ele <- userVariables) {
            if (f.getKey.equals(ele.getKey)) {
              flag = false
              updateGlobalVariable(f, ele.getValueID)
              break()
            }
          }
        }
        if (flag) insertGlobalVariable(f, userName)
    }
    userVariables.foreach {
      f =>
        var flag = true
        breakable {
          for (ele <- saves) {
            if (ele.getKey.equals(f.getKey)) {
              flag = false
              break()
            }
          }
          if (flag) removeGlobalVariable(f.getKeyID)
        }
    }

  }
} 
Example 3
Source File: CoreSpan.scala    From money   with Apache License 2.0 5 votes vote down vote up
package com.comcast.money.core

import java.lang.Long

import com.comcast.money.api._

import scala.collection.JavaConverters._
import scala.collection.concurrent.TrieMap


case class CoreSpan(
  id: SpanId,
  name: String,
  handler: SpanHandler) extends Span {

  private var startTimeMillis: Long = 0L
  private var startTimeMicros: Long = 0L
  private var endTimeMillis: Long = 0L
  private var endTimeMicros: Long = 0L
  private var success: java.lang.Boolean = true

  // use concurrent maps
  private val timers = new TrieMap[String, Long]()
  private val noted = new TrieMap[String, Note[_]]()

  def start(): Unit = {
    startTimeMillis = System.currentTimeMillis
    startTimeMicros = System.nanoTime / 1000
  }

  def stop(): Unit = stop(true)

  def stop(result: java.lang.Boolean): Unit = {
    endTimeMillis = System.currentTimeMillis
    endTimeMicros = System.nanoTime / 1000
    this.success = result

    // process any hanging timers
    val openTimers = timers.keys
    openTimers.foreach(stopTimer)

    handler.handle(info)
  }

  def stopTimer(timerKey: String): Unit =
    timers.remove(timerKey) foreach {
      timerStartInstant =>
        record(Note.of(timerKey, System.nanoTime - timerStartInstant))
    }

  def record(note: Note[_]): Unit = noted += note.name -> note

  def startTimer(timerKey: String): Unit = timers += timerKey -> System.nanoTime

  def info(): SpanInfo =
    CoreSpanInfo(
      id,
      name,
      startTimeMillis,
      startTimeMicros,
      endTimeMillis,
      endTimeMicros,
      calculateDuration,
      success,
      noted.toMap[String, Note[_]].asJava)

  private def calculateDuration: Long =
    if (endTimeMicros <= 0L && startTimeMicros <= 0L)
      0L
    else if (endTimeMicros <= 0L)
      (System.nanoTime() / 1000) - startTimeMicros
    else
      endTimeMicros - startTimeMicros
} 
Example 4
Source File: JpaReadSideImplSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.persistence.jpa

import java.lang.Long
import java.util.concurrent.CompletionStage

import com.lightbend.lagom.internal.javadsl.persistence.jdbc.JdbcPersistentEntityRegistry
import com.lightbend.lagom.javadsl.persistence.TestEntity.Evt
import com.lightbend.lagom.javadsl.persistence._
import com.lightbend.lagom.javadsl.persistence.jpa.JpaReadSide
import com.lightbend.lagom.javadsl.persistence.jpa.TestEntityJpaReadSide
import play.api.inject.guice.GuiceInjectorBuilder

import scala.concurrent.duration._

class JpaReadSideImplSpec extends JpaPersistenceSpec with AbstractReadSideSpec {
  private lazy val injector                            = new GuiceInjectorBuilder().build()
  protected override lazy val persistentEntityRegistry = new JdbcPersistentEntityRegistry(system, injector, slick)

  private lazy val jpaReadSide: JpaReadSide = new JpaReadSideImpl(jpa, offsetStore)

  def processorFactory(): ReadSideProcessor[Evt] =
    new TestEntityJpaReadSide.TestEntityJpaReadSideProcessor(jpaReadSide)

  private lazy val readSide = new TestEntityJpaReadSide(jpa)

  def getAppendCount(id: String): CompletionStage[Long] = readSide.getAppendCount(id)

  override def afterAll(): Unit = {
    super.afterAll()
  }
} 
Example 5
Source File: JdbcReadSideSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence.jdbc

import java.lang.Long
import java.util.concurrent.CompletionStage

import com.lightbend.lagom.internal.javadsl.persistence.jdbc.JdbcPersistentEntityRegistry
import com.lightbend.lagom.internal.javadsl.persistence.jdbc.JdbcSessionImpl
import com.lightbend.lagom.javadsl.persistence.TestEntity.Evt
import com.lightbend.lagom.javadsl.persistence._
import play.api.inject.guice.GuiceInjectorBuilder

import scala.concurrent.duration._

class JdbcReadSideSpec extends JdbcPersistenceSpec with AbstractReadSideSpec {
  private lazy val injector                            = new GuiceInjectorBuilder().build()
  protected override lazy val persistentEntityRegistry = new JdbcPersistentEntityRegistry(system, injector, slick)

  override def processorFactory(): ReadSideProcessor[Evt] =
    new JdbcTestEntityReadSide.TestEntityReadSideProcessor(jdbcReadSide)

  protected lazy val session: JdbcSession = new JdbcSessionImpl(slick)
  private lazy val readSide               = new JdbcTestEntityReadSide(session)

  override def getAppendCount(id: String): CompletionStage[Long] = readSide.getAppendCount(id)

  override def afterAll(): Unit = {
    super.afterAll()
  }
} 
Example 6
Source File: CarbonInputMetrics.scala    From carbondata   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark

import java.lang.Long

import org.apache.spark.executor.InputMetrics

import org.apache.carbondata.common.logging.LogServiceFactory
import org.apache.carbondata.core.constants.CarbonCommonConstants
import org.apache.carbondata.core.util.TaskMetricsMap
import org.apache.carbondata.hadoop.CarbonMultiBlockSplit
import org.apache.carbondata.spark.InitInputMetrics



class CarbonInputMetrics extends InitInputMetrics{
  @transient val LOGGER = LogServiceFactory.getLogService(this.getClass.getName)
    var inputMetrics: InputMetrics = _
    // bytes read before compute by other map rdds in lineage
    var existingBytesRead: Long = _
    var recordCount: Long = _
    var inputMetricsInterval: Long = _
    var carbonMultiBlockSplit: CarbonMultiBlockSplit = _

  def initBytesReadCallback(context: TaskContext,
      carbonMultiBlockSplit: CarbonMultiBlockSplit, inputMetricsInterval: Long) {
    inputMetrics = context.taskMetrics().inputMetrics
    existingBytesRead = inputMetrics.bytesRead
    recordCount = 0L
    this.inputMetricsInterval = inputMetricsInterval
    this.carbonMultiBlockSplit = carbonMultiBlockSplit
  }

  def incrementRecordRead(recordRead: Long) {
    val value: scala.Long = recordRead
    recordCount = recordCount + value
    if (recordCount > inputMetricsInterval) {
      inputMetrics.synchronized {
        inputMetrics.incRecordsRead(recordCount)
        updateBytesRead()
      }
      recordCount = 0L
    }
  }

  def updateBytesRead(): Unit = {
    inputMetrics
      .setBytesRead(existingBytesRead
                    + TaskMetricsMap.getInstance().getReadBytesSum(Thread.currentThread().getId))
  }

  def updateAndClose() {
    if (recordCount > 0L) {
      inputMetrics.synchronized {
        inputMetrics.incRecordsRead(recordCount)
      }
      recordCount = 0L
    }
    // if metrics supported file system ex: hdfs
    if (!TaskMetricsMap.getInstance().isCallbackEmpty(Thread.currentThread().getId)) {
      updateBytesRead()
      // after update clear parent thread entry from map.
      TaskMetricsMap.getInstance().removeEntry(Thread.currentThread().getId)
    } else if (carbonMultiBlockSplit.isInstanceOf[CarbonMultiBlockSplit]) {
      // If we can't get the bytes read from the FS stats, fall back to the split size,
      // which may be inaccurate.
      try {
        inputMetrics.incBytesRead(carbonMultiBlockSplit.getLength)
      } catch {
        case e: java.io.IOException =>
          LOGGER.warn("Unable to get input size to set InputMetrics for task:" + e.getMessage)
      }
    }
  }

  override def updateByValue(value: Object): Unit = {

  }
} 
Example 7
Source File: package.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package passera

import scala.language.implicitConversions

package object numerics {
  implicit def toRicherInt(x: Int): RicherInt = new RicherInt(x)
  implicit def toRicherInt(x: scala.runtime.RichInt) = new YetRicherInt(x.self.asInstanceOf[Int])

  implicit def toRicherLong(x: Long): RicherLong = new RicherLong(x)
  implicit def toRicherLong(x: scala.runtime.RichLong) = new YetRicherLong(x.self.asInstanceOf[Long])

  class RicherInt(x: Int) extends Proxy {
    def self: Any = x

    import java.lang.Integer

    def bitCount = Integer.bitCount(x)
    def highestOneBit = Integer.highestOneBit(x)
    def lowestOneBit = Integer.lowestOneBit(x)
    def numberOfLeadingZeros = Integer.numberOfLeadingZeros(x)
    def numberOfTrailingZeros = Integer.numberOfTrailingZeros(x)

    def reverse = Integer.reverse(x)
    def reverseBytes = Integer.reverseBytes(x)
    def rotateLeft(dist: Int) = Integer.rotateLeft(x, dist)
    def rotateRight(dist: Int) = Integer.rotateRight(x, dist)
    def signum = Integer.signum(x)

    def <<@(dist: Int) = rotateLeft(dist)
    def >>@(dist: Int) = rotateRight(dist)
  }

  class YetRicherInt(x: Int) extends Proxy {
    def self: Any = x
    def to(y: Long, step: Long = 1L) = x.toLong to y by step
    def until(y: Long, step: Long = 1L) = x.toLong until y by step
    def max(y: Long) = x.toLong max y
    def min(y: Long) = x.toLong min y
  }

  class RicherLong(x: Long) extends Proxy {
    def self: Any = x

    import java.lang.Long

    def bitCount = Long.bitCount(x)
    def highestOneBit = Long.highestOneBit(x)
    def lowestOneBit = Long.lowestOneBit(x)
    def numberOfLeadingZeros = Long.numberOfLeadingZeros(x)
    def numberOfTrailingZeros = Long.numberOfTrailingZeros(x)

    def reverse = Long.reverse(x)
    def reverseBytes = Long.reverseBytes(x)
    def rotateLeft(dist: Int) = Long.rotateLeft(x, dist)
    def rotateRight(dist: Int) = Long.rotateRight(x, dist)
    def signum = Long.signum(x)

    def <<@(dist: Int) = rotateLeft(dist)
    def >>@(dist: Int) = rotateRight(dist)
  }

  class YetRicherLong(x: Long) extends Proxy {
    def self: Any = x
  }
} 
Example 8
Source File: SlowMonitorInterceptor.scala    From ez-framework   with Apache License 2.0 5 votes vote down vote up
package com.ecfront.ez.framework.service.gateway.interceptor

import java.lang.Long

import com.ecfront.common.AsyncResp

import scala.collection.mutable


object SlowMonitorInterceptor extends GatewayInterceptor {

  var time: Long = _
  var includes: Set[String] = _
  var excludes: Set[String] = _

  def init(_time: Long, _includes: Set[String], _excludes: Set[String]): Unit = {
    time = _time
    includes = _includes.map(_.toLowerCase())
    excludes = _excludes.map(_.toLowerCase())
  }


  override def before(obj: EZAPIContext, context: mutable.Map[String, Any], p: AsyncResp[EZAPIContext]): Unit = {
    context += "ez_start_time" -> System.currentTimeMillis()
    p.success(obj)
  }

  override def after(obj: EZAPIContext, context: mutable.Map[String, Any], p: AsyncResp[EZAPIContext]): Unit = {
    val useTime = System.currentTimeMillis() - context("ez_start_time").asInstanceOf[Long]
    if (includes.nonEmpty) {
      // 存在包含网址过滤,仅记录在此网址中请求
      if (includes.contains(obj.method + ":" + obj.templateUri)) {
        logSlow(useTime, obj)
      }
    } else if (excludes.nonEmpty) {
      // 存在不包含网址过滤,此网址中请求不记录
      if (!excludes.contains(obj.method + ":" + obj.templateUri)) {
        logSlow(useTime, obj)
      }
    } else {
      // 记录所有请求
      logSlow(useTime, obj)
    }
    p.success(obj)
  }

  private def logSlow(useTime: Long, obj: EZAPIContext): Unit = {
    if (useTime > time) {
      logger.warn(s"[RPC][SlowTime] Request [${obj.method}:${obj.realUri}] use time [$useTime] ms")
    } else {
      logger.trace(s"[RPC][Time] Request [${obj.method}:${obj.realUri}] use time [$useTime] ms")
    }
  }

} 
Example 9
Source File: AntiDDoSInterceptor.scala    From ez-framework   with Apache License 2.0 5 votes vote down vote up
package com.ecfront.ez.framework.service.gateway.interceptor

import java.lang.Long
import java.util.concurrent.ConcurrentSkipListSet

import com.ecfront.ez.framework.core.logger.Logging
import com.ecfront.ez.framework.service.gateway.helper.AsyncRedisProcessor
import io.vertx.core.{AsyncResult, Handler}


object AntiDDoSInterceptor extends Logging {

  private val limitIPs = new ConcurrentSkipListSet[String]()

  private var enable: Boolean = _
  private var reqRatePerMinute: Int = _
  private var illegalReqRatePerMinute: Int = _
  private val FLAG_LIMIT = "ez:rpc:limit:"
  private val DEFAULT_EXPIRE: Int = 60

  def init(_reqRatePerMinute: Int, _illegalReqRatePerMinute: Int): Unit = {
    enable = true
    reqRatePerMinute = _reqRatePerMinute
    illegalReqRatePerMinute = _illegalReqRatePerMinute
  }

  def isLimit(reqIp: String): Boolean = {
    limitFilter(reqIp)
    limitIPs.contains(reqIp)
  }

  private def limitFilter(reqIp: String): Unit = {
    if (enable) {
      AsyncRedisProcessor.client().incr(FLAG_LIMIT + reqIp, new Handler[AsyncResult[Long]] {
        override def handle(event: AsyncResult[Long]): Unit = {
          val currReqRate = event.result()
          if (currReqRate == 1) {
            AsyncRedisProcessor.client().expire(FLAG_LIMIT + reqIp, DEFAULT_EXPIRE, new Handler[AsyncResult[Long]] {
              override def handle(event: AsyncResult[Long]): Unit = {}
            })
          }
          AsyncRedisProcessor.client().incrby(FLAG_LIMIT + reqIp, 0, new Handler[AsyncResult[Long]] {
            override def handle(event: AsyncResult[Long]): Unit = {
              val currErrorReqRate = event.result()
              if (currErrorReqRate == 0) {
                AsyncRedisProcessor.client().expire(FLAG_LIMIT + "illegal:" + reqIp, DEFAULT_EXPIRE, new Handler[AsyncResult[Long]] {
                  override def handle(event: AsyncResult[Long]): Unit = {}
                })
              }
              if (currReqRate > reqRatePerMinute || currErrorReqRate > illegalReqRatePerMinute) {
                limitIPs.add(reqIp)
                logger.error(s"Too frequent requests, please try again later from $reqIp")
              } else {
                limitIPs.remove(reqIp)
              }
            }
          })
        }
      })
    }
  }

  def addIllegal(reqIp: String): Unit = {
    if (enable) {
      AsyncRedisProcessor.client().incr(FLAG_LIMIT + "illegal:" + reqIp, new Handler[AsyncResult[Long]] {
        override def handle(event: AsyncResult[Long]): Unit = {}
      })
    }
  }

} 
Example 10
Source File: MetricsProcessor.scala    From ez-framework   with Apache License 2.0 5 votes vote down vote up
package com.ecfront.ez.framework.service.gateway.metrics

import java.lang.Long

import com.ecfront.common.Resp
import com.ecfront.ez.framework.core.logger.Logging
import io.vertx.core.json.JsonObject
import io.vertx.core.metrics.Measured
import io.vertx.core.{Handler, Vertx}
import io.vertx.ext.dropwizard.MetricsService

trait MetricsProcessor extends Logging {

  private var metricsService: MetricsService = _
  private var vertx: Vertx = _

  private[gateway] def register(_vertx: Vertx): Resp[Void] = {
    vertx = _vertx
    metricsService = MetricsService.create(vertx)
    Resp.success(null)
  }

  def getMetrics(service: Measured): JsonObject = {
    metricsService.getMetricsSnapshot(service)
  }

  def getMetrics(name: String): JsonObject = {
    metricsService.getMetricsSnapshot(name)
  }

  def statistics(intervalSec: Int, service: Measured): Unit = {
    vertx.setPeriodic(intervalSec * 1000, new Handler[Long] {
      override def handle(event: Long): Unit = {
        doStatistics(service)
      }
    })
  }

  protected def doStatistics(service: Measured): Unit

} 
Example 11
Source File: TimerHelper.scala    From ez-framework   with Apache License 2.0 5 votes vote down vote up
package com.ecfront.ez.framework.core.helper

import java.lang.Long
import java.util.concurrent.{ScheduledThreadPoolExecutor, TimeUnit}

object TimerHelper {

  private val ex = new ScheduledThreadPoolExecutor(1)

  def periodic(initialDelay: Long, period: Long, fun: => Unit): Unit = {
    val task = new Runnable {
      def run() = fun
    }
    ex.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS)
  }

  def periodic(period: Long, fun: => Unit): Unit = {
    periodic(0L, period, fun)
  }

  def timer(delay: Long, fun: => Unit): Unit = {
    val task = new Runnable {
      def run() = fun
    }
    ex.schedule(task, delay, TimeUnit.SECONDS)
  }

}