Thursday, September 04, 2014

Java 7/JEE 6 features

  • Swing
  • IO and New IO
    • The java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system. A zip file system provider is also available in JDK 7. The following resources provide more information:
    • File I/O (featuring NIO 2.0) in the Java Tutorials; NIO stands for non-blocking I/O
    • Developing a Custom File System Provider
    • Zip File System Provider
  • Networking
    • The URLClassLoader.close method has been added. This method effectively eliminates the problem of how to support updated implementations of the classes and resources loaded from a particular codebase, and in particular from JAR files
  • Security
  • Concurrency Utilities
  • Rich Internet Applications (RIA)/Deployment
  • Requesting and Customizing Applet Decoration in Dragg able Applets
  • Embedding JNLP File in Applet Tag
  • Deploying without Codebase
  • Handling Applet Initialization Status with Event Handlers
  • Java 2D
  • Java XML - JAXP, JAXB, and JAX-WS
  • Internationalization
  • java.lang Package -Multithreaded Custom Class Loaders in Java SE 7
  • JDBC 4.1 introduces the following features:
    • The ability to use a try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement
    • RowSet 1.1: The introduction of the RowSetFactory interface and the RowSetProvider class, which enable you to create all types of row sets supported by your JDBC driver.
  • Binary Literals - In Java SE 7, the integral types (byte, short, int, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number.
  • Underscores in Numeric Literals - Any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.
  • Strings in switch Statements - You can use the String class in the expression of a switch statement.
  • Type Inference for Generic Instance Creation - You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.
  • Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods - The Java SE 7 complier generates a warning at the declaration site of a varargs method or constructor with a non-reifiable varargs formal parameter. Java SE 7 introduces the compiler option -Xlint:varargs and the annotations @SafeVarargs and @SuppressWarnings({"unchecked", "varargs"}) to supress these warnings.
  • The try-with-resources Statement - The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements the new java.lang.AutoCloseable interface or the java.io.Closeable interface can be used as a resource. The classes java.io.InputStream, OutputStream, Reader, Writer, java.sql.Connection, Statement, and ResultSet have been retrofitted to implement the AutoCloseable interface and can all be used as resources in a try-with-resources statement.
  • Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking - A single catch block can handle more than one type of exception. In addition, the compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throws clause of a method declaration.

Deprecated features in Java 7

Deprecated features in Java EE 6

  • Java API for RESTful Web Services (JAX-RS) JSR 311
  • Contexts and Dependency Injection for the Java EE Platform (CDI) JSR 299
  •  JSR 330: Dependency Injection for Java
  • Bean Validation  JSR 303
  • Enhanced Web Tier Capabilities
    •  web fragments and shared framework pluggability
    •  Servlet 3.0, JSR 315 -  asynchronous processing and support for annotations.
    • JSF 2.0, JSR 314 (facelets)
    • Support for Ajax in JSF 2.0
  •  JSR 318: Enterprise JavaBeans 3.1
    • No-interface view
    • Singletons.
    • Asynchronous session bean invocation.
    • Simplified Packaging
    • EJB Lite
    • embeddable API and container for use in the Java SE environment
    • , JSR 317: Java Persistence 2.0.
  • Profiles and Pruning
Spring Vs JEE 6

CDI Info

Components bound to lifecycle contexts
Webtier to enterprise tier wiring
CDI brings transactional support to web tier
CDI introduces the concept of managed beans
Annotations to define scope, qualifier, transactions, security, pooling
@inject, @default, @alternative, @named

@TransactionalAttribute, @RolesAllowed, @sessionScoped, @Qualifier


Interceptors

Monday, August 25, 2014

Oracle PL/SQL functions and procedures

PL/SQL Function

DECLARE
   a number;
   b number;
   c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
    z number;
BEGIN
   IF x > y THEN
      z:= x;
   ELSE
      Z:= y;
   END IF;

   RETURN z;
EXCEPTION
   WHEN NO_DATA_FOUND THEN
      DBMS_OUTPUT.PUT_LINE('No such employee: ' || Emp_number);

END;

Calling a function from another function/procedure
BEGIN
   a:= 23;
   b:= 45;
   c := findMax(a, b);
   dbms_output.put_line(' Maximum of (23,45): ' || c);

END;

PL/SQL Procedure

DECLARE
   a number;
   b number;
   c number;

PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
   IF x < y THEN
      z:= x;
   ELSE
      z:= y;
   END IF;
EXCEPTION
   WHEN NO_DATA_FOUND THEN
      DBMS_OUTPUT.PUT_LINE('No such employee: ' || Emp_number);
END;

Calling a procedure
  1. From the SQL prompt.
 EXECUTE [or EXEC] procedure_name;
  1. Within another procedure – simply use the procedure name.
 procedure_name;

Friday, August 22, 2014

Rule Engine

Drools - steps to use it in a typical program
  1. create working memory
  2. asset objects (insert into working memory)
  3. fire all rules
  4. retrieve objects
Rule attributes
- name
- group
- description
- priority

Rules
  1. Production rules (inference rules) - if x, then y
  2. Reaction Riles - wait for a set of events
  3. Stateful
Rete algorithm (Forward Chaining)
  1. iterate through antecedants
  2. each time an antecedant is matched, add knowledge of consequence
  3. do this until goal is reached
Guvnor - Business rules management system

RESTful WebServices - API Keys


Http methods
Get (read), header, post(create), put(update), trace, delete(delete)

API keys are used for
  • Limit API usage, security

API flow sequence
  • Log in to PayPal developer site - register your application by logging into the PayPal Developer site using a PayPal account, and by going to the Applications tab. 
  • PayPal provides a client_id and secret - You will be issued a set of test credentials (‘client_id’ and ‘secret’) that you can use to authenticate your API calls using the OAuth 2.0 protocol.
  • Client calls /token endpoint with client_id and secret_key - You then obtain an access token for your application by sending a request to the ‘/v1/oauth2/token’ endpoint. You need to authenticate your access token request (using HTTP Basic Auth) with your application credentials (client_id and secret_key) obtained as described above. The ‘client_id’ and ‘secret’ becomes your user-id and password in HTTP Basic Auth.  If you’re using cURL, you can pass the client_id and secret as -u ":"
  • PayPal returns the access token - PayPal, acting as the “authorization server”, verifies your application credentials and returns an access token. The specific kind of access token that PayPal provides is a “Bearer Token”. PayPal also provides the token type in the response, which indicates the type as Bearer.
  • Client calls PayPal Rest API with access token - When you make the API calls, make request by adding the access token in the ‘Authorization’ header using the following syntax (as defined in the OAuth 2.0 protocol):
Authorization: {tokenType} {accessToken}
    Example: Authorization: Bearer EEwJ6tF9x5...4599F

    • Access token validity and expiration - PayPal-issued access tokens can be used to access all the REST API endpoints. These tokens have a finite lifetime and you must write code to detect when an access token expires. You can do this either by keeping track of the ‘expires_in’ value returned in the response from the token request (the value is expressed in seconds), or handle the error response (401 Unauthorized) from the API endpoint when an expired token is detected.
    link: https://developer.paypal.com/docs/integration/direct/paypal-oauth2/

    Common Web Security vulnerabilities


      Principle to remember: Filter input escape output
      SQL injection (user input is not filtered for special characters) 

      Example:
      1. A form is displayed on a web application that contains some text fields
      2. These text fields data are not validated on the client/server side so it lets any data in
      3. The data entered is directly used in building an SQL query
      4. A malicious user enters some bad data in the text field which contains an executable SQL statement to corrupt the database or display unintended results
      5. So, instead of executing "SELECT * FROM products WHERE id_product=$id_product", the application executes "SELECT * FROM products WHERE id_product=$id_product UNION Select * from USERS"
      Cross Site Scripting (code injection by malicious to pages used by real users) - this happens when developers do not check the input and let arbitrary data in to the database. Then, this arbitrary data (such as a javascript embedded in script tag)  is displayed on the web page. When a user performs an action on the web page, sensitive data such as sessionId or personal data is sent unknowingly to the malicious web site. This is very similar to SQL injection but instead of sending SQLs in text fields, a text containing script tag is sent to the server side to be stored in the database only to be displayed later.

      Example:
      1. A real website displays a form containing name etc.
      2. Since there is a bug in the server side code, it lets any text to be entered in the text field
      3. A malicious user enters a text which contains some javascript embedded in script tags
      4. The server side application persists this data into database
      5. The application has a web page that displays a list of all names
      6. When a real user retrieves this webpage, it displays the names but also executes javascript
      7. When the user submits or performs some action on this webpage, it sends cookies etc to a malicious website.
      CORS - Cross Origin Resource Sharing

      CSRF - Cross Site Request Forgery
      This attack happens if a user does not logout from a good website. Say for example, a good website transfers money using this URL: amount=100.00&routingNumber=1234&account=9876

      A evil website may have HTML code with hidden input fields for amount, routing number and account. It may have an image that says "Win MoneY" which when clicked will submit the hidden form fields to the URL for the good website. Since the user is already authenticated and forgot to logoff, the transaction will be executed without the user knowing about it.

      One solution is to use the Synchronizer Token Pattern. This solution is to ensure that each request requires, in addition to our session cookie, a randomly generated token as an HTTP parameter. When a request is submitted, the server must look up the expected value for the parameter and compare it against the actual value in the request. If the values do not match, the request should fail.

      We can relax the expectations to only require the token for each HTTP request that updates state. This can be safely done since the same origin policy ensures the evil site cannot read the response. Additionally, we do not want to include the random token in HTTP GET as this can cause the tokens to be leaked. So, the new URL looks like this:
      amount=100.00&routingNumber=1234&account=9876&_csrf=

      You will notice that we added the _csrf parameter with a random value. Now the evil website will not be able to guess the correct value for the _csrf parameter (which must be explicitly provided on the evil website) and the transfer will fail when the server compares the actual token to the expected token.

      https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html

      If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.

      Improper identity and access management
      - forget password mgmt features

      Not implementing API keys for clients

      Denial of service
      - flooding a website/webservice with requests so that legitimate users can't use it

      Wednesday, August 06, 2014

      Configuring SSL offloading (LB-OHS-WL)

      LB (F5-SSL) to WL(http) plugin to WL cluster(http)

      • Sticky sessions is default
      • SSL ends at LB
      • In F5, I needed to configure a header to be passed with the requests called WL-Proxy-SSL and set the value to true (WL-Proxy-SSL: true)
      • Cockie name goes in the plugin properties (JSESSIONID by default) and deployment descriptor
      • WLProxySSLPassThrough should be set to ON, so that the OHS proxy/plug-in will pass the WL-Proxy-SSL header on to WebLogic Server
      • Configure the Adminserver so that it would acknowledge the proxy plugin headers.  This field is titled "WebLogic - Plug-In Enabled" and can be found on the page Configuration->General in the Advanced section

      Tuesday, July 15, 2014

      SOAP WebServices

      SOAP
      • port type is interface
      • binding is implementation

      Monday, May 19, 2014

      J2EE architecture notes

      Designer -- thinks about functional requirements
      Architect - thinks about non-functional requirements

      Architecture
      1. software elements
      2. relationship among elements
      3. external visible properties of these elements

      non-functional requirements
      1. constraints (financial, processing )
      2. systemic quality (*bility)

      Goals of architecture
      1. resolve issues related to non-functional requires
      2. quality
      3. reduce risks, document them
      4. facilitate design
      5. document why certain decisions are made
      6. governance, policy making, best practice

      Architecture workflow
      1. select an arch type of the system (tiers, layers)
      2. Create a detailed deploy diagram for arch significant usecases
      3. refine arch model to satisfy non functional requirements
      4. Create and test arch baseline
      5. Document tech choices
      6. Create a arch template from the final deployment diagram

      Tuesday, January 28, 2014

      Gym schedule

      same as other scheduling application for small business
      - shows

      priests small business app


      1. schedule events/appointments, integrated with calendar
      2. lists supplies needed
      Customer
      - Search for a priest
      - Search for a pooja service
      - Select a priest and pooja, date
      - Pay for service
      - Order supplies

      Priest
      - Accept a pooja request
      - List events
      - Add his details to directory
      - Look at fees, reports

      Tuesday, December 24, 2013

      Git workflow commands

      Pull from your remote repository to make sure everything is up to date
        git pull origin master
      

      Create a new local branch for keeping your changes way from your local master branch
        git branch my_new_feature
      

      Switch to that branch and start working
        git checkout my_new_feature
      

      After finishing work and running successfully any cukes/specs/tests, commit
        git commit -am "Implemented my new super duper feature"
      

      Then, switch back to local master and pull if you need to also merge any changes since you first pulled
        git checkout master
        git pull origin master
      

      Merge the local feature branch to master and run any cukes/specs/tests and if everything passes push changes
        git merge my_new_feature
        git push origin master
      

      This is my preference: I delete the temporary local branch when everything is merged and pushed
        git branch -d my_new_feature
      
      
      reference(copied from): http://amiridis.net/posts/13 

      Monday, October 28, 2013

      Coherence 3.6 FAQ

      coherence Command line console is also a full member of the cluster
      If you want to just query, not to join the cluster as a member, then use coherence-extend or 3.7 has REST API client

      if request efects more than 20% of cluter members, unicast is used Otherwise multicasr is used.
      ACcknowledgement is always unicast.
      TCMP = unicast + multicast
      unicast is based on destination address
      multicasr is no destination, broadcast

      two requirements for objects to be put in cache:
      java beans
      some form of serialization

      3 args should match for all cluster members
      -Dtangosol.coherence.ttl=0
      -Dtangosol.coherence.cluster=XYZCluster
      -Dtangosol.coherence.clusterport=7009

      local_storage = false means, the member joins the cluster as a non-storage memeber. It does not store any data but stil can put and get data..

      Implement PortableObject interface for cross-platform communication

      I got class sizes of 339, 93 and 75 for default, ExternalizableLite and PortableObject.

      LocalCache
      - No fault tolerance
      - exists along with application heap
      - instant read and writes


      replicated cache
      - writes are a problem because cache.put() returns only when all caches are synced with the write (put is blocking or synchronous call)
      - provides zero latency reads
      - since cache is replicated, it provides high availability
      - suited for read only or read mostly (data loaded during initialization)

      partitioned cache
      - data is assigned to certain buckets and these buckets are assigned to each partition
      - synchronously maintains backup of partitions on other machines
      - we always know the mapping between data key and partition owner so reads are always 1 network hop, writes
      are 2 (one for write and one for backup write)
      - number of partitions are always prime number

      Near cache
      -Holds frequently used data from partition
      -If some other member updates data, it is possible to update it in near cache by using synchronization strategy
      -if the local client asks for a data item existing in near cache that changed on remote partition, remote partition will first remove the data item from near cache to invalidate it. Then, this data item is read from remote partition.
      - Use to defined above