mercredi 1 février 2017

get most precise implicit at run time

sorry for the bad title.
I'm using a library that has a base trait and multiple implementations of this trait. However, instead of traditional method overriding, method specialization is provided by methods taking implicit arguments. The general pattern is as follows

class Cont[TT](val n : Int)

trait I[ +Self  ] {
  final def foo[TT >: Self](implicit num : Cont[TT]) = num.n
}

trait B extends I[ B] 

object B {
  implicit def Mint : Cont[B] = new Cont[B](53)
}

class S extends B with I[S]

object S{
  implicit def HMint : Cont[S] = new Cont[S](54)

}

B is the "base type" of which you will have several subclasses(of which S in an example). Each of this subclasses would provide a few implicits(like we do for Cont in the example), one for each method it wants to specialize. If a certain implicit is not defined, the one from B is used(not shown on the code above). The methods that you actually want to call on B and its subclasses are defined in trait I and there is one type for each.
My problem is that I want to write generic functions taking as arguments a collection of B or its subclasses and calling methods on them, but I want the most specific implicits to be called. The problem is that differently from method overriding, the "compile time" type defines which method is going to be called. For example:

val s = new S
val b : B = s
(b.foo,s.foo)
res50: (Int, Int) = (53,54)

Can I write my generic functions in any way that the most specific method will be called? If not, are there some light changes on the library that would allow that? Finally, does the patter used by this library has a name? It's really hard to look for information about a pattern whose name one doesn't know.

What is the difference between returning this and inner class Bullder?

I have seen examples of builder patterns where this is returned in all public methods and other examples where a inner class Builder() is used instead of returning this with a build() method inside.

So what is the difference and what/when should I use which one?

Design Pattern - Which Design Pattern to use in this case

I've created a Dataset class used to store and manipulate a dataset. A different class, called Dataset Iris, extends Dataset because Dataset is Principal class where every different datasets (iris and so on) extends it because they have a their feature and a different methods to load it(I can load from a file .txt, .data or database and so on...).

