Saturday, 8 April 2017

Canvas - accept mousewheel events (WPF)

WPF da Canvas ning MouseWheel eventini handle qilish
 
  Odatda Canvas yaratib, unga ixtiyoriyta Children add qilganimizda
  va undagi MouseWheel eventini qayta ishlashimiz uchun:
     canvas1.Background = Brushes.Transparent; deb olishimiz yoki umumiy olganda
     yaratgan canvas1 objectimizning Background qiymatini o'rnatishimiz kerak;
aks holda MouseWheel event ni hadle qila olmaymiz. Chunki default holatda
Canvas Background siz yaratiladi.
Masalan:
 
  ...

  Canvas canvas1 = new Canvas();
  canvas1.Background = Brushes.Transparent;
  Label label = new Label();
  label.Content = "This is Text";
  label.Foreground = Brushes.Blue;
       label.FontSize = 12;
       label.FontWeight = FontWeights.Bold;
  canvas1.Children.add(label);
  canvas1.MouseWheel+=Canvas1_Mouseheel;
  ...
  void Canvas1_Mouseheel()
  {
  ...
  }

Using Column and Row deffinations in WPF


WPF da Column va Row deffination lardan foydalanish

Window da ishlaganimizda yoki UserControlda ishlaganimizda
uni Row va Column larga ajratgan holda contentlarni joylashtirishimiz mumkin
buning uchun Grid quyidagi tartibda aniqlanishi lozim:
   <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="400" Name="column1"/>
            <ColumnDefinition Width="*" Name="column2"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
</Grid>

Ushubu code yordamida biz Grid ni 2ta Column va 1ta Row ga ajratib yaratdik.
Endi Ixtiyoriy elementni add qilishni qaraymiz. Row yoki Column lar avtomatik
0 dan boshlab indexlangan boladi.

...
<Button x:Name="btnResult" Content="Результать" HorizontalAlignment="Left" Margin="78,16,0,0" VerticalAlignment="Top" Width="75" Click="btnResult_Click"
                Grid.Column="0"/>
<Button x:Name="btnReport" Content="Отчёть" HorizontalAlignment="Left" Margin="78,16,0,0" VerticalAlignment="Top" Width="75" Click="btnReport_Click"
                Grid.Column="1"/>
...

Demak, yuqoridagi code ning ma'nosi shundaki,
btnResult tugmasi 1-columnga add qilindi, btnResult esa 2-Column ga add qilindi.

Bu nima uchun kerak?
 Biz Grid ni Column va Row lar yordamida xoxlagancha bolaklarga ajaratib har bir yacheykasiga content joylashtira olamiz!
Savol: Yacheykalarga Splitter qoyish mumkinmi? Ya'ni mouse bilan uning sizeni change qiboladimi?
 Javob: Albatta boladi!
Masalan:
 <Window x:Class="MySamples.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplicationSample2"
        mc:Ignorable="d"
        Title="MainWindow" Height="728" Width="1024" WindowStartupLocation="CenterScreen"
        WindowState="Maximized">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="400" Name="column1"/>
            <ColumnDefinition Width="*" Name="column2"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>      
       
        <Button x:Name="btnResult" Content="Результать" HorizontalAlignment="Left" Margin="78,16,0,0" VerticalAlignment="Top" Width="75" Click="btnResult_Click"
                Grid.Column="0"/>
        <ListBox Name="listBox1" Margin="0,50,0,0"
                 ItemsSource="{Binding Items}" Grid.Column="0" Width="380" Height="650">
            <ListBox.ItemTemplate>
                <DataTemplate>

                    <StackPanel Orientation="Horizontal" Background="Aqua">
                        <Label Content="{Binding recNo}" Width="100"/>
                        <Button Content="{Binding Path=wellName}" Width="120" Background="AliceBlue"/>
                        <Button>
                            <Button.Content>
                                <TextBlock Text="{Binding Path=x0, StringFormat='X: {0}'}" Width="70"/>
                            </Button.Content>
                        </Button>
                        <Button>
                            <Button.Content>
                                <TextBlock Text="{Binding Path=y0, StringFormat='Y: {0}'}" Width="70"/>
                            </Button.Content>
                        </Button>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <GridSplitter Grid.Column="0"
                        HorizontalAlignment="Right"
                        Background="Green"
                        ShowsPreview="False"
                        Width="5" Height="Auto"/>
        <TextBlock Text="this is second block" Grid.Column="1" Margin="10,0,0,0"/>
        <ScrollViewer Grid.Column="1" CanContentScroll="True" Margin="0,0,0,0"
                      HorizontalAlignment="Left" VerticalAlignment="Top" VerticalScrollBarVisibility="Auto"
                      HorizontalScrollBarVisibility="Auto">

            <Canvas Name="canvas1" Grid.Column="1" Width="1500" Height="950" HorizontalAlignment="Left"
                    VerticalAlignment="Top" Margin="0,0,0,0">
            </Canvas>
        </ScrollViewer>
    </Grid>
