Tuesday, 28 February 2017

Using Netty in Java

Usuful links:
1. https://en.wikipedia.org/wiki/Netty_(software)
2. https://habrahabr.ru/post/277695/

NettyClient.java:

package socketclient.netty;

import com.thetransactioncompany.jsonrpc2.JSONRPC2Request;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import socketclient.common.ClientRequest;

/** * Created by Mansurjon on 2/9/2017. */

public class NettyClient<T> {
    protected final int SOCKET_WAIT_TIME = 100;
    protected final int SOCKET_LOOP_MAX_COUNT = 5;
    private  String host;
    private  int port;
    private Channel channel;
    private Boolean isOpen = false;
    private EventLoopGroup group;
    public Channel getChannel() {
        return channel;
    }
    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public boolean start() {
        group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new NettyClientInitializer());
        try {
            channel = bootstrap.connect(host, port).sync().channel();
        } catch (InterruptedException e) {
            return false;
            //e.printStackTrace();        }
        isOpen = channel.isActive();
        return isOpen;
    }
    public String ececute(ClientRequest clientRequest){
        if (isOpen){
            JSONRPC2Request request=new
                JSONRPC2Request(clientRequest.getMethodName(),
                clientRequest.getReqParams(),clientRequest.getRequestID());
            this.channel.write(request.toString() + "\r\n");
            int loopTimeout = 0;
            while (NettyClientHandler.jsonResponse.equals("")&&
                            loopTimeout<SOCKET_LOOP_MAX_COUNT){
                try {
                    loopTimeout++;
                    Thread.sleep(SOCKET_WAIT_TIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            this.channel.flush();
            group.shutdownGracefully();
            return NettyClientHandler.jsonResponse;
        }
        return "";
    }

    public EventLoopGroup getGroup() {
        return group;
    }

    public void close(){
        if (!isOpen){
            this.channel.flush();
            this.channel.close();
            this.channel.close();
            group.shutdownGracefully();
            isOpen = false;group = null;
        }
    }
}


NettyClientHandler.java:

package socketclient.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;

public class NettyClientHandler extends ChannelInboundMessageHandlerAdapter<String> {
    public static String jsonResponse ="";
    @Override    public void endMessageReceived(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("Javob olindi");    }

    @Override    public void messageReceived(ChannelHandlerContext ctx, String jsonString) 
                                              throws Exception {
        jsonResponse = jsonString;
    }
}

NettyClientInitializer.java:

package socketclient.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, 
                                            Delimiters.lineDelimiter()));
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        pipeline.addLast("handler", new NettyClientHandler());

    }
}






Netty Serverni quyidagi ko'rinishda yaratish mumkin:

Server.java:


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/** * Created by Mansurjon on 2014/6/28. */

public class Server {
    private static final int PORT=1010;
    public static void main(String[] args) throws InterruptedException {
        new Server(PORT).run();
    }
    private final  int port;

    public Server(int port){
        this.port = port;
    }

    public void run()  {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            System.out.println("Port:"+port);
            System.out.println("Our server running normally!:)");
            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ServerInitializer());
            ChannelFuture future = bootstrap.bind(port).sync();
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}


ServerHandler.java:

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import common.MethodParser;

/** * Created by Mansurjon on 2014/6/28. */

public class ServerHandler extends ChannelInboundMessageHandlerAdapter<String> {

    private static final ChannelGroup channels = new DefaultChannelGroup();

    @Override    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    }

    @Override    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    }

    @Override    public void messageReceived(ChannelHandlerContext ctx, String jsonString) 
                                                           throws Exception {
        System.out.println("-----------------");
        System.out.println("NettyClient info:"+ctx.channel().remoteAddress());
        System.out.println("Request from client:"+jsonString);
        String result = MethodParser.invoke(jsonString);
        System.out.println("Response to client:"+result);
        System.out.println("-----------------");

        Channel incoming = ctx.channel();
        incoming.write(result+"\r\n");
        incoming.flush();
        incoming.close();
        incoming.closeFuture();
    }

}

ServerInitializer.java:

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/** * Created by Mansurjon on 2014/6/28. */

public class ServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();

        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, 
                                               Delimiters.lineDelimiter()));
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        pipeline.addLast("handler", new ServerHandler());
    }

}



Test qilish uchun:
ClientTest.java

package socketclient;

import socketclient.common.ClientRequest;
import socketclient.common.GetAvlDataRequest;
import socketclient.common.GetObjectListRequest;
import socketclient.common.ServerInfo;

