I'm trying to understand how to make and use a proxy design pattern. I have no idea what am i doing wrong. Any suggestions would be appreciated:
Load method should simulate downloading configuration from remote server... and it kinda does. The 2 seconds delay should be launched just once, and then it should go smoothly.
public interface ConfigLoader {
String load();
}
RealObject
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.RandomStringUtils;
import pl.sdacademy.prog.streams.MyExepction;
#Getter
#Setter
public class ConfigLoaderImplementation implements ConfigLoader {
private String configuration;
private String serverUrl;
public ConfigLoaderImplementation(final String serverUrl) {
this.serverUrl = serverUrl;
}
#Override
public String load() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new MyException("Sleeping canceled!", e);
}
System.out.println("Configuration from " + getServerUrl() + " downloaded successfully");
String generatedConfiguration = RandomStringUtils.randomAlphabetic(10);
setConfiguration(generatedConfiguration);
return generatedConfiguration;
}
}
Proxy
import lombok.Data;
#Data
public class ConfigLoaderProxy implements ConfigLoader {
private ConfigLoader proxy;
public ConfigLoaderProxy(String url) {
this.proxy = proxy;
}
#Override
public String load() {
if (proxy == null) {
proxy = new ConfigLoaderImplementation("www.blablA.com");
return proxy.load();
} else {
return proxy.load();
}
//todo
}
}
Test class, with main
public class ConfigLoaderDemo {
public static void main(String[] args) {
ConfigLoader proxy = new ConfigLoaderProxy("sdasd");
proxy.load();
proxy.load();
proxy.load();
}
}
public class ConfigLoaderProxy implements ConfigLoader {
private final ConfigLoader configLoader;
private String configuration;
public ConfigLoaderProxy(final ConfigLoader configLoader) {
this.configLoader = configLoader;
}
#Override
public String load() {
if (configuration == null) {
configuration = configLoader.load();
}
return configuration;
}
}
Related
I am doing a CRUD web application using Spring boot, spring mvc and Spring Data JPA. I wanted to test my code in the main class with adding a new client. It returns me a NullPointerException. I already check my code with a debug mode. Honestly I don't see where is exactly the issue, so, if it's possible to help it will be a pleasure.
Entity class :
#Entity
#Table(name="cliente")
public class Cliente implements Serializable{
#Id #GeneratedValue
private Integer idCliente;
private String iceCliente;
private String nombreCliente;
private String apellidoCliente;
private String direccionCliente;
private String telefonoCliente;
private String emailCliente;
private TipoCliente tipoCliente;
private String cuidadCliente;
public Cliente() {
super();
}
public Cliente(String iceCliente, String nombreCliente, String apellidoCliente, String direccionCliente,
String telefonoCliente, String emailCliente, TipoCliente tipoCliente, String cuidadCliente) {
super();
this.iceCliente = iceCliente;
this.nombreCliente = nombreCliente;
this.apellidoCliente = apellidoCliente;
this.direccionCliente = direccionCliente;
this.telefonoCliente = telefonoCliente;
this.emailCliente = emailCliente;
this.tipoCliente = tipoCliente;
this.cuidadCliente = cuidadCliente;
}
public Integer getIdCliente() {
return idCliente;
}
public void setIdCliente(int idCliente) {
this.idCliente = idCliente;
}
public String getIceCliente() {
return iceCliente;
}
public void setIceCliente(String iceCliente) {
this.iceCliente = iceCliente;
}
public String getNombreCliente() {
return nombreCliente;
}
public void setNombreCliente(String nombreCliente) {
this.nombreCliente = nombreCliente;
}
public String getApellidoCliente() {
return apellidoCliente;
}
public void setApellidoCliente(String apellidoCliente) {
this.apellidoCliente = apellidoCliente;
}
public String getDireccionCliente() {
return direccionCliente;
}
public void setDireccionCliente(String direccionCliente) {
this.direccionCliente = direccionCliente;
}
public String getTelefonoCliente() {
return telefonoCliente;
}
public void setTelefonoCliente(String telefonoCliente) {
this.telefonoCliente = telefonoCliente;
}
public String getEmailCliente() {
return emailCliente;
}
public void setEmailCliente(String emailCliente) {
this.emailCliente = emailCliente;
}
public TipoCliente getTipoCliente() {
return tipoCliente;
}
public void setTipoCliente(TipoCliente tipoCliente) {
this.tipoCliente = tipoCliente;
}
public String getCuidadCliente() {
return cuidadCliente;
}
public void setCuidadCliente(String cuidadCliente) {
this.cuidadCliente = cuidadCliente;
}
ClienteService :
#Service
#Transactional
public class ClienteServiceImpl implements ClienteService {
#Autowired
ClienteRepository clienteRepository;
#Override
public Cliente agregarCliente(Cliente cliente) {
return clienteRepository.save(cliente);
}
#Override
public Cliente editarCliente(Cliente cliente) {
Optional<Cliente> clienteDB = this.clienteRepository.findById(cliente.getIdCliente());
if (clienteDB.isPresent()) {
Cliente clienteUpdate = clienteDB.get();
clienteUpdate.setIdCliente(cliente.getIdCliente());
clienteUpdate.setIceCliente(cliente.getIceCliente());
clienteUpdate.setNombreCliente(cliente.getNombreCliente());
clienteUpdate.setApellidoCliente(cliente.getApellidoCliente());
clienteUpdate.setDireccionCliente(cliente.getDireccionCliente());
clienteUpdate.setCuidadCliente(cliente.getCuidadCliente());
clienteUpdate.setTelefonoCliente(cliente.getTelefonoCliente());
clienteUpdate.setEmailCliente(cliente.getEmailCliente());
clienteRepository.save(clienteUpdate);
return clienteUpdate;
} else {
throw new RessourceNotFoundException(
"Cliente no encontrado con nombre de usuario : " + cliente.getIdCliente());
}
}
#Override
public List<Cliente> obtenerCliente() {
return this.clienteRepository.findAll();
}
#Override
public void removeCliente(Integer idCliente) {
Optional<Cliente> clienteDB = this.clienteRepository.findById(idCliente);
if (clienteDB.isPresent()) {
this.clienteRepository.delete(clienteDB.get());
} else {
throw new RessourceNotFoundException("Cliente no encontrado con nombre de usuario : " + idCliente);
}
}
#Override
public Cliente obtenerClientePorId(Integer idCliente) {
Optional<Cliente> clienteDB = this.clienteRepository.findById(idCliente);
if (clienteDB.isPresent()) {
return clienteDB.get();
} else {
throw new RessourceNotFoundException("Cliente no encontrado con nombre de usuario : " + idCliente);
}
}
ClienteRepository :
#Repository
public interface ClienteRepository extends JpaRepository<Cliente, Integer> {
}
ClienteController :
#RestController
//#RequestMapping("/index")
public class ClienteController {
#Autowired
private ClienteService clienteService;
#GetMapping("/clientes")
public ResponseEntity<List<Cliente>> obtenerCliente() {
return ResponseEntity.ok().body(clienteService.obtenerCliente());
}
#GetMapping("/clientes/{id}")
public ResponseEntity<Cliente> obtenerClientePorId(#PathVariable Integer idCliente) {
return ResponseEntity.ok().body(clienteService.obtenerClientePorId(idCliente));
}
#PostMapping("/clientes")
public ResponseEntity<Cliente> agregarCliente(#RequestBody Cliente cliente) {
return ResponseEntity.ok().body(this.clienteService.agregarCliente(cliente));
}
#PutMapping("/clientes/{id}")
public ResponseEntity<Cliente> editarCliente(#PathVariable Integer idCliente, #RequestBody Cliente cliente) {
cliente.setIdCliente(idCliente);
return ResponseEntity.ok().body(this.clienteService.editarCliente(cliente));
}
#DeleteMapping("/clientes/{id}")
public HttpStatus removeCliente(#PathVariable Integer idCliente) {
this.clienteService.removeCliente(idCliente);
return HttpStatus.OK;
}
Main class :
#SpringBootApplication
//#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class NestideasFacturasApplication {
#Autowired
public static ClienteService clienteService = new ClienteServiceImpl();
public static void main(String[] args) {
SpringApplication.run(NestideasFacturasApplication.class, args);
System.out.println("Application démarrée");
System.out.println(clienteService);
clienteService.agregarCliente(new Cliente("16565465", "Hassan", "JROUNDI", "Said Hajji", "0662165537",
"hassan.jroundi#outlook.fr", TipoCliente.EMPREZA, "Salé"));
System.out.println(clienteService);
}
Stacktrace :
Stacktrace
First, for your test scenario, it's better to use ApplicationRunner.
NestideasFacturasApplication must implement ApplicationRunner, and override run method. Then you can write your test scenario in run.
Code :
#SpringBootApplication
public class NestideasFacturasApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(NestideasFacturasApplication.class, args);
}
#Override
public void run(ApplicationArguments args) {
//Your test scenario ...
}
}
Second, Change injection of ClienteService like below
#Autowired
private ClienteService clienteService;
So we have (Entire code)
#SpringBootApplication
public class NestideasFacturasApplication implements ApplicationRunner {
#Autowired
private ClienteService clienteService;
public static void main(String[] args) {
SpringApplication.run(NestideasFacturasApplication.class, args);
}
#Override
public void run(ApplicationArguments args) {
//Your test scenario
System.out.println("Application démarrée");
System.out.println(clienteService);
clienteService.agregarCliente(new Cliente("16565465", "Hassan", "JROUNDI", "Said Hajji", "0662165537", "hassan.jroundi#outlook.fr", TipoCliente.EMPREZA, "Salé"));
}
}
My java class is throwing some error. In my class i am using this to get my data.
((myDataDetails) Names.get(0)).InputParamNames().add("SomeValue");
But it is throwing error
Here is my Pohjo Class.
package common.pojo;
import java.util.Date;
import java.util.List;
public class myDataDetails
{
private String myID;
private List<String> InputParamNames;
private List InputParamData;
public String getmyID() {
return this.myID;
}
public void setmyID(String myID) {
this.myID = myID;
}
public List<String> getInputParamNames() {
return this.InputParamNames;
}
public void setInputParamNames(List<String> InputParamNames) {
this.InputParamNames = InputParamNames;
}
public List getInputParamData() {
return this.InputParamData;
}
public void setInputParamData(List InputParamData) {
this.InputParamData = InputParamData;
}
}
What should I need to change in pojo to avoid this exception.
Your class 'myDataDetails' needs to extend from LinkedHashMap in order to cast it.
What you have right now is a regular POJO class that is not an instance of LinkedHashMap, so you can't cast it as such.
EDIT: It should look like this
package common.pojo;
import java.util.Date;
import java.util.List;
import java.util.LinkedHashMap;
public class myDataDetails extends LinkedHashMap<Object, Object>
{
private String myID;
private List<String> InputParamNames;
private List InputParamData;
public String getmyID() {
return this.myID;
}
public void setmyID(String myID) {
this.myID = myID;
}
public List<String> getInputParamNames() {
return this.InputParamNames;
}
public void setInputParamNames(List<String> InputParamNames) {
this.InputParamNames = InputParamNames;
}
public List getInputParamData() {
return this.InputParamData;
}
public void setInputParamData(List InputParamData) {
this.InputParamData = InputParamData;
}
}
I am new to CDI with Dagger. I have the following structure. The issue is when I go to fetch backendService in class Main, only the direct backendService is fetched, but the underlying User dependency remains null. Is there anything wrong with this setup.
Class MyComponent
import javax.inject.Singleton;
import dagger.Component;
#Singleton
#Component(modules = {UserModule.class, BackEndServiceModule.class})
public interface MyComponent {
User user();
BackendService backendService();
void inject(Main main);
void injectIntoBackendService(BackendService backendService);
}
Class User:
import javax.inject.Inject;
public class User {
private String firstName;
private String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return "User [firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
Class UserModule
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
#Module
public class UserModule {
#Provides #Singleton User providesUser() {
return new User("Lars", "Vogel");
}
}
BackendService
import javax.inject.Inject;
import javax.inject.Named;
public class BackendService {
#Inject public User user;
private String serverUrl;
#Inject
public BackendService(#Named("serverUrl") String serverUrl) {
this.serverUrl = serverUrl;
}
public boolean callServer() {
System.out.println("User: " + user);
if (user !=null && serverUrl!=null && serverUrl.length()>0) {
System.out.println("User: " + user + " ServerUrl: " + serverUrl);
return true;
}
return false;
}
}
BackEndServiceModule
import javax.inject.Named;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
#Module
public class BackEndServiceModule {
#Provides
#Singleton
BackendService provideBackendService(#Named("serverUrl") String serverUrl) {
return new BackendService(serverUrl);
}
#Provides
#Named("serverUrl")
String provideServerUrl() {
return "http://www.vogella.com";
}
#Provides
#Named("anotherUrl")
String provideAnotherUrl() {
return "http://www.google.com";
}
}
Main
import javax.inject.Inject;
public class Main {
#Inject public BackendService backendService;
public void callService() {
boolean callServer = backendService.callServer();
if (callServer) {
System.out.println("Server call was successful. ");
} else {
System.out.println("Server call failed. ");
}
}
public static void main(String[] args) {
Main m = new Main();
MyComponent component = DaggerMyComponent.builder().build();
component.inject(m);
m.callService();
}
}
Please have a look at field injection vs constructor injection. You try to use both partially, ending up to use neither.
#Singleton
#Component(modules = {UserModule.class, BackEndServiceModule.class})
public interface MyComponent {
User user();
BackendService backendService();
void inject(Main main);
// you don't need that if you create the object!
// void injectIntoBackendService(BackendService backendService);
}
When in doubt, use constructor injection. As the name suggests..define dependencies in the constructor and get rid of any other #Inject.
#Singleton // add singleton here, use constructor injection!
public class BackendService {
public User user;
private String serverUrl;
#Inject
public BackendService(#Named("serverUrl") String serverUrl, User user) {
this.serverUrl = serverUrl;
this.user = user;
}
}
And when you don't need any further setup you don't need any #Provides annotated methods either, so get rid of provideBackendService(#Named("serverUrl") String serverUrl) please. We specified the scope on the implementation class above.
I also wrote an article about a few basic things to keep in mind when using Dagger.
I am still new to Android, I'm primarily an iOS developer.
I don't know why I can't test to see whether or not the ListArray is empty or not. I need to test and use the size of it anyways.
This is declared within the class:
Projects projects = new Projects();
The following code does not like projects.videos.size() being compared nil or 0.
try
{
if (projects != null)
{
int numberOfVideos = projects.videos.size();
if(numberOfVideos==0)
{
// myStringArray = new String[projects.videos.size()];
//
//
//
// for (int i = 0;i < projects.videos.size();i++)
// {
// myStringArray[i] = projects.videos.get(i);
// }
}
else
{
// myStringArray = new String[1];
// myStringArray[0] = "No projects";
}
}
else
{
System.out.println("Sucess");
}
}
catch (Exception e)
{
System.out.println(e);
System.out.println("somethingbad has happened");
System.out.println(projects.videos.size());
}
This is what the projects class looks like:
package com.example.musicvideomaker;
import java.util.ArrayList;
import java.util.UUID;
import java.io.Serializable;
#SuppressWarnings("serial")
public class Projects implements Serializable{
public String projectName;
public String musicStuff;
public String songTitle;
public String guid;
public boolean isBuiltVideo;
public boolean isListOfBuiltVideos;
public int selectedIndex;
public ArrayList<String> videos;
public ArrayList<String> builtVideos;
public ArrayList<Number> tPoints;
public void setProjectName(String projectName)
{
this.projectName = projectName;
}
public void setMusicStuff(String musicStuff)
{
this.musicStuff = musicStuff;
}
public void setSongTitle(String songTitle)
{
this.songTitle = songTitle;
}
public void setGuid()
{
UUID uuid = UUID.randomUUID();
this.guid = uuid.toString();
}
public void isBuiltVideo(boolean isBuiltVideo)
{
this.isBuiltVideo = isBuiltVideo;
}
public void isListOfBuiltVideos(boolean isListOfBuiltVideos)
{
this.isListOfBuiltVideos = isListOfBuiltVideos;
}
public void setSelectedIndex(int selectedIndex)
{
this.selectedIndex = selectedIndex;
}
public void addRecordedVideo(String recordedVideo)
{
this.videos.add(recordedVideo);
}
public void addBuiltVideo(String builtVideo)
{
this.builtVideos.add(builtVideo);
}
public void addTPoint(Number tPoint)
{
this.tPoints.add(tPoint);
}
}
I removed int numberOfVideos = projects.videos.size();
Instead of using if(numberOfVideos==0) I used projects.videos == null
I think it was because my projects are null so it crashes when trying to pull the size of the arrayList.
I am new to play framework and I have project with java in play framework connected to the mongoDB via MorphiaPlay. My problem is that I cannot add data. This is some of my code
public class Sign extends Controller{
static Form<Group> groupForm = form(Group.class);
public static Result index() throws Exception {
// redirect to the "group Result
return redirect(routes.Sign.group());
}
public static Result group() {
return ok(views.html.sign.render(Group.all(), groupForm));
}
public static Result newGroup() {
Form<Group> filledForm = groupForm.bindFromRequest();
if(filledForm.hasErrors()) {
return badRequest(views.html.sign.render(Group.all(), filledForm));
} else {
Group.create(filledForm.get());
return redirect(routes.Sign.group());
}
}
}
#Entity
public class Group {
#Id
public ObjectId id;
#Required
public String name;
public String email;
public String username;
public String password;
public static List<Group> all() {
if (MorphiaObject.datastore != null) {
return MorphiaObject.datastore.find(Group.class).asList();
} else {
return new ArrayList<Group>();
}
}
public static void create(Group group) {
MorphiaObject.datastore.save(group);
}
And the error is
Execution exception
[NullPointerException: null]
In C:\lo\app\models\Group.java at line 37.
public static void create(Group group) {
MorphiaObject.datastore.save(group);
}
My morphiaObject class
package controllers;
public class MorphiaObject extends GlobalSettings{
static public Mongo mongo;
static public Morphia morphia;
static public Datastore datastore;
#Override
public void onStart(play.Application arg0) {
super.beforeStart(arg0);
Logger.debug("** onStart **");
try {
MorphiaObject.mongo = new Mongo("127.0.0.1", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}
MorphiaObject.morphia = new Morphia();
MorphiaObject.datastore = MorphiaObject.morphia.createDatastore(MorphiaObject.mongo, "project");
MorphiaObject.datastore.ensureIndexes();
MorphiaObject.datastore.ensureCaps();
Logger.debug("** Morphia datastore: " + MorphiaObject.datastore.getDB());
}
}
Can you please help!