The worst large application pitfall is maintaining a huge code base with hundreds of dependencies - such a monolith slows down developers as they try to incorporate new features. Instead, partition your code into components, each gets its own folder or a dedicated codebase, and ensure that each unit is kept small and simple.
The ultimate solution is to develop small software: divide the whole stack into self-contained components that don't share files with others, each constitutes very few files (e.g. API, service, data access, test, etc.) so that it's very easy to reason about it.
CLR Exception Handing And Memory ManagementShiny Zhu
The document discusses best practices for exception handling and memory management in .NET Framework development. It covers topics like when to throw exceptions, what data to include, catching and rethrowing exceptions, implementing the dispose pattern, and using statements. It also discusses memory management techniques like finalizers, handle collectors, and adding/removing memory pressure.
Exception handling in Java allows programs to deal with errors and unexpected conditions gracefully. The try block encloses code that might throw exceptions. When an exception is thrown, the runtime system searches the call stack for a catch block that can handle the exception. The finally block always executes after the try and catch blocks complete to ensure cleanup code runs. Custom exceptions can be created by extending the Exception class.
The document discusses various techniques for determining where to start testing a legacy application, including:
1) Analyzing code coverage reports to find which parts of the code are most used.
2) Checking version control history to identify files that change frequently.
3) Conducting code reviews to find areas that modify data.
4) Running static code analysis tools to locate sections likely to contain bugs.
The document advocates starting testing with the highest priority areas identified using these techniques, and provides examples of writing initial tests against a sample codebase.
JFtp is an open source Java FTP client that allows users to securely transfer files using SFTP, SMB, NFS, HTTP and other protocols. It can be run directly from a web browser or downloaded as a JAR file. The source code is available on SourceForge and can be compiled using Apache Ant to build a runnable JAR file. The program utilizes external Java libraries like JCraft's JSch for SFTP functionality.
- An error occurred during program execution that resulted in abnormal termination and wrong execution results.
- There are three main ways to handle exceptions in ASP.NET: using try-catch blocks, error events, and custom error pages.
- Try-catch blocks allow catching and handling specific exceptions, error events handle errors at the page and application level, and custom error pages display for all unhandled errors.
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)CODE WHITE GmbH
This document discusses Java deserialization vulnerabilities and provides an overview of how they work. It notes that many Java technologies rely on serialization which can enable remote code execution if not implemented securely. The document outlines the history of vulnerabilities found, how to find vulnerabilities, and techniques for exploiting them, using examples like the Javassist/Weld gadget. It also summarizes vulnerabilities the speaker's company Code White found, including in products from Symantec, Atlassian, Commvault, and Oracle.
CLR Exception Handing And Memory ManagementShiny Zhu
The document discusses best practices for exception handling and memory management in .NET Framework development. It covers topics like when to throw exceptions, what data to include, catching and rethrowing exceptions, implementing the dispose pattern, and using statements. It also discusses memory management techniques like finalizers, handle collectors, and adding/removing memory pressure.
Exception handling in Java allows programs to deal with errors and unexpected conditions gracefully. The try block encloses code that might throw exceptions. When an exception is thrown, the runtime system searches the call stack for a catch block that can handle the exception. The finally block always executes after the try and catch blocks complete to ensure cleanup code runs. Custom exceptions can be created by extending the Exception class.
The document discusses various techniques for determining where to start testing a legacy application, including:
1) Analyzing code coverage reports to find which parts of the code are most used.
2) Checking version control history to identify files that change frequently.
3) Conducting code reviews to find areas that modify data.
4) Running static code analysis tools to locate sections likely to contain bugs.
The document advocates starting testing with the highest priority areas identified using these techniques, and provides examples of writing initial tests against a sample codebase.
JFtp is an open source Java FTP client that allows users to securely transfer files using SFTP, SMB, NFS, HTTP and other protocols. It can be run directly from a web browser or downloaded as a JAR file. The source code is available on SourceForge and can be compiled using Apache Ant to build a runnable JAR file. The program utilizes external Java libraries like JCraft's JSch for SFTP functionality.
- An error occurred during program execution that resulted in abnormal termination and wrong execution results.
- There are three main ways to handle exceptions in ASP.NET: using try-catch blocks, error events, and custom error pages.
- Try-catch blocks allow catching and handling specific exceptions, error events handle errors at the page and application level, and custom error pages display for all unhandled errors.
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)CODE WHITE GmbH
This document discusses Java deserialization vulnerabilities and provides an overview of how they work. It notes that many Java technologies rely on serialization which can enable remote code execution if not implemented securely. The document outlines the history of vulnerabilities found, how to find vulnerabilities, and techniques for exploiting them, using examples like the Javassist/Weld gadget. It also summarizes vulnerabilities the speaker's company Code White found, including in products from Symantec, Atlassian, Commvault, and Oracle.
This document provides an overview of Java essentials including:
- Java addressed issues with C/C++ like inconsistent frameworks and memory management issues.
- Java introduced a common framework, garbage collection, and object oriented programming.
- The history of Java versions from 1.0 to 6.0 is summarized.
- A simple "Hello World" Java program is broken down and explained.
Salesforce provides an interface for testing callouts named HttpCalloutMock used to cover remote callouts. While adequate for simple callouts, in the real world you often need something more flexible, as in the case of multiple and varying responses from the same or varying endpoints. More precise testing and coverage can be obtained by extending the standard interface. Join us as we demonstrate a solution to use to enable the flexibility required for complex integration and synchronization apps.
This document summarizes a C# web security class presentation from October 2010. It introduces various types of web attacks like SQL injection and cross-site scripting. It provides examples of vulnerable practice websites like Hackme Bank and Hackme Books to demonstrate SQL injection. It also lists resources for web security checklists, tools for scanning websites, and anonymization techniques. Common fixes for SQL injection like using stored procedures and parameterized queries are also discussed.
Spring Certification Questions and Spring Free test are tests created to demonstrate all the functions of our mock exams. You will be able to access ten full questions and will have ten minutes of time for finishing the test.
There are several components you can interact with when you take our mock exams:
Take a look at the progress bar at the top; it will tell how you are progressing through the exam.
Read the question and select only the answers you think are correct by checking the corresponding check box.
Navigate the spring questions using the "Previous" and "Next" buttons.
Mark the spring questions you wish to review later. All the questions you have marked will be listed on the right in the section "marked questions". You will be able to jump directly to the question from this list.
If you want to take a look at the correct answers for a question, just click the "Solution" button. In the solution section you will be able to check your answers as well as find a full explanation of the question.
Keep an eye on the countdown. This will tell you how much time is remaining. When the countdown expires, the test will be automatically submitted.
Once the test is submitted, the "result" section will expand. Here, you will be able to review all the questions of the test. From here, you can also navigate directly to each question.
The document discusses reversing Microsoft patches to reveal vulnerable code. It describes downloading patches and extracting files, using DarunGrim2 for binary differencing to locate code changes between patched and unpatched binaries, analyzing differences to find potential vulnerability fixes while removing false positives, and debugging to validate findings by crashing applications with malformed files. The goal is to create zero-day exploits and vulnerability signatures.
Java Deserialization Vulnerabilities - The Forgotten Bug ClassCODE WHITE GmbH
This document discusses Java deserialization vulnerabilities. It provides an introduction to how Java serialization works and what the security issues are. Specifically, it describes how an attacker can exploit vulnerabilities to remotely execute code on a server by deserializing malicious objects. The document gives examples of past vulnerabilities found in various Java applications and frameworks. It also provides tips for finding vulnerabilities and generating payloads to demonstrate exploits.
The document discusses exceptions in .NET programming. It explains that exceptions are error conditions that occur during execution and can be caught and handled in code. The .NET Framework includes many predefined exception classes and developers can create custom exception classes. Exception handling blocks use try, catch, and finally keywords to catch exceptions at different levels and log or report errors to help debug problems.
Here are the steps to implement a filter to redirect requests to a maintenance page:
1. Create a class that implements the Filter interface.
2. Add init(), doFilter() and destroy() methods.
3. In doFilter(), get the request URI and check if it is the home page URL.
4. If it is the home page, get the response and send a redirect to the maintenance page.
5. Else, pass the request and response to the filter chain.
6. Map the filter in web.xml, specifying the URL pattern as /* to apply to all requests.
7. Create the maintenance page that displays the message.
8. Deploy and test
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Christian Schneider
The hidden danger of Java deserialization vulnerabilities – which often lead to remote code execution – has gained extended visibility in the past year. The issue has been known for years; however, it seems that the majority of developers were unaware of it until recent media coverage around commonly used libraries and major products. This talk aims to shed some light about how this vulnerability can be abused, how to detect it from a static and dynamic point of view, and -- most importantly -- how to effectively protect against it. The scope of this talk is not limited to the Java serialization protocol but also other popular Java libraries used for object serialization.
The ever-increasing number of new vulnerable endpoints and attacker-usable gadgets has resulted in a lot of different recommendations on how to protect your applications, including look-ahead deserialization and runtime agents to monitor and protect the deserialization process. Coming at the problem from a developer’s perspective and triaging the recommendations for you, this talk will review existing protection techniques and demonstrate their effectiveness on real applications. It will also review existing techniques and present new gadgets that demonstrates how attackers can actually abuse your application code and classpath to craft a chain of gadgets that will allow them to compromise your servers.
This talk will also present the typical architectural decisions and code patterns that lead to an increased risk of exposing deserialization vulnerabilities. Mapping the typical anti-patterns that must be avoided, through the use of real code examples we present an overview of hardening techniques and their effectiveness. The talk will also show attendees what to search the code for in order to find potential code gadgets the attackers can leverage to compromise their applications. We’ll conclude with action items and recommendations developers should consider to mitigate this threat.
--
This talk was presented by Alvaro Muñoz & Christian Schneider at the OWASP AppSecEU 2016 conference in Rome.
This document provides an overview of Rich Internet Applications (RIA) and the Adobe Flex software development kit. It discusses how Flex uses MXML and ActionScript to create RIA applications that interact with the Flash plugin. It also covers related technologies like Adobe AIR, BlazeDS, and LifeCycle Data Services that allow Flex applications to communicate with backend services. Examples of MXML code and Flex application architecture are provided.
This document provides information about exception handling in Java. It discusses what exceptions are, why they occur, and the different types of exceptions. It also describes exception handling mechanisms in Java like try, catch, throw, throws and finally. Specific examples of exception handling using these keywords are provided. The advantages of exception handling in Java are also mentioned.
The old is new, again. CVE-2011-2461 is back!Luca Carettoni
As a part of an ongoing investigation on Adobe Flash SOP bypass techniques, we identified a vulnerability affecting old releases of the Adobe Flex SDK compiler. Further investigation traced the issue back to a well known vulnerability (CVE20112461), already patched by Adobe. Old vulnerability, let's move on? Not this time. CVE20112461 is a very interesting bug. As long as the SWF file was compiled with a vulnerable Flex SDK, attackers can still use this vulnerability against the latest web browsers and Flash plugin. Even with the most recent updates, vulnerable Flex applications hosted on your domain can be exploited. In this presentation, we will disclose the details of this vulnerability (Adobe has never released all technicalities) and we will discuss how we conducted a large scale analysis on popular websites, resulting in the identification of numerous Alexa Top 50 sites vulnerable to this bug. Finally, we will also release a custom tool and a Burp plugin capable of detecting vulnerable SWF applications. If you’re a breaker, you will learn a new technique and enjoy our exploits. If you’re a builder, you will learn how to mitigate this attack. In both cases, you can help us to eradicate CVE20112461. After all, Troopers is about making the world a safer place.
Mauro Gentile, Luca Carettoni
The document provides an overview of testing Apex code in Salesforce, including:
- Why unit testing is important for developing robust, error-free code that meets the minimum 75% test coverage requirement.
- How to write Apex test classes annotated with @isTest and define test methods using testMethod.
- Using Test.startTest() and Test.stopTest() to test governor limits.
- Examples of testing a trigger, visualforce controller, web services callouts, and external API callouts.
- Best practices for testing such as using System.assert(), achieving 100% coverage, and testing different user contexts with System.runAs().
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPAli Shah
Exception handling in C# uses four keywords: try, catch, finally, and throw. The try block identifies code that might cause exceptions. The catch block handles exceptions, while finally ensures code is always executed. Exceptions are represented by classes derived from System.Exception, and common exceptions include NullReferenceException and DivideByZeroException. ADO.NET provides objects like SqlConnection and SqlCommand to connect C# applications to SQL Server databases using connection strings. Data can be queried, inserted, and read from databases through these objects.
This document provides an overview of unit testing in PHP using the PHPUnit framework. It describes frequently used PHPUnit methods like assertEquals(), assertInstanceOf(), setUp() and tearDown(). It explains how to write test cases for exceptions using annotations like @expectedException. It provides examples of good practices for writing readable and maintainable test cases, such as splitting tests into independent cases and being descriptive with test names.
Unit testing best practices are based on principles rather than strict standards. The principles include making tests easy to understand, fail only when there is a problem with the code under test, find all problems with the code, have minimal duplication, and run quickly. Some standards that help satisfy these principles include writing tests before code using test-driven development, separating tests from production code, and avoiding dependencies on external systems by using stubs and mocks. Well-written tests that follow these principles can serve as documentation.
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!Priyanka Aash
"We propose a new exploit technique that brings a whole-new attack surface to defeat path normalization, which is complicated in implementation due to many implicit properties and edge cases. This complication, being under-estimated or ignored by developers for a long time, has made our proposed attack vector possible, lethal, and general. Therefore, many 0days have been discovered via this approach in popular web frameworks written in trending programming languages, including Python, Ruby, Java, and JavaScript.
Being a very fundamental problem that exists in path normalization logic, sophisticated web frameworks can also suffer. For example, we've found various 0days on Java Spring Framework, Ruby on Rails, Next.js, and Python aiohttp, just to name a few. This general technique can also adapt to multi-layered web architecture, such as using Nginx or Apache as a proxy for Tomcat. In that case, reverse proxy protections can be bypassed. To make things worse, we're able to chain path normalization bugs to bypass authentication and achieve RCE in real world Bug Bounty Programs. Several scenarios will be demonstrated to illustrate how path normalization can be exploited to achieve sensitive information disclosure, SMB-Relay and RCE.
Understanding the basics of this technique, the audience won't be surprised to know that more than 10 vulnerabilities have been found in sophisticated frameworks and multi-layered web architectures aforementioned via this technique."
Exceptions represent errors that occur during program execution. The try-catch block allows exceptions to be handled gracefully. A try block contains code that might throw exceptions, while catch blocks specify how to handle specific exception types if they occur. Checked exceptions must either be caught or specified in a method's throws clause, as they represent conditions outside the programmer's control. Unchecked exceptions like NullPointerException indicate programming errors and do not require catching or specifying.
This lab document describes using the Metasploit framework to perform exploits against Windows systems. It consists of six sections: installing Metasploit, adding a remote user to Windows XP, gaining remote command shell access to Windows XP, using DLL injection to open a remote VNC connection, remotely installing a rootkit on Windows, and setting up the Metasploit web interface. The document provides background on exploit frameworks and payloads, and guides students through exercises to complete each section.
This presentation discusses the most neglected quality axis : code documentation. See good and bad examples, best practices on documenting code and why you should try not to ignore it :)
Presentation date: 2014-11-28
Place: Thessaloniki Java Meetup Group (SKG)
This document provides an overview of Java essentials including:
- Java addressed issues with C/C++ like inconsistent frameworks and memory management issues.
- Java introduced a common framework, garbage collection, and object oriented programming.
- The history of Java versions from 1.0 to 6.0 is summarized.
- A simple "Hello World" Java program is broken down and explained.
Salesforce provides an interface for testing callouts named HttpCalloutMock used to cover remote callouts. While adequate for simple callouts, in the real world you often need something more flexible, as in the case of multiple and varying responses from the same or varying endpoints. More precise testing and coverage can be obtained by extending the standard interface. Join us as we demonstrate a solution to use to enable the flexibility required for complex integration and synchronization apps.
This document summarizes a C# web security class presentation from October 2010. It introduces various types of web attacks like SQL injection and cross-site scripting. It provides examples of vulnerable practice websites like Hackme Bank and Hackme Books to demonstrate SQL injection. It also lists resources for web security checklists, tools for scanning websites, and anonymization techniques. Common fixes for SQL injection like using stored procedures and parameterized queries are also discussed.
Spring Certification Questions and Spring Free test are tests created to demonstrate all the functions of our mock exams. You will be able to access ten full questions and will have ten minutes of time for finishing the test.
There are several components you can interact with when you take our mock exams:
Take a look at the progress bar at the top; it will tell how you are progressing through the exam.
Read the question and select only the answers you think are correct by checking the corresponding check box.
Navigate the spring questions using the "Previous" and "Next" buttons.
Mark the spring questions you wish to review later. All the questions you have marked will be listed on the right in the section "marked questions". You will be able to jump directly to the question from this list.
If you want to take a look at the correct answers for a question, just click the "Solution" button. In the solution section you will be able to check your answers as well as find a full explanation of the question.
Keep an eye on the countdown. This will tell you how much time is remaining. When the countdown expires, the test will be automatically submitted.
Once the test is submitted, the "result" section will expand. Here, you will be able to review all the questions of the test. From here, you can also navigate directly to each question.
The document discusses reversing Microsoft patches to reveal vulnerable code. It describes downloading patches and extracting files, using DarunGrim2 for binary differencing to locate code changes between patched and unpatched binaries, analyzing differences to find potential vulnerability fixes while removing false positives, and debugging to validate findings by crashing applications with malformed files. The goal is to create zero-day exploits and vulnerability signatures.
Java Deserialization Vulnerabilities - The Forgotten Bug ClassCODE WHITE GmbH
This document discusses Java deserialization vulnerabilities. It provides an introduction to how Java serialization works and what the security issues are. Specifically, it describes how an attacker can exploit vulnerabilities to remotely execute code on a server by deserializing malicious objects. The document gives examples of past vulnerabilities found in various Java applications and frameworks. It also provides tips for finding vulnerabilities and generating payloads to demonstrate exploits.
The document discusses exceptions in .NET programming. It explains that exceptions are error conditions that occur during execution and can be caught and handled in code. The .NET Framework includes many predefined exception classes and developers can create custom exception classes. Exception handling blocks use try, catch, and finally keywords to catch exceptions at different levels and log or report errors to help debug problems.
Here are the steps to implement a filter to redirect requests to a maintenance page:
1. Create a class that implements the Filter interface.
2. Add init(), doFilter() and destroy() methods.
3. In doFilter(), get the request URI and check if it is the home page URL.
4. If it is the home page, get the response and send a redirect to the maintenance page.
5. Else, pass the request and response to the filter chain.
6. Map the filter in web.xml, specifying the URL pattern as /* to apply to all requests.
7. Create the maintenance page that displays the message.
8. Deploy and test
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Christian Schneider
The hidden danger of Java deserialization vulnerabilities – which often lead to remote code execution – has gained extended visibility in the past year. The issue has been known for years; however, it seems that the majority of developers were unaware of it until recent media coverage around commonly used libraries and major products. This talk aims to shed some light about how this vulnerability can be abused, how to detect it from a static and dynamic point of view, and -- most importantly -- how to effectively protect against it. The scope of this talk is not limited to the Java serialization protocol but also other popular Java libraries used for object serialization.
The ever-increasing number of new vulnerable endpoints and attacker-usable gadgets has resulted in a lot of different recommendations on how to protect your applications, including look-ahead deserialization and runtime agents to monitor and protect the deserialization process. Coming at the problem from a developer’s perspective and triaging the recommendations for you, this talk will review existing protection techniques and demonstrate their effectiveness on real applications. It will also review existing techniques and present new gadgets that demonstrates how attackers can actually abuse your application code and classpath to craft a chain of gadgets that will allow them to compromise your servers.
This talk will also present the typical architectural decisions and code patterns that lead to an increased risk of exposing deserialization vulnerabilities. Mapping the typical anti-patterns that must be avoided, through the use of real code examples we present an overview of hardening techniques and their effectiveness. The talk will also show attendees what to search the code for in order to find potential code gadgets the attackers can leverage to compromise their applications. We’ll conclude with action items and recommendations developers should consider to mitigate this threat.
--
This talk was presented by Alvaro Muñoz & Christian Schneider at the OWASP AppSecEU 2016 conference in Rome.
This document provides an overview of Rich Internet Applications (RIA) and the Adobe Flex software development kit. It discusses how Flex uses MXML and ActionScript to create RIA applications that interact with the Flash plugin. It also covers related technologies like Adobe AIR, BlazeDS, and LifeCycle Data Services that allow Flex applications to communicate with backend services. Examples of MXML code and Flex application architecture are provided.
This document provides information about exception handling in Java. It discusses what exceptions are, why they occur, and the different types of exceptions. It also describes exception handling mechanisms in Java like try, catch, throw, throws and finally. Specific examples of exception handling using these keywords are provided. The advantages of exception handling in Java are also mentioned.
The old is new, again. CVE-2011-2461 is back!Luca Carettoni
As a part of an ongoing investigation on Adobe Flash SOP bypass techniques, we identified a vulnerability affecting old releases of the Adobe Flex SDK compiler. Further investigation traced the issue back to a well known vulnerability (CVE20112461), already patched by Adobe. Old vulnerability, let's move on? Not this time. CVE20112461 is a very interesting bug. As long as the SWF file was compiled with a vulnerable Flex SDK, attackers can still use this vulnerability against the latest web browsers and Flash plugin. Even with the most recent updates, vulnerable Flex applications hosted on your domain can be exploited. In this presentation, we will disclose the details of this vulnerability (Adobe has never released all technicalities) and we will discuss how we conducted a large scale analysis on popular websites, resulting in the identification of numerous Alexa Top 50 sites vulnerable to this bug. Finally, we will also release a custom tool and a Burp plugin capable of detecting vulnerable SWF applications. If you’re a breaker, you will learn a new technique and enjoy our exploits. If you’re a builder, you will learn how to mitigate this attack. In both cases, you can help us to eradicate CVE20112461. After all, Troopers is about making the world a safer place.
Mauro Gentile, Luca Carettoni
The document provides an overview of testing Apex code in Salesforce, including:
- Why unit testing is important for developing robust, error-free code that meets the minimum 75% test coverage requirement.
- How to write Apex test classes annotated with @isTest and define test methods using testMethod.
- Using Test.startTest() and Test.stopTest() to test governor limits.
- Examples of testing a trigger, visualforce controller, web services callouts, and external API callouts.
- Best practices for testing such as using System.assert(), achieving 100% coverage, and testing different user contexts with System.runAs().
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPAli Shah
Exception handling in C# uses four keywords: try, catch, finally, and throw. The try block identifies code that might cause exceptions. The catch block handles exceptions, while finally ensures code is always executed. Exceptions are represented by classes derived from System.Exception, and common exceptions include NullReferenceException and DivideByZeroException. ADO.NET provides objects like SqlConnection and SqlCommand to connect C# applications to SQL Server databases using connection strings. Data can be queried, inserted, and read from databases through these objects.
This document provides an overview of unit testing in PHP using the PHPUnit framework. It describes frequently used PHPUnit methods like assertEquals(), assertInstanceOf(), setUp() and tearDown(). It explains how to write test cases for exceptions using annotations like @expectedException. It provides examples of good practices for writing readable and maintainable test cases, such as splitting tests into independent cases and being descriptive with test names.
Unit testing best practices are based on principles rather than strict standards. The principles include making tests easy to understand, fail only when there is a problem with the code under test, find all problems with the code, have minimal duplication, and run quickly. Some standards that help satisfy these principles include writing tests before code using test-driven development, separating tests from production code, and avoiding dependencies on external systems by using stubs and mocks. Well-written tests that follow these principles can serve as documentation.
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!Priyanka Aash
"We propose a new exploit technique that brings a whole-new attack surface to defeat path normalization, which is complicated in implementation due to many implicit properties and edge cases. This complication, being under-estimated or ignored by developers for a long time, has made our proposed attack vector possible, lethal, and general. Therefore, many 0days have been discovered via this approach in popular web frameworks written in trending programming languages, including Python, Ruby, Java, and JavaScript.
Being a very fundamental problem that exists in path normalization logic, sophisticated web frameworks can also suffer. For example, we've found various 0days on Java Spring Framework, Ruby on Rails, Next.js, and Python aiohttp, just to name a few. This general technique can also adapt to multi-layered web architecture, such as using Nginx or Apache as a proxy for Tomcat. In that case, reverse proxy protections can be bypassed. To make things worse, we're able to chain path normalization bugs to bypass authentication and achieve RCE in real world Bug Bounty Programs. Several scenarios will be demonstrated to illustrate how path normalization can be exploited to achieve sensitive information disclosure, SMB-Relay and RCE.
Understanding the basics of this technique, the audience won't be surprised to know that more than 10 vulnerabilities have been found in sophisticated frameworks and multi-layered web architectures aforementioned via this technique."
Exceptions represent errors that occur during program execution. The try-catch block allows exceptions to be handled gracefully. A try block contains code that might throw exceptions, while catch blocks specify how to handle specific exception types if they occur. Checked exceptions must either be caught or specified in a method's throws clause, as they represent conditions outside the programmer's control. Unchecked exceptions like NullPointerException indicate programming errors and do not require catching or specifying.
This lab document describes using the Metasploit framework to perform exploits against Windows systems. It consists of six sections: installing Metasploit, adding a remote user to Windows XP, gaining remote command shell access to Windows XP, using DLL injection to open a remote VNC connection, remotely installing a rootkit on Windows, and setting up the Metasploit web interface. The document provides background on exploit frameworks and payloads, and guides students through exercises to complete each section.
This presentation discusses the most neglected quality axis : code documentation. See good and bad examples, best practices on documenting code and why you should try not to ignore it :)
Presentation date: 2014-11-28
Place: Thessaloniki Java Meetup Group (SKG)
1. The document provides instructions for installing Tomcat and setting up a basic web application with servlets on a Windows system. It describes downloading and installing Java, setting the JAVA_HOME environment variable, downloading and installing Tomcat, and creating a simple "HelloWorld" servlet application.
2. It then gives examples of additional servlet programming concepts like sending request parameters, generating HTML tables, using sessions, servlet forwarding, and accessing databases with JDBC.
3. For each example, it provides the HTML, Java code, and instructions for compiling and running the servlets on the Tomcat server.
Best Coding Practices For Android Application DevelopmentKetan Raval
Learn how to make coding at the time of android application development. Best practices for coding for android app development. Points to take care at the time of development application.
Java history, versions, types of errors and exception, quiz SAurabh PRajapati
this ppt contains history and basic facts of object oriented programming language java, difference between JIT, JVM, JRE and JDK. it also having information about different versions of java. advantages over other language, difference between error and exception with its types is also included. explanation of final variable and string to int conversation is also added. in the end some twisted question of it which sharpen the knowledge of its basic are added. beyond this some programming examples with output is there too. hope u find it useful...!! thanku..!!
The document discusses error handling in ASP.NET programs. It describes three main ways to handle errors: try-catch blocks, error events, and custom error pages. Try-catch blocks allow catching and handling specific exceptions. Error events like Page_Error and Application_Error handle uncaught exceptions. Custom error pages can be configured in the web.config file to display friendly error messages to users.
Node. js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Node. js is an open source, cross-platform run time environment for developing server-side and networking applications
The document discusses object oriented programming concepts related to exception handling in Java. It covers the benefits of exception handling such as separating error handling code from regular logic and propagating errors up the call stack. It also describes key exception handling constructs like try, catch, throw and throws. The different exception models of termination and resumption are explained along with the exception hierarchy in Java.
This document provides a Java coding standard for code structure, documentation, naming conventions, and recommendations. It outlines how to structure packages, program files, classes, methods, and code layout. It provides conventions for naming packages, files, classes, variables, methods and other identifiers. It gives recommendations for classes, exception handling, variables, methods, technical points and applying common sense. Code examples are provided to demonstrate the conventions.
Robot Framework is a test automation framework that allows test cases to be written using keywords. It provides simple APIs to create custom test libraries and outputs test reports in XML format. Test suites are organized into files and directories and can be executed from the command line using options to control execution and output reporting. This generates log, report and XML output files containing the test results.
This document provides a brief summary of the key elements in a SCORM 1.2 manifest.xml file. It explains the basic structure including the XML header, <manifest> root element, <organizations> and <organization> elements to define the course structure, <item> elements for each module, <resource> elements to link modules to content files, and closing tags. It emphasizes keeping the manifest concise by only including the minimum required elements and omitting unnecessary details like a full file listing. The goal is to have an easy to read and edit manifest for basic SCORM compliance.
Annotation processing allows for metadata to be added to Java programs without altering the program itself. Annotations can be defined and used to provide information for compilers or allow runtime/compile-time processing. Annotation processors provide a hook into the Java compilation process to generate source code and compile errors/warnings. They work by processing annotated elements in rounds. Testing annotation processors is challenging but libraries like Google's compile-testing library can help. Annotation processing also works on Android by setting up the processor as a Java module and using plugins like android-apt.
The document outlines Tequila Coding Style Version 1.0, including general coding practices for object-oriented programming, development, and application security. It discusses file organization, naming conventions, indentation, whitespace, comments, declarations, and initialization. Key recommendations include using classes and exceptions, avoiding global variables, following semantic naming conventions, proper indentation and comments, and initializing variables on declaration.
the slide about Exception handling in java and the file and io handling in java .inbuilt java packages in for java exception.for beginner in programming
This document provides release notes and supplementary information for Delphi 7. It notes that some components have been deprecated and recommends newer alternatives. It also describes changes made to string handling functions, warnings added by the compiler, and issues fixed in streaming of subcomponents. Finally, it provides notes on various other topics like Apache, UDDI, Windows XP input, and databases.
C++ - UNIT_-_V.pptx which contains details about File ConceptsANUSUYA S
The document discusses file handling in C++. It explains that files are used to store data permanently on a storage device. There are three main classes used for file handling - ifstream for input, ofstream for output, and fstream for both input and output. The key file handling operations include opening a file using open(), reading from a file using read(), writing to a file using write(), and closing a file using close(). It also discusses opening files in different modes, reading and writing binary data to files, and handling exceptions that may occur during file operations.
This document provides an overview of Firefox extension development using JavaScript. It discusses JavaScript basics like variables, functions, and debugging with alerts. It also covers how to access and manipulate the DOM to work with XUL elements in the extension's GUI. Developers are instructed to place JavaScript code files in the extension's content directory and link them to XUL files using the chrome URI. Further reading links are included to learn more about XUL elements and JavaScript.
This document provides an overview of Firefox extension development using JavaScript. It discusses JavaScript basics like variables, functions, and debugging with alerts. It also covers how to access and manipulate the DOM to work with XUL elements in a GUI. Developers are instructed to place JavaScript code files in the extension's content directory and link them to XUL files using the chrome URI. Further reading links are included to learn more about XUL elements, JavaScript, and tutorials for non-programmers.
How to test infrastructure code: automated testing for Terraform, Kubernetes,...Yevgeniy Brikman
This talk is a step-by-step, live-coding class on how to write automated tests for infrastructure code, including the code you write for use with tools such as Terraform, Kubernetes, Docker, and Packer. Topics covered include unit tests, integration tests, end-to-end tests, test parallelism, retries, error handling, static analysis, and more.
The document summarizes the structure and contents of an Android project in Eclipse. It describes the important folders like src, gen, res, and files like AndroidManifest.xml. It explains that src contains Java source files, gen contains generated files like R.java, res contains app resources like images and layouts. It provides guidelines on code formatting, naming conventions, and best practices for organizing an Android project.
Similar to Perfomatix - Java Coding Standards (20)
SOCRadar's Aviation Industry Q1 Incident Report is out now!
The aviation industry has always been a prime target for cybercriminals due to its critical infrastructure and high stakes. In the first quarter of 2024, the sector faced an alarming surge in cybersecurity threats, revealing its vulnerabilities and the relentless sophistication of cyber attackers.
SOCRadar’s Aviation Industry, Quarterly Incident Report, provides an in-depth analysis of these threats, detected and examined through our extensive monitoring of hacker forums, Telegram channels, and dark web platforms.
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsPeter Muessig
The UI5 tooling is the development and build tooling of UI5. It is built in a modular and extensible way so that it can be easily extended by your needs. This session will showcase various tooling extensions which can boost your development experience by far so that you can really work offline, transpile your code in your project to use even newer versions of EcmaScript (than 2022 which is supported right now by the UI5 tooling), consume any npm package of your choice in your project, using different kind of proxies, and even stitching UI5 projects during development together to mimic your target environment.
Flutter is a popular open source, cross-platform framework developed by Google. In this webinar we'll explore Flutter and its architecture, delve into the Flutter Embedder and Flutter’s Dart language, discover how to leverage Flutter for embedded device development, learn about Automotive Grade Linux (AGL) and its consortium and understand the rationale behind AGL's choice of Flutter for next-gen IVI systems. Don’t miss this opportunity to discover whether Flutter is right for your project.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Takashi Kobayashi and Hironori Washizaki, "SWEBOK Guide and Future of SE Education," First International Symposium on the Future of Software Engineering (FUSE), June 3-6, 2024, Okinawa, Japan
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
Odoo ERP software
Odoo ERP software, a leading open-source software for Enterprise Resource Planning (ERP) and business management, has recently launched its latest version, Odoo 17 Community Edition. This update introduces a range of new features and enhancements designed to streamline business operations and support growth.
The Odoo Community serves as a cost-free edition within the Odoo suite of ERP systems. Tailored to accommodate the standard needs of business operations, it provides a robust platform suitable for organisations of different sizes and business sectors. Within the Odoo Community Edition, users can access a variety of essential features and services essential for managing day-to-day tasks efficiently.
This blog presents a detailed overview of the features available within the Odoo 17 Community edition, and the differences between Odoo 17 community and enterprise editions, aiming to equip you with the necessary information to make an informed decision about its suitability for your business.
DDS Security Version 1.2 was adopted in 2024. This revision strengthens support for long runnings systems adding new cryptographic algorithms, certificate revocation, and hardness against DoS attacks.
2.
Table of Content
1. Project Structure Practises
1.1 Introduction
1.2 Directory Layout
1.3 The Root Directory
1.4 The src/main Directory
1.5 The src/main Directory
2. Error Handling Practises
2.1 Clean Up Resources in a Finally Block or Use a Try-With-Resource
Statement
2.2 Use a Finally Block
2.3 Prefer Specific Exceptions
2.4 Document the Exceptions You Specify
2.5 Throw Exceptions With Descriptive Messages
2.6 Catch the Most Specific Exception First
2.7 Don’t Catch Throwable
2.8 Don’t Ignore Exceptions
2.9 Don’t Log and Throw
2.10 Wrap the Exception Without Consuming it
3. File Organization
4. Source code style guidelines
5. Implementation Comments
6. Declarations
7. Standards for Statements
8. Naming Conventions
4. 1. Project Structure Practises
1.1. Introduction
The worst large application pitfall is maintaining a huge code base with
hundreds of dependencies - such a monolith slows down developers as they
try to incorporate new features. Instead, partition your code into
components, each gets its own folder or a dedicated codebase, and ensure
that each unit is kept small and simple.
The ultimate solution is to develop small software: divide the whole stack
into self-contained components that don't share files with others, each
constitutes very few files (e.g. API, service, data access, test, etc.) so that it's
very easy to reason about it.
So promoting a uniform directory structure across projects is also one of its
important aspects. Here we’ll be following standard directory layout of a
typical Maven project.
1.2. Directory Layout
A typical Maven project has a pom.xml file and a directory structure based on
defined conventions:
└───maven-project
├───pom.xml
├───README.txt
├───NOTICE.txt
├───LICENSE.txt
└───src
├───main
│ ├───java
│ ├───resources
│ ├───filters
│ └───webapp
5. ├───test
│ ├───java
│ ├───resources
│ └───filters
├───it
├───site
└───assembly
The default directory layout can be overridden using project descriptors, but
this is uncommon and discouraged.
1.3. The Root Directory
This directory serves as the root of every Maven project.
Following are the standard files and subdirectories that are typically found at
root:
● maven-project/pom.xml – defines dependencies and modules needed
during the build lifecycle of a Maven project
● maven-project/LICENSE.txt – licensing information of the project
● maven-project/README.txt – summary of the project
● maven-project/NOTICE.txt – information about third-party libraries
used in the project
● maven-project/src/main – contains source code and resources that
become part of the artifact
● maven-project/src/test – holds all the test code and resources
● maven-project/src/it – usually reserved for integration tests used by
the Maven Failsafe Plugin
● maven-project/src/site – site documentation created using the Maven
Site Plugin
● maven-project/src/assembly – assembly configuration for packaging
binaries
6. 1.4. The src/main Directory
src/main is the most important directory of a Maven project. Anything that is
supposed to be part of an artifact, be it a jar or war, should be present here.
Its subdirectories are:
● src/main/java – Java source code for the artifact
● src/main/resources – configuration files and others such as i18n files,
per-environment configuration files, and XML configurations
● src/main/webapp – for web applications, contains resources like
JavaScript, CSS, HTML files, view templates, and images
● src/main/filters – contains files that inject values into configuration
properties in the resources folder during the build phase
1.5. The src/test Directory
The directory src/test is the place where tests of each component in the
application reside.
Note that none of these directories or files will become part of the artifact.
Let's see its subdirectories:
● src/test/java – Java source code for tests
● src/test/resources – configuration files and others used by tests
● src/test/filters – contains files that inject values into configuration
properties in the resources folder during the test phase
2. Error Handling Practises
2.1 Clean Up Resources in a Finally Block or Use a
Try-With-Resource Statement
It happens quite often that you use a resource in your try block, like an
InputStream, which you need to close afterwards. A common mistake in
these situations is to close the resource at the end of the try block.
public void doNotCloseResourceInTry() {
FileInputStream inputStream = null;
try {
File file = new File("./tmp.txt");
7. inputStream = new
FileInputStream(file);
// use the inputStream to read a file
// do NOT do this
inputStream.close();
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
}
}
The problem is that this approach seems to work perfectly fine as long as no
exception gets thrown. All statements within the try block will get executed,
and the resource gets closed.
But you added the try block for a reason. You call one or more methods
which might throw an exception, or maybe you throw the exception yourself.
That means you might not reach the end of the try block. And as a result, you
will not close the resources.
You should, therefore, put all your clean up code into the finally block or use
a try-with-resource statement.
2.2 Use a Finally Block
In contrast to the last few lines of your try block, the finally block gets always
executed. That happens either after the successful execution of the try block
or after you handled an exception in a catch block. Due to this, you can be
sure that you clean up all the opened resources.
public void closeResourceInFinally() {
FileInputStream inputStream = null;
try {
File file = new File("./tmp.txt");
inputStream = new FileInputStream(file);
// use the inputStream to read a file
} catch (FileNotFoundException e) {
log.error(e);
} finally {
8. if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error(e);
}
}
}
}
2.3 Prefer Specific Exceptions
The more specific the exception is that you throw, the better. Always keep in
mind that a coworker who doesn’t know your code, or maybe you in a few
months, need to call your method and handle the exception.
Therefore make sure to provide them as much information as possible. That
makes your API easier to understand. And as a result, the caller of your
method will be able to handle the exception better or avoid it with an
additional check.
So, always try to find the class that fits best to your exceptional event, e.g.
throw a NumberFormatException instead of an IllegalArgumentException.
And avoid throwing an unspecific Exception.
public void doNotDoThis() throws Exception {
...
}
public void doThis() throws NumberFormatException {
...
}
2.4 Document the Exceptions You Specify
Whenever you specify an exception in your method signature, you should
also document it in your Javadoc. That has the same goal as the previous
best practice: Provide the caller as much information as possible so that he
can avoid or handle the exception.
9. So, make sure to add a @throws declaration to your Javadoc
and to describe the situations that can cause the exception.
/**
* This method does something extremely useful ...
*
* @param input
* @throws MyBusinessException if ... happens
*/
public void doSomething(String input) throws MyBusinessException {
...
}
2.5 Throw Exceptions With Descriptive Messages
The idea behind this best practice is similar to the two previous ones. But this
time, you don’t provide the information to the caller of your method. The
exception’s message gets read by everyone who has to understand what had
happened when the exception was reported in the log file or your monitoring
tool.
It should, therefore, describe the problem as precisely as possible and
provide the most relevant information to understand the exceptional event.
Don’t get me wrong; you shouldn’t write a paragraph of text. But you should
explain the reason for the exception in 1-2 short sentences. That helps your
operations team to understand the severity of the problem, and it also
makes it easier for you to analyze any service incidents.
If you throw a specific exception, it's class name will most likely already
describe the kind of error. So, you don’t need to provide a lot of additional
information. A good example of that is the NumberFormatException. It gets
thrown by the constructor of the class java.lang.Long when you provide a
String in the wrong format.
try {
new Long("xyz");
} catch (NumberFormatException e) {
10. log.error(e);
}
The name of the NumberFormatException class already tells you the kind of
problem. Its message only needs to provide the input string that caused the
problem. If the name of the exception class isn’t that expressive, you need to
provide the required information in the message.
17:17:26,386 ERROR Test Exception Handling:52-java.lang.Number Format
Exception: For input string: "xyz"
2.6 Catch the Most Specific Exception First
Most IDEs help you with this best practice. They report an unreachable code
block when you try to catch the less specific exception first.
The problem is that only the first catch block that matches the exception gets
executed. So, if you catch an IllegalArgumentException first, you will never
reach the catch block that should handle the more specific
NumberFormatException because it’s a subclass of the Illegal Argument
Exception.
Always catch the most specific exception class first and add the less specific
catch blocks to the end of your list.
You can see an example of such a try-catch statement in the following code
snippet. The first catch block handles all NumberFormatExceptions and the
second one all IllegalArgumentExceptions which are not a
NumberFormatException.
public void catchMostSpecificExceptionFirst() {
try {
doSomething("A message");
} catch (NumberFormatException e) {
log.error(e);
} catch (IllegalArgumentException e) {
log.error(e)
}
11. }
2.7 Don’t Catch Throwable
Throwable is the superclass of all exceptions and errors. You can use it in a
catch clause, but you should never do it!
If you use Throwable in a catch clause, it will not only catch all exceptions; it
will also catch all errors. Errors are thrown by the JVM to indicate serious
problems that are not intended to be handled by an application. Typical
examples for that are the OutOfMemoryError or the StackOverflowError.
Both are caused by situations that are outside of the control of the
application and can’t be handled.
So, better don’t catch a Throwable unless you’re absolutely sure that you’re in
an exceptional situation in which you’re able or required to handle an error.
public void doNotCatchThrowable() {
try {
// do something
} catch (Throwable t) {
// don't do this!
}
}
2.8 Don’t Ignore Exceptions
The developer was probably pretty sure that it would never be thrown and
added a catch block that doesn’t handle or logs it. And when you find this
block, you most likely even find one of the famous “This will never happen”
comments.
public void doNotIgnoreExceptions() {
try {
// do something
} catch (NumberFormatException e) {
// this will never happen
}
12. }
Well, you might be analyzing a problem in which the impossible happened.
So, please, never ignore an exception. You don’t know how the code will
change in the future. Someone might remove the validation that prevented
the exceptional event without recognizing that this creates a problem. Or the
code that throws the exception gets changed and now throws multiple
exceptions of the same class, and the calling code doesn’t prevent all of
them.
You should at least write a log message telling everyone that the unthinkable
just had happened and that someone needs to check it.
public void logAnException() {
try {
// do something
} catch (NumberFormatException e) {
log.error("This should never happen: " + e);
}
}
2.9 Don’t Log and Throw
That is probably the most often ignored best practice in this list. You can find
lots of code snippets and even libraries in which an exception gets caught,
logged and rethrown.
try {
new Long("xyz");
} catch (NumberFormatException e) {
log.error(e);
throw e;
}
13. It might feel intuitive to log an exception when it occurred and
then rethrow it so that the caller can handle it appropriately. But it will write
multiple error messages for the same exception.
17:44:28,945 ERROR TestExceptionHandling:65 -
java.lang.NumberFormatException: For input string: "xyz"
Exception in thread "main" java.lang.NumberFormatException: For input
string: "xyz"
at
java.lang.NumberFormatException.forInputString(NumberFormatException.j
ava:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.(Long.java:965)
at
com.stackify.example.TestExceptionHandling.logAndThrowException(TestExc
eptionHandling.java:63)
at
com.stackify.example.TestExceptionHandling.main(TestExceptionHandling.ja
va:58)
The additional messages also don’t add any information. As explained in best
practice #4, the exception message should describe the exceptional event.
And the stack trace tells you in which class, method, and line the exception
was thrown.
If you need to add additional information, you should catch the exception
and wrap it in a custom one. But make sure to follow best practice number 9.
public void wrapException(String input) throws MyBusinessException {
try {
// do something
} catch (NumberFormatException e) {
throw new MyBusinessException("A message that describes the error.", e);
}
}
14. So, only catch an exception if you want to handle it. Otherwise,
specify it in the method signature and let the caller take care of it.
2.10 Wrap the Exception Without Consuming it
It’s sometimes better to catch a standard exception and to wrap it into a
custom one. A typical example of such an exception is an application or
framework-specific business exception. That allows you to add additional
information and you can also implement special handling for your exception
class.
When you do that, make sure to set the original exception as the cause. The
Exception class provides specific constructor methods that accept a
Throwable as a parameter. Otherwise, you lose the stack trace and message
of the original exception which will make it difficult to analyze the exceptional
event that caused your exception.
public void wrapException(String input) throws MyBusinessException {
try {
// do something
} catch (NumberFormatException e) {
throw new MyBusinessException("A message that describes the error.", e);
}
}
3. File Organization
Java source are named as *. java while the compiled Java byte code is named as
*.class file. Each Java source file contains a single public class or interface. Each
class must be placed in a separate file. This also applies to non-public classes too.
If a file consists of sections, they should be separated by blank lines and an optional
comment, identifying each section. Files longer than 2000 lines should be avoided.
Java classes should be packaged in a new java package for each self-contained
project or group of related functionality. Preferably there should be an HTML
document file in each directory briefly outlining the purpose and structure of the
package. Java Source files should have the following ordering: Package and Import
statements, beginning comments, Class and Interface Declarations. There should
15. not be any duplicate import statements. There should not be any
hardcoded values in code. Max. No of Parameters in any class should be 12.
4. Source code style guidelines
Beginning Comments
All source files should begin with a c-style header as follows carrying the Title,
Version, Date in mm/dd/yy format and the copyright information.
The header should be followed the package and import statements and then
the documentation comments exactly in the following sequence and
indented to the same level.
The tags see, since and deprecated are not mandatory and may be used
when required.
Indentation
Four spaces should be used as the unit of indentation. The indentation
pattern should be consistently followed throughout.
16. Left and Right braces
The starting brace should be at the end of the conditional and the ending
brace must be on a separate line and aligned with the conditional. It is
strongly recommended that all conditional constructs define a block of code
for single lines of code.
Wrapping Lines
Lines longer than 80 characters should be avoided. When an expression will
not fit on a single line, it should be broken according to these general
principles:
● Break after a comma.
● Break after an operator.
● Prefer higher-level breaks to lower-level breaks.
● Align the new line with the beginning of the expression at the same
level on the previous line.
● If the above rules lead to confusing code or to code that's squished up
against the right margin, just indent 4 spaces instead.
Example
White Space
Blank Lines
Blank lines improve readability by the setting of sections of code that are
logically related.
Two blank lines should be used in the following circumstances:
● Between sections of a source file
● Between class and interface definitions
17. One blank line should always be used in the following
circumstances:
● Between methods.
● Between the local variables in a method and its first statement.
● Before a block or single-line comment.
● Between logical sections inside a method to improve readability.
● Before and after comments.
Blank Spaces
Blank spaces should be used in the following circumstances:
● A keyword followed by a parenthesis should be separated by a space.
Example: while (true)
● A blank space should appear after commas in argument lists.
● All binary operators except a period ‘.’ should be separated from their
operands by spaces. Blank spaces should never separate unary
operators such as unary minus, increment (“++”), and decrement (“--”)
from their operands.
● The expressions in a for statement should be separated by blank
spaces.
Example:
● Casts should be followed by a blank space.
However blank space should not be used between a method name and its
opening
parenthesis. This helps to distinguish keywords from method calls.
18. 5. Implementation Comments
Java codes should have implementation comments delimited by /*...*/ or //. For
commenting out code a double slash i.e. // is recommended, while for multiple or
single-line comments given as an overview of code, the c-style comments i.e. /* */
should be used. For clarity in code, comments should be followed by a blank line.
Code should have four styles of implementation comments as follows and anything
that goes against a standard should always be documented.
Block Comments
Block comments are used to provide descriptions of files, methods, data
structures and algorithms. Block comments should be used at the beginning
of each file and in places where code is to be explained. They can be used in
places such as before or within methods. Block comments inside a method
should be indented to the same level as the code they describe. A block
comment should be preceded by a blank line to set it apart from the rest of
the code. Block comments should be delimited by /*...*/.
During the process of development, the developer may need to leave some
portions of the code to be reviewed and enhanced later. These portions
should be specifically commented with a /* FIX ME */ tag specifying clearly
the modifications to be made and the date of
marking. This construct should, however, be sparingly used.
Single-Line & Trailing Comments
Short comments can appear on a single line indented to the level of the code
that follows. A single-line comment may be preceded by a blank line if it gives
clarity to code. It is recommended that single-line comments also be
delimited by /*...*/.
Very short comments may appear on the same line as the code they describe
but should be shifted far enough to separate them from the statements.
They may be used for explaining the use of a variable or any statement and
should also be delimited by /*...*/.
Commenting Codes
The // comment delimiter can comment out a complete line or only a partial
line. It should not be used on consecutive multiple lines for text comments,
19. however, it may be used in single or consecutive multiple lines
for commenting out sections of code.
Documentation Comment
Java codes should have documentation comments delimited by /**...*/.
Documentation comments are meant to describe the specification of the
code, from an implementation-free perspective to be read by developers
who might not necessarily have the source code at hand.
Simple Documentation comments should add to the clarity of code and
should be followed by a blank line.
Classes and Interfaces
All comments using Javadoc conventions should be shown. Each class should
be documented describing the purpose of the class, guaranteed invariants,
usage instructions, and/or usage examples.
Variables
First, the static variables should be declared in the sequence public also all
the static variables defined before the methods in the classes, then
protected, then package level and then the private followed by instance
variables in the same sequence. Nature, purpose, constraints, and usage of
static and instances variables should be documented using Javadoc
conventions.
A blank line should follow the declarations.
Operators
The parenthesis should be effectively used to avoid operator precedence.
Methods
20. Each method should declare the Javadoc tags exactly in the
sequence as given below. Each line item begins with an asterisk. All
subsequent lines in the multiline component are to be indented so that they
line up vertically with the previous line. For reference, the Javadoc tags are
explained in detail in Annexure.
Example
Description
Every method should include a header at the top of the source code that
documents all of the information that is critical to understanding it.
A detailed description of the method may include the intent of method i.e. what
and why the method does, what a method should be passed as parameters and
what it returns, any Known bugs, exceptions that the method throws, information
on visibility decisions., how a method changes the object, pre and post conditions,
side effects, dependencies, implementation notes, who should be calling this
method, whether the method should or should not be overridden, were to invoke
super when overriding, control flow or state dependencies that need to exist before
calling this method.
PARAMETER SECTION
Describes the type, class, or protocol of all the methods or routine arguments.
Should describe the parameters intended use and constraints. Every function
parameter value should be checked before being used (Usually check for nulls and
Data Validation).
21. EXAMPLE:
RETURNS SECTION
This section is used to describe the method return type. Specifically, it needs to
detail the actual data type returned, the range of possible return values, and where
applicable, error information returned by the method. Every function should return
the correct value at every function return point or throw correct Exceptions in case
of Errors.
Example:
* @return Possible values are 1..n.
EXCEPTION SECTION
The purpose section is a complete description of all the non-system exceptions that
this method throws. A description of whether the exception is recoverable or not
should also be included. If applicable, a recovery strategy for the exception can be
described here.
In addition to the method documentation, it is also required to include comments
within the methods to make it easier to understand, maintain, and enhance.
● The control structures i.e. what each control structure, such as loop,
does should be documented.
● Any assumptions or calculations should be documented.
● Each local variable should have an end line comment describing its
use.
● Any complex code in a method should be documented if it is not
obvious.
● If there are statements that must be executed in a defined order then
this fact should be documented.
6. Declarations
22. One declaration per line is recommended since it encourages
commenting and enhances the clarity of code. The order and position of
declaration should be as follows:
First, the static/class variables should be placed in the sequence: First public class
variables, protected, package/default level i.e. with no access modifier and then the
private. As far as possible static or class fields should be explicitly instantiated by
the use of static initializers because instances of a class may sometimes not be
created before a static field is accessed.
● Instance variables should be placed in the sequence: First public instance
variables, protected,
● package level with no access modifier and then private.
● Next, class constructors should be declared.
● This should be followed by the inner classes, if applicable
● Class methods should be grouped by functionality rather than by scope or
accessibility to make
● reading and understanding the code easier.
● Declarations for local variables should be only at the beginning of blocks e.g.
at the beginning of a try-catch construct.
● Local declarations that hide declarations at higher levels should be avoided.
For example, the same variable name in an inner block.
● Numerical constants should not be coded directly except 1, 0, -1.
7. Standards for Statements
Each line should contain at most one statement. While compound statements are
statements that contain lists of statements enclosed in braces. The enclosed
statements should be indented one more
level than the compound statement. The opening brace should be at the end of the
line that begins the compound statement. The closing brace should begin a line and
be indented to the beginning of the compound statement. Braces should be used
around all statements, even single statements, when they are part of a control
structure, such as an if-else or for statement. A boolean expression/function should
only be compared to a boolean constant. goto statements should be avoided. Try to
move invariable computation outside the loop.
E.g. D += 9*24*pie *x
Where pie is a constant then 9*24*pie can be moved out and assigned to a local
variable and used inside a loop where x changes in the loop
23. ● return Statements
A return statement with a value should not use parentheses unless they make the
return value more
obvious in some way.
Example:
● if, if-else Statements
The ‘if’ keyword and conditional expression must be placed on the same line.
The if statements must
always use braces {}
Example:
● for Statements
A for statement should have the following form:
When using the comma operator in the initialization or update clause of a for
statement, avoid the complexity of using more than three variables. If
needed, separate statements before the for loop (for the initialization clause)
or at the end of the loop (for the update clause) may be used. The keyword
‘for’ and the parenthesis should be separated by a space and the expressions
in a for statement should be separated by blank space. The statement block
is placed on the next line. The closing curly brace starts in a new line,
indented to match its corresponding opening statement.
24. ● while Statements
The ‘while’ construct uses the same layout format as the ‘if’ construct. The
‘while’ keyword should appear on its own line, immediately followed by the
conditional expression. The keyword ‘while’ and the parenthesis should be
separated by a space. The statement block is placed on the next line. The
closing curly brace starts in a new line, indented to match its corresponding
opening statement.
Example:
● do-while Statements
The DO..WHILE form of the while construct should appear as shown below:
Examples:
The statement block is placed on the next line. The closing curly brace starts
in a new line, indented to match its corresponding opening statement.
● switch Statements
The ‘switch’ construct should use the same layout format as the ‘if’ construct.
The ‘switch’ keyword should appear on its own line, immediately followed by
its test expression. The keyword ‘switch’ and the parenthesis should be
separated by a space.
The statement block should be placed on the next line. The closing curly
brace starts in a new line, indented to match its corresponding opening
statement. Every time a case falls through i.e. does not include a break
statement, a comment should be added where the break statement would
normally be. Every switch statement must include a default case. A break in
the default case is redundant, but it prevents an error if another case is
added later and therefore may be added. All missing switch case break
statements should be correct and marked with a comment.
Examples:
25.
● try-catch Statements
In the try/catch construct the ‘try’ keyword should be followed by the open
brace in its own line. This is followed by the statement body and the close
brace on its own line. This may follow any number of ‘catch’ phrases -
consisting of the ‘catch’ keyword and the exception expression on its own
line with the ‘catch’ body; followed by the close brace on its own line.
Try-catch should be accomplished with finally block to destroys all Objects
not required. There should not be any empty try-catch blocks.
Example:
8. Naming Conventions
26. Naming conventions make programs more understandable by
making them easier to read. Following conventions should be followed while
naming a class or a member:
● Use full English descriptors that accurately describe the variable, method or
class. For example, the use of names like totalSales, currentDate instead of
names like x1, y1, or fn.
● Terminology applicable to the domain should be used. Implying that if user
refers to clients as customers, then the term Customer should be used for
the class, not Client.
● The mixed-case should be used to make names readable with lower case
letters, in general, capitalizing the first letter of class names and interface
names.
● Abbreviations should not be used as far as possible, but if used, should be
documented and consistently used.
● Very long or similar names for classes or methods should be avoided.
● Standard acronyms such as SQL should also be represented in the mixed
case as sqlDatabase().
Standards for Methods
Naming Methods
Methods should be named using a full English description, using mixed case with
the first letter of any non-initial word capitalized. It is also common practice for the
first word of a method name to be a strong, active verbs. e.g. getValue(), printData(),
save() ,delete(). This convention results in methods whose purpose can often be
determined just by looking at its name. It is recommended that accessor methods
be used to improve the maintainability of classes.
Getters
Getters are methods that return the value of a field. The word ‘get’ should be
prefixed to the name of the field, unless it is a boolean field where ‘is’ should be
prefixed to the name of the field . e.g. getTotalSales(), isPersistent(). Alternately the
prefix ‘has’ or ‘can’ instead of ‘is’ for boolean getters may be used. For example,
getter names such as hasDependents() and canPrint() can be created. Getters
should always be made protected, so that only subclasses can access the fields
except when an ‘outside class’ needs to access the field when the getter
27. method may be made public and the setter protected.
Setters
Setters, also known as mutators, are methods that modify the values of a field. The
word ‘set’ should be prefixed to the name of the field for such methods type.
Example: setTotalSales(),setPersistent(boolean isPersistent)
Getters for Constants
Constant values may need to be changed over a period of time. Therefore
constants should be implemented as getter methods. By using accessors for
constants there is only one source to retrieve the value. This increases the
maintainability of the system.
Accessors for Collections
The main purpose of accessors is to encapsulate the access to fields. Collections,
such as arrays and vectors need to have getter and setter method and as it is
possible to add and remove to and from collections, accessor methods need to be
included to do so. The advantage of this approach is that the collection is fully
encapsulated, allowing changes later like replacing it with another structure, like a
linked list.
Examples: getOrderItems(), setOrderItems(), insertOrderItem(), deleteOrderItem(),
newOrderItem()
Method Visibility
For a good design, the rule is to be as restrictive as possible when setting the
visibility of a method. If a method doesn’t have to be private then it should have
default access modifier, if it doesn’ t have to be
default then it should be made protected and if it doesn’ t have to protected only
then it should be made public. Wherever a method is made more visible it should
be documented why.
Access modifiers for methods should be explicitly mentioned in cases like interfaces
where the default permissible access modifier is public.
Standards for Parameters (Arguments) To Methods
28. Parameters should be named following the same conventions as for
local variables. Parameters to a method are documented in the header
documentation for the method using the javadoc@param tag.
However:
● Cascading method calls like method1().method2() should be avoided.
● Overloading methods on argument type should be avoided.
● It should be declared when a class or method is thread-safe.
● Synchronized methods should be preferred over synchronized blocks.
● The fact that a method invokes wait should always be documented
● Abstract methods should be preferred in base classes over those with
default no-op implementations.
● All possible overflow or underflow conditions should be checked for a
computation.
There should be no space between a method/constructor name and the
parenthesis but there should be a blank space after commas in argument lists.
9. Naming Convention standards
Naming Variables
Use a full English descriptor for variable names to make it obvious what the field
represents. Fields, that are collections, such as arrays or vectors, should be given
names that are plural to indicate that they represent multiple values. Variable
names should not start with an
underscore _ or dollar sign $ characters and should be short and meaningful. The
choice of a variable name should be mnemonic i.e., designed to indicate to the
casual observer the intent of its use. Single character variable names should be
avoided except for temporary
“throwaway” variables.
Naming Components
For names of components, full English descriptor should be used, postfixed by the
Component type. This makes it easy to identify the purpose of the component as
well as its type, making it easier to find each component in a list. Therefore names
like NewHelpMenuItem, CloseButton should be preferred over Button1, Button2,
29. etc.
Naming Constants
Constants, whose values that do not change, are typically implemented as static
final fields of classes. They should be represented with full English words, all in
uppercase, with underscores between the words like FINAL_VALUE.
Naming Collections
A collection, such as an array or a vector, should be given a pluralized name
representing the types of objects stored by the array. The name should be a full
English descriptor with the first letter of all non-initial words capitalized like
customers, orderItems, aliases
Naming Local Variables
In general, local variables are named following the same conventions as used for
fields, in other words use of full English descriptors with the first letter of any
non-initial word in uppercase. For the sake of convenience, however, this naming
convention is relaxed for several specific types of local variable like Streams, Loop
counters, Exceptions.Name hiding or data hiding refers to the practice of naming a
local variable, argument, or methods the same or similar as that of another one of
greater scope in same or super class. This may lead to confusion and should be
avoided.
Naming Streams
When there is a single input and/or output stream being opened, used, and then
closed within a method the common convention is to use ‘in’ and ‘out’ for the
names of these streams, respectively.
Naming Loop Counters
Loop counters are a very common use for local variables therefore the use of i, j, or
k, is acceptable for loop counters where they are obvious. However, if these names
are used for loop counters, they should be used consistently. For complex nested
loops the counters should be given full meaningful English descriptors.
30.
10. Variable Assignments
Assigning several variables to the same value in a single statement should be
avoided, i.e., we should avoid constructs like var1 = var2 = var3 = 0;
Assignment operator should not be used in a place where it can be easily confused
with the equality operator.
Embedded assignments in an attempt to improve run-time performance should be
avoided
Variable Visibility
For reasons of encapsulation, fields should not be declared public. All fields should
be declared private unless necessary otherwise. Fields should never be accessed
directly, instead accessor methods should be used i.e. private members should be
accessed through methods. All fields should be declared private and accessed by
getter and setter methods also called accessors.
Documenting & Declaring a Variable
Every field should be documented well enough so that other developers can
understand it. There is a need to document description, all applicable invariants,
visibility decisions. Wherever a field is made more visible it should be documented
why. There are some conventions regarding the declaration and documentation of
local variable. These conventions are:
● Declare one local variable per line of code.
● Document local variables with an end line comment.
● Declare local variables at the top of the block of code.
● Use local variables for one thing only at a time.
● However the following should be taken into consideration while using
variables:
● Instance variables should not be declared public.
● Implicit initializers for static or instance variables should not be relied and
initialization should be explicit.
● Use of static should be minimized as they act like globals. They make
methods more context dependent, hide possible side effects, sometimes
present synchronized access problems and are the source of fragile,
31. non-extensible constructions. Also, neither static variables nor
methods are overridable in any useful sense in subclasses.
● Generally prefer double to float and use int for compatibility with standard
Java constructs and classes.
● Use final and/or comment conventions to indicate whether instance
variables that never have their values changed after construction are
intended to be constant (immutable) for the lifetime of the object.
● Declare and initialize a new local variable rather than reusing/reassigning an
existing one whose value happens to no longer be used at that program
point.
● Assign null to any reference variable that is no longer being used to enable
garbage collection.
● Same names of variables or methods should be avoided in methods and
subclasses
11. Best Practices
Efficient String Concatenation:- For making a long string by adding different small
strings always use append method of java.lang.StringBuffer and never use ordinary
‘+’ operator for adding up strings.
Optimal Use Of Garbage Collector:- For easing out the work of java Garbage
Collector always set all referenced variables used to ‘null’ explicitly thus
de-referencing the object which is no more required by the application and allowing
Garbage Collector to swap away that variable thus realizing memory.
Writing Oracle Stored Procedures Optimally:- Avoid using ‘IN’ and ‘NOT IN’ clause
and rather try to use ‘OR’ operator for increasing the response time for the Oracle
Stored Procedures.
Using variables in any Code Optimally:- Try to make minimum number of
variables in JSP/Java class and try to use already made variables in different
algorithms shared in the same JSP/Java class by setting already populated variable
to ‘null’ and then again populating that variable with new value and then reusing
them.