Java

java

[Java] How to Convert .csv to Shapefile shape format (.shp)?

On my previous project, i had a request to provide a csv to shp converter feature. After googling for a while, i found a simple java code snippet, i modified some of its part so i could integrate it on my GIS project and hope it will be more flexible.

This is part of inflasi3.csv file that will be converted into shp

KOTA,LAT,LON,JULIL2009,AGUS2009,9-Sep,OKT2009,9-Nov,DES2009,10-Jan,10-Feb,10-Mar,10-Apr,MEI2010,JUNI2010
BANDA ACEH,5.546181947,95.32366186,0.8,1.45,1.82,-1.3,0.45,-0.23,-0.3,-0.04,0.7,-0.47,0.63,0.63
TARAKAN,3.276090324,117.6193848,0.99,0.97,1.53,-0.74,0.64,1.76,0.24,0.2,0.08,0.09,-0.19,1.44
MANADO,1.493103951,124.8409503,0.46,0.65,-0.36,0.83,1.27,0.38,-1.35,1.25,1.29,-1.32,-0.64,-0.12

And this is my java class,

package com.baculsoft.main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.geotools.data.DataStoreFactorySpi;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureStore;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureCollections;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;

public class Csv2Shape {

    public static void main(String[] args) throws Exception {
        File file = new File("inflasi3.csv");

        FeatureCollection<SimpleFeatureType, SimpleFeature> collection = FeatureCollections.newCollection();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        SimpleFeatureType TYPE = null;
        try {
            String line = reader.readLine();
            
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("location:Point,");

            String[] headers = line.split("\\,"); 
            for (String header : headers) {
                stringBuilder.append("").append(header).append(":String,");
            }

            TYPE = DataUtilities.createType("Location", stringBuilder.substring(0, stringBuilder.toString().length() - 1));
            GeometryFactory factory = JTSFactoryFinder.getGeometryFactory(null);

            for (line = reader.readLine(); line != null; line = reader.readLine()) {
                String split[] = line.split("\\,");

                String name = split[0]; 
                double latitude = Double.parseDouble(split[1]);
                double longitude = Double.parseDouble(split[2]);

                Object[] o = new Object[split.length+1];
                for (int i = 2; i < o.length; i++) {
                    o[i] = split[i-1];
                }

                o[0] = factory.createPoint(new Coordinate(longitude, latitude));
                o[1] = name;

                SimpleFeature feature = SimpleFeatureBuilder.build(TYPE, o, null);
                collection.add(feature);
            }
        } finally {
            reader.close();
        }
        File newFile = new File("inflasi4.shp");

        DataStoreFactorySpi factory = new ShapefileDataStoreFactory();

        Map<String, Serializable> create = new HashMap<String, Serializable>();
        create.put("url", newFile.toURI().toURL());
        create.put("create spatial index", Boolean.TRUE);

        ShapefileDataStore newDataStore = (ShapefileDataStore) factory.createNewDataStore(create);
        newDataStore.createSchema(TYPE);
        newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);

        Transaction transaction = new DefaultTransaction("create");

        String typeName = newDataStore.getTypeNames()[0];
        FeatureStore<SimpleFeatureType, SimpleFeature> featureStore;
        featureStore = (FeatureStore<SimpleFeatureType, SimpleFeature>) newDataStore.getFeatureSource(typeName);

        featureStore.setTransaction(transaction);
        try {
            featureStore.addFeatures(collection);
            transaction.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            transaction.rollback();
        } finally {
            transaction.close();
        }
    }
}

And this is my pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.edw</groupId>
    <artifactId>CSV2SHP</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>CSV2SHP</name>
    <url>http://maven.apache.org</url>
    
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- use the latest snapshot -->
        <geotools.version>8.4</geotools.version>
    </properties>
  
    <repositories>
        <repository>
            <id>maven2-repository.dev.java.net</id>
            <name>Java.net repository</name>
            <url>http://download.java.net/maven/2</url>
        </repository>
        <repository>
            <id>osgeo</id>
            <name>Open Source Geospatial Foundation Repository</name>
            <url>http://download.osgeo.org/webdav/geotools/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-swing</artifactId>
            <version>${geotools.version}</version>
        </dependency>
    </dependencies>