</Window>
 

Wednesday, 1 March 2017

toString() in Java



Java toString() metodi

Ixtiyoriy ob’yektni string(satr) ko’rinishida ifodalash uchun doimo toString() metodidan foydalanamiz
toString() metodi ob’yektning satr ko’rinishini qaytaradi. Ixtiyoriy ob’yektni chop qilganimizda Java kompilyatori ob’ekt ichidagi toString() metodini ishlatadi. Agar toString() metodi overrid qilinmagan bo’lsa obektning byte ko’rinishi chop qilinadi. toString() metodini overrid qilish orqali ob’ekt haqidagi kerakli ma’lumotlarni qaytarishimiz mumkin.
Misollar:
#1. toString() metodini overrid qilmasdan ob’ektni chop qilish
Book.java:

/**
 * Created by Mansurjon on 3/1/2017.
 */
public class Book {
   
private int id;
   
private String name;
   
private String author;
   
private float price;

   
public int getId() {
       
return id;
    }

   
public void setId(int id) {
       
this.id = id;
    }

   
public String getName() {
       
return name;
    }

   
public void setName(String name) {
       
this.name = name;
    }

   
public String getAuthor() {
       
return author;
    }

   
public void setAuthor(String author) {
       
this.author = author;
    }

   
public float getPrice() {
       
return price;
    }

   
public void setPrice(float price) {
       
this.price = price;
    }

   
public Book(int id, String name, String author, float price) {
       
this.id = id;
       
this.name = name;
       
this.author = author;
       
this.price = price;
    }
}
BookMain.java
package tostring;

/**
 * Created by Mansurjon on 3/1/2017.
 */
public class BookMain {
   
public static void main(String[] args) {
        Book book =
new Book(1,"Философия Java", "B.Ekkel", 82);
        System.
out.println(book);

    }

}
Natija:
Book@1c63996


#2. toString() metodini overrid qilish
Book.java:
package tostring;

/**
 * Created by Mansurjon on 3/1/2017.
 */
public class Book {
   
private int id;
   
private String name;
   
private String author;
   
private float price;

   
public int getId() {
       
return id;
    }

   
public void setId(int id) {
       
this.id = id;
    }

   
public String getName() {
       
return name;
    }

   
public void setName(String name) {
       
this.name = name;
    }

   
public String getAuthor() {
       
return author;
    }

   
public void setAuthor(String author) {
       
this.author = author;
    }

   
public float getPrice() {
       
return price;
    }

   
public void setPrice(float price) {
       
this.price = price;
    }

   
public Book(int id, String name, String author, float price) {
       
this.id = id;
       
this.name = name;
       
this.author = author;
       
this.price = price;
    }

   
@Override
   
public String toString() {
       
return "Kitob haqida ma'lumotlar: {" +
               
"id=" + id +
               
", name='" + name + '\'' +
               
", author='" + author + '\'' +
               
", price=" + price +
                
'}';
    }
}

BookMain.java
BookMain.java
package tostring;

/**
 * Created by Mansurjon on 3/1/2017.
 */
public class BookMain {
   
public static void main(String[] args) {
        Book book =
new Book(1,"Философия Java", "B.Ekkel", 82);
        System.
out.println(book);

    }

}
Natija:
Kitob haqida ma'lumotlar: {id=1, name='Философия Java', author='B.Ekkel', price=82.0}


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

Tasks and Threads

  Differences Between Task And Thread: 1. The Thread class is used for creating and manipulating a thread in Windows.  2. A Task represents ...