Down to Stack Traces, up from Heap DumpsAndrei Pangin
Глубже стек-трейсов, шире хип-дампов
Stack trace и heap dump - не просто инструменты отладки; это потайные дверцы к самым недрам виртуальной Java машины. Доклад будет посвящён малоизвестным особенностям JDK, так или иначе связанным с обоходом хипа и стеками потоков.
Мы разберём:
- как снимать дампы в продакшне без побочных эффектов;
- как работают утилиты jmap и jstack изнутри, и в чём хитрость forced режима;
- почему все профилировщики врут, и как с этим бороться;
- познакомимся с новым Stack-Walking API в Java 9;
- научимся сканировать Heap средствами JVMTI;
- узнаем о недокументированных функциях Хотспота и других интересных штуках.
No dark magic - Byte code engineering in the real worldtcurdt
ften byte code engineering is perceived as "black magic" and considered too low level. This session will not bore you with all the details of the JVM specification but provide you with a practical overview of how this byte code "swizzling" can be used in the real world instead. Several projects have sucessfully leveraged this technique to achieve some amazing things (e.g. AOP). This session will go through some of these examples and try to outline the differences between the two major libraries (BCEL and ASM). Maybe your next project can then benefit from some of this "magic".
Matlab code for An overview of solar photovoltaic panel modeling based on ana...Pourya Parsa
This paper provides a comprehensive review of available models of photovoltaic panel. Modeling and simulation of photovoltaic panel (PV) in virtual environment helps in designing and performance analysis of solar based power system. This paper analyses the currently available models from two different aspects. First aspect is based on electrical characteristics of PV panel using electrical equivalent circuit or through set of mathematical equations. The other aspect is based on the characteristics of PV panel under different environmental conditions. Environmental conditions include varying temperature and non-uniform solar irradiance due to partial shading. Varying environmental conditions causes continuous change in PV panel operating point corresponding to Maximum Power Point (MPP). Therefore an accurate PV panel model built with robust control that includes these environmental conditions will certainly improve the overall performance of the solar power plant. This paper can help researchers in selecting a specific objective based PV panel model out of several models available in literature.
Down to Stack Traces, up from Heap DumpsAndrei Pangin
Глубже стек-трейсов, шире хип-дампов
Stack trace и heap dump - не просто инструменты отладки; это потайные дверцы к самым недрам виртуальной Java машины. Доклад будет посвящён малоизвестным особенностям JDK, так или иначе связанным с обоходом хипа и стеками потоков.
Мы разберём:
- как снимать дампы в продакшне без побочных эффектов;
- как работают утилиты jmap и jstack изнутри, и в чём хитрость forced режима;
- почему все профилировщики врут, и как с этим бороться;
- познакомимся с новым Stack-Walking API в Java 9;
- научимся сканировать Heap средствами JVMTI;
- узнаем о недокументированных функциях Хотспота и других интересных штуках.
No dark magic - Byte code engineering in the real worldtcurdt
ften byte code engineering is perceived as "black magic" and considered too low level. This session will not bore you with all the details of the JVM specification but provide you with a practical overview of how this byte code "swizzling" can be used in the real world instead. Several projects have sucessfully leveraged this technique to achieve some amazing things (e.g. AOP). This session will go through some of these examples and try to outline the differences between the two major libraries (BCEL and ASM). Maybe your next project can then benefit from some of this "magic".
Matlab code for An overview of solar photovoltaic panel modeling based on ana...Pourya Parsa
This paper provides a comprehensive review of available models of photovoltaic panel. Modeling and simulation of photovoltaic panel (PV) in virtual environment helps in designing and performance analysis of solar based power system. This paper analyses the currently available models from two different aspects. First aspect is based on electrical characteristics of PV panel using electrical equivalent circuit or through set of mathematical equations. The other aspect is based on the characteristics of PV panel under different environmental conditions. Environmental conditions include varying temperature and non-uniform solar irradiance due to partial shading. Varying environmental conditions causes continuous change in PV panel operating point corresponding to Maximum Power Point (MPP). Therefore an accurate PV panel model built with robust control that includes these environmental conditions will certainly improve the overall performance of the solar power plant. This paper can help researchers in selecting a specific objective based PV panel model out of several models available in literature.
Не так давно Гор Нишанов представил свой доклад: C++ Coroutines a negative overhead abstraction. В этом докладе Гор упомянул, что предложенный дизайн корутин позволяет их использовать практически в любых окружениях, в том числе и с "бедным" C++ рантаймом.
Я решил попробовать запустить корутины в следующих окружениях: обычное приложение, драйвер ОС Windows, EFI приложение. Только в одном из этих окружений есть полноценный C++ рантайм и поддержка исключений, в остальных ничего этого нет. Более того, EFI приложение вообще выполняется до старта ОС.
Я хочу рассказать о том, как мне удалось запустить корутины в этих окружениях, поговорим о том, какие проблемы существуют в асинхронном системном программировании и как их можно обойти.
This talk is a look into some of the surprising performance cases in Java -- with the goal of illustrating a few simple truths about the nature of compilers.
RxJava и Android. Плюсы, минусы, подводные камниStfalcon Meetups
Ярослав Герьятович
Android Engineer в компании Attendify . Спикер на UA Mobile'14 . Идеолог функционального и реактивного подхода в проектировании Android приложений.
It has thread dumps to be referred from another presentation titled 'Debugging performance bottlenecks in java enterprise application' at http://www.slideshare.net/AjitBhingarkar/debugging-performance-bottlenecks-in-java-enterprise-application-42246703.
JVM Mechanics: Understanding the JIT's TricksDoug Hawkins
In this talk, we'll walkthrough how the JIT optimizes a piece Java code step-by-step. In doing so, you'll learn some of the amazing feats of optimization that JVMs can perform, but also some surprisingly simple things that prevent your code from running fast.
JEEConf 2017 - Having fun with JavassistAnton Arhipov
Javassist makes Java bytecode manipulation simple. At ZeroTurnaround we use Javassist a lot to implement the integrations for our tools.
In this talk we will go through the examples of how Javassist can be applied to alter the applications behavior and do all kind of fun stuff with it.
Why is it interesting? Because while trying to do unusual things in Java, you learn much more about the language and the platform itself and learning about Javassist will actually make you a better Java developer!
Не так давно Гор Нишанов представил свой доклад: C++ Coroutines a negative overhead abstraction. В этом докладе Гор упомянул, что предложенный дизайн корутин позволяет их использовать практически в любых окружениях, в том числе и с "бедным" C++ рантаймом.
Я решил попробовать запустить корутины в следующих окружениях: обычное приложение, драйвер ОС Windows, EFI приложение. Только в одном из этих окружений есть полноценный C++ рантайм и поддержка исключений, в остальных ничего этого нет. Более того, EFI приложение вообще выполняется до старта ОС.
Я хочу рассказать о том, как мне удалось запустить корутины в этих окружениях, поговорим о том, какие проблемы существуют в асинхронном системном программировании и как их можно обойти.
This talk is a look into some of the surprising performance cases in Java -- with the goal of illustrating a few simple truths about the nature of compilers.
RxJava и Android. Плюсы, минусы, подводные камниStfalcon Meetups
Ярослав Герьятович
Android Engineer в компании Attendify . Спикер на UA Mobile'14 . Идеолог функционального и реактивного подхода в проектировании Android приложений.
It has thread dumps to be referred from another presentation titled 'Debugging performance bottlenecks in java enterprise application' at http://www.slideshare.net/AjitBhingarkar/debugging-performance-bottlenecks-in-java-enterprise-application-42246703.
JVM Mechanics: Understanding the JIT's TricksDoug Hawkins
In this talk, we'll walkthrough how the JIT optimizes a piece Java code step-by-step. In doing so, you'll learn some of the amazing feats of optimization that JVMs can perform, but also some surprisingly simple things that prevent your code from running fast.
JEEConf 2017 - Having fun with JavassistAnton Arhipov
Javassist makes Java bytecode manipulation simple. At ZeroTurnaround we use Javassist a lot to implement the integrations for our tools.
In this talk we will go through the examples of how Javassist can be applied to alter the applications behavior and do all kind of fun stuff with it.
Why is it interesting? Because while trying to do unusual things in Java, you learn much more about the language and the platform itself and learning about Javassist will actually make you a better Java developer!
Presentation on handling non-existence of data in Java et. al. (e.g. the problem with pesky nulls) and an introduction to the Option monad in Scala as a "solution" to this problem.
I presented this talk June, 28th 2013 at CPH Scala Group meeting, and a week later, July 3rd, at the "Scala User Group Århus" meetup.
In this short introduction, I try to frame the problem, i.e. the large amounts of error-prone null-checking code we usually have to write in Java, and Introduce the Option monad (Some/None) in Scala, as a solution. I explain the basics of what the Option class provides, and various ways of using it, ranging from basic level isEmtpy, over pattern-matching to more advanced fully functional "collection-style" (e.g. map, flatMap) operations and finally by using the for-comprehension.
Also includes links to relevant resources for further reading on the last slide.
This talk presents Origami, a library providing "monadic folds" to accumulate values (like mean, standard deviation, min/max) on "streams" of values which can be coming from iterators, scalaz-stream processes or Akka data flows.
This is the material that I prepared for gathering best practices in exception handling that we aim to follow. I used the content stated in the references section.
In our recent webinar at Junxion Strategy we share insights about how the right-sized approach to materiality will help your strategy and reporting efforts start on the right foot, and practical approaches to brand development that tie together your inspiring vision for change, your business strategy, and accountability for your social performance. Whether your business is considering next steps, or first steps, in your journey towards socially responsible corporate citizenship, these are two essential practices to master if you want to "walk the talk" with confidence.
A presentation to demonstrate how our company will assess and develop a roadmap for change in a company rescue scenario by spencer greening - spencergreening674@hotmail.com
Qcon2011 functions rockpresentation_scalaMichael Stal
This is the part I of the tutorial I planned to give at QCon 2011 on Functional Programming with Scala. It also includes Scala 2.8 as well as upcoming features
Understanding bytecode and what bytecode is likely to be generated by a Java compiler helps the Java programmer in the same way that knowledge of assembler helps the C or C++ programmer. Java bytecode is the form of instructions that Java virtual machine executes. This knowledge is crucial when debugging and doing performance and memory usage tuning. The presenter will share his knowledge on what bytecode means for your platform and how to create compiler while using some awesome tools.
Beyond parallelize and collect - Spark Summit East 2016Holden Karau
As Spark jobs are used for more mission critical tasks, beyond exploration, it is important to have effective tools for testing. This talk expands on “Effective Testing For Spark Programs” (not required to have been seen) to discuss how to create large scale test jobs without depending on collect & parallelize which limit the sizes of datasets we can work with. Testing Spark Streaming jobs can be especially challenging, as the normal techniques for loading test data don’t work and additional work must be done to collect the results and stop streaming. We will explore the difficulties with testing Streaming Programs, options for setting up integration testing, beyond just local mode, with Spark, and also examine best practices for acceptance tests.
This webinar by Oleksandr Navka (Lead Software Engineer, Consultant, GlobalLogic) was delivered at Java Community Webinar #1 on August 12, 2020.
Webinar agenda:
- The new structural unit of the program is Java Records
- Updated instanceof statement
- Updated switch operator
More details and presentation: https://www.globallogic.com/ua/about/events/java-community-webinar-1/
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
1. CAND NAG ARVIND GUDISEVA 1
EXCEPTION HANDLING IN SCALA
JAVA WAY OF EXCEPTION HANDLING IN SCALA
TRY / CATCH / FINALLY
Onlyone catch blockis neededandcasesare usedto handle individual exceptions
PRESENT CODE
def oracleSample(oraConnWeb: Connection): Unit = {
logger.info(" :: Start Def :: oracleSample :: ")
try {
val oraStmt = oraConnWeb.createStatement()
var sqlSelect = """select * from emp"""
logger.info("SQL: " + sqlSelect)
val rs = oraStmt.executeQuery(sqlSelect)
while (rs.next){
println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3))
}
oraStmt.close()
}
catch {
case e: Throwable => e.printStackTrace()
}
logger.info(" :: End Def :: oracleSample :: ")
}
2. CAND NAG ARVIND GUDISEVA 2
MODIFIED CODE
def oracleSample(oraConnWeb: Connection): Unit = {
logger.info(" :: Start Def :: oracleSample :: ")
try {
val oraStmt = oraConnWeb.createStatement()
var sqlSelect = """select * from emp"""
logger.info("SQL: " + sqlSelect)
val rs = oraStmt.executeQuery(sqlSelect)
while (rs.next){
println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3))
}
oraStmt.close()
}
catch {
case ex: java.sql.SQLException => throw new java.sql.SQLException("SQLException: " +
ex.printStackTrace())
case ex: oracle.net.ns.NetException => throw new
oracle.net.ns.NetException(1,ex.printStackTrace().toString)
case ex: java.net.UnknownHostException => throw new
java.net.UnknownHostException("UnknownHostException: " + ex.printStackTrace())
case ex: java.sql.SQLSyntaxErrorException => throw new
java.sql.SQLSyntaxErrorException("SQLSyntaxErrorException: " + ex.printStackTrace())
case ex: Exception => throw new Exception("Exception: " + ex.printStackTrace())
}
logger.info(" :: End Def :: oracleSample :: ")
}
IMPROVISED CODE
def oracleSample(oraConnWeb: Connection): Unit = {
logger.info(" :: Start Def :: oracleSample :: ")
try {
3. CAND NAG ARVIND GUDISEVA 3
val oraStmt = oraConnWeb.createStatement()
var sqlSelect = """select * from emp1"""
logger.info("SQL: " + sqlSelect)
val rs = oraStmt.executeQuery(sqlSelect)
while (rs.next){
println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3))
}
oraStmt.close()
}
catch {
case ex: Exception => throw new CandAllExceptions(ex)
}
finally {
// Nothing
}
logger.info(" :: End Def :: oracleSample :: ")
}
WHAT IS THE PROBLEM?
Scala hasomittedCheckedExceptions. These exceptionsviolate SOLID –Open/ Close principle,
because we can’tthrow a newexceptioninasubclasswithoutpropagatingitaroundtoall the
existingclassesinthe hierarchy,aswell as methodscallingthose methods.
Scala’ssupportfor CheckedExceptionsisforcompatibilitywithJavacode. If we don’tintendtocall
a Scala code from Javacode,we shouldnotbe usingCheckedExceptions.
THROW NEW EXCEPTION
Throwingthe exceptionback tothe callingfunctionandhandlingthe exceptionsstackina
centralizedfashion.
PRESENT CODE
private def executeShell(shellStr: String) = {
logger.info(" :: Start Def :: executeShell :: ")
val shellCommand: String = shellStr
logger.info("Shell Command: " + shellCommand)
val sqoopProcess = Process(shellCommand).!!
logger.info("Shell Process: " + sqoopProcess)
logger.info(" :: End Def :: executeShell :: ")
}
IMPROVISED CODE
4. CAND NAG ARVIND GUDISEVA 4
private def executeShell(shellStr: String) = {
logger.info(" :: Start Def :: executeShell :: ")
try {
val shellCommand: String = shellStr
logger.info("Shell Command: " + shellCommand)
val stdOutput = new StringBuilder
val stdError = new StringBuilder
val processStatus: Int = shellCommand ! ProcessLogger(stdOutput append _, stdError append
_)
logger.info("Status Code: " + processStatus)
logger.info("Standard Output: " + stdOutput)
logger.info("Standard Error: " + stdError)
if(processStatus != 0){
val customCause = new RuntimeException("Non-zero Exit Code: (" + processStatus + ")")
val customException = new RuntimeException(customCause)
throw new CandCustomException(customException.getMessage, customException.getCause)
}
}
catch {
case ex: CandCustomException => throw new CandCustomException("CandCustomException: " +
ex.getMessage)
case ex: Exception => throw new CandAllExceptions(ex)
}
finally {
// Nothing
}
logger.info(" :: End Def :: executeShell :: ")
}
WHAT IS THE PROBLEM?
Shell / Processexceptionswere nevercaughtbyScalacode. Itwas handledbyJVM,whichwas
runningthe process. Enhance the code to use ProcessLoggerinsteadof Process.
PROCESS SHELL EXCEPTIONS:
Caused by: java.lang.RuntimeException: Unable to instantiate
org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
java.io.IOException: Hive exited with status 1
USE PROCESSLOGGER INSTEAD OF PROCESS
INFO contrct.GenCustContract$: Status Code: 1
INFO contrct.GenCustContract$: Standard Output: Warning: Please set $ZOOKEEPER_HOME to the root of
your Zookeeper installation.
INFO contrct.GenCustContract$: Standard Error:
ERROR util.CandCustomException: Message: java.lang.RuntimeException: Non-zero Exit Code: (1)
5. CAND NAG ARVIND GUDISEVA 5
@THROWS ANNOTATION
Onlyuseful if Scalacode iscalledfromJavaProgram. Is notof muchvalue as we needto
encapsulate the callingfunctionwithatryand catch.
@throws(classOf[CandAllExceptions])
def testThrows (oraConnWeb: Connection) = {
logger.info(" :: Start Def :: testThrows :: ")
val i: Int = 1
val j: Int = 0
println("Result: " + i/j)
logger.info(" :: End Def :: testThrows :: ")
}
def callTest = {
try{
testThrows(OraDBCon.getNaiApplCon())
}
catch {
case ex: Exception => throw new CandAllExceptions(ex)
}
}
CUSTOM EXCEPTIONS
Everyexceptionhasamessage andcause. CustomExceptionare extendedfromRuntimeException.
Hence,message andcause needstobe populatedwhengeneratingaCustomException.
package com.cisco.cand.util
import grizzled.slf4j.Logger
class CandCustomException(message: String = null, cause: Throwable = null) extends
RuntimeException(CandCustomException.customMessage(message, cause), cause)
/**
* Created by Nag Arvind Gudiseva on 08-July-2016.
*/
object CandCustomException {
val logger = Logger(classOf[CandCustomException])
logger.info(" :: Start Object :: CandCustomException :: ")
def customMessage(message: String, cause: Throwable) = {
if (message != null) {
logger.error("Message: " + message)
message
}
else if (cause != null){
logger.error("Cause: " + cause.toString())
cause.toString()
}
else
6. CAND NAG ARVIND GUDISEVA 6
null
}
logger.info(" :: End Object :: CandCustomException :: ")
}
EXCEPTIONS STACK / CENTRALIZED HANDLING OF ALL EXCEPTIONS
The purpose of thisCentralizedExceptionhandlingistokeepthe catchclause of code cleanand
simple. Exceptiontype isrecognizedasperthe exceptioninstance andthe stacktrace isprinted.
package com.cisco.cand.util
import grizzled.slf4j.Logger
/**
* Created by Nag Arvind Gudiseva on 11-July-2016.
*/
object CandAllExceptions {
val logger = Logger(classOf[CandAllExceptions])
logger.info(" :: Start Object :: CandAllExceptions :: ")
class CandAllExceptions(exception: Exception) extends Exception {
if (exception.isInstanceOf[java.sql.SQLSyntaxErrorException]){
throw new java.sql.SQLSyntaxErrorException("SQLSyntaxErrorException: " +
exception.printStackTrace)
}
else if(exception.isInstanceOf[java.sql.SQLException]){
throw new java.sql.SQLException("SQLException: " + exception.printStackTrace)
}
else if (exception.isInstanceOf[oracle.net.ns.NetException]){
throw new oracle.net.ns.NetException(1,exception.printStackTrace.toString)
}
else if (exception.isInstanceOf[java.net.UnknownHostException]){
throw new java.net.UnknownHostException("UnknownHostException: " +
exception.printStackTrace)
}
else if (exception.isInstanceOf[org.apache.thrift.transport.TTransportException]){
throw new org.apache.thrift.transport.TTransportException("ThriftTransportException: " +
exception.printStackTrace)
}
else if (exception.isInstanceOf[java.lang.NullPointerException]){
throw new java.lang.NullPointerException("NullPointerException: " +
exception.printStackTrace)
}
else if (exception.isInstanceOf[java.io.IOException]){
throw new java.io.IOException("IOException: " + exception.printStackTrace)
}
else if (exception.isInstanceOf[java.lang.RuntimeException]){
throw new java.lang.RuntimeException("RuntimeException: " + exception.printStackTrace)
}
else if (exception.isInstanceOf[java.lang.ArithmeticException]){
throw new java.lang.ArithmeticException("ArithmeticException: " +
exception.printStackTrace)
}
else{
throw new Exception("Exception: " + exception.printStackTrace)
}
}
logger.info(" :: End Object :: CandAllExceptions :: ")
}
7. CAND NAG ARVIND GUDISEVA 7
FINAL NOTE
Enhancedexceptionshandlingcode isinjectedtothe existingScalacode. There isno change inthe
existingfunctionality.