</project>

This is the screenshot of my viewer (geoexplorer) after i uploaded inflasi4.shp, which is the result of converting inflasi3.csv
converting from csv to shp

Hope it helps other, have fun (H)

A Simple Hello World using Java

This is an example of a simple hello world using Java.

interface Printer {
    void print(Message message);    
}

class Message {
    private String message;
    
    public Message(String message) {
        this.message = message;    
    }
    
    public void print(Printer printer) {
        printer.print(this);    
    }
    
    public String toString() {
        return message;   
    }    
}

abstract class AbstractPrinterFactory {
    public static AbstractPrinterFactory getFactory(){
        return new SystemOutPrinterFactory();   
    }
    public abstract Printer getPrinter();    
}

class SystemOutPrinterFactory extends AbstractPrinterFactory {
    public Printer getPrinter() {
        return new SystemOutPrinter();   
    }    
}

class SystemOutPrinter implements Printer {
    public void print(Message message) {
        System.out.println(message);   
    }    
}

public class HelloWorld {
    public static void main(String[] args) {
        Message message = new Message("Hello, World!");
        AbstractPrinterFactory factory = AbstractPrinterFactory.getFactory();
        Printer printer = factory.getPrinter(); 
        message.print(printer);       
    }           
}

Just for fun (H)

eBook Apa yang Cocok bagi Pemula yang Baru Belajar Java?

Kebetulan lagi rame di kaskus programmer forum, tentang ebook yang cocok untuk pemula. Supaya ga jawab berulang-ulang, mending gw tulis disini aja deh.

Untuk melatih pondasi, coba baca bukunya donald knuth
Donald Knuth

lalu lanjut ke buku-nya deitel deitel, java how to program
Deitel Deitel

klo dah faseh naik ke bukunya gang of four, bruce eckel dan kathy sierra
Gang of Four

Bruce Eckel

kathy sierra

klo ada waktu iseng, buknya Joshua Bloch seru juga
Joshua Bloch

kemudian lanjut ke bukunya craig walls dan gavin king
Craig Walls

Gavin King

kalo dah faseh abis itu langsung ke bukunya Debu Panda dan Reza Rahman
EJB3

Semoga membantu untuk para calon-calon programmer diluar sana, Maju Terus Ilmu Pengetahuan Indonesia…!!

How To Check Window’s Opened Comm Port using Java

On my latest project, i need to connect my java application to a GSM Modem, in order to sending and receiving SMS text. But before my application connected to opened comm port, i need to check which port number is opened. So this is a small java class to check my opened comm port. Btw, im using rtxt libraries to help me communicate with the opened port.

import gnu.io.CommPortIdentifier;
import java.util.Enumeration;

public class Main {
    
    private void doSomething() {
        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        System.out.println(portList.hasMoreElements());
        while (portList.hasMoreElements()) {
            CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
            System.out.println(portId.getName());
        }
    }
    
    public static void main(String[] args) {
        Main main = new Main();
        main.doSomething();
    }
}

Dont forget to add rxtx libraries your java’s path. You can find the Window’s installation path, here.

Hope it helps other, have fun 🙂

A Weird Exception When Using Java’s BigDecimal, java.lang.ArithmeticException: Rounding necessary

I found this weird exception when im trying to convert double values to BigDecimal,

java.lang.ArithmeticException: Rounding necessary
	at java.math.BigDecimal.divideAndRound(BigDecimal.java:1439)
	at java.math.BigDecimal.setScale(BigDecimal.java:2394)
	at java.math.BigDecimal.setScale(BigDecimal.java:2437)

This is my java code

BigDecimal bgAvg = new BigDecimal(0);
bgAvg = bgAvg.add(new BigDecimal(myDoubleValue).setScale(2));

Somehow the error is gone after i changed my code into this

BigDecimal bgAvg = new BigDecimal(0);
bgAvg = bgAvg.add(BigDecimal.valueOf(myDoubleValue).setScale(2));

Hope it helped others, have fun with Java 😉