Showing posts with label design patterns in java. Show all posts
Showing posts with label design patterns in java. Show all posts

July 07, 2022

How to use observable pattern to notify stock market breakouts entry stoploss


Created a stock market application by implementing observable pattern.
In observable pattern the subsribers will be notified when ever there is any event occured in publishers object. In our example stock is the publisher ( Observables) and we kept a list of subscribers list in NotificationManager class.



Stock.java


package com.learning.designpattern.observer;

import java.io.File;
/**
 * Stock class
 * Act as Observable or publisher
 * 
 * Where ever a change happens in Stock object (publisher), it will notifies the subscribers
 * 
 * two methods stoploss() & entry() corresponds to file opening and saving events
 * 
 *
 * 
 * 
 * @author smithesh k k
 *
 */
public class Stock {

private Breakout breakout;
public NotificationManager events;

public Stock() {
this.events = new NotificationManager(); 
}

public void stoploss(String nseTicker) {
if (!nseTicker.isEmpty()) {
this.breakout = new Breakout(nseTicker);
events.notify(Alerts.STOPLOSS.toString(), breakout);
}
}

public void entry(String nseTicker) {
if (!nseTicker.isEmpty()) {
this.breakout = new Breakout(nseTicker);
events.notify(Alerts.ENTRY.toString(), breakout);
}
}

}

NotificationManager.java


/**
 * 
 */
package com.learning.designpattern.observer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  NotificationManager
 *  
 *  keeps the subscriber list ( watchlist), through NotificationManager you can subscribe or unsusbscribe for an event
 *  
 *  notify() helps to notify the subscribers/observer's
 * 
 * 
 * @author bijuvas
 *
 */
public class NotificationManager {

private Map<String, List<EventListener>> watchlist;
public NotificationManager() {
this.watchlist = new HashMap<>();
addEvents();
}
public void notify(String eventType, Breakout file) {
List<EventListener> users = watchlist.get(eventType);
users.forEach(user -> {
user.update(eventType, file);
});
}
public void subscribe(String eventType, EventListener listener) {
List<EventListener> users = watchlist.get(eventType);
users.add(listener);
}
public void unsubscribe(String eventType, EventListener listener) {
List<EventListener> users = watchlist.get(eventType);
users.remove(listener);
}

public void addEvents() {
final Alerts[] alerts = Alerts.values();
for (Alerts event : alerts) {
            this.watchlist.put(event.toString(), new ArrayList<>());
        }
}
}

EventListener.java


/**
 * 
 */
package com.learning.designpattern.observer;

/**
 * EventListener
 * 
 * update()
 * 
 * @author sreekumar
 *
 */
public interface EventListener {
public void update(String eventType, Breakout breakout);
}


EmailNotificationListener.java


/**
 * 
 */
package com.learning.designpattern.observer;

/**
 * EmailNotificationListener
 * 
 * @author perambra kozhikode
 *
 */
public class EmailNotificationListener implements EventListener {
private String email;
public EmailNotificationListener(String email) {
this.email = email;
}

@Override
public void update(String eventType, Breakout breakout) {
System.out.println(" email send to "+email +" for "+eventType);
}

}


MainClass.java


/**
 * 
 */
package com.learning.designpattern.observer;

/**
 * @author valiyakode
 *
 */
public class MainClass {

/**
* @param args
*/
public static void main(String[] args) {
Stock editor = new Stock();
NotificationManager event = editor.events;
event.subscribe(Alerts.STOPLOSS.toString(), new EmailNotificationListener("test@gmail.com"));
editor.stoploss("SGX");
}

}


Breakout.java


/**
 * 
 */
package com.learning.designpattern.observer;

/**
 * @author Zamorins Guruvayoorappan college
 *
 */
