Archive for the ‘Genel’ Category.

Java Deserialization:Reading an Object Stream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.*;
public class UnserializeBoolean {

    public UnserializeBoolean() {
        Boolean booleanData = null;
        try {
            FileInputStream fis = new FileInputStream("boolean.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);
            booleanData = (Boolean) ois.readObject();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Unserialized boolen from " + "boolean.ser");
        System.out.println("Boolean data: " + booleanData);
        System.out.println("Compare data with true: " + booleanData.equals(new Boolean("true")));
    }
    public static void main(String [] args) {
        UnserializeBoolean uab = new UnserializeBoolean();
    }
}

Java Serialization: Writing an Object Stream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.io.*;
public class SerializeBoolean {
    public SerializeBoolean() {
        Boolean booleanDAta = new Boolean("true");
        try {
            FileOutputStream fos = new FileOutputStream("boolean.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(booleanDAta);
            oos.close();
        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }
    public static void main(String [] args) {
        SerializeBoolean ab = new SerializeBoolean();
    }
}

Java ReentrantReadWriteLock Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.xml.crypto.Data;

public class ReadWriteMap {
    final Map m = new TreeMap();
    final ReentrantReadWriteLock rw1 = new ReentrantReadWriteLock();
    final Lock r = rw1.readLock();
    final Lock w = rw1.writeLock();

    public Data get(String key) {
        r.lock();
        try {
            return m.get(key);
        } finally  {
            r.unlock();
        }
    }

    public Data put(String key,Data value) {
        w.lock();
        try {
            return m.put(key, value);
        }
        finally {
            w.unlock();
        }
    }

    public void clear() {
        w.lock();
        try {
            m.clear();
        }
        finally {
            w.unlock();
        }
    }
}

Java BlockingQueue Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Producer implements Runnable {
   private final BlockingQueue queue;
   Producer(BlockingQueue q) { queue = q; }
   public void run() {
     try {
       while(true) { queue.put(produce()); }
     } catch (InterruptedException ex) { ... handle ...}
   }
   Object produce() { ... }
 }

 class Consumer implements Runnable {
   private final BlockingQueue queue;
   Consumer(BlockingQueue q) { queue = q; }
   public void run() {
     try {
       while(true) { consume(queue.take()); }
     } catch (InterruptedException ex) { ... handle ...}
   }
   void consume(Object x) { ... }
 }

 class Setup {
   void main() {
     BlockingQueue q = new SomeQueueImplementation();
     Producer p = new Producer(q);
     Consumer c1 = new Consumer(q);
     Consumer c2 = new Consumer(q);
     new Thread(p).start();
     new Thread(c1).start();
     new Thread(c2).start();
   }
 }

Java TimerClass and TimerTask Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

public class TimerReminder {
    Timer timer;

    public TimerReminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000);
    }

    class RemindTask extends TimerTask {
        public void run() {
            System.out.format("Time's up!%n");
            timer.cancel(); //Terminate the timer thread
        }
    }

    public static void main(String [] args) {
        System.out.format("About to schedule task.%n");
        new TimerReminder(5);
        System.out.format("Task scheduled.%n");
    }
}

OpenGl glPointSize() Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include
#include

using namespace std;

void glut_display_cb(void);
void my_init(void);

int main(int argc, char * argv[])
{
    glutInit(&argc, argv);
    glutInitWindowSize(600, 600);
    glutInitWindowPosition(250, 250);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutCreateWindow("glPointSize example");
    glutDisplayFunc(glut_display_cb);

    my_init();
    glutMainLoop();

    return 0;
}

void glut_display_cb(void){
    glClearColor(0.9f, 0.9f, 0.9f, 0.9f);
    glClear(GL_COLOR_BUFFER_BIT);
    glBegin(GL_POINT);
         glVertex2f(points[i].get_X(),points[i].get_Y());
    glEnd();
}

void my_init(void)
{
    // any initialization before the main loop of GLUT goes here
    glViewport(0,0,600,600);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-300,300,-300,300,-10,10);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glPointSize(10);
}

OpenGl glLineWidth() Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include
#include

using namespace std;

void glut_display_cb(void);
void my_init(void);

int main(int argc, char * argv[])
{
    glutInit(&argc, argv);
    glutInitWindowSize(600, 600);
    glutInitWindowPosition(250, 250);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutCreateWindow("glPointSize example");
    glutDisplayFunc(glut_display_cb);

    my_init();
    glutMainLoop();

    return 0;
}

void glut_display_cb(void){
    glClearColor(0.9f, 0.9f, 0.9f, 0.9f);
    glClear(GL_COLOR_BUFFER_BIT);
  glLineWidth (3);
    glBegin(GL_TRIANGLE_FAN);
    glVertex2f(1.0f, 0.0f);
    glVertex2f(90.0f, 10.0f);
    glVertex2f(90.0f, 90.0f);
    glVertex2f(10.0f, 90.0f);
        glVertex2f(100.0f, 45.0f);
  glEnd();
}

void my_init(void)
{
    // any initialization before the main loop of GLUT goes here
    glViewport(0,0,600,600);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-300,300,-300,300,-10,10);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

Netbeans Kullanarak Ubuntuda C++ ile OpenGl Kodlama

OpenGl kodlamadan önce ekran kartımızın ubuntu tarafından tanındığından emin olmamız gerekmetedir. Bunun için glxinfo komutunu kullanıyoruz.

ugur@ugur-laptop:~$ glxinfo
name of display: :0.0
display: :0  screen: 0
direct rendering: Yes

konsolda direct rendering:yes satırını görmemiz ekran kartımızın tanımlı olduğunu gösteririr. Ayrıca glxgears komutu ile de ekran kartı test edilebilir. Daha sonra ubuntuda visual effects lerin kapalı olduğundan emin olmalıyız. A

İlk önce www.netbeans.com adresinden netbeans ın son sürümünü indiriyoruz. İnen dosyanın executable iznini verdikten sonra konsoldan ./dosya_adı şeklinde çalıştırıp netbeans kurulumumuzu tamamlıyoruz. Netbeans i kurduktan sonra OpenGl için gerekli kütüphaneleri synaptic package manager dan indiriyoruz. İndirmemiz gereken dosyalar freeglut3,freeglut3-dbg,freeglut3-dev ve glui-dev dir. Bu dosyaları yükledikten sonra opengl ve glut için gerekli kütüphaneleri kullanabileceğiz.

Şimdi netbeans in build path ine kütüphanelerimizi eklememiz gerekmektedir. Bunun projeye sağ tıklayıp properties->linkers ın altındaki sağ menüde yer alan libraries ın yanındaki … butonundan

/usr/lib/libGLU.a
/usr/lib/libglui.a
/usr/lib/libglut.a

kütüphanelerini ekliyoruz. Artık netbeans de opengl kodlayıp derleyebiliriz.

Uğur Dönmez

Get HTML from an URL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.io.*;
import java.net.*;

public class GetHTML {