/** * Created by Mansurjon on 2/17/2017. */

public class ClientTest {
    public static void main(String[] args) {
        ServerInfo serverInfo = new ServerInfo.ServerInfoBuilder("localhost",1010).build();
        GetObjectListRequest getObjectListRequest = new GetObjectListRequest(10L,"uz",
"1789uqw-19788912",100L);
        GetAvlDataRequest getAvlDataRequest = new GetAvlDataRequest(9L,"en","avl data");
        ClientRequest clientRequest = new ClientRequest("getObjectList",getObjectListRequest);
        Client client1 = new Client.ClientBuilder(serverInfo).
                                                 setRequest(clientRequest).execute();
        System.out.println("this is server resp.:"+client1.getResponse());
    }
}


Sunday, 26 February 2017

LinkedBlockingQueue in Java Example program

Ma'lumki LinkedBlockingQueue JDK 1.5dan boshlab foydalaniladi.
"Queue" so'zi navbat("Очередь") ma'nosini bildiradi.  LinkedBlockingQueue java.util.concurrent paketiga tegishli. 
BlockingQueue ga element qo'shish uchun put, add yoki offer ishlatiladi. BlockingQueue dan birinchi turgan elementni "olish" uchun take(), poll() yoki remove() ishlatiladi.
Misollar:

Misol #1: BlockingQueue sinfi ob’ektini yaratish va unga qiymat berish

BlockingQueue<String> myQueue = new LinkedBlockingQueue<>(10);
try {

    for (int i=1;i<=10;i++)

        myQueue.put("m"+i);

} catch (InterruptedException e) {

    e.printStackTrace();

}
 
Misol #2: 1-misoldagi myQueue ob’ekti qiymatlarini 2ta thread(поток) yordamida navbatma-navbat o’qish.

Bunda Threadlar tezligi turlicha:

package linkedblockingqueue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/** * Created by Mansurjon on 2/16/2017. */
public class Sample3 {

    private static BlockingQueue<String> myQueue = new LinkedBlockingQueue<>(10);
    public static void main(String[] args) {
        try {
            for (int i=1;i<=10;i++)
                myQueue.put("m"+i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Our queue:"+ myQueue);
        new Thread(new Runnable() {
            @Override            public void run() {

                while (!myQueue.isEmpty())
                    try {
                        String data = myQueue.take();
                        System.out.println("Thread 1:"+data);
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

            }
        },"myThread1").start();

        new Thread(new Runnable() {
            @Override            public void run() {
                while (!myQueue.isEmpty())
                    try {
                        String data = myQueue.take();
                        System.out.println("Thread 2:"+data);
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

            }
        },"myThread2").start();
}}

-------------------------
Natija:
Our queue:[m1, m2, m3, m4, m5, m6, m7, m8, m9, m10]
Thread 1:m1
Thread 2:m2
Thread 1:m3
Thread 1:m4
Thread 1:m5
Thread 1:m6
Thread 1:m7
Thread 2:m8
Thread 1:m9
Thread 1:m10

Saturday, 13 September 2014

Reflections in CSharp


Using Reflections in C#

       Tip ekzemplyarini dnamik yaratishda, tipnig mavjud ob’yekt bilan aloqasini ta’minlashda, mavjud ob’yektning tipini aniqlashda va uning metodlarini ishlatishda(chaqirishda) yoki uning maydonlari va xususiyatlariga dostup olishda Reflectiondan foydalaniladi.
Masalan,
string myStringValue=”Learning reflections in C#”;
System.Type type= myStringValue.GetType();
System.Console.WriteLine(type);
Natija: Sytem.String
Ushbu misolda GetType orqali reflection ishlatildi va ob’yektning tipi aniqlandi
     Reflection – shunday jarayonki unda dastur vaziyatga qarab o’z struktura va ko’rinishini o’zgartirishi mumkin.
Question 1: Dastur ishlayotgan vaqtda biror string tipidagi o’zgaruvchining faqat nominigina bilgan holda uning qiymatini qanday o’zgartirish mumkin?
Answer:
class Program
    {
        private static string a="test1", b="test2", c="test3";
        private static string s = "test string";
        static void Main(string[] args)
        {
            Console.WriteLine("O'zgaruvchi nomini kiriting:");
            string varName = Console.ReadLine();
            Console.WriteLine("O'zgaruvchi yangi qiymatini kiriting:");
            string newValue = Console.ReadLine();
            Type t = typeof(Program);
            FieldInfo fieldInfo=t.GetField(varName,BindingFlags.NonPublic|BindingFlags.Static);
            if (fieldInfo != null)
            {
                string varInfo1 = string.Format("{0} o'zgaruvchining joriy qimati:{1}",fieldInfo.Name,fieldInfo.GetValue(null));
                Console.WriteLine(varInfo1);
                fieldInfo.SetValue(null,newValue);
                string varInfo2 = string.Format("{0} o'zgaruvchining yangi qimati:{1}", fieldInfo.Name, fieldInfo.GetValue(null));
                Console.WriteLine(varInfo2);
            }
            else Console.WriteLine("Bunday o'zgaruvchi aniqlanmagan!");
           
            Console.ReadLine();
        }
    }

Joriy koddagi assembly(project, ya'ni assemblyni build qilganda .exe yoki .dll fayl ko'rinishga o'tadi) tiplarni(projectdagi classlar, interfacelar,…) aniqlash
Projectda quyidagilar aniqlangan bo’lsin:
namespace xyz.Test1.fullinfo
{
    public class ClassTest
    {
       //…
    }
}
namespace ReflactionTest
{
    abstract class AbstractClassTest
    {
       //…
    }
}
namespace ReflactionTest
{
    interface Interface1
    {
       //…
    }
}
Barcha assembly tiplar ro’yxatini quyidagi kod yordamida aniqlash mumkin:
namespace ReflactionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Type[] assemblyTypes = assembly.GetTypes();
            foreach (Type t in assemblyTypes)
                Console.WriteLine(t.Name);
            Console.ReadLine();
        }
    }
}
Natija:
ClassTest
ArstractClassTest
Interface1

Sinf nomi orqali undagi metodni Reflection yordamida ishlatish:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Type testType = typeof(TestClass);
            ConstructorInfo ctor = testType.GetConstructor(System.Type.EmptyTypes);
            if(ctor != null)
            {
                object instance = ctor.Invoke(null);
                MethodInfo methodInfo = testType.GetMethod("TestMethod");
                Console.WriteLine(methodInfo.Invoke(instance, new object[] { 20 }));
            }
            Console.ReadKey();
        }
    }

    public class TestClass
    {
        private int testValue = 35;

        public int TestMethod(int numberToAdd)
        {
            return this.testValue + numberToAdd;
        }
    }
}