public class Breakout{  //implements Strategies{

public Breakout(String nseTicker) {

}


Alerts.java


/**
 * 
 */
package com.learning.designpattern.observer;

/**
 * @author lijesh
 *
 */
public enum Alerts {
TARGET1, ENTRY, TARGET2, STOPLOSS;

}


Full source code


Git url
 

July 25, 2018

Okhttp 3 SSL handshake Exception solved

Okhttp 3 SSL handshake issue solved


When negotiating a connection to an HTTPS server, OkHttp needs to know which TLS versions and cipher suites to offer

package com.belazy.okhttp;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;

import okhttp3.CipherSuite;
import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.TlsVersion;

/**
 * Alan john
 *
 */
public class OkhttpSSLExample {
public static void main(String[] args) {
try {
OkHttpClient client = new OkHttpClient();
client = OkhttpSSLExample.enableTls12OVersion(client).build();
RequestBody body = RequestBody.create(null, new byte[] {});
Request request = new Request.Builder()
.url("https://freesourcecode.okhttp.com/posts/sample")
.post(body).build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
public static OkHttpClient.Builder enableTls12OVersion(OkHttpClient okHttpClient) {
OkHttpClient.Builder client = okHttpClient.newBuilder();
try {
client.connectTimeout(120, TimeUnit.SECONDS).writeTimeout(120,
TimeUnit.SECONDS).readTimeout(130, TimeUnit.SECONDS).build();
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, null, null);
client.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));

List<CipherSuite> customCipherSuites = Arrays.asList(CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384);

ConnectionSpec connectionSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2).cipherSuites(customCipherSuites.toArray(new CipherSuite[0]))
.build();
List<ConnectionSpec> specs = new ArrayList<>();
specs.add(connectionSpec);
specs.add(ConnectionSpec.COMPATIBLE_TLS);
specs.add(ConnectionSpec.CLEARTEXT);
client.connectionSpecs(specs);

} catch (Exception exc) {
exc.printStackTrace();
}
return client;
}
}


Use this code instead

ConnectionSpec connectionSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
     .tlsVersions(TlsVersion.TLS_1_2).cipherSuites(customCipherSuites.toArray(new CipherSuite[0]))
     .allEnabledTlsVersions().supportsTlsExtensions(false).allEnabledCipherSuites().build();

Okhttp works on java 1.7 or above.
API is designed in builder pattern.


OkHttp Interceptors

SLF4J with Logback to create a static singleton HttpLoggingInterceptor

private static final Logger log = LoggerFactory.getLogger(HttpClient.class);
log.debug("interceptor");
OkHttpClient interceptorClient = new OkHttpClient.Builder()
    .addInterceptor(HttpClient.getLoggingInterceptor())
    .build();


content type x-www-form-urlencoded

public static final MediaType FORM = MediaType.parse("multipart/form-data");

RequestBody formBody = new FormBody.Builder().add("likes", "Zombie movies").build();
Request request = new Request.Builder().url("https://datascientist/chippu/chunkz.php").post(formBody).build();
Response response = client.newCall(request).execute();



To enable cache

int cacheSize = 10 * 512 * 512; // 5MB
OkHttpClient.Builder builder = new OkHttpClient.Builder()
        .cache(new Cache(context.getCacheDir(), cacheSize)



April 19, 2012

Design pattern in java

Desing Pattern 

                       In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. So patterns are formalized best practices that you must implement yourself in your application. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved. Many patterns imply object-orientation or more generally mutable state, and so may not be as applicable in functional programming languages, in which data is immutable or treated as such.
Design patterns reside in the domain of modules and interconnections. At a higher level there are architectural patterns that are larger in scope, usually describing an overall pattern followed by an entire system.
                    There are many types of design patterns, like Algorithm strategy patterns addressing concerns related to high-level strategies describing how to exploit application characteristic on a computing platform.
                    Computational design patterns addressing concerns related to key computation identification. Execution patterns that address concerns related to supporting application execution, including strategies in executing streams of tasks and building blocks to support task synchronization.
Implementation strategy patterns addressing concerns related to implementing source code to support program organization, and the common data structures specific to parallel programming.

To Know more about Design pattern in java 


--
Thanking you...


Facebook comments