Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Java Sort Map by Value

Java Sort Map By Value


The following snippet works for any Type


static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
return map.entrySet()
.stream()
.sorted(comparingByValue())
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}

Reverse Order

static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
return map.entrySet()
.stream()
.sorted(comparingByValue(reverseOrder()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}


Complete Code with test!

import java.util.*;

import static java.lang.System.out;
import static java.util.Collections.reverseOrder;
import static java.util.Map.Entry.comparingByValue;
import static java.util.stream.Collectors.toMap;

public class MapUtil {

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
return map.entrySet()
.stream()
.sorted(comparingByValue())
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueReverseOrder(Map<K, V> map) {
return map.entrySet()
.stream()
.sorted(comparingByValue(reverseOrder()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}

public static void main(String[] args) {
Map<Integer, String> unsortedMap = Map.of(
1, "G",
2, "J",
3, "A",
4, "Y",
5, "N",
6, "O");

out.println(sortByValue(unsortedMap));
out.println(sortByValueReverseOrder(unsortedMap));
}

}




JavaCV Configuration in Windows

I had published a article on how to configure JavaCV on windows machine about 5 year back. Since then a lot of changes has been made to JavaCV:
  • The repository host Google Code stopped their services
  • JavaCV team moved to github with a different package name. They have replaced the "com.googlecode.javacv.cpp." package with "org.bytedeco.opencv." or "org.bytedeco.javacv"
  • They ( probably OpenCV too) moved some classes here and there.  eg:  the static method cvSaveImage is now under org.bytedeco.opencv.helper.opencv_imgcodecs.cvSaveImage package. It was on com.googlecode.javacv.cpp.opencv_highgui.cvSaveImage  before.
  • Finally the good thing is the installation/setup steps has been easier than before.  This is because they have wrapped all libraries files (dll, so ) into the platform specific jar files and we don't need to install and configure the OpenCV binaries separately

Setup Steps:

1) Install the JDK on your system. 

You can choose between 3 options:
  • OpenJDK http://openjdk.java.net/install/ or
  • Sun JDK http://www.oracle.com/technetwork/java/javase/downloads/ or
  • IBM JDK http://www.ibm.com/developerworks/java/jdk/

2) Download the JavaCV binaries.

2.a) Manually:
2.b) Automatically - Using Maven (Recommended)
<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacv-platform</artifactId>
    <version>1.5.3</version>
</dependency>

3) Project Setup:

3.a) Basic project using Eclipse/Netbeans,Intellij or other IDE
Extract the JavaCV binaries and add all the jars into your classpath.

3.b) Maven Project Setup:
If you want to use Maven you need to add the dependencies as in 2.b) in your pom.xml file. There is already a sample project available on GitHub. Download it and import into  your IDE. It has a sample code to capture images from webcam.

GitHub Sample Project URL: https://github.com/gtiwari333/JavaCV-Test-Capture-WebCam


Sample Code to Capture Images from WebCam:



Happy Coding ...

AngularJS Download File From Server - Best way with Java Spring Backend

Here's how you can download a file from server using AngularJS.

In this example, the client sends a API call to Java server to download a file /api/download/{id} and server sends the base64 data stream download for a given file id.

Below is the snippet from working code. The code is pretty descriptive.
This will allow you to download any type of file.

AngularJS controller method:

function downloadReportFile(fileId) {
    Download.downloadQueuedReport({id: fileId}, function (response) {

        var anchor = angular.element('<a/>');
        anchor.attr({
            href: 'data:application/octet-stream;base64,' + response.data,
            target: '_self',
            download: response.headers.filename        });

        angular.element(document.body).append(anchor);
        anchor[0].click();

    });
}

AngularJS service to do the API call:


'downloadQueuedReport': {
    method: 'GET',
    url: 'api/download/:id',
    params: {id: '@id'},
    transformResponse: function (data, headers) {
        var response = {};
        response.data = data;
        // take note of headers() call        response.headers = headers();
        return response;
    }
},

Spring Powered Backend REST API 

@RequestMapping(value = "api/download/{id}",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
 public ResponseEntity<byte[]> downloadReportFile(@PathVariable Long id) {
    log.debug("REST request to download report file");

    File file = getReportFile(id); // a method that returns file for given ID
    if (!file.exists()) { // handle FNF
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    try {
        FileSystemResource fileResource = new FileSystemResource(file);

        byte[] base64Bytes = Base64.encodeBase64(IOUtils.toByteArray(fileResource.getInputStream()));

        HttpHeaders headers = new HttpHeaders();
        headers.add("filename", fileResource.getFilename());

        return ResponseEntity.ok().headers(headers).body(base64Bytes);
    } catch (IOException e) {
        log.error("Failed to download file ", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

}

Java Tutorials - Kindle epub/mobi format

Learning the java language can be tough if you follow wrong documents. It's always best to follow the official tutorials provided by Oracle. They have provided all the Java Tutorials which are present on its website in ePub and mobi format.

You can download all of them at
http://www.oracle.com/technetwork/java/javase/java-tutorial-downloads-2005894.html

Check for the latest version of above page. Currently the link contains docs for Java8. It will prompt you the link for new version once later versions are released.

Spring MVC download content of String as text file

To download a text file out of a String :

JSP View :
 <a href="download">Download String </a> 

Controller Method :

 @RequestMapping(value = "/download", method = RequestMethod.GET)
 public @ResponseBody
 void downloadFile(HttpServletResponse resp) {
  String downloadFileName= "download.txt";
  String downloadStringContent= getStringToWrite(); // implement this
  try {
   OutputStream out = resp.getOutputStream();
   resp.setContentType("text/plain; charset=utf-8");
   resp.addHeader("Content-Disposition","attachment; filename=\"" + downloadFileName + "\"");
   out.write(downloadStringContent.getBytes(Charset.forName("UTF-8")));
   out.flush();
   out.close();

  } catch (IOException e) {
  }
 }

Check this as well : spring mvc download a file from server

Spring MVC file download from server example code

To download a file - from request parameter

JSP View :
 <a href="downloadFile?fileName=log.txt">Download String </a> 

Controller Method :


@RequestMapping(value = "/downLoadFile", method = RequestMethod.GET)
public void downLoadFile( HttpServletRequest request, HttpServletResponse response ) {
try {
 String fileName = request.getParameter( "fileName" );
 File file = getFileToDownload(fileName) // implement this to return a valid file object
 InputStream in = new BufferedInputStream( new FileInputStream( file ) );

 response.setContentType( "text/plain" ); // define your type
 response.setHeader( "Content-Disposition", "attachment; filename=" + fileName  );

 ServletOutputStream out = response.getOutputStream( );
 IOUtils.copy( in, out ); //import org.apache.commons.io.IOUtils;
 response.flushBuffer( );
} catch ( Exception e ) {
 e.printStackTrace( );
}
}

 

Java - Convert HTML to PDF File - Using iText

Here's how you can convert HTML to PDF using iText and Flying Saucer PDF libraries in Java. The steps are described within the code below.

You can easily add some methods below to read HTML content from a file and convert the HTML file to PDF ( instead of HTML string to PDF).

package g.t.test;

import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
public class HtmlToPDFConverter {

    public static void convert(String htmlContent, File pdfFile) throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        //step1: render html to memory         
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(htmlContent);
        renderer.layout();
        renderer.createPDF(os);

        //step2: conver to byte array stream         
        byte[] pdfAsBytes = os.toByteArray();
        os.close();

        //step3: write byte array stream to file         
        FileOutputStream fos = new FileOutputStream(pdfFile);
        fos.write(pdfAsBytes);
        fos.flush();
        fos.close();
    }

    // let's test !! 
    public static void main(String[] args) throws Exception{
        convert("<html> <body> " +
            "<h1>Hello Crazy World !!</h1> <br/> " +
            "<h2> I hope you are doing great.</h2> " +
            "</body> </html>", new File("test.pdf"));
    }
}

Used Maven Dependencies:

<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>2.1.7</version>
</dependency>
<dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>flying-saucer-pdf</artifactId>
    <version>9.0.9</version>
</dependency>


Check if a class extends another at Runtime : Java

Summary :

  • If you want to know whether or not a Class extends another, use Class#isAssignableFrom(Class)
  • Class#isAssignableFrom(Class) also returns true if both classes are same
  • To find if an object is instance of a class use instanceof operator
  • To know if a class is direct sub class of another class then use Class#getSuperClass().equals(Class)

Setup :

We have an interface MyInterface and three classes MyBaseClass, MySubClass and SomeOtherClass with the below hierarchy.

interface MyInterface {
}

class MyBaseClass implements MyInterface {
}

class MySubClass extends MyBaseClass {
}

class SomeOtherClass {
}   

Tests:

   

public class Test {
  
  public static void main( String[] args ) {
    
    /*
     * Checking if a class is same as or is a superclass or superinterface
     * 
     * of another class (the class in parameter)
     */
    System.out.println( MyBaseClass.class.isAssignableFrom( MyBaseClass.class ) );// true : same class
    System.out.println( MyBaseClass.class.equals( MyBaseClass.class ) );// true : same class
    System.out.println( MyBaseClass.class.isAssignableFrom( MySubClass.class ) );// true : superclass
    System.out.println( MyInterface.class.isAssignableFrom( MySubClass.class ) );// true : superinterface
    System.out.println( MyBaseClass.class.isAssignableFrom( SomeOtherClass.class ) );// false : the two classes has no relation
    System.out.println( MySubClass.class.isAssignableFrom( MyBaseClass.class ) );// false : MySubClass is not the superclass
    
    /*
     * Checking if a object is instance of a class
     */
    
    IMyInterface object = new MyBaseClass( );
    System.out.println( object instanceof MyInterface ); // true
    System.out.println( object instanceof MyBaseClass ); // true
    System.out.println( object instanceof MySubClass ); // false
    System.out.println( object instanceof SomeOtherClass );// false
    
    /*
     * check if a class is direct superclass of another
     */
    
    System.out.println( MySubClass.class.getSuperclass( ).equals( MyInterface.class ) );// false : its not a directsuper class, interface
    System.out.println( MyBaseClass.class.getSuperclass( ).equals( MyInterface.class ) );// false : its not a directsuper class, interface
    System.out.println( MySubClass.class.getSuperclass( ).equals( MyBaseClass.class ) );// true : MyBaseClass is extending MySubClass
  }
}
   

Full code :

   

public class Test {
  
  public static void main( String[] args ) {
    
    /*
     * Checking if a class is same as or is a superclass or superinterface
     * 
     * of another class (the class in parameter)
     */
    System.out.println( MyBaseClass.class.isAssignableFrom( MyBaseClass.class ) );// true : same class
    System.out.println( MyBaseClass.class.equals( MyBaseClass.class ) );// true : same class
    System.out.println( MyBaseClass.class.isAssignableFrom( MySubClass.class ) );// true : superclass
    System.out.println( MyInterface.class.isAssignableFrom( MySubClass.class ) );// true : superinterface
    System.out.println( MyBaseClass.class.isAssignableFrom( SomeOtherClass.class ) );// false : the two classes has no relation
    System.out.println( MySubClass.class.isAssignableFrom( MyBaseClass.class ) );// false : MySubClass is not the superclass
    
    /*
     * Checking if a object is instance of a class
     */
    
    IMyInterface object = new MyBaseClass( );
    System.out.println( object instanceof MyInterface ); // true
    System.out.println( object instanceof MyBaseClass ); // true
    System.out.println( object instanceof MySubClass ); // false
    System.out.println( object instanceof SomeOtherClass );// false
    
    /*
     * check if a class is direct superclass of another
     */
    
    System.out.println( MySubClass.class.getSuperclass( ).equals( MyInterface.class ) );// false : its not a directsuper class, interface
    System.out.println( MyBaseClass.class.getSuperclass( ).equals( MyInterface.class ) );// false : its not a directsuper class, interface
    System.out.println( MySubClass.class.getSuperclass( ).equals( MyBaseClass.class ) );// true : MyBaseClass is extending MySubClass
  }
}

interface MyInterface {
}

class MyBaseClass implements MyInterface {
}

class MySubClass extends MyBaseClass {
}

class SomeOtherClass {
}

      
   

Java - OS independent line separator

 You might already knew, the new line character depends on your OS.
  • \n for Unix
  • \r\n for Windows and 
  • \r for old Macs
  • and so on

Always use
System.getProperty("line.separator")
OR
Java 7's way: System.lineSeparator()

This will let you find out OS specific line separator instead of judging yourself and hard coding it. It also helps you in avoiding bugs.

Bonus information:
The new line characters originated from the old type writer era.
  • Carriage return - CR = \r
  • Line feed - LF = \n
Read wikipedia article for more information about new line characters.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path - Solution

Solution to the Java Web Project error : " The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path ".

Add the javax.servlet-api library (servlet.jar) to class path. If you're using maven add the following dependency ( scope = provided, runtime dependency will be provided by the servlet container i.e your web server eg : tomcat, jboss etc)



        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

Logging levels - meanings and use

All the popular logging frameworks follow the similar convention and naming for log levels. There are five priority levels in use.

Order ( high priority to low):
  • FATAL ERROR WARN INFO DEBUG TRACE
Meaning and Use:
  1. debug to write debugging messages which should not be printed when the application is in production.
  2. info for messages similar to the "verbose" mode of many applications.
  3. warn for warning messages which are logged to some log but the application is able to carry on without a problem.
  4. error for application error messages which are also logged to some log but, still, the application can hobble along. Such as when some administrator-supplied configuration parameter is incorrect and you fall back to using some hard-coded default value.
  5. fatal for critical messages, after logging of which the application quits abnormally.
 Additionally, there are two other levels. They have the obvious meanings.
  1. ALL
  2. OFF

nepali english date conversion logic - working java code


My friend Manoj has written about Nepali-English date conversion in this post. Take a look :

http://forjavaprogrammers.blogspot.com/2012/06/how-to-convert-english-date-to-nepali.html

He has explained the algorithm in detail about how to convert English dates into Nepali dates with java code.

java spring - read properties file variable from xml -PropertyPlaceholderConfigurer

Java springframework xml configuration file - how to read properties file variables from spring xml :
We have to use PropertyPlaceholderConfigurer bean for this.

1).properties file location -

  • src/main/resource @ maven managed project
  • OR at classpath

2)The xml code to initialize/read properties file, 

hibernate annotation inheritance mappedsuperclass - common columns in super class

When you are using annotations for hibernate object relational mapping, there might be the case that we need to abstract out some common columns that goes into all table definitions. These columns might be ID, DFlag, LastModifiedDate etc..
In such case we can take advantage of @MappedSuperclass annotation to achieve inheritance in hibernate annotation.

Example :

Super class BaseTable that contains common column definitions:

@MappedSuperclass
public abstract class BaseTable {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private int id;

    @Column(name = "dflag")
    private int dFlag;

    @Column(name = "lastmodifieddate")
    private Date lastModifiedDate;
    
    //other required columns
....
}

Extending it to use in other tables :


@Entity
@Table(name = "LoginUser")
public class LoginUser extends BaseTable  implements Serializable{

    private static final long serialVersionUID = -1920053571118011085L;

    @Column(name = "username")
    private String username;

    @Column(name = "password")
    private String password;

    @Column(name = "invalidCount")
    private int invalidCount;
    
    //other required tables
   ...
}


It works !

mysql hibernate unicode support - character set, collate

I just did following configurations to achieve Unicode support in my Java+Hibernate+MySQL project.

Configuring MySQL to support Unicode - set Character Set and Collate as :
CREATE TABLE YOUR_DB_NAME
 CHARACTER SET "UTF8"
 COLLATE "utf8_general_ci";

NOTE : You Need to do "ALTER TABLE" instead of "CREATE TABLE", 
      if you are going to modify existing DB.

Hibernate JDBC connection string :
jdbc.url=jdbc:mysql://localhost:3306/YOUR_DB_NAME?useUnicode=true&characterEncoding=UTF-8

Hibernate Configuration:
<hibernate-configuration>
<session-factory>
    ...
    <property name="hibernate.connection.charSet">UTF-8</property>
    <property name="hibernate.connection.characterEncoding">UTF-8</property>
    <property name="hibernate.connection.useUnicode">true</property>
    ...
</session-factory>
</hibernate-configuration>

Java code to find public IP address (servlet and client side code)


Java code to find public IP address :

URL url= new URL("http://gt-tests.appspot.com/ip");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String ip = in.readLine();
System.out.println("IP : "+ip);

I created a simple servlet app on google app engine  and posted at http://gt-tests.appspot.com/ip .

The servlet code returns the public address of client, it looks like :

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  PrintWriter out = resp.getWriter();
  // Get client's IP address
  String addr = req.getRemoteAddr();
  out.println(addr);
  ...

eclipse proguard maven project configuration - java obfuscate

I am going to describe how can can configure proguard and maven to obfuscate a java project. If you need help on how to configure maven project in eclipse see my earlier post.

A)Project configs
    <!-- Project configs -->
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.gt</groupId>
    <artifactId>maven-proguard-test</artifactId>
    <packaging>jar</packaging>
    <version>-ver.01</version>
    <name>maven-proguard-test-application</name>

    <properties>
        <project.build.mainClass>com.gt.App</project.build.mainClass>
    </properties>

Speech Recognition Java Code - HMM VQ MFCC ( Hidden markov model, Vector Quantization and Mel Filter Cepstral Coefficient)

Hi everyone,
I have shared speech recognition code in google code :
http://code.google.com/p/speech-recognition-java-hidden-markov-model-vq-mfcc/

You can find complete source code for speech recognition using  HMM, VQ, MFCC ( Hidden markov model, Vector Quantization and Mel Filter Cepstral Coefficient). Feel free to use and modify this code.

The project report that accompanies this code is here.
http://ganeshtiwaridotcomdotnp.blogspot.com/2011/06/final-report-text-prompted-remote.html

Introduction to the project :
http://ganeshtiwaridotcomdotnp.blogspot.com/2010/12/text-prompted-remote-speaker.html

simple ball game by colored object motion tracking - image processing opencv javacv

DEMO VIDEO:  simple ball game by colored object motion tracking - using javacv opencv to detect the path of moving object. This is earliest version of the game.


Full Code :
Java Collision Detection and bounce

Colored object tracking in java- javacv code


You need to integrate the ideas from above links.
The full (integrated code will be uploaded shortly)

Object tracking in Java - detect position of colored spot in image

Red spot in image - position to be detected later
Object Tracking plays important role in Image Processing research projects. In this example, I am showing how we can detect the position [(x, y) coordinates ] of a colored spot in given image using JavaCV (Java wrapper for OpenCV ).



Input image :
This image has a red colored spot. And our objective is to track the position coordinate of the spot in image.The example below uses thresholding in HSV space and simple moment calculations given in OpenCV library.





You can use this code to track an object in a video sequence - say live web-cam capture video.


Detecting Position of a spot in Threshold image:
    static Dimension getCoordinates(IplImage thresholdImage) {
        int posX = 0;
        int posY = 0;