Question 2: Base Calss “bolalari”ni qanday aniqlash mumkin?
Answer 1:
Masalan, BaseClass nomi BasePerson b.sa:
 var result = AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(assembly => assembly.GetTypes())
                       .Where(type => type.IsSubclassOf(typeof(BasePerson)));
            foreach (Type item in result)
            {
                var personObject = Activator.CreateInstance(item);
                MethodInfo methodInfo = item.GetMethod("<Person sinfidagi metod nomi>");
                //ParameterInfo[] parameters = methodInfo.GetParameters();
                object[] parameters = new object[] { parametr1,parametr2,…,parametrN };
                var methodResult = methodInfo.Invoke(personObject, parameters);
                     …
            }
Answer 2:
BaseLogic sinfi abstract shaklda aniqlangan va u check(column1,column2) metodiga ega, undan inherities olgan barcha sinflardning check metodi natijalarini olish:
` var logicList = new List<BaseLogic>();
                var types = Assembly.GetExecutingAssembly().GetTypes();
                foreach (var type in types)
                {
                    if (type.IsSubclassOf(typeof(BaseLogic)))
                    {
                        logicList.Add((BaseLogic)Activator.CreateInstance(type));
                    }
                }
Ishlatishda:
logicList.Where(w=>w.Weight<=weight).ToList().ForEach(logic=>
            {
                primeryKeyColumn.Parent = _tables.Find(f => f.ID == primeryKeyColumn.ParentID);
                forignKeyColumn.Parent = _tables.Find(f => f.ID == forignKeyColumn.ParentID);
                var relationship = logic.Check(primeryKeyColumn,forignKeyColumn);
}

Kabi bo’ladi

Used LINKS:

Ifloslangan havoda yugurish bilan shug’ullanish: xavflar, maslahatlar va Toshkentdagi vaziyat

  Bugun(19.11.2025) Toshkentning havo ifloslanish darajasi — AQI 200–250oralig’ida bo’ldi Yugurish paytida o‘pka orqali o‘tadigan havo hajm...