Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

2023-06-03

Java

 https://www.youtube.com/watch?v=X80nJ5T7YpE Spring Boot + JWT

https://www.youtube.com/watch?v=t4-416mg6iU  OAuth


/libs/some.jar

mvn install:install-file -Dfile=some.jar -DgroupId=asdf.com -DartifactId=artif -Dversion=1.9.9 -Dpackaging=jar -DgeneratePom=true

2023-03-10

Spring Boot

Create new test: Ctrl +  Shift + t


Security:

 https://amigoscode.com/courses/728126/lectures/13124158

https://www.youtube.com/watch?v=KxqlJblhzfI

https://www.youtube.com/watch?v=b9O9NI-RJ3o

Dan Vega: 

https://www.youtube.com/playlist?list=PLZV0a2jwt22s5NCKOwSmHVagoDW8nflaC


ObjectMapper:

https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html

https://www.baeldung.com/jackson-object-mapper-tutorial


https://link.springer.com/book/10.1007/978-1-4842-3676-5

Pro Spring Boot 2

An Authoritative Guide to Building Microservices, Web and Enterprise Applications, and Best Practices


@Entity


@PrePersist

void onCreate() {

this.setCreated(LocalDateTime.now());

this.setModified(LocalDateTime.now());

}


@PreUpdate

void onUpdate() {

this.setModified(LocalDateTime.now());

}


# H2-Console: http://localhost:8080/h2-console

# jdbc:h2:mem:testdb

spring.h2.console.enabled=true


<form id="logout" action="/logout" method="POST">

<input type="hidden" name="_csrf" value="{{_csrf.token}}" />

</form>

<script>

$(function(){

$('#logoutLink').click(function(){

$('#logout').submit();

});

});

</script>


JAVA DTO Pattern Tutorial 
https://www.youtube.com/watch?v=5yquJa2x3Ko&t=193s

RuntimeException:
@ResponseStatus(HttpStatus.NOT_FOUND)
public class TestRuntimeException extends RuntimeException{
public TestRuntimeException(String id_not_found) {
}
}
String to JSON: https://github.com/amigoscode/java-streams/blob/main/src/test/java/com/amigoscode/mockdata/MockData.java
public static List<Person> getPeople() throws IOException {
    InputStream inputStream = Resources.getResource("people.json").openStream();
    String json = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    Type listType = new TypeToken<ArrayList<Person>>() {
    }.getType();
    return new Gson().fromJson(json, listType);
}

spring-data-jpa-course: https://github.com/amigoscode/spring-data-jpa-course/blob/section-7/src/main/resources/application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/amigoscode
spring.datasource.username=
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=true

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

server.error.include-message=always
server.error.include-binding-errors=always

spring:
h2.console.enabled: true
datasource:
url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
username: sa
password:
driver-class-name: org.h2.Driver
jpa:
hibernate.ddl-auto: create-drop
show-sql: true
defer-datasource-initialization: true
# properties.hibernate.format_sql: true

postgresql tips: https://youtu.be/9SGDpanrc8U?t=2273

@Bean
CommandLineRunner commandLineRunner() {
return args -> {
System.out.println("Command line runner hooray");
};
}

@Transient means the field is not for DB

Spring Data JPA https://www.youtube.com/watch?v=8SGI_XS5OPw

How To Handle Exceptions 
https://www.youtube.com/watch?v=PzK4ZXa2Tbc
https://www.youtube.com/watch?v=jFZ4lLLkT7M

??? complete course??? https://www.youtube.com/watch?v=8SGI_XS5OPw&list=PLwvrYc43l1MzeA2bBYQhCWr2gvWLs9A7S
fullstack https://www.youtube.com/watch?v=i-hoSg8iRG0&list=PLwvrYc43l1MzeA2bBYQhCWr2gvWLs9A7S&index=4

Spring Security Tutorial - [NEW] [2023] https://www.youtube.com/watch?v=b9O9NI-RJ3o

@Bean
CommandLineRunner commandLineRunner() {
    return args -> {
        System.out.println(Arrays.toString(args));
    };
}