    public String getHTML(String urlToRead) {
        URL url; // The URL to read
        HttpURLConnection conn; // The actual connection to the web page
        BufferedReader rd; // Used to read results from the web page
        String line; // An individual line of the web page HTML
        String result = ""; // A long string containing all the HTML
        try {
            url = new URL(urlToRead);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = rd.readLine()) != null) {
                result += line;
            }
            rd.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

JFreeChart

1. Overview

JFreeChart is a free chart library for the Java(tm) platform. It is designed for use in applications, applets, servlets and JSP. JFreeChart is distributed with complete source code subject to the terms of the GNU Lesser General Public Licence, which permits JFreeChart to be used in proprietary or free software applications.

2. Features

JFreeChart can generate pie charts, bar charts (regular and stacked, with an optional 3D-effect), line charts, scatter plots, time series charts (including moving averages, high-low-open-close charts and candlestick plots), Gantt charts, meter charts (dial, compass and thermometer), symbol charts, wind plots, combination charts and more. Additional features include: • data is accessible from any implementation of the defined interfaces; • export to PNG and JPEG image file formats (or you can use Java’s ImageIO library to export to any format supported by ImageIO); • export to any format with a Graphics2D implementation including: – PDF via iText (http://www.lowagie.com/iText/); – SVG via Batik (http://xml.apache.org/batik/); • tool tips; • interactive zooming; • chart mouse events (these can be used for drill-down charts or information pop-ups); • annotations; • HTML image map generation; • works in applications, servlets, JSP (thanks to the Cewolf project1) and applets; • distributed with complete source code subject to the terms of the GNU Lesser General Public License (LGPL).

3. Configuring Eclipse for JFreeChart

To begin with, you need to download the JFreeChart and JCommon distributions, unpack them on your local machine, and generate the API documentation. The following steps are necessary: 1. Download the latest version of the JCommon class library: http://www.jfree.org/jcommon/ …and unpack it to a directory on your computer (almost anywhere is fine). 2. From the ant subdirectory of the just-unpacked JCommon, run ant javadoc to generate the Javadocs locally. If you are unfamiliar with Ant, you can skip this step, but then Eclipse won’t be able to show you the Javadoc popups for JCommon. 3. Download the latest version of the JFreeChart class library: http://www.jfree.org/jfreechart/ …and unpack it to a directory on your computer (again, almost anywhere is fine). 4. From the ant subdirectory of the just-unpacked JFreeChart, run ant javadoc to generate the Javadocs locally. As with step 2, you can skip this step, but then you’ll be missing the API documentation. Now, launch Eclipse, and carry out the following steps to configure JFreeChart and JCommon as user libraries: 5. In Eclipse, select Preferences… from the Window menu, then choose the Java –>Build Path -> User Libraries node in the tree. 6. Click on the New… button and enter JCommon 1.0.12 as the name for a new user library. 7. Ensure that the JCommon 1.0.12 item is selected in the list, then click the Add JARs… button and select the jcommon-1.0.12.jar file from the JCommon directory created back in step 1. 8. Double-click the item that says “Source attachment: (None)”, then click the External folder… button, then select the source directory for JCommon. 9. Double-click the item that says “Javadoc location: (None)”, then click the Browse…button, then select the javadoc directory from JCommon (see step 2). 10. Click on the New… button and enter JFreeChart 1.0.7 as the name for a new user library. 11. Ensure that the JFreeChart 1.0.7 item is selected in the list, then click on the Add JARs… button and select the jfreechart-1.0.7.jar file from the JFreeChart directory (see step 3). 12. Double-click the item that says “Source attachment: (None)”, then click the External folder… button, then select the source directory for JFreeChart. 13. Double-click the item that says “Javadoc location: (None)”, then click the Browse…button, then select the javadoc directory from JFreeChart (see step 4).

4. Creating an Eclipse Project that uses JFreeChart

Now that JFreeChart and JCommon are configured as user libraries, it is straightforward to develop an application that uses these libraries: 1. In Eclipse, select New -> Project… from the File menu, select Java Project from the list and click the Next button. 2. Enter MyAppThatUsesJFreeChart as the project name and click the Finish button. 3. Right-click on the project in the Package Explorer then select Properties from the pop-up menu. In the properties window click on the Add Library… button and select both the JCommon and JFreeChart libraries. Click OK. 4. Create a new source file.

5. Example Codes and Charts

5.1 Bar Chart
Code

import java.awt.Color; import java.awt.Dimension; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartFrame; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.data.category.DefaultCategoryDataset; public class Bar { public static void main3(String [] args){ DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(1.0, “Row 1″, “Column 1″); dataset.addValue(5.0, “Row 1″, “Column 2″); dataset.addValue(3.0, “Row 1″, “Column 3″); dataset.addValue(2.0, “Row 2″, “Column 1″); dataset.addValue(3.0, “Row 2″, “Column 2″); dataset.addValue(2.0, “Row 2″, “Column 3″); JFreeChart chart = ChartFactory.createBarChart( “Bar Chart Demo”, // chart title “Category”, // domain axis label “Value”, // range axis label dataset, // data PlotOrientation.VERTICAL, // orientation true, // include legend true, // tooltips? false // URLs? ); chart.setBackgroundPaint(Color.white); CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.setBackgroundPaint(Color.lightGray); plot.setRangeGridlinePaint(Color.white); BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setSeriesPaint(0, Color.gray); renderer.setSeriesPaint(1, Color.orange); renderer.setDrawBarOutline(false); renderer.setItemMargin(0.0); ChartPanel chartPanel = new ChartPanel(chart, false); chartPanel.setPreferredSize(new Dimension(500, 270)); ChartFrame frame = new ChartFrame(“Bar”, chart); frame.pack(); frame.setVisible(true); } }

Chart


5.1 Pie Chart
Code

import java.awt.Color; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartFrame; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PiePlot; import org.jfree.data.general.DefaultPieDataset; public class Pie { public static void main(String [] args){ DefaultPieDataset data = new DefaultPieDataset(); data.setValue(“Category 1″, 43.2); data.setValue(“Category 2″, 27.9); data.setValue(“Category 3″, 79.5); // create a chart… JFreeChart chart = ChartFactory.createPieChart3D( “Sample Pie Chart”, data, true, // legend? true, // tooltips? false // URLs? ); PiePlot plot = (PiePlot) chart.getPlot(); plot.setSectionPaint(“Category 1″, new Color(200, 255, 255)); plot.setSectionPaint(“Category 2″, new Color(200, 200, 255)); plot.setExplodePercent(“Category 2″, 0.30); ChartFrame frame = new ChartFrame(“First”, chart); frame.pack(); frame.setVisible(true); } }

Chart