Strony

2017-10-06

JavaEE - wyświetlenie całego URI za pomocą UriInfo

UriInfo (za pomocą którego jest możliwe wyciągnięcie całego URI) można wstrzyknąć za pomocą adnotacji @Context jako pole klasy:
package pl.marceen.test.boundary;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

@Stateless
@Path("test")
public class TestRestReceiver {
    private final static Logger logger = LoggerFactory.getLogger(TestRestReceiver.class);

    @Context
    private UriInfo uriInfo;

    @GET
    @Path("logStatus")
    public String logStatus() {
        logger.info("Path: {}", uriInfo.getAbsolutePath());

        return "OK";
    }
}
Można wstrzyknąć UriInfo również jako atrybut metody:
package pl.marceen.test.boundary;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

@Stateless
@Path("test")
public class TestRestReceiver {
    private final static Logger logger = LoggerFactory.getLogger(TestRestReceiver.class);

    @GET
    @Path("logStatus")
    public String logStatus(@Context UriInfo uriInfo) {
        logger.info("Path: {}", uriInfo.getAbsolutePath());

        return "OK";
    }
}

2017-01-16

Centos6 - add and remove User

Add User

sudo adduser newuser
sudo passwd newuser

Delete User

sudo userdel -r newuser
You can add the flag “-r” to the command if you would like to simultaneously remove the users’s home directory and files.

2017-01-11

EntityManager - find list of objects with handled NoResultException

public List findAllElements(Task task) {
        logger.info("Try to find elements - task: {}", task.getId());

        try {
            return em.createNamedQuery(Element.FIND_ALL_BY_TASK, Element.class)
                    .setParameter("task", task)
                    .getResultList();
        } catch (NoResultException e) {
            logger.info(ELEMENT_NOT_FOUND_MSG);

            return Collections.emptyList();
        }
}

2016-12-29

Testy logów z log4j

Tworzymy klasę w /src/test/java/pakiet
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;

import java.util.ArrayList;
import java.util.List;

public class LogsHistorySaver extends AppenderSkeleton {
    private List logs;

    public void setUp() {
        logs = new ArrayList<>();
        Logger.getRootLogger().addAppender(this);
    }

    public void tearDown() {
        Logger.getRootLogger().removeAppender(this);
    }

    public List getLogs() {
        return logs;
    }

    @Override
    protected void append(LoggingEvent event) {
        logs.add(new Event(event.getLevel(), String.valueOf(event.getMessage())));
    }

    @Override
    public void close() {

    }

    @Override
    public boolean requiresLayout() {
        return false;
    }

    public class Event {
        private Level level;
        private String message;

        Event(Level level, String message) {
            this.level = level;
            this.message = message;
        }

        public Level getLevel() {
            return level;
        }

        public String getMessage() {
            return message;
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("Event{");
            sb.append("level=").append(level);
            sb.append(", message='").append(message).append('\'');
            sb.append('}');
            return sb.toString();
        }
    }
}
I korzystamy w niej w teście w spoób następujący:
public class KaboomTest {

    private Kaboom sut;

    private LogsHistorySaver logsHistorySaver = new LogsHistorySaver();

    @Before
    public void setUp() throws Exception {
        logsHistorySaver.setUp();
    }

    @Test
    public void log() throws Exception {
        //when
        sut.build();

        //then
        List logs = logsHistorySaver.getLogs();

        assertThat(logs.size()).isEqualTo(3);
        assertThat(logs.get(0).getLevel()).isEqualTo(Level.INFO);
        assertThat(logs.get(0).getMessage()).isEqualTo("First log");
        assertThat(logs.get(1).getLevel()).isEqualTo(Level.INFO);
        assertThat(logs.get(1).getMessage()).isEqualTo("Second log");
        assertThat(logs.get(2).getLevel()).isEqualTo(Level.INFO);
        assertThat(logs.get(2).getMessage()).isEqualTo("Third log");
    }
}

2016-12-28

Mockito - mock final class

Mockito w wersji 2.4.2 umożliwia mockowanie finalnych klas (oraz metod).

Wystarczy dodać plik
src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
zawierający jedną linię tekstu:
mock-maker-inline
Maven dependency:

    org.mockito
    mockito-core
    2.4.2

Stream zamiast forEach

Bez użycia streama (trzeba definiować listę obiektów):
private List buildTransactions(AccountNumber accountNumber) {
    List transactions = new ArrayList<>();
    accountNumber
        .getAccountHistoryList()
        .forEach(accountHistory -> transactions.add(transactionBuilder.build(accountHistory)));

    return transactions;
}
Używając streama możemy tworzenie listy obiektów pominąć:
private List buildTransactions(AccountNumber accountNumber) {
    return accountNumber
        .getAccountHistoryList()
        .stream()
        .map(accountHistory -> transactionBuilder.build(accountHistory))
        .collect(Collectors.toList());
}
Update: Można jeszcze bardziej elegancko:
private List buildTransactions(AccountNumber accountNumber) {
    return accountNumber
        .getAccountHistoryList()
        .stream()
        .map(transactionBuilder::build)
        .collect(Collectors.toList());
}