regex matching a string with no single quotes in powershell

Hi I'm trying to create a script in powershell that finds a string in a file and then modifies it but I'm having issues matching the string I want.
So, I'm trying to make sure that I can find this type of string
|d where d is is any digit, the string must not be in single or double quotes.
SO I'd like to match |1 or |12 or |333
So far this is what I have:
\|[0-9]+ is returning strings with or without single quotes around it, so |1 and also '|5';
\'\|[0-9]\'+ returns only strings with single quotes around it, so matches '|4' but not |3
\\'|'(?:\\'|[^'])*'|(\[0-9]+) as the first one, it is returning strings with or without single quotes around it, so |1 and also '|5';
\[^']\|[0-9][?']\+ I thought this would say something like exclude ' at the beginning and at the end of the string, but it doesn't work at all
Now, you might have understood that I really don't know much about regex, so I'm trying options in the online regex checker here https://regex101.com/ but it appears to be behaving slightly different than powershell.
Now, what do I have to do to match a string without the quotes? I don't necessarily want the solution, but perhaps some hint would be appreciated :-)

Retrieving data from the db with an ID or with a search term?

I 'm building an application to store and retrieve books, but I have an issue with retrieving data from the db.
I'm using REST and testing with postman. Everything works OK. Currently I have a series of methods written in Java at the backend like so

@Override
    @POST
    @Path("/add")
    //@Produces("application/json") 
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)

    public Response addBook(Book book) {        
        dbAccess.connectToDb();
        return dbAccess.addBook(book);
    }

    @Override
    @DELETE
    @Path("/{id}/delete")
    @Produces("application/json")
    public Response deleteBook(@PathParam("id") int id) {
        dbAccess.connectToDb();
    return  dbAccess.deleteBook(id);
    }

    @Override
    @GET
    @Path("/{id}/get")
    @Produces("application/json")
    public Book getBook(@PathParam("id") int id) {
        dbAccess.connectToDb();
        return dbAccess.getBook(id);
    }

So in postman I have a request like http://localhost:8080/book-storage-REST/book/15/get to retrieve a record.
Eventually I will write a front end, maybe in angular, which allows users to do their searches and display the results back to them.
Now, in the real world, a user of course wouldn't use an ID to search for a record, but he/she will be more likely to use the author name or book title. So my question is:
do I need to rewrite the methods above and not use an id parameter or should the front end do the job of taking a search term (title or author), query the db to find the equivalent id, do the necessry filtering in case of more than 1 record and only then, call the relevant methods above wth only one ID?

update values with subquery returns not updatable

Hi all, I have a question about updating two values in a sql table using a subquery. My database is called books and the below table books too:

id   title    author   location_id
11  Tera    Netrear 4
14  Disser  Bubu    1
15  Tenno   Puoio   4
16  Oban    Tyrone  5
18  Sisnobi Teru    3

Location_id is indeed another table as it's a foreign key in this table but that shouldn't matter. So what I want to do is to change all the location_id currently at 4 to 2. I know i could do it like this
update books set location_id = 1 where location_id = 4 but I'd like to know if I could do it with a subquery, something like update (SELECT * from books where location_id = 4) as thebook set thebook.location_id = 2 but when I run this query it tells me that the target table thebook UPDATE is not updatable. Why is that and can this be achieved - I don't really mind if it's not performant etc, I think it should be possible but I can't quite get the right way to do it...
So, the idea is, make a selection first then change a/more value/s on that selection, this is the concept I'm try to prove.
Any idea?

Getting all records from sql database generates error

Hi there, I've come across an issue while trying to get all the records from a SQL database in java.
A bit of necessary introduction here.
I'm not using any framework just JDBC and the getAllBooks method is part of a REST call. The failing method is essentially doing this:
-getting the number of all records in the db;
-getting all the ids and use them to get the records, store them in an array and return that array;
Unfortunately the call generates the following error in the while loop:

SEVERE: Servlet.service() for servlet [Jersey Web Application] in context with path [/book-storage-REST] threw exception
java.lang.IllegalArgumentException: the object parameter to marshal() is not marshallable
    at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:280)
    at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:163)
    at com.sun.jersey.json.impl.provider.entity.JSONListElementProvider.writeList(JSONListElementProvider.java:145)
    at com.sun.jersey.core.provider.jaxb.AbstractListElementProvider.writeTo(AbstractListElementProvider.java:264)
    at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:302)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1510)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

Ok, the code now:

