Java and Scala Dynamic Load of a Class

I was in the need to dynamically create a Object from the Database and execute a method to run a task. This object can be different based on the requirements from user input.

/**
  * Handle Execution returned from database
  *
  * @param ex
  * @param text
  * @param sender
  */
def handleExecution(ex: Execution, text: String, sender: Sender): Unit = {

  if (ex.execution.split(":").size == 3 ) {
    val cname = ex.execution.split(":")(1)
    val fname = ex.execution.split(":")(2)

    try {
      val theclass = Class.forName(cname).newInstance().asInstanceOf[TExecutionService]

      if (theclass.isInstanceOf[TExecutionService]) {
        val output = theclass.run(text)
        Logger.debug("Output from " + cname + ".run " + text + " -- " + output)
        handleOutput(output, sender)
      }
    } catch {
      case exception: Throwable => {
        Logger.debug("Error in HandleExecution " + ex + " with exception " + exception)
        throw exception
      }
    }
  }

 

Although Scala is a Typed Language it was not difficult to assure that I would have a run method for the returned class and execute this code dynamically.

 

Playframework 2.5.0 and slick Log SQL Statements/Queries

In playframework 2.5.x in your logback.xml file add the following line.

<logger name="slick.jdbc.JdbcBackend.statement" level="DEBUG" />

Playframework 2.5. correct postgres configuration

In application.conf at the end of the file do:

slick.dbs.default.driver = "slick.driver.PostgresDriver$"
slick.dbs.default.db.driver = "org.postgresql.Driver"
slick.dbs.default.db.url = "jdbc:postgresql://localhost:5432/database"
slick.dbs.default.db.user = "username"
slick.dbs.default.db.password = "password"

Search vs List all in Angular 2

Handling search and the List of all items in Angular 2 in the same Component

Using the tutorial of Angular 2 for hero search was the base for this, although I wanted that the same table to show the All the items when the search was inactive without having to do a new component (one for searching and another one for listing all products).

On the template I setup the call of the enableSearch and disableSearch events

Search:&nbsp;
<input id=”search-box” (keyup)=”enableSearch()” [(ngModel)]=”searchValue” />
<button (click)=”disableSearch()”>clear search</button>

the enableSearch is fired on keyup meaning someone is starting to search for a name or keyword.

the disableSearch is fired on click of the button “clear search”

I used the two way binding of searchValue so I can clear the searched text when I disable the search

In the component method enableSearch I set a flag searchEnable = true and setup the Observable relation to this.products this way if the search is Enabled I wont set it up again and kill the observable with this new call.

products: Observable<Product[]>;
private searchTerms = new Subject<string>();

parents : Product[];

selectedCategory: Product;

db: Product[];

searchValue : string = ”;

private searchEnabled:boolean = false;

Initially I make the call for the full items list using getProducts

ngOnInit() :void {
this.products = this.productService.getProducts();
}

When the search is enabled by the keyup event this is executed

    enableSearch() {
if (!this.searchEnabled) {
this.products = this.searchTerms
.debounceTime(500)        // wait for n ms pause in events
.distinctUntilChanged()   // ignore if next search term is same as previous
.switchMap( term => term   // switch to new observable each time
// return the http search observable
? this.productService.search(term)
// or the observable of empty products if no search term
: this.productService.getProducts()
)
.catch(error => {
// TODO: real error handling
console.log(error);
return Observable.of<Product[]>([]);
});
}

this.search(this.searchValue);

this.searchEnabled = true;
}

// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}

 

if the search wasn’t enable I set up the observable and put the search term into the observable stream 😡 . The ternary operator would only fire the list if I had the search typed so to get always a result list I had to make these changes, so the table would be filled when a search was on and when there was no search.

And the code bellow disables the search and displays all the products available

disableSearch() {
this.searchValue = ”;
this.searchEnabled = false;
this.products = this.productService.getProducts();
}

I set the searchValue to an empty string and disable the searchEnabled value and getProducts from the Service.

 

 

Select ComboBox two way binding in Angular 2

This is a note for me or anyone that needs it…

@Component({
providers: [CategoryService],
template: `
Add uma Category

Nome

Parent Category
[(ngModel)]=”category.parent_id”>

*ngFor=”let p of categories” [value]=”p.id”[attr.selected]=”p.id == category.parent_id”>
{{p.name}}

<button (click)=”add()”>Save</button>
<button (click)=”goBack()”>Back</button>
`
})

Basically this makes the item from a parent category select onclick and onchange and when rendered the selected attribute will equal the value of category.parent_id

attr accesses all the attributes of the Element and it has a property binding so the value of the resulting evaluation of p.id == category.parent_id will set it’s selected attribute value.

category: Category = {id:0, name: “”, description: “”, parent_id:0};

Also on the component I have

getCategories() : void {
this.categoryService.getCategories().then( res => this.categories = res);
}

To show all categories on the category select combobox

ngOnInit pulls the categories

ngOnInit() : void {
this.getCategories(); // <–
this.route.params
// (+) converts string ‘id’ to a number
.switchMap((params: Params) => this.categoryService.getCategory(+params[‘id’]))
.subscribe((category: Category) => this.category = category);
}

 

 

 

Proteccionismo

Acreditar que um país deva ter medidas proteccionistas na importação e reclamar dos preços altos não é maluquice é exigir um mercado que se ajuste à necessidade dos consumidores. Se não houver ajuste o produtor continuará a criar desculpas e a aumentar preços sem melhorar métodos de produção e controlo de qualidade beneficiando de um monopólio.
O tipo de ajustes a que me refiro pode ser visto como a ordem do presidente Temer em 2016 de permitir a importação do feijão para terminar com a alta do preço do mesmo.
Claro que ter barreiras à importação e depois ter toda a classe alta a se beneficiar de suas viagens para contornar essas barreiras é a permissão para uma sociedade menos igual e a criação/preservação de um sistema de castas.

Scala Playframework connect to mysql

I’m writting this because I had issues following the documentation that comes with playframework
the docs are wrong or at least for me it gave me an error.

The docs states that to connect to a mysql database server you have to do the following:

If you need to connect to another JDBC-compliant database, first add the corresponding driver library to your application dependencies in build.sbt e.g.:

libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.18"

This above works ok, I had no problems.

Then add the corresponding JDBC configuration to the conf/application.conf file:

db.url=jdbc:mysql:database_name
db.driver=org.mysql.Driver
db.user=root
db.pass=secret

This above now has problems namely the db.driver section it returned me an error
java.lang.ClassNotFoundException: org.mysql.Driver

Searching the internet I found this answer

http://solvedstack.com/questions/steps-needed-to-use-mysql-database-with-play-framework-2-0

So the correct working version is:

db.default.driver=com.mysql.jdbc.Driver
db.default.user=root
db.default.pass=secret

db.default.url=”jdbc:mysql://localhost/database_name?characterEncoding=UTF-8″

Maybe for others this is easy to spot but for me it wasn’t.