My actually code is this and run, but my teacher tells to me that I should apply "Decorator" design pattern to solve it, but looking the Decorator UML I don't think it because I haven't the "Concrete component" (I can create . What do you think about it? Is a Decorator design pattern or other (like template methods)?

Dataset

public class Dataset
{
    private int nFeature;
    private int nRecord;
    private ArrayList<Integer> featureUsed;
    private String nomeDataset;

    //public double Mat [][];
    private ArrayList<ArrayList<Double>> Mat;


    public double Distanza(int i, ArrayList<Double> centroide)
    {
        double Sum=0;
        for(int j=0; j<nFeature; j++)
            Sum+=Math.pow((centroide.get(j) - Mat.get(j).get(i)), 2);
        return Math.sqrt(Sum);
    }

    public double getCell(int i, int j)
    {
        return Mat.get(j).get(i);
    }

    public void initMat()
    {
       Mat = new ArrayList<ArrayList<Double>>();
       featureUsed = new ArrayList<Integer>();

       for(int i=0; i< nFeature; i++)
       {
           Mat.add(new ArrayList<Double>());
           featureUsed.add(i); 
       }
    }


    public void writeDataset()
    {
        for(int i=0; i< nRecord; i++)
        {
            for(int j=0; j < nFeature; j++)
            {
                System.out.print( Mat.get(j).get(i)+ " ");
            }
            System.out.println("\n");
        }
    }

    public ArrayList<Double> getRecord(int i_r)
    {
        ArrayList<Double> record = new ArrayList<Double>();
        for(int i=0; i<nFeature; i++)
            record.add( Mat.get(i).get(i_r));

        return record;
    }

    public Dataset(int nFeature, String Nome) 
    {       
        setnFeature(4);
        setNomeDataset(Nome);
        initMat();
    }


    public Dataset(ArrayList<ArrayList<Double>> MatInput, ArrayList<Integer> featureSelected, int nRecord)
    {
        Mat = new ArrayList<ArrayList<Double>>();
        this.featureUsate = new ArrayList<Integer>(featureSelected);
        this.nRecord = nRecord;
        this.setnFeature(featureSelected.size());

        for(int i=0; i<featureSelected.size(); i++)
            setCol( MatInput.get( featureSelected.get(i)));

    }

    public Dataset() {
        // TODO Auto-generated constructor stub
    }


    public void setCol( ArrayList<Double> colVal)
    {
        this.Mat.add(colVal);
    }

    public ArrayList<ArrayList<Double>> getMat()
    {
        return this.Mat;
    }
    public int getnFeature() {
        return this.nFeature;
    }
    public int getnRecord() {
        return this.nRecord;
    }
    public void setnFeature(int nFeature) 
    {
        this.nFeature = nFeature;
        return;
    }
    public void setnRecord(int nRecord) {
        this.nRecord=nRecord;
        return;
    }

    public void setTable(int Colonna, Double Valore) 
    {
        Mat.get(Colonna).add(Valore);
    }
    public String getNomeDataset() {
        return this.nomeDataset;
    }

    public void setNomeDataset(String nomeDataset) {
         this.nomeDataset = new String(nomeDataset);
    }

    public double[][] toMatrix()
    {
        double[][] matrix = new double[this.getnRecord()][this.getnFeature()];
        for(int i=0; i< nRecord; i++)
        {
            for(int j=0; j < nFeature; j++)
            {
                matrix[i][j] = Mat.get(j).get(i);
            }
        }
        return matrix;
    }

    public ArrayList<Integer> getFeatureUsed()
    {return this.featureUsed;}
}

DatasetIris

public class DatasetIris extends Dataset
{


    private String[] nomiFeature = {"Petal Length",
                                    "Petal Width",
                                    "Sepal Length",
                                    "Sepal Width"
                                    };  

    public DatasetIris(String NomeFile) throws IOException
    {
        super(4,NomeFile);
        super.setnRecord( CaricaDataset(NomeFile) );
    }

    // Other DatasetIris with their load (database or other type of files)?
    protected int loadDataset(String pathFile) throws IOException
    {
        int iRecord = 0;
        BufferedReader bufferLetto = null;
        String line = "";
        String cvsSplitBy = ",";

        try {
            bufferLetto = new BufferedReader(new FileReader(pathFile));

            while ((line = bufferLetto.readLine()) != null) 
            {
                if (line.length() > 0) 
                {
                    String[] cell = line.split(cvsSplitBy);
                    this.addRow(cell);
                    iRecord++;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferLetto != null) {
                try {
                    bufferLetto.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return iRecord;
    }

    // New File.data to Mat
    public void addRow(Object cell[]) 
    {
        for(int i=0; i<getnFeature(); i++)
            super.setTable(i, Double.parseDouble(cell[i].toString()));
    }

}

Java Database Design Pattern Suggestion

We are working on a Java application which will store user profiles. We have multiple trusted sources (all of them are tables from same oracle database) to create, update user profiles.

We do not have a direct mapping of user profile fields from sources. The field values are derived based on some logic.

Here is a sample of user profile fields in our application

**Application User Profile**

 1. User Login
 2. First Name
 3. Email
 4. Location
 5. Start Date
 6. End Date

Source 1: Database table

 1. User Login
 2. First Name
 3. Last Name
 4. Action Type
 6. Action Date

Source 2: Database table

 1. User Login
 2. Email

Which Java design pattern would you suggest for our scenario? (Assuming we will always read data from the same database, so is DAO not suggestible?)

As explained above, we have multiple sources and the logic to derive user profile fields values from source is different from each source and we don't have all fields in all sources.

Thank you,
Sash

Is storing the connection pool in a singleton a bad practice?

I just read this question and the answer claims:

"Lets assume db connection object is singleton in my application"

This is a must not. Your database connection MUST NEVER BE (yes, bolded and with capitals to make sure you and every reader never make this mistake) a singleton object. Your Connection con MUST NOT be part of a singleton to keep it open all the time. Instead, use a proper database connection pool that will take care of opening the necessary physical database connections and keep them alive through the live of your application.

We of course use a connection pool to take care of our, well, connections. Still, we store this pool in a singleton. How else would one ensure that it lives throughout the application? Ist his bad practice?

Javascript oop object pool pattern [on hold]

In this code example there is a way to implement the object pool pattern?

An example in php and java

// parents
function Parent() {
  this.id = 'Parent';
}

// childs
function Child1() {
  Parent.call(this);
  this.id = 'Child1';
  this.name = 'Mario';
}
Child1.prototype = Object.create(Parent.prototype);

function Child2() {
  Parent.call(this);
  this.id = 'Child2';
  this.name = 'Luigi';
}
Child2.prototype = Object.create(Parent.prototype);

When to register OP_WRITE

I use NIO with reactor pattern to connect a server to a client. My codes are as follows: Server side codes, in the block of if(selectionKey.isWritable){} :

public void isWritable(SelectionKey selectionKey) throws Exception {

        SocketChannel socketChannel =
                (SocketChannel) selectionKey.channel();

        Integer myInteger = (Integer) selectionKey.attachment();

        if (myInteger == null){
            int myJob = jobFacade.isAnyJob(socketChannel, 100 /*deadline*/);
            if (myJob > 0){

                ByteBuffer inputBuffer = ByteBuffer.wrap("available\n".getBytes("UTF-8"));
                socketChannel.write(inputBuffer);
                myInteger = myJob;
                socketChannel.register(
                        selector, SelectionKey.OP_WRITE, myInteger);

            }else if (myJob == -1){

                ByteBuffer inputBuffer = ByteBuffer.wrap("unavailable\n".getBytes("UTF-8"));
                socketChannel.write(inputBuffer);
                socketChannel.close();

                UnsupportedOperationException un = new UnsupportedOperationException();
                throw un;

            }else if (myJob == -2){

                ByteBuffer inputBuffer = ByteBuffer.wrap("pending\n".getBytes("UTF-8"));
                inputBuffer.flip();
                socketChannel.write(inputBuffer);
                myInteger = null;
                socketChannel.register(
                        selector, SelectionKey.OP_WRITE, myInteger);

            }
//            is there any new job to do?
        }else{

            int myInt = myInteger.intValue();

            if ( myInt > 0 ){

                long startRange = jobFacade.findByID(myInt);
                sendTextFile(startRange, Integer.parseInt(properties.getProperty("workUnit")),
                             properties.getProperty("textPath"), socketChannel);
                myInteger = -3;
                socketChannel.register(
                        selector, SelectionKey.OP_WRITE, myInteger);

            }else if (myInt == -3){

                sendAlgorithmFile(socketChannel, properties.getProperty("algorithmPath"));
                myInteger = -4;
                socketChannel.register(
                        selector, SelectionKey.OP_WRITE, myInteger);
//                send algorithm file

            }else if (myInt == -4){
                int isOK = jobFacade.isAccepted(socketChannel.socket().getInetAddress().toString(),
                                                Long.parseLong(properties.getProperty("deadline")));
                if(isOK == -1){

                    ByteBuffer inputBuffer = ByteBuffer.wrap("notaccepted\n".getBytes("UTF-8"));
                    socketChannel.write(inputBuffer);
                    myInteger = null;
                    socketChannel.register(
                            selector, SelectionKey.OP_WRITE, myInteger);
                }else {

                    ByteBuffer inputBuffer = ByteBuffer.wrap("accepted\n".getBytes("UTF-8"));
                    socketChannel.write(inputBuffer);
                    myInteger = isOK;
                    socketChannel.register(
                            selector, SelectionKey.OP_READ, myInteger);
                }
//                send "accepted" or "not accepted"
            }
        }
    }

It is no need to know what my methods in each block do except that these methods generate a number with this order at first. 1)myInteger=null, 2) myInteger > 0, 3) myInteger = -3, 4) myInteger = -4 In this order, OP-WRITE will register consecutively for four times. And this part is so important. So lets see my Client side code and then I will tell you my problem:

BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            sentence = inFromServer.readLine();
            System.out.println("Response from Server : " + sentence);


            if (sentence.equals("available")){

                BufferedReader inFromServer1 = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                while ((sentence = inFromServer1.readLine()) != null) {
                     myJob = myJob + sentence ;
                }


inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String acception = inFromServer.readLine();
                if (acception.equals("accepted")){

                    File file = new File("account.json");
                    byte[] bytes = new byte[2048];
                    InputStream inputStream = new FileInputStream(file);
                    OutputStream outputStream = clientSocket.getOutputStream();
                    int count;
                    try {
                        while ((count = inputStream.read(bytes)) > 0){
                            outputStream.write(bytes, 0, count);
                        }
                        outputStream.close();
                        inputStream.close();

                    }catch (IOException io){}

                    continue;

                }else if (acception.equals("notaccepted")){

                    continue;

                }

Now, my problem is that when I run my server and then my client, my server will run without waiting for my client to get input stream. First, the client get "available" but when the second getInputStream will be reached in client, the server paced all the phase of OP-WRITE registering and wait for client to get streams of data (As I defined in my code). Actually, my server do its job well. It will pass all the stages in required order. But the problem is that sending and receiving data is not synchronous. I do not know what my problem is. But I guess when I register OP-WRITE consecutively, it means that my server did not send all bytes of data, so just the first getInputStream will get the data. On the other hand, I need this order to run my program. So, Is there any Idea?