Software Testing Tutorial - Learn Unit Testing and Integration Testing: https://www.youtube.com/watch?v=Geq60OVyBPg
Mockito: https://youtu.be/Geq60OVyBPg?t=2835
@ExtendWith(MockitoExtension.class)
ArgumentCaptor: https://youtu.be/Geq60OVyBPg?t=3506
given(repo.findById(anyInt()),willReturn(true)

Microservices Using Spring Boot and Spring Cloud
https://www.youtube.com/watch?v=p485kUNpPvE&list=PLwvrYc43l1Mwqpf9i-1B1gXfMeHOm6DeY

10 common mistakes:
Constructor Dependency Injection (not setter)
DefaultExceptionHandler https://youtu.be/CT8dbbe783s?t=558

2023-01-10

Select properJava collection


 
https://github.com/encapsulin/coreJava/blob/main/src/speedCalc/MainCollections.java

-=start=-
///////////////////////////////
addFirst()class java.util.ArrayDeque1000000: 134 ms 
addFirst()class java.util.ArrayDeque2000000: 107 ms 
addFirst()class java.util.ArrayDeque3000000: 60 ms 
addFirst()class java.util.ArrayDeque4000000: 70 ms 
addFirst()class java.util.ArrayDeque5000000: 105 ms 
removeFirst()class java.util.ArrayDeque: 22 ms 

addFirst()class java.util.LinkedList1000000: 285 ms 
addFirst()class java.util.LinkedList2000000: 38 ms 
addFirst()class java.util.LinkedList3000000: 176 ms 
addFirst()class java.util.LinkedList4000000: 155 ms 
addFirst()class java.util.LinkedList5000000: 152 ms 
removeFirst()class java.util.LinkedList: 85 ms 

addFirst()class java.util.ArrayList50000: 194 ms 
addFirst()class java.util.ArrayList100000: 615 ms 
addFirst()class java.util.ArrayList150000: 1080 ms 
addFirst()class java.util.ArrayList200000: 1509 ms 
addFirst()class java.util.ArrayList250000: 1941 ms 
removeFirst()class java.util.ArrayList: 5289 ms 

///////////////////////////////
addLast()class java.util.ArrayList1000000: 32 ms 
addLast()class java.util.ArrayList2000000: 78 ms 
addLast()class java.util.ArrayList3000000: 25 ms 
addLast()class java.util.ArrayList4000000: 18 ms 
addLast()class java.util.ArrayList5000000: 37 ms 
removeLast()class java.util.ArrayList: 27 ms 

addLast()class java.util.ArrayDeque1000000: 50 ms 
addLast()class java.util.ArrayDeque2000000: 18 ms 
addLast()class java.util.ArrayDeque3000000: 29 ms 
addLast()class java.util.ArrayDeque4000000: 18 ms 
addLast()class java.util.ArrayDeque5000000: 18 ms 
removeLast()class java.util.ArrayDeque: 55 ms 

addLast()class java.util.LinkedList1000000: 157 ms 
addLast()class java.util.LinkedList2000000: 211 ms 
addLast()class java.util.LinkedList3000000: 210 ms 
addLast()class java.util.LinkedList4000000: 15 ms 
addLast()class java.util.LinkedList5000000: 214 ms 
removeLast()class java.util.LinkedList: 86 ms 

///////////////////////////////
addMiddle()class java.util.ArrayList50000: 86 ms 
removeMiddle()class java.util.ArrayList: 89 ms 

addMiddle()class java.util.LinkedList50000: 1480 ms 
removeMiddle()class java.util.LinkedList: 1479 ms 

addMiddle()class java.util.ArrayDeque50000: 16636 ms 
-=stop=-

foxminded
https://youtu.be/IFL7qnRR6YE?t=2070
https://youtu.be/IFL7qnRR6YE?t=5895

2022-06-30

Java Map

Map map = new HashMap<>(); 
IntStream.range(0,4).forEach(i->map.put("str"+i,i)); 
System.out.println(map);
 ///////////////////////////////////////////
   

        List<Map.Entry<String, Integer>> list = map.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .sorted((a,b)->b.getValue()-a.getValue())
                .limit(3).collect(Collectors.toList());
        System.out.printf("\nList:%s:%d", list.get(0).getKey(), list.get(0).getValue());
        list.forEach(entry -> System.out.printf("\n%s:%d", entry.getKey(), entry.getValue()));

        Optional<Map.Entry<String, Integer>> opt = map.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .limit(3).findFirst();
        System.out.printf("\nOpt:%s:%d", opt.get().getKey(), opt.get().getValue());

Map<String, Integer> map2 = map.entrySet().stream()
                .sorted((a,b)->b.getValue()-a.getValue())
                .limit(1).collect(Collectors.toMap(m->m.getKey(),m->m.getValue()));
        System.out.println("map2:" + map2);

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
map.forEach((k, v) -> System.out.println((k + ":" + v)));
map.entrySet().stream()
.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); }