public Book[] getAllBooks()
    {
        Book[] books = null;        
        try
        {
            resultSet = statement.executeQuery(SqlStrings.SELECT_NUMBER_ALL_RECORDS);//runs "SELECT COUNT(*) from books";           
            resultSet.next();
            int dbRecordNo = resultSet.getInt(1);//get number of record
            resultSet = statement.executeQuery("SELECT books.id FROM books");//get all ids
            books = new Book[dbRecordNo];

            int i = 0;
            while(resultSet.next() && i < dbRecordNo)
            {
                int bookId = Integer.parseInt(resultSet.getString("id"));
                books[i] = getBook(bookId);         
                System.out.println();
                i++;
            }

            return books;
        } 
        catch (SQLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

The problem seems to be occurring because I use && i < dbRecordNo in while(resultSet.next() && i < dbRecordNo). I run a few tests and if I remove that && statement the while loop runs absolutely fine. So, I can't quite understand why this while(resultSet.next()) goes through the resultSet absolutely fine and this instead while(resultSet.next() && i < dbRecordNo) goes through only once then returns and generates the error.
I could probably try other ways (I haven't explored any other yet but I guess I could create a hashmap of ids and book objects and then extract the book objects from there) but I'm interested to know why this isn't working as it's just a simple while loop with an additional condition. Debugging doesn't really clarify it because, as I said, it only runs for i = 0, when i is 1 it fails to get the record

Testing a console input/output

Hi guys, I was trying to test a method which takes a user input, does something and then returns that input but I'm having some issues with it. I've attempted a few solutions, mostly described in SE, I will leaave them out of this
post and discuss instead the one that seemed the most likely to work instead.
This is the method that I'm trying to test (other code omitted for brevity):

public int getUserInput() {
        int choice = 0;
        boolean isValidInput = false;
        System.out.printf("Welcome. Select action: %d for READ, %d for CREATE, %d for UPDATE, %d for DELETE, %d for EXIT.", OperationOptions.READ.getValue(), OperationOptions.CREATE.getValue(), OperationOptions.UPDATE.getValue(), OperationOptions.DELETE.getValue(), OperationOptions.EXIT.getValue());
        while(!isValidInput)
            try {                 
                choice = scanner.nextInt();
                if(choice == OperationOptions.READ.getValue() || choice == OperationOptions.CREATE.getValue() || choice == OperationOptions.UPDATE.getValue() || choice == OperationOptions.DELETE.getValue() || choice == OperationOptions.EXIT.getValue())
                {
                    isValidInput = true;
                }
                else
                {
                    isValidInput = false;
                    System.out.println(String.format(Messages.NOT_ALLOWED_VALUES, OperationOptions.READ.getValue(), OperationOptions.CREATE.getValue(), OperationOptions.UPDATE.getValue(), OperationOptions.DELETE.getValue(), OperationOptions.EXIT.getValue()));
                }

                scanner.hasNextLine();
            }
            catch(InputMismatchException e) {
                 System.out.println(Messages.NOT_NUMERICAL_ERROR);
                 isValidInput = false;
                 scanner.nextLine();                 
            }
        return choice;
    }

A word about the test. What I had in mind was to test the actual input, so have a test that fakes the input, then calls the method and check that the fake input is the same as the one returned from that method. That would be
the first test, then chose another input and make sure it generates an exception and so on.

So this is my test class

package com.test.userInteraction;

import static org.junit.Assert.assertEquals;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.PrintStream;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class UserInputTest {
    UserInput userInput;
    private final InputStream systemIn = System.in;
    private final PrintStream systemOut = System.out;

    private ByteArrayInputStream testIn;
    private ByteArrayOutputStream testOut;

    @Before
    public void setUpOutput() {
        testOut = new ByteArrayOutputStream();
        System.setOut(new PrintStream(testOut));
    }
    private String getOutput() {
        return testOut.toString();
    }

    @After
    public void restoreSystemInputOutput() {
        System.setIn(systemIn);
        System.setOut(systemOut);
    }

    @Test
    public void testCase1() {
          int testString = 3;

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out;
        try {
            out = new ObjectOutputStream(bos);
            out.writeInt(testString);
            out.close();
            byte[] int_bytes = bos.toByteArray();
            provideInput(int_bytes);
            userInput = new UserInput();
            int userInput2 = userInput.getUserInput();
            assertEquals(testString, userInput2);

            bos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void provideInput(byte[] int_bytes) {
        testIn = new ByteArrayInputStream(int_bytes);
        System.setIn(testIn);

    }
}

So the problem is that it fails when it reachesint userInput2 = userInput.getUserInput(); inside getUserInput when it reaches choice = scanner.nextInt(); it generates a InputMismatchException and then controls goes back to choice = scanner.nextInt(); and then fails but I can't quite figure out why
The stack trace in the test is

java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at com.test.userInteraction.UserInput.getUserInput(UserInput.java:34)
    at com.test.userInteraction.UserInputTest.testCase1(UserInputTest.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

Any idea what is going on? It's like it doesn't like the fake input somehow

Scanner not passing control to the keyboard

Hi all,
I'm having some issues with the Scanner not waiting for input from the keyboard.
The first method processChoice takes the userChoice and the idea is that in the switch statement there is a call to a method getUserInputForProcessing that takes the action and there scanner takes an input but it's not passing the control to the keyboard,
it goes directly to the Exception because nextLine is empty, not entirely sure why. Is that because it's inside a switch statement?

public void processChoice(int userChoice, BookManager bookManager) {
        switch(userChoice) {
            case 0:
                System.out.println("Goodbye.");
                System.exit(0);
                break;
            case 1:
                System.out.println("You chose READ");
                getUserInputForProcessing("READ");
                bookManager.read();
                break;
            case 2:
                System.out.println("You chose CREATE");
                bookManager.create();
                break;
            case 3:
                System.out.println("You chose UPDATE");
                bookManager.update();
                break;
            case 4:
                System.out.println("You chose DELETE");
                getUserInputForProcessing("DELETE");

                bookManager.delete();
                break;

        }

    }

    public  String getUserInputForProcessing(String action)
    {

        Scanner scanner = new Scanner(System.in);
        System.out.printf("You chose %s: ", action);
        String nextLine = "";

        if(action.equals(READ) || action.equals(DELETE) )
        {
            System.out.println("Enter the searching criterion");
        }
        try
        {
            nextLine = scanner.nextLine();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        scanner.close();
        return nextLine;
    }

CRUD operations on a db record not using the ID in hibernate

Hi all,
I have an application which saves data (books details like book title, author and location) to a mySql db and performs CRUD operations.
I thought I'd use hibernate to take care of the ORM side of things and everything was OK when it came to create a record, but for RUD operations I had an issue.
If I'm a user, I'm likely to be willing to find a book by its author, title or location, certainly not by its ID and yet as far as I can see, hibernate uses IDs for these kind of operations.
I dug a bit further and eventually resorted to Criteria objects which apparently allow you do perform operations creating your own criteria, see below for the update functionality:

 public void update() {
        // code to modify a book
        Session session = sessionFactory.openSession();
        String searchTerm = "Jack";
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Book.class);
        Book uniqueResult = (Book) criteria.add(Restrictions.eq("author", searchTerm)).uniqueResult();
        uniqueResult.setTitle("Amended plus one");
        session.update(uniqueResult);
        session.getTransaction().commit();
        session.close();        
    }

The problem is that criteria have been deprecated and I can't find a good alternative to that, which now makes me question my choice to use hibernate in the first place. What do you guys think? I wouldn't mind using hibernate but I find hard to believe that to find a record I have to use an ID and not the author, title or whatever else, unless of course you can get the ID of the record from the searchTerm like author etc but I couldn't find a way, all the examples online relied on an ID to be passed on to the query, which I find very odd.
If you fancy looking at the application, it can be found here https://github.com/Antobbo/book-storage/tree/master/src/main/java/com/test (it's not a big project, lol)

Find duplicates in ArrayList and store them in another ArrayList

Hi guys,
I am having an issue finding duplicates in an arrayList.
Here is some code

        studentRecords.add(new Student("Jo", "Pip", "JP000", LocalDate.of(1999,9,23), Sex.FEMALE));
        studentRecords.add(new Student("Tara", "Bot", "TB345", LocalDate.of(1991,9,1), Sex.FEMALE));
        studentRecords.add(new Student("Mara", "Lewart", "ML456", LocalDate.of(1988,5,23), Sex.FEMALE));
        studentRecords.add(new Student("Anna", "Clarke", "AC010", LocalDate.of(1999,1,1), Sex.FEMALE));
        studentRecords.add(new Student("Frank", "Boia", "FB300", LocalDate.of(2001,8,13), Sex.MALE));
        studentRecords.add(new Student("Anna", "Clarke", "AC010", LocalDate.of(1999,1,1), Sex.FEMALE));
        studentRecords.add(new Student("Jo", "Pip", "JP000", LocalDate.of(1999,9,23), Sex.FEMALE));

This is the list of student records stored in an ArrayList.
I have to make sure that I identify the duplicates and store the duplicates in another arrayList, duplicateRecords for the sake of argument.
Now, the first thing I tried was to do something like this

public void findDuplicates() {
        if(!studentRecords.isEmpty()) {
            duplicateRecords = new ArrayList<Student>();
            for(int i = 0; i < studentRecords.size(); i++) {
                for(int j = 1; j < studentRecords.size(); j++) {
                    if(studentRecords.get(i).equals(studentRecords.get(j)) && i != j) {
                        duplicateRecords.add(studentRecords.get(i));
                    }
                }
            }
        }
        printDetails(studentRecords);
        System.out.println("############");
        printDetails(duplicateRecords);

    }                   

Which is buggy because, of course, it adds the record for Anna twice. I guess the complexity comes in if there are multiple duplicates, for example what happens if there are 3 records for Anna Clarke? In theory I'd want that to be twice in the duplicateRecords because it is a double duplicate
I can't really think of another approach though, any ideas?

Returning optionals from java8 stream operation

Hi guys, I'm a little stuck with something here.
Basically I have a a method which, given a List of Students will have to filter out those who are younger than 60yrs old and should return a List of Students who are over 60yrs old but I want this to be a list of Optionals rather than just a List of Students. THe difficulty is that I can't find a way to return a list of optionals like List<Optional>. I can return an optional if I use things like findFirst() or findAny()
return studentList.stream().filter(x -> x.getAge() > 60).findAny();
or i could return a simple list of students
return studentList.stream().filter(x -> x.getAge() > 60).collect(Collectors.toList());
but I want all the Students over 60 in a list of Optional.
Any idea how that can be done if it can be done that is?
thanks

Implementing Factory pattern

Hi guys, as part of an exercise I was involved with, I had to use the factory pattern to create a series of different objects, however I'd like to keep a list or map for what it matters of these objects and I'm getting a bit into troubles here.
So basically, I have a CSV file containing some data which I'd like to use to construct my objects: the data in the spreadsheet is arranged in the following cols:
name, surname, date_of_birth, type
and I'm essentially reading from the spreadsheet and using the factory pattern I'm building a series of Employee objects, either full time or part time (that's stored inside the type column in the spreadsheet).
This has been done but I'd like to keep a list of all the employees, regardless of whether they are full time or part time and I'm not sure how and where to populate that list, that's why I got a bit stack.
Here is what I've done (in a nutshell)

  • I have an abstract Employee class which is my model
  • a FulltimeEmployee and ParttimeEmployee concrete classes implementing the EMployee class
  • an EmployeeFactory class which determines whether the employee is part time or full time and builds the objects accordingly
  • a ReadData class which reads the spreadsheet and calls the factory class with the data needed to build the objects
  • a EmployeeTestingMain with main which creates a ReadData object and kicks off everything.

Ideally I'd like to keep a list of all these objects in my main class, but considering the above that's not entirely possible. So my question is, where do I create this list and where do I populate it from?
I feel that the list should be populated from the factory class because this is where I'm creating the full time/part time objects but then for me to access it form the main class I'd have to create this list as a static, and I'm not convinced. What are your thoughts?
I'm including the code below, just so you have an idea of what I've done.

Employee

package com.factoryPattern.model;

public abstract class Employee {

    private String name;
    private String surname;
    private String dob;
    private String type;

    public Employee(String name, String surname, String dob, String type) {
        this.name = name;
        this.surname = surname;
        this.dob = dob;
        if(type != null) {
            this.type = type;
        }
        else {
            this.type = "unspecified";
        }

    }

    public String getName() {
        return name;
    }

    public String getSurname() {
        return surname;
    }

    public String getDob() {
        return dob;
    }

    public String getType() {
        return type;
    }

    @Override
    public String toString() {
        return "Employee [name=" + name + ", surname=" + surname + ", dob=" + dob + ", type=" + type + "]";
    }

    public abstract void printDetails();

}

FullTimeEmployee

package com.factoryPattern.impl;

import com.factoryPattern.model.Employee;

public class FulltimeEmployee extends Employee{

    public FulltimeEmployee(String name, String surname, String dob, String type) {
        super(name, surname, dob, type);
    }
    @Override
    public void printDetails() {
        System.out.println("This is a full time employer");
        System.out.println(super.toString());       
    }

}

PartTimeEmployee

package com.factoryPattern.impl;

import com.factoryPattern.model.Employee;

public class PartimeEmployee extends Employee {

    public PartimeEmployee(String name, String surname, String dob, String type) {
        super(name, surname, dob, type);
    }

    @Override
    public void printDetails() {
        System.out.println("This is a part time employer");
        System.out.println(super.toString());
    }

}

EmployeeFactory

package com.factoryPattern.factory;

import com.factoryPattern.impl.FulltimeEmployee;
import com.factoryPattern.impl.PartimeEmployee;
import com.factoryPattern.model.Employee;

public class EmployeeFactory {
    public static void buildEmployee(String name, String surname, String dob, String type) {
        Employee employee = null;
        switch(type) {
        case "part_time":
            employee = new PartimeEmployee(name, surname, dob, type);
            employee.printDetails();
            break;
        case "full_time":
            employee = new FulltimeEmployee(name, surname, dob, type);
            employee.printDetails();
            break;          
        }

    }
}

ReadData

package com.facrotyPattern.fileReaders;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.factoryPattern.factory.EmployeeFactory;

import java.io.FileReader;

public class ReadData {
    private static final String READ_FILE_PATH = System.getProperty("user.dir") + "/Files/employees.csv";
    private static final String COMMA_DELIMITER = ",";
    //private Map<String, String> employeeProperties = new HashMap<String, String>();

    public void readDataFromDoc() {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(READ_FILE_PATH));
            String line = "";           
            br.readLine();          
            while ((line = br.readLine()) != null) 
           {
               String[] employeeDetails = line.split(COMMA_DELIMITER);
               for (int i = 0; i < employeeDetails.length; i++) {
                   //System.out.println(employeeDetails[i]);

               }
               EmployeeFactory.buildEmployee(employeeDetails[0], employeeDetails[1], employeeDetails[2], employeeDetails[3]);
               //populateMap(employeeDetails);

           }

        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        } 

       catch (IOException e) {
            e.printStackTrace();
        }

       finally {
            try {
                br.close();
            }
            catch(IOException ie) {
                System.out.println("Error occured while closing the BufferedReader");
                ie.printStackTrace();
            }
       }

    }

//  private void populateMap(String[] employeeDetails) {
//      employeeProperties.put("name", employeeDetails[0]);
//      employeeProperties.put("surname", employeeDetails[1]);
//      employeeProperties.put("date_of_birth", employeeDetails[2]);
//      employeeProperties.put("type", employeeDetails[3]);
//      
//          
//  }
}

Main class

package com.factoryPattern.testingClass;

import com.facrotyPattern.fileReaders.ReadData;

public class EmployeeTestingMain {

    public static void main(String[] args) {

        ReadData fileReader = new ReadData();
        fileReader.readDataFromDoc();

    }

}

Some feedback on the design

Hi all,
I haven't used the forum for a while so lot of the functionalities are new to me and I have to admit I found some of them really counter intuitive/annoying.

For a start, the way to reply to threads, that "Reply to this topic" button at the bottom that then turns into a small window which is incredibly annoying. Yes you can press esc and that turns into a full window but there you lose all the formatting options (code, quote etc): why can't we hav a normal full size window with all the options to reply to a thread as a default?
Then I tried to edit a post after I replied: I couldn't find an edit button to do so, that's extremely annoying and frustrating, where, if any, is the edit button?!
EDIT: about the edit button: I discovered that it's there, only it only appears at the bottom of the page so to see it you have to scroll all the way to the bottom first before thrying to edit something, still annoying, but less than what I first believed...

There might be more things, I will add when I discover them.
cheers

Creating a simple REST application

Hi guys,
I wonder if this is something I could do on this forum.
I've never worked with REST, so I thought that it could be a good exercise to try to develop a very small and simple Java application and try to make use of REST as well.
I found a brief which seems simple enough, I'll share it with you (I'm happy to change this of course if you think it's useful as for me it's just practice).

As a Rest Client
I want to submit new orders for bricks
So I can start customers’ orders

Given
A customer wants to buy any number of bricks
When 
A "Create Order" request for a number of bricks is submitted
Then
An Order reference is returned
And
The Order reference is unique to the submission

There will be more stuff later about retrieving an Order, but I thought this is a good start.

Now, I said above that I have no experience with REST, so I've been doing a bit of research and before I start coding I thought it might be a good idea to sort of clarify how we should proceed and the tech needed (I could also upload everything to git so that anybody else interested in it could benefit).

I guess I could start with a normal Java project, have a POJO Order class and a Brick one and a main class which would create the necessary objects, they seem to be the very minimum to start with.
As to how to proceed after that, I might need a bit of a guidance – that's providing that I started the right way of course.

In terms of storage, what's the easiest, using an SQL database of some Spring inbuilt database if there is any such a thing – I'd like to simplify the storage as much as possible so that I can concentrate more on the java code.

Is it a good idea to use Spring boot?
I know this is gonna be a very long thread, but I think it might be useful.

Sorting ArrayList with a comparator, how to

Hi guys, I was trying to sort an arrayList using a comparator but I didn't have much luck, or at least it seems like there is something slightly wrong with it.
I have these objects in the arrayList

employeeCollection.add(new Employee("Dan", 112));
employeeCollection.add(new Employee("Tim", 2));
employeeCollection.add(new Employee("Rick", 11));
employeeCollection.add(new Employee("Jack", 19));
employeeCollection.add(new Employee("Sid", 1));

and before sorting I have this

Name: Dan: 
ID number: 112:
Name: Tim: 
ID number: 2:
Name: Rick: 
ID number: 11:
Name: Jack: 
ID number: 19:
Name: Sid: 
ID number: 1:

and after sorting I have this:

Name: Dan: 
ID number: 112:
Name: Jack: 
ID number: 19:
Name: Rick: 
ID number: 11:
Name: Sid: 
ID number: 1:
Name: Tim: 
ID number: 2:

so it didn't go that well. Here is the code I've used, and the questions are:
-why isn't this sorted properly?
-what would I need to do to sort it in ascending order

/*
 * This tests Array list of employees*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TestCollections {
    private static List<Employee> employeeCollection = new ArrayList<Employee>();

    public static void main(String[] args) {
        createEmployees();

    }

    private static void createEmployees() {
//      for(int i = 0; i < 10; i++) {
//          Employee employee = new Employee("Jo_" + i, i);
//          employeeCollection.add(employee);
//      }
        employeeCollection.add(new Employee("Dan", 112));
        employeeCollection.add(new Employee("Tim", 2));
        employeeCollection.add(new Employee("Rick", 11));
        employeeCollection.add(new Employee("Jack", 19));
        employeeCollection.add(new Employee("Sid", 1));

        printEmployees();

        //Collections.sort(employeeCollection);
        // Sorting
        Collections.sort(employeeCollection, new Comparator<Employee>() {
            @Override
            public int compare(Employee employee, Employee employee1)
            {

                return  employee.getName().compareTo(employee1.getName());
            }
        });

        printEmployees();
    }

    private static void printEmployees() {
        employeeCollection.forEach(listItem -> System.out.println(listItem));

    }

}

and the Employee class

public class Employee {

    private String name;
    private int idNumber;

    public Employee(String name, int idNumber) {    
        this.name = name;
        this.idNumber = idNumber;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getIdNumber() {
        return idNumber;
    }
    public void setIdNumber(int idNumber) {
        this.idNumber = idNumber;
    }

    @Override
    public String toString() {
        return String.format("%s: %s: \n%s: %d:", "Name", getName(), "ID number", getIdNumber());
    }

    // Overriding the compareTo method
   public int compareTo(Employee employee) {
      return (this.name).compareTo(employee.name);
   }

   // Overriding the compare method to sort the age 
   public int compare(Employee employee, Employee employee1) {
      return employee.idNumber - employee1.idNumber;
   }
}

Error returning a boolean from method

Hi guys,
I seem to have an issue with a boolean method returining a value. Here is the code excerpt - irrelevant code omitted:

public class StreamsTest {

    public static void main(String[] args) {
        String[] arr = new String[]{"a", "b", "c"};         
        //convert array to string with streams
        List<String> list = Arrays.stream(arr).collect(Collectors.toList());        
        isElementInIt(list);   
    }

    static boolean isElementInIt(List<String> list) {
        if(list.isEmpty()) {
            return false;
        }
        else {
            for (String string : list) {
                if (string.contains("a")) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }       
    }
}

STS says that the isElementInIt method should return a boolean value, but it's already doing that whatever happens, so I'm not too sure why the error. Any idea?
thanks