środa, 18 czerwca 2025

[Java Spring] Elastic search part 2

 Part before 

Today I add to code other index (collection). I didn`t use easy lib. I use classic search ( with add).

I made similar endpoit -> get all && add. There is base for filter data search.

Intresting thing: Before add element, you can`t get data, beacuse you get exception.

I add mapper too. Golden rule, always get dto, never entity


Commit:

https://github.com/mikoxp/ProgramingRecipes/commit/b5785734a278aab035ed6549e584a74f14ba7cc2

sobota, 14 czerwca 2025

[Java Spring] Elastic search first step



Hello. Today I want to introduction how use elasticsearch with Spring Boot. I thought that other tools to optimization database, but It isn't. 

Elasticsearch is something like object database.

Object database rules

  • download fast[GET], add slow[PUT]
  • only operate on the entire entry
Example ( It is most important)
https://github.com/mikoxp/ProgramingRecipes/commit/12569037e81afd4fbbcabc649df5afbccdd4e0fe

Implementation elastic was simple. I used docker and docker-compose to start elastic.

Api Spring boot. I will be honest. It was boring. Something dependencies and repository similar to relational database.
So it is all. I want try other implementation, but it is next post.

czwartek, 30 maja 2024

[Java Example] Object checker

Story 

Some times ago, I was taking with my friend about problems. One of them interesed me.
The problem can be expresed in sentence "How to protect yourself against SQL injection".
I wasn't interested in protection as protection, because  it's a set of rules to check.
I wanted check anything on any object.

Analysis

Object or JSON or something else. This is not important. All of them have a fields. Fields have infinite number of types and names. So I thought few days. Solution is easy all fields == (key,value) and not problem.   

Step of work.
1. Change object to List of (key,value)
2. Load rules
3. Check all element by rules*
4. Return result

* One rule should check one type for example. "Check all number. Number must be not negative. 

Language:

 I prefer java, but good choose is too JS,C#, python but not C++( I think so, but I may be wrong)

Implementation

Abstract Code have few line. Used is in source.
--------------------------------------------------------

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;


public abstract class ObjectChecker {

    private List<Validator> validators;

    private final ObjectMapper mapper;

    public ObjectChecker() {
        mapper=new ObjectMapper();
        validators=new ArrayList<>();
        initValidators();
    }

    public boolean checkFields(Object object) {
        Map map = mapper.convertValue(object, Map.class);
        return map.keySet().stream().allMatch(key -> {
            Object o = map.get(key);
            if (isMap(o)) {
                if (!checkFields(o)) {
                    return false;
                }
            }
            return checkField(""+key,o);
        });
    }

    private boolean checkField(String key,Object value){
        return validators.stream().allMatch(el->el.valid(key,value));
    }

    private boolean isMap(Object o){
        if(o instanceof Map<?,?>){
            return true;
        }
        return false;
    }

    protected abstract void initValidators();

    protected void addValidator(Validator validator){
        validators.add(validator);
    }
}

------------------------------------------------------------------------------------

public interface Validator {

    boolean valid(String key,Object value);
}

Code

czwartek, 23 marca 2023

[Let`s go with golang] Count of files

 Today I write simple program 'Count file in directories'. It is similar as repack files.

I wanted count files in directories ( with subdirectories). By the way check config so two thing one program.

Source:

https://github.com/mikoxp/learn_code/tree/code/go/count%20files


niedziela, 12 lutego 2023

[Let`s go with golang] Stack Implementation

 Good Night

Today I think and I want write something. I finished study some time ago. When I learn C, I must implemented list (one-way,two-way,stack). Today I write in go so I write code. I write it to long, because I haven't written in a long time. I hope this will change.

Function file:

package elements

import "fmt"

type Element struct {
    Value int
    next  *Element
}

func WriteOut(el Element) {
    fmt.Print(el.Value)
    if el.next != nil {
        fmt.Print(" -> ")
        WriteOut(*el.next)
    } else {
        fmt.Println("")
    }
}
func Create(value int) Element {
    result := Element{Value: value}
    return result
}
func Add(el Element, value int) Element {
    result := Element{Value: value, next: &el}
    return result
}
func Take(el Element) Element {
    return *el.next
}

Main file:

package main

import (
    "fmt"

    stack "com.moles.stack/elements"
)

func main() {
    fmt.Println("Start")
    s := stack.Create(1)
    stack.WriteOut(s)
    s = stack.Add(s, 2)
    stack.WriteOut(s)
    s = stack.Add(s, 3)
    stack.WriteOut(s)
    s = stack.Add(s, 4)
    stack.WriteOut(s)
    s = stack.Take(s)
    stack.WriteOut(s)
    s = stack.Add(s, 5)
    stack.WriteOut(s)
}

Console result:

$ go run .

Start

1

2 -> 1

3 -> 2 -> 1

4 -> 3 -> 2 -> 1

3 -> 2 -> 1

5 -> 3 -> 2 -> 1


----------------SOURCE-------------------------------------------

piątek, 4 listopada 2022

[Let`s go with golang] Eratosthenes Sieve

I start weekend, so I write simple algorithm :)
Some time ago I searched Archimedes sieve, but I found Eratosthenes Sieve, 
 Today I implement it, because I can.

func EratosthenesSieve(n int) []int {
    numbersNoFirst := make([]bool, n)
    result := make([]int, 0)
    if n < 1 {
        return result
    }
    numbersNoFirst[0] = true
    for i := 2; i <= n; i++ {
        if numbersNoFirst[i-1] {
            continue
        }
        j := 2
        for i*j <= n {
            numbersNoFirst[(i*j)-1] = true
            j++
        }
    }

    for i := 0; i < n; i++ {
        if !numbersNoFirst[i] {
            result = append(result, i+1)
        }
    }
    return result[:]
}

czwartek, 2 września 2021

[Java Example] Add and remove in collect. Other



Hello. Today I want to show you how important it is to compare objects correctly.

For example code: Set<Element> set=new HashSet<>();
...
set.remove(elementA);
set.add(elementA);
You think this is stupid. Remove element and add the same element-> result before=after, but I say not necessarily. If this is set of Integer or String ok code is stupid, but for custom class object you can make situations where `before` is not `after`.
Code:
Class Element:
public class Element {
private int id;
private int value;

public Element(int id, int value) {
this.id = id;
this.value = value;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Element element = (Element) o;
return id == element.id;
}

@Override
public int hashCode() {
return Objects.hash(id);
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}

@Override
public String toString() {
return "Element{" +
"id=" + id +
", value=" + value +
'}';
}
}
Class Main:
public class Main {

public static void main(String[] args) {
Element elementA=new Element(1,1);
Element elementB=new Element(1,2);

Set<Element> data=new HashSet<>();
System.out.println("Set init empty: "+data);
data.add(elementA);
System.out.println("Set add A: "+data);
data.remove(elementB);
System.out.println("Set remove B: "+data);
data.add(elementB);
System.out.println("Set add B: "+data);
data.add(elementA);
System.out.println("Set add A: "+data);
}
}
Result in terminal
Set init empty: []
Set add A: [Element{id=1, value=1}]
Set remove B: []
Set add B: [Element{id=1, value=2}]
Set add A: [Element{id=1, value=2}]


Everyone who write in Java, known hash and equels. it is most often generated, but when you change something, it may be more useful in other ways.The road straight ahead is not always the best.