for (String key : map.keySet()) { System.out.println(key + ":" + map.get(key)); }

for (Integer value : map.values()) { System.out.println(value); }

2022-06-16

Java ArrayDeque

ArrayDeque<Integer> q = new ArrayDeque<>();

IntStream.range(0, 5).forEach((i) -> {q.addFirst(i);});
System.out.println(q);

IntStream.range(0, 5).forEach((i) -> {
System.out.printf("%d, ", q.pollFirst());
} );

System.out.println(q);

        ArrayDeque<Integer> q = new ArrayDeque<>();


        IntStream.range(0, 5).forEach((i) -> { q.addFirst(i);  });

        System.out.println(q);

//[4, 3, 2, 1, 0]


        IntStream.range(0, 5).forEach((i) ->{System.out.printf("%d,",q.pollFirst());});

//4, 3, 2, 1, 0, 


        System.out.println(q); //[]

        //q.clear();

 ###################################




2022-06-09

Java Collections

 https://www.programcreek.com/2014/04/check-if-array-contains-a-value-java/

1. Four Different Ways to Check If an Array Contains a Value

1) Using List:

public static boolean useList(String[] arr, String targetValue) {
	return Arrays.asList(arr).contains(targetValue);
}

2) Using Set:

public static boolean useSet(String[] arr, String targetValue) {
	Set<String> set = new HashSet<String>(Arrays.asList(arr));
	return set.contains(targetValue);
}

3) Using a simple loop:

public static boolean useLoop(String[] arr, String targetValue) {
	for(String s: arr){
		if(s.equals(targetValue))
			return true;
	}
	return false;
}

4) Using Arrays.binarySearch():
binarySearch() can ONLY be used on sorted arrays. If the array is sorted, you can use the following code to search the target element:

public static boolean useArraysBinarySearch(String[] arr, String targetValue) {	
	int a =  Arrays.binarySearch(arr, targetValue);
	if(a > 0)
		return true;
	else
		return false;
}
Comparator<Arrow> cmp = Comparator
        .comparing(Arrow::getWeight)
        .thenComparing(Arrow::getCount, Comparator.reverseOrder())
        .thenComparing((a, b) -> Character.compare(a.ch, b.ch));

listChar.sort(cmp);
 
List<Employee> sortedEmployees = employees.stream()
                .sorted(cmp).collect(Collectors.toList());

////////////////////////////////////////////////////////////////////////////////////////////////////////// 

 Collections.sort(scores, new Comparator<Score>() {

        public int compare(Score o1, Score o2) {
            return o2.getScores().get(0).compareTo(o1.getScores().get(0));
        }
    });
Collections.sort(scores, (s1, s2) -> { return s1 - s2; });
Collections.binarySearch(cats, key);

String s = list.stream().map(Objects::toString)
.sorted(Comparator.reverseOrder()).collect(Collectors.joining(""));
int[] arr = {1,2,3};
var list = Arrays.stream(arr).boxed().toList();

list.subArray(int begin, int end)

2020-03-06

Class StringBuilder

Modifier and Type Method and Description
StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(char[] str)
StringBuilder append(char[] str, int offset, int len)
StringBuilder append(CharSequence s)
StringBuilder append(CharSequence s, int start, int end)
StringBuilder append(double d)
StringBuilder append(float f)
StringBuilder append(int i)
StringBuilder append(long lng)
StringBuilder append(Object obj)
StringBuilder append(String str)
StringBuilder append(StringBuffer sb)
StringBuilder appendCodePoint(int codePoint)
int capacity()
char charAt(int index)
int codePointAt(int index)
int codePointBefore(int index)
int codePointCount(int beginIndex, int endIndex)
StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)
void ensureCapacity(int minimumCapacity)
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
int indexOf(String str)
int indexOf(String str, int fromIndex)
StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] str)
StringBuilder insert(int index, char[] str, int offset, int len)
StringBuilder insert(int dstOffset, CharSequence s)
StringBuilder insert(int dstOffset, CharSequence s, int start, int end)
StringBuilder insert(int offset, double d)
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long l)
StringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, String str)
int lastIndexOf(String str)
int lastIndexOf(String str, int fromIndex)
int length()
int offsetByCodePoints(int index, int codePointOffset)
StringBuilder replace(int start, int end, String str)
StringBuilder reverse()
void setCharAt(int index, char ch)
void setLength(int newLength)
CharSequence subSequence(int start, int end)
String substring(int start)
String substring(int start, int end)
String toString()
void trimToSize()

Class String

Modifier and Type Method and Description
char charAt(int index)
int codePointAt(int index)
int codePointBefore(int index)
int codePointCount(int beginIndex, int endIndex)
int compareTo(String anotherString)
int compareToIgnoreCase(String str)
String concat(String str)
boolean contains(CharSequence s)
boolean contentEquals(CharSequence cs)
boolean contentEquals(StringBuffer sb)
static String copyValueOf(char[] data)
Equivalent to valueOf(char[]).
static String copyValueOf(char[] data, int offset, int count)
Equivalent to valueOf(char[], int, int).
boolean endsWith(String suffix)
boolean equals(Object anObject)
boolean equalsIgnoreCase(String anotherString)
static String format(Locale l, String format, Object... args)
Returns a formatted string using the specified locale, format string, and arguments.
static String format(String format, Object... args)
Returns a formatted string using the specified format string and arguments.
byte[] getBytes()
byte[] getBytes(Charset charset)
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
Deprecated. 
This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default charset.
byte[] getBytes(String charsetName)
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
int hashCode()
int indexOf(int ch)
int indexOf(int ch, int fromIndex)
int indexOf(String str)
int indexOf(String str, int fromIndex)
String intern()
boolean isEmpty()
static String join(CharSequence delimiter, CharSequence... elements)
static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
int lastIndexOf(int ch)
int lastIndexOf(int ch, int fromIndex)
int lastIndexOf(String str)
int lastIndexOf(String str, int fromIndex)
int length()
boolean matches(String regex)
int offsetByCodePoints(int index, int codePointOffset)
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
boolean regionMatches(int toffset, String other, int ooffset, int len)
String replace(char oldChar, char newChar)
String replace(CharSequence target, CharSequence replacement)
String replaceAll(String regex, String replacement)
String replaceFirst(String regex, String replacement)
String[] split(String regex)
String[] split(String regex, int limit)
boolean startsWith(String prefix)
boolean startsWith(String prefix, int toffset)
CharSequence subSequence(int beginIndex, int endIndex)
String substring(int beginIndex)
String substring(int beginIndex, int endIndex)
char[] toCharArray()
String toLowerCase()
String toLowerCase(Locale locale)
String toString()
String toUpperCase()
String toUpperCase(Locale locale)
String trim()
static String valueOf(boolean b)
Returns the string representation of the boolean argument.
static String valueOf(char c)
Returns the string representation of the char argument.
static String valueOf(char[] data)
Returns the string representation of the char array argument.
static String valueOf(char[] data, int offset, int count)
Returns the string representation of a specific subarray of the char array argument.
static String valueOf(double d)
Returns the string representation of the double argument.
static String valueOf(float f)
Returns the string representation of the float argument.
static String valueOf(int i)
Returns the string representation of the int argument.
static String valueOf(long l)
Returns the string representation of the long argument.
static String valueOf(Object obj)
Returns the string representation of the Object argument.