Saturday, 3 February 2018

Converting image from File to byte array





    private byte[] image2byte(File file, String mimeType) {
                if (!mimeType.contains("image")) {
                    return null;
                }

                byte[] imageByte = null;
                String formatName = getFormatName(mimeType);


                BufferedImage bi;
                try {
                    bi = ImageIO.read(file);

                    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                        boolean done = ImageIO.write(bi, formatName, baos);

                        baos.flush();

                        imageByte = baos.toByteArray();
                    }

                } catch (IOException ex) {
                    logger.error(ex.getMessage());
                }
                return imageByte;
            }





OR
 

    try {
            // Write the image to a buffer
            imagebuffer = new ByteArrayOutputStream();
            ImageIO.write(image, "png", imagebuffer);

            // Return a stream from the buffer
            return new ByteArrayInputStream(
                imagebuffer.toByteArray());
        } catch (IOException e) {
            return null;
        }


Monday, 8 January 2018

How to convert a primitive char array into a List


Arrays.asList()  only taking objects and convert them into a list; however primitive types, like char,  are not considered instances.

char[] chars = "I hate it".charArray();
List charList = Arrays.asList(chars);

char array is an object instance. so, here charList is a collection to hold a single array object, but not individual chars.

I didn't find a clever way, but having to convert a single char into its wrapper and then collect them into a collection.


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author YNZ
 */
public class ConvertPrimArrayIntoList {

    public static void main(String[] args) {

        //a primitive array
        char[] chars = "I hate it. ".toCharArray();
        

        //
        List charList = new ArrayList<>();
        for (char c : chars) {
            charList.add(c);
        }

        System.out.println("size of charList " + charList.size());
        
        //in java 8
        String str = "what is happening? ";
        List listOfChar = str.chars().mapToObj(c -> new Character((char) c)).collect(Collectors.toList());
        System.out.println("List chars : " + listOfChar);

    }

}



Saturday, 6 January 2018

java.util.ConcurrentModificationException: null

This error happens when removing an element in a for- loop.  Using an iterator and its remove method then the error will be solved.


using an iterator to solve the concurrent modification exception, caused by using for loop.
            for (Iterator it = foundCopy.iterator(); it.hasNext();) {
                Yard yard = it.next();
                if (checked.contains(yard.getInterest())) {
                    it.remove();
                }
            }


Or usign java 8, streaming and then filtering. 

Thursday, 2 November 2017

Queue Deque LinkedList

Java Deque interfaces abstract both a Queue(FIFO) and a Stack(LIFO), and both can be implemented in a LinkedList or ArrayQueue.

For a stack: using Deque methods, i.e. push() at a head and pop() query and remove from a head.
For a queue: using Deque methods, i.e. offer() or add()  at a tail and poll()  query and remove from the head.

* peek() is a query at the head, but not removing it. it is different from pop() or poll();

package String;
import java.util.Deque;import java.util.LinkedList;
import java.util.stream.IntStream;
public class ReverseStringQMethod {

    public static void main(String[] args) {
        String str = "I love this game";        
        System.out.println(str);

        Deque deque = new LinkedList();
        //Used as a stack        str.chars().map(c -> (char) c).forEach(c -> deque.push((char) c));
        char[] reversed = new char[deque.size()];
        IntStream.range(0, reversed.length).forEach(i -> {
            reversed[i] = deque.pop();            System.out.print(reversed[i]);        });
    }
}

Tuesday, 31 October 2017

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:

org.hibernate.LazyInitializationException:
failed to lazily initialize a collection of role: com.yardbud.datamodel.Yard.images, could not initialize proxy - no Session

The exception above is well-known as using hibernate lazy fetching.

As the exception said, "no Session". The error is due to when fetching lazy attributes the session has been closed. typically, you load an entity using Hibernate session and work through it and then close it. The Hibernate doesn't support lazy initialization for a detached entity. Once the session is closed, then the entity cannot make any further call on the database.


So how to solve this issue?
Using static method Hibernate.initialize(entity.getXXX());



References:

The best way to handle the LazyInitializationException

Get org.hibernate.LazyInitializationException in spring boot integration test




Wednesday, 20 September 2017

Async-Rest API


How to handle a long job in a Rest API? A task may take a long time to compute and therefore resource may not be ready at once.

In such case, rest controller may feedback request by an HTTP status, i.e. accepted and a task token, meanwhile, it spawns a thread to carry out this long job. Once the job is done, the result will be put a queue or a database, where it waits for the user to fetch it.

A client may use task token to check the job status, (in processing, or completed); Once it is completed, the client may use the token to query the result back.

References:
https://farazdagi.com/2014/rest-and-long-running-jobs/
http://www.nurkiewicz.com/2013/03/deferredresult-asynchronous-processing.html

Monday, 28 August 2017

How Vaadin manage navigation in Spring Boot

Using Vaadin(GWT) front-end in the Spring boot.

Vaadin UI : it is a single component container, which holds a single layout component.
Vaadin View: it is a CustomComponent or a layout, while implementing vaadin view interface.

When using Vaadin with Spring boot, the above should be annotated by
@SpringUI and @SpringView respectively; so that it will be picked up in the Spring context.

When navigating between pages in Vaadin,  actually it is partially replaced by another view or the whole UI is replaced by another UI.

A Vaadin UI holds a navigator, and a SpringNavigatorProvider that manages the Vaadin views.
Navigator should be declared and instantiated in the UI. It should be associated with the
SpringNavigatorProvider.

As using Spring boot, SpringNavigatorProvider is auto-wired(injected).
Views will be automatically registered in the provider.





Vaadin Spring

Vaadin Spring Add-on

Vaadin Navigator Problem

View and Navigation

Vaadin Spring Code Example

Github vaadin-valo-demo

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...