Tuesday, August 15, 2023

java: spring boot: How to search project issues in the stack trace

 

>PROBLEM

The application throws a lot of exceptions and you get confused to understand the cause because there are so many compiler complaints.


>SOLUTION

Follow by the example below.
If you go to the first compiler's complaint, you'll be mislead.

To find the real cause, the one that triggered the others, begin from the bottom to the top of the stack trace (the yellow in the example). 
The issue was caused for a field notation error. On the database the field is denoted by "pass" and not "password". Check the images at the bottom.


2023-08-15 09:37:23 # [restartedMain] # ERROR # o.s.boot.SpringApplication # method: reportFailure # Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'appController': Unsatisfied dependency expressed through field 'wsSvc'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'wsSvcImpl': Unsatisfied dependency expressed through field 'encryptionSvc'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'encryptionSvc': Unsatisfied dependency expressed through field 'securitySvc'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securitySvc': Unsatisfied dependency expressed through field 'accControlSvc'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accControlSvc': Unsatisfied dependency expressed through field 'accControlRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accControlRepository' defined in com.drillback.setget5.model.repository.security.AccControlRepository defined in @EnableJpaRepositories declared on JpaConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)! Reason: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'wsSvcImpl': Unsatisfied dependency expressed through field 'encryptionSvc'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'encryptionSvc': Unsatisfied dependency expressed through field 'securitySvc'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securitySvc': Unsatisfied dependency expressed through field 'accControlSvc'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accControlSvc': Unsatisfied dependency expressed through field 'accControlRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accControlRepository' defined in com.drillback.setget5.model.repository.security.AccControlRepository defined in @EnableJpaRepositories declared on JpaConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)! Reason: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'encryptionSvc': Unsatisfied dependency expressed through field 'securitySvc'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securitySvc': Unsatisfied dependency expressed through field 'accControlSvc'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accControlSvc': Unsatisfied dependency expressed through field 'accControlRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accControlRepository' defined in com.drillback.setget5.model.repository.security.AccControlRepository defined in @EnableJpaRepositories declared on JpaConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)! Reason: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securitySvc': Unsatisfied dependency expressed through field 'accControlSvc'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accControlSvc': Unsatisfied dependency expressed through field 'accControlRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accControlRepository' defined in com.drillback.setget5.model.repository.security.AccControlRepository defined in @EnableJpaRepositories declared on JpaConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)! Reason: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accControlSvc': Unsatisfied dependency expressed through field 'accControlRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accControlRepository' defined in com.drillback.setget5.model.repository.security.AccControlRepository defined in @EnableJpaRepositories declared on JpaConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)! Reason: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accControlRepository' defined in com.drillback.setget5.model.repository.security.AccControlRepository defined in @EnableJpaRepositories declared on JpaConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)! Reason: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!

Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)! Reason: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!

Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract com.drillback.setget5.model.repository.security.AccControl com.drillback.setget5.model.repository.security.AccControlRepository.findByEmailAndMsg(java.lang.String,java.lang.String)!

Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: password of: com.drillback.setget5.model.repository.security.AccControl [from com.drillback.setget5.model.repository.security.AccControl ac where ac.email=:email and ac.password=:password]

Caused by: org.hibernate.QueryException: could not resolve property: password of: com.drillback.setget5.model.repository.security.AccControl [from com.drillback.setget5.model.repository.security.AccControl ac where ac.email=:email and ac.password=:password]

Caused by: org.hibernate.QueryException: could not resolve property: password of: com.drillback.setget5.model.repository.security.AccControl








>ENV

Java


Wednesday, July 12, 2023

RabbitMQ: Application terminated: factory failed to instantiate due to: Unsupported or unrecognized SSL message.

 

>PROBLEM


Attempt to access the RabbitMQ service, throws the follwing:


Application terminated: factory failed to instantiate due to: Unsupported or unrecognized SSL message.

javax.net.ssl.SSLException: java.net.SocketException: Connection reset

at sun.security.ssl.Alert.createSSLException(Alert.java:127)

at sun.security.ssl.TransportContext.fatal(TransportContext.java:370)

at sun.security.ssl.TransportContext.fatal(TransportContext.java:313)

at sun.security.ssl.TransportContext.fatal(TransportContext.java:308)

at sun.security.ssl.SSLTransport.decode(SSLTransport.java:141)

at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1290)

...

Suppressed: java.net.SocketException: Connection reset by peer: socket write error

at java.net.SocketOutputStream.socketWrite0(Native Method)

at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)

...

Caused by: java.net.SocketException: Connection reset

at java.net.SocketInputStream.read(SocketInputStream.java:210)

at java.net.SocketInputStream.read(SocketInputStream.java:141)

at sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:475)

...

javax.net.ssl.SSLException: java.net.SocketException: Connection reset

at sun.security.ssl.Alert.createSSLException(Alert.java:127)

at sun.security.ssl.TransportContext.fatal(TransportContext.java:370)

at sun.security.ssl.TransportContext.fatal(TransportContext.java:313)

...

Caused by: java.net.SocketException: Connection reset

at java.net.SocketInputStream.read(SocketInputStream.java:210)

at java.net.SocketInputStream.read(SocketInputStream.java:141)

at sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:475)


>SOLUTION


Enable or disable the SSL protocol.

An example of the properties file (application.yml):


  rabbit-host: mydomain.com 

  rabbit-port: 5672

  rabbit-ssl: false

  rabbit-user: john doe

  rabbit-pass: secret



Java code snippet to check the "rabbit-ssl" property:


if (PropertiesYml.BROKER_SSL) {

try {

factory.useSslProtocol();

this.connection = factory.newConnection();

} catch (KeyManagementException | NoSuchAlgorithmException | IOException | TimeoutException e) {

logger.error(String.format("Application terminated: factory failed to instantiate due to: %s.", e.getMessage()));

}

} else {

try {

this.connection = factory.newConnection();

} catch (IOException | TimeoutException e) {

logger.error(String.format("Application terminated: factory failed to instantiate due to: %s.", e.getMessage()));

}

}


>ENV

RabbitMQ v3.7.8
Erlang v21.2.6
Java 17

RabbitMQ: Caused by: com.rabbitmq.client.ShutdownSignalException: connection error, java.io.IOException, Caused by: java.io.EOFException


>PROBLEM


Attempt to connect to RabbitMQ returns the following:


java.io.IOException

at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:129)

at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:125)

at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:396)

...

Caused by: com.rabbitmq.client.ShutdownSignalException: connection error

...

Caused by: java.io.EOFException

at java.io.DataInputStream.readUnsignedByte(DataInputStream.java:290)

...

Caused by: com.rabbitmq.client.ShutdownSignalException: connection error

...

Caused by: java.io.EOFException

at java.io.DataInputStream.readUnsignedByte(DataInputStream.java:290)

...

java.io.IOException

at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:129)

at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:125)

at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:396)

...

Caused by: com.rabbitmq.client.ShutdownSignalException: connection error

Caused by: java.io.EOFException

at java.io.DataInputStream.readUnsignedByte(DataInputStream.java:290)

...



>SOLUTION


Check the following:

1.Usually, the console management uses 15672 port.

2. Usually, the HTTP request via app (web service/microserve) uses 5672

3. Make sure to enable these ports when working with container (docker).

4. Avoid using /api  on a RESTful web service because "/api" is already used by the native rabbitmq's ws,



An example of the properties file (application.yml):

  rabbit-host: mydomain.com 

  rabbit-port: 5672

  rabbit-ssl: false

  rabbit-user: john doe

  rabbit-pass: secret


>ENV

RabbitMQ v3.7.8
Erlang v21.2.6
Java 17

Thursday, June 1, 2023

software engineering: reducing risks and issues when deploying on production

 

>PROBLEM

While developing an application, you have worked using local env(environment), using your local database or cloud resources of your own.
Then, it comes the time when you need to deploy to production or another job's env.
It is the moment that may happen the usual setbacks, issues showing differences among the job's env versus your local env.

The question is:
How may you reduce the issues when deploying on another env?


>SOLUTION

The full evaluation of all possibilities is impossible, so I'll offer you an example, and  by analogy you may apply to yours.

One very trivial item from our checklist is the resources closing, like files and database connections.
This example uses PostgreSQL database and the connections issues.

In our checklist we may have these two basic items:
1- How does the job's database env differ from my local database?
2- How to test my application to make sure that all resources are really closed when it is terminated?


Solving item 2 - Is your app functioning well?

First, make sure that your application is closing all resources.
For instance, if using PostgreSQL, do:

a - Before starting the app, run:

SELECT sum(numbackends) FROM pg_stat_database;
The cmd returns the number of busy connections, for example: 8

b - Start your app and run some features.

c - Repeat step "a".
Take note.

d - Close the app and repeat step 'a'.

e - Compare de results.

NOTE: try to do this during periods the database hasn't an intense usage because the usage fluctuation may interfere and you have to do some guessing, but you may be lucky if you perform the test when no other new outside connection occurs among the procedures. Choose a proper time when your team is out, or not working with the resource.


Solving item 1 - How does the job's configuration differ from yours?

Considering that you have no access to the configurations of your job's database, as usual, do this:

Choose a moment when your job's database resource has little activity.
Start your app, then close it abruptly, forcing it to terminate without closing your database resources.
Repeat it many times until you the connection to the database is denied, but counting.
The denial is easy to check using DBeaver, DBSchema, PgAdmin, etc.

If your database denies access, you have two possibilities:
Or your job's configuration is restrictive or poor.
A restrictive configuration limits on purpose the number of available connections.
The poor configuration just happens to go as it is without further knowledge of the guy who did it.

After the test, it is recommended that you create another local database having the same restriction of your job's configuration. That way, you'll have one problem less when deploying to the job's env.

>ENV

PostgreSQL (any database)
Any application.


Tuesday, January 10, 2023

angular fails rendering elements (dropdowns, edtitor, etc.)


>PROBLEM

Suddenly, the angular project fails rendering some elements, like dropdowns, editors, and they disappear or stops working.


>SOLUTION

*** SEE ADDITIONAL NOTES BELOW, BEFORE PROCEEDING.


1. Stop the app.

2. Clean the cache:

Linux:

$ANGULAR_PROJECT/modules/setget-ax/ramnode1/.angular/cache/$VERSION/angular-webpack/*

$ANGULAR_PROJECT/drillback/modules/setget-ax/ramnode1/.angular/cache/$VERSION/babel-webpack/*


Example:

rm -Rf $ANGULAR_PROJECT/drillback/modules/setget-ax/ramnode1/.angular/cache/13.3.10/babel-webpack/*


Windows using CygWin

rm -Rf $ANGULAR_PROJECT\modules\setget-ax\ramnode1\.angular\cache\$VERSION\angular-webpack\*

rm -Rf $ANGULAR_PROJECT\drillback\modules\setget-ax\ramnode1\.angular\cache\$VERSION\babel-webpack

3. Restart the app


*** ADDITIONAL NOTES:

1. Instead of deleting the cache, you may move to a temporary folder just in case of rollback.


2. Sometimes, if a widget freezes, it may be a browser issue.

Before cleaning the cash, try to close the browser and make sure that there are no remaining threads.

Use tasklist (Windows) or ps aux (Linux).

Reopen the browser and test again.


3. Sometimes, Windows may get unstable, mostly after a system update.
Restart Windows.
Yeh! It may be strange, but it happened to me sometimes that just rebooting Windows solved the issue. 



>ENV

Angular CLI: 14.2.9
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64


[MYREF]:
y;faq-angular fails rendering elements (dropdowns, edtitor, etc.)<memo<angular;.

Monday, December 12, 2022

postgreSQL: how to copy (duplicate) a row with binary data

 

>PROBLEM

You need to duplicate a table's row copying from a previous one that contains decode binary data that we shal avoid using copy/paste.


>SOLUTION

Notice that in this example, prtkey and pubkey are binary fields using bytea type.

The uptime is a timestamptz not null field.

 

INSERT INTO keysvc (id,title,pvtkey,pubkey,status,uptime) VALUES( 2, 'ramnode4',null ,null ,1, CURRENT_TIMESTAMP);  

with keys as (SELECT pvtkey, pubkey, uptime FROM keysvc where id = 1)
update keysvc set pvtkey=(select pvtkey from keys), pubkey=(select pubkey from keys), uptime=(select uptime from keys) where id =40;

NOTE: this solution was also published by myself at this date on 
There you'll find another alternative.

>ENV

PostgreSQL


Thursday, December 8, 2022

angular: [webpack-dev-server] Disconnected! polyfills.js:1 [webpack-dev-server] Trying to reconnect...

  

>PROBLEM


When you access the Angular app, the browser's console returns the following message, that keeps repeating:

[webpack-dev-server] Disconnected!
polyfills.js:1 [webpack-dev-server] Trying to reconnect...


>SOLUTION


When starting the Angular app using the "--host" flag, it may also require the "--disable-host-check" flag.

It usually happens when using docker, and it is required the "--host" flag to enable access to the app.


Notice that, when you start the service using just the "host" flag, you get this advice:


  Warning: This is a simple server for use in testing or debugging Angular applications

  locally. It hasn't been reviewed for security issues.

  Binding this server to an open connection can result in compromising your application or

  computer. Using a different host than the one passed to the "--host" flag might result in

  websocket connection issues. You might need to use "--disable-host-check" if that's the

  case.

  


>ENV

Angular CLI: 14.2.9

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64

debian/docker




[MYREF]:
y;faq-angular [webpack-dev-server] Disconnected! polyfills.js:1 [webpack-dev-server] Trying to reconnect...<memo<angularx;.

Monday, November 28, 2022

Refused to apply style from 'http://localhost:80/api/index' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

 


>PROBLEM

Attempt to access the server returns:

Refused to apply style from 'http://localhost:80/api/index' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.


>SOLUTION 


This kind of issue usually happens because it was not possible to reference the sources.

In this examples, the code was developed using "/" as root URL by the respective spring annotation:

  @RequestMapping("/")   

In this specific case this annotation may be omitted, because the framework assumes it as default, but shown here to clarify.


And the access was:

  http://localhost:8047/


After, the root URL was mapped to "/sg5", using:

  @RequestMapping("/sg5")


And the access was switched:

  http://localhost:8047/sg5


Considering the changes also made in the security layer (in this case the spring security class), it is also required to refactor the static references adding "../" before them.


NOTES: 

1. JavaScript scripts generates CORS messages instead of MIME message. 

To solve, check the example below:

- BEFORE:

<script src="bootstrap/js/bootstrap.min.js"></script>



- SOLUTION: relative path was fixed:

<script src="../bootstrap/js/bootstrap.min.js"></script>


2. Possibly, It may be necessary to update the application's CORS configuration depending of its architecture.


>ENV

springboot

java17



[MYREF]:
y;faq-Refused to apply style from 'http://localhost:8047/sg5/index' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.<memo<springboot;.

Saturday, November 26, 2022

linux: docker: docker: Error response from daemon: driver failed programming external connectivity on endpoint


>PROBLEM


Attempt to start a docker container, returns:

  Error response from daemon: driver failed programming external connectivity on endpoint YOUR_CONTAINER_NAME

  (a8dc1e2b183712da69829c9efd642bf2bdcb504556a8dbd3324902adcb79fc3b): (

  iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 0/0 --dport SOME_PORT_HERE -j DNAT --to-destination 172.17.0.2:8048 ! -i docker0

  : iptables: No chain/target/match by that name. 

   (exit status 1))

  Error: failed to start containers: YOUR_CONTAINER_NAME


>SOLUTION

This kind of issue has more than one cause.
It will be described two of them, very common causes.


1. iptables config

Set the following iptables rule before the others, at the beginning:

  iptables -t nat -A POSTROUTING -o docker0 -j MASQUERADE


2. Restart docker

If you already has set procedure below and if it happens again, try to do:

  systemctl restart docker



>ENV

docker/debian based distributions



[MYREF]:

y;faq-docker: Error response from daemon: driver failed programming external connectivity on endpoint<memo<docker;.


Thursday, November 24, 2022

linux: OpenVz: docker: iptables nat issue: iptables v1.8.7 (legacy): can't initialize iptables table `nat': Table does not exist (do you need to insmod?)


 >PROBLEM

Common scenarios:

1. Docker installation fails on Linux distributions,

 or  

2. Attempt to run "iptables -t nat -L -n" command fails.


Both scenarios return the same message:

iptables v1.8.7 (legacy): can't initialize iptables table `nat': Table does not exist (do you need to insmod?)
Perhaps iptables or your kernel needs to be upgraded.


Reason:

Docker uses iptables during installations where the S.O. has this firewall command by default.


>SOLUTION


Make sure that is the case by running the following command:

iptables -t nat -L -n


If it fails, there are two main possibilities.
Choose first the easier one.

- If using a cloud hosting, check with the support service to "enable NatFilter".

or

- Maybe a system upgrade is required, sometimes even the kernel.


A successful test, when the NatFilter is enabled shall return something like this:

$ iptables -t nat -L -n

Chain PREROUTING (policy ACCEPT)

target     prot opt source               destination

Chain INPUT (policy ACCEPT)

target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)

target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)

target     prot opt source               destination


>ENV

cloud hosting

OpenVz/debian 9-11/Ubunto18-22



MYREF: 
y;faq-iptables v1.8.7 (legacy): can't initialize iptables table `nat': Table does not exist (do you need to insmod?)<memo<linux;.

Saturday, November 19, 2022

windows: npm: angular: 'ng' is not recognized as an internal command

 

>PROBLEM

Running the command "ng v", returns:

  'ng' is not recognized as an internal command

  'ng' nĂ£o Ă© reconhecido como um comando interno  (Portuguese)


>SOLUTION


This procedure is about Windows O.S.

After attempting to solve the problem through other experiences, I got no solution.

My Path seemed to be corrupted and there were no files under the user's folder, for instance at:

  C:\Users\<USER>\AppData\Roaming\npm\node_modules


So, to solve the issue, I decided to restart the environment installation from scratch.

This same procedure were executed several times, including restarting the sytem, until the success came. :-)

  1. Uninstall node.js using the windows "Add remove application...".

  2. Remove leftovers. Sometimes there are "skeleton" folder left behind. In my case, it was: C:\Users\<USER>\AppData\Roaming\npm\node_modules

  3. Run the node.js as Administrator. Make sure of that, because it is important.

  4. After the installation is fineshed, check it:
    node --version
    npm --version

  5. Install @angular/cli that it is the lib that provides the "ng" command, as global installation (important: not locally).

  6. The previous command will install the latest version. If you're working with a specific version, go to the angular project's root folder and check the package.json file to verify which version the project is working with: 
    "dependencies": {
     ...
     "@angular/cli": "^13.2.2",  
    ...

  7. Under the project's root folder, install cli using the same version:
    npm install @angular/cli@13.2.2

  8. Eventually, check it the project's env:
    ng v

  9. It shall return the same version used for the project.








>ENV

Angular
Node.js 16


Monday, November 7, 2022

angular: ERROR: TypeError: Cannot read properties of undefined (reading 'valid')

 

>PROBLEM


When the page loads, the browser's console shows the following error:

  ERROR: TypeError: Cannot read properties of undefined (reading 'valid')






>SOLUTION

1. Check if the HTML template uses form validation. For instance: f.form.valid.

Example:

  <button type="submit" class="btn btn-primary" [disabled]="!f.form.valid">Create info</button>


2. Check the form binding.

It shall be something like this:
#f="ngForm"


>BEFORE

        <form name="modalForm" id="modal_create_info_form" #f novalidate
          (ngSubmit)="f.form.valid && createInfo(modalSelector.value)">

>AFTER

        <form name="modalForm" id="modal_create_info_form" #f="ngForm" novalidate
          (ngSubmit)="f.form.valid && createInfo(modalSelector.value)">



3. Make sure that it declared the respective libs:
 

import { FormControl } from '@angular/forms';

or

// import { FormControl, AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';



>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64

Wednesday, November 2, 2022

angular: template/component renderization failure

 

>PROBLEM


The template/component fails to renderize (it doesn't appear where it should).


>SOLUTION


Considering an example component in the component.html file: 

<my-component></my-component>


Supposing multi-level modules, declare the component in the first level module.


>firts-level.module.ts

import { MyComponentComponent } from './first level path/MyComponentComponent.component';


@NgModule({

  declarations: [

    // ...

    MyComponentComponent,

  ],


NOTE: if the component has parent-child binding, check also its configuration.



>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


angular: Error: Inlining of fonts failed. An error has occurred while retrieving

 


>PROBLEM


Angular compilation fails returning the following message:


  Error: Inlining of fonts failed. An error has occurred while retrieving https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap over the internet.

  getaddrinfo ENOTFOUND fonts.googleapis.com





>SOLUTION


Check your Internet connection.



>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


Friday, October 28, 2022

angular: Error: NG0301

 

>PROBLEM


The angular app throws the following error during attempt to open a child modal:

   Error: NG0301

This error may have many types of causes.
It usually means some issue between the component and the template configuration or some subjacent library version incompatibility.

Below there are the four different solutions from different real cases that worked for me.

NOTE: the 3rd solution is the one that I most use. If you are sure that nothing changed in your code, try it. Run the "npm audit fix --force" once or more, but make sure that a node_modules backup is made before. If this folder gets corrupted, fixing it is time-consuming.


>SOLUTION #1


>before

<button id="btn_update_activity_" type="button" class="btn btn-primary icon-config icon-update_20g"
  style="margin-top: 5px; margin-left: 5px;" (click)="openModal(template)">Open modal</button>

<ng-template #template>

>after

Found duplicated ng-template reference.
The second one was switched to solve the conflict.

<button id="btn_update_todo_" type="button" class="btn btn-primary icon-config icon-update_20g"
  style="margin-top: 5px; margin-left: 5px;" (click)="openModal(templateUpTodo)">Open modal</button>

<ng-template #templateUpTodo>



>SOLUTION #2


>before

- todos.component.ts (parent-child biding):

  <!-- xxmodal TODO UPDATE -->

  <app-uptodo [theTodo]="todoi" [email]="email" [stoken]="stoken" [activity]="activity" [activities]="activities"

  (click)="setTodoi(todo)" (updateEvent)="updateTodo($event)"></app-uptodo>

  <!-- xxupdate -->



- uptodo.component.ts (child):

export class UptodoComponent implements OnInit {

  modalRef: BsModalRef;

  @Input()

  email: string;

  @Input()

  stoken: string;

  @Input()

  activities = [];

  @Input()

  theTodo: any;

  activity: string;

  @Output()

  updateEvent = new EventEmitter<string>();


>after

- uptodo.component.ts (child):

export class UptodoComponent implements OnInit {

// ...

  @Input()

  activity: string;

  @Output()

  updateEvent = new EventEmitter<string>();



>SOLUTION #3

Make a backup of the node_modules folder in another place.
Stop the app.

1. Run the command:
npm install

2. Apply the fix command:
npm audit fix

3. Usually there are issues. Run again with --force flag, one or many times:
npm audit fix --force

4. Restart the app.


>SOLUTION #4

If the issue happens too frequently, maybe an update may solve it.
Do:
npm update

Please!!! Create a backup first to not cry later!  :-)

NOTE:
After the update, it may appear some VSCode error messages.
Restart VSCode.


>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64






MyRef;
y;faq-Error: NG0301<memo<angularx;.

Saturday, October 15, 2022

angular: ngx-bootstrap modal fails when closing

 

>PROBLEM

Attempt to close the modal fails.






ERROR TypeError: Cannot read properties of undefined (reading 'hide')
    at main.js:1:434209
    at UT (main.js:1:69900)
    at s (main.js:1:70062)
    at HTMLButtonElement.<anonymous>


>SOLUTION

BEFORE

The new modal component code:

import { Component, OnInit, TemplateRef } from '@angular/core';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';

@Component({
  selector: 'app-deltodo',
  templateUrl: './deltodo.component.html',
  styleUrls: ['./deltodo.component.scss'],
})
export class DeltodoComponent implements OnInit {

  modalRef: BsModalRef;
  title: string;

  constructor() {}


  ngOnInit(): void {}

}

AFTER

The modal component code:

 

import { Component, OnInit, TemplateRef } from '@angular/core';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';

@Component({
  selector: 'app-deltodo',
  templateUrl: './deltodo.component.html',
  styleUrls: ['./deltodo.component.scss'],
})
export class DeltodoComponent implements OnInit {

  title: string;
  // list: any[] = [];

  constructor(public modalRef: BsModalRef) {}

  ngOnInit(): void {}

}

 

  


>ENV

angularx_ngx_bootstrap_modal_

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64

Friday, September 9, 2022

angular tutorial: After some time without programming, I need a refresh! :-)

 

>PROBLEM


Like as everybody never forgets... What a lie!  :-)

After sometime without using a technology, you need "swap from disk to memory".


>SOLUTION


Create a revision summary.

Example here.


>ENV

Angular

Thursday, September 1, 2022

node.js: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

 

>PROBLEM


A request generates the following error:

  Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client


>SOLUTION


It happens when some exception occurs before returning the request, for instance a "res.sent" statement.

Debug the application step-by-step.

To simplify, you may comment on the code from the start.

Tip: check database exceptions not treated.

Having more than one exception becomes tricky if you can't reproduce the same request.


Be sure to fix all possible exceptions.

TIPS

- Verify database possible exceptions (undefined/null values).
- If using JWT, check possible "jwt session expired" exception.
- "if conditions" and "redirections".
Some if conditions may not avoid running the code ahead from it.
- Make sure that you have guarded your arguments checking if they are possibly null or undefined.
- Unexpected type values.
 JavaScript is not a typed language, so part of the code may get something different from expected.

The above tips are just some of them. 


>ENV

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


Saturday, August 27, 2022

node.js: date-and-time offset = dateObj.getTimezoneOffset() TypeError: Cannot read properties of undefined (reading 'getTimezoneOffset')

 

>PROBLEM


Supposing using date-and-time lib:

  npm install date-and-time --save

  const date = require('date-and-time')


and the date returning the standard format, something like this (locale: Brazil):

obj.createdAt = 'Fri Aug 26 2022 21:14:34 GMT-0300 (HorĂ¡rio PadrĂ£o de BrasĂ­lia)';


the compiler throws the following error:

  date-and-time offset = dateObj.getTimezoneOffset() 

  TypeError: Cannot read properties of undefined (reading 'getTimezoneOffset')



>SOLUTION


***WRONG

created_at: date.format(obj.createdAt, 'YYYY/MM/DD HH:mm:ss'),


>RIGHT

created_at: date.format(new Date(obj.createdAt), 'YYYY/MM/DD HH:mm:ss'),



>ENV

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


Tuesday, August 16, 2022

javascript: TypeError: Cannot read properties of undefined

 


>PROBLEM


TypeError: Cannot read properties of undefined


>SOLUTION


This error may have many causes.

Here, it's shown a tricky one — cyclic reference, when one file references the other.

Check the example below:


>file1 - SecTools.js

const UserSvc = require('../../models/business/UserSvc');

static verifySToken(req) {

if (req === 'undefined' || req == null) return false;

let userStoken = UserSvc.stokenSvc[req.body.email];

//...

}


>file2: UserSvc.js

const SecTools = require('../security/SecTools');

myOtherfunction() {

user.token = SecTools.signWithJwt(user.email);

}

The SecTools has reference to UserSvc, and vice-e-versa.


Remove the cyclic reference to fix the issue.


>IMPORTANT NOTE

When it happens an error during runtime, the same message may happen.
For instance, if the code calls a persistence method that is not recognized (found), to debug the app try to comment previous operations before that method is called. There is a good probability that one operation before (above the call that fails) is throwing an exception that results with this message.
It happens with many compilers, for many programming languages.
Something "mad", unexpected, think about this hypotheses.
Do not take compiler messages as they were always possible to show the real problem that it is causing the issue.


>ENV

Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64


express: Error: Cannot find module ...code: 'MODULE_NOT_FOUND'

 


>PROBLEM

Express returns compilation error:


node:internal/modules/cjs/loader:488

      throw e;

      ^

node:internal/modules/cjs/loader:488
      throw e;
      ^

Error: Cannot find module 'M:\work\devcli_\javascript\jstopics\
   express\node_sequelize_ultering_ml40643\prj\node_modules\sequelize\types'
    at createEsmNotFoundErr (node:internal/modules/cjs/loader:960:15)
    at finalizeEsmResolution (node:internal/modules/cjs/loader:953:15)
    at resolveExports (node:internal/modules/cjs/loader:482:14)
    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.&lt;anonymous&gt; (M:\work\devcli_\javascript\jstopics\
       express\node_sequelize_ultering_ml40643\prj\models\security\SecTools.js:5:19)
    at Module._compile (node:internal/modules/cjs/loader:1101:14) {
  code: 'MODULE_NOT_FOUND',
  path: 'M:\\work\\devcli_\\javascript\\jstopics\\
      express\\node_sequelize_ultering_ml40643\\prj\\node_modules\\sequelize\\package.json'
}




 

>SOLUTION


The tip is in this line (red):

Error: Cannot find module 'M:\work\devcli_\javascript\jstopics\express\node_sequelize_ultering_ml40643\prj\node_modules\sequelize\types'

that means the class loader was not able to find a reference.
Check the require statements that contain the type.

In this example, it was found the mistake in this declaration:

const { Utils } = require('sequelize/types');



>ENV

Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64

Monday, August 8, 2022

java: javax.mail fails to send email to Gmail account returning: 535-5.7.8 Username and Password not accepted. Learn more at


 >PROBLEM

Attempt to send email fails returning the following message:

javax.mail fails to send email to Gmail account returning: 535-5.7.8 Username and Password not accepted. Learn more at


>SOLUTION

Since 05/30/2022 , you may lose access to apps that are using less secure sign-in technology.
To help keep your account secure, Google will no longer support the use of third-party apps or devices which ask you to sign in to 
your Google Account using only your username and password. 

To solve this issue, there are options available.
A fast approach is to use the "App Password" option that generates a new password for the application to get access.

Using this option, the only thing necessary is to replace the previous user's password in your java code with the new password generated.

Go to "Fix Problems", then "Use an App Password".
Follow by the pictures.















>Extra

Configuration used:

PROPS.put("mail.debug", "false");

PROPS.put("mail.smtp.port", "587");

PROPS.put("mail.smtp.auth", "true");

PROPS.put("mail.smtp.starttls.enable", "true");

PROPS.put("mail.smtp.host", "smtp.googlemail.com");

PROPS.put("mail.smtp.ssl.trust", "smtp.gmail.com");

PROPS.put("mail.smtp.ssl.protocols", "TLSv1.2");

PROPS.put("mail.smtp.host", "smtp.gmail.com");

session = Session.getInstance(PROPS, new javax.mail.Authenticator() {

&#64;Override

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(SENDER, PASSWORD);

}

});


>ENV

Java (javax.mail)
Windows

Wednesday, August 3, 2022

angular/node.js: debugging "Warning: Module not found: Error: Can't resolve..."


 >PROBLEM


After installing MongoDB libs

npm i --save mongoose

npm install @types/mongoose --save-dev


-- used for MongoClient

npm install --save mongodb

npm install --save dotenv



Warning: Module not found: Error: Can't resolve


./node_modules/mongodb/lib/bson.js:12:9-28 - Warning: Module not found: Error: Can't resolve 'bson-ext' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/deps.js:36:2-40 - Warning: Module not found: Error: Can't resolve 'kerberos' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/deps.js:43:2-49 - Warning: Module not found: Error: Can't resolve '@mongodb-js/zstd' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/deps.js:51:2-36 - Warning: Module not found: Error: Can't resolve 'snappy' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/deps.js:54:75-105 - Warning: Module not found: Error: Can't resolve 'snappy/package.json' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/utils.js:1399:32-87 - Warning: Critical dependency: the request of a dependency is an expression

./node_modules/mongodb/lib/utils.js:1407:32-68 - Warning: Module not found: Error: Can't resolve 'mongodb-client-encryption' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'



>SOLUTION


Sometimes, we are not sure if the environment is consistent or not.

The issue reported here was caused by the last lib installed (mongodb) in the app's env.

If you want to check this, you may skip steps and go straight to the fourth approach topic, at the end.

If you do want to recheck your app's env, you may start from the 1st approach.

First of all, stop the application, and close the IDE (VSCode/Eclipse, etc.).


1. APPROACH


- try:

npm cach verify


Retest.


2. APPROACH


If the 1st step didn't work, try to unistall the last libs installed.

In this case, it was the following:


npm uninstall mongoose

npm uninstall  @types/mongoose

npm uninstall mongodb

npm uninstall dotenv


- do:

npm cach clean

or

npm cach clean --force


- reinstall them:


npm i --save mongoose

npm install @types/mongoose --save-dev

npm install --save mongodb

npm install --save dotenv


- do:

npm install


- restart the app.


3. APPROACH


If the 2nd step didn't work, remove all cache and node_modules, reinstalling the libs.


- alternatively install:

npm install node-gyp -g


- run:

npm cache clean --force

rm -Rf node_modules

npm install

npm cache verify


- restart the app.


4. APPROACH


If the 3rd step didn't work, probably it is some lib issue.

To discover the cause, the libs were tested one at a time.


To discover the cause, test the libs one at a time.

Making rollback, both libs were uninstalled.

The it was reinstalled mongoose and tested with minimal code.

Passed.

Then, it was installed MongoClient and tested with minimal code.

The issue returned.

To discover the cause, the code was commented and tested one statement at a time, restarting the app.

First:

import * as mongoDB from 'mongodb';

import * as dotenv from 'dotenv';

After, code was commented and the cause was this line:

    const client = new mongoDB.MongoClient('mongodb://localhost:27017/test');




NOTE:

Sometimes it is necessary to repeat the procedure of cleaning, uninstalling, and installing until the application starts successfully (remember to stop the app and close the IDE):

npm cache clean --force
npm uninstal ... (all the libs to be uninstalled - rollback)
npm install
restart the app


5. APPROACH - Version Issue? Solving the mystery

After identifying the cause through the tests performed, it was possible to try another version to solve the mysterious incompatibility. So, the previous version was uninstalled and replace by another one, in this case a version already working fine in another demo application.

Current version to be replaced:
"mongoose": "^6.5.0",

Uninstalling:
npm uninstall mongoose --no-save

Replacing:
npm install --save mongoose@^5.8.3

Restarting application: success.





6. FINAL TIPS

The compiler for certain kinds of problems returns messages that are not very helpful.
If you stick on the error messages, you get stuck because they have nothing to do with the real cause.
Do not wait for a kind message telling necessarily the real issue behind the exception because it is not always possible.
Checking the result, you will not see something like that:
"Please, fix my mongoose version... blah, blah, blah'.    :-)   :-|   




7. Rule of thumb

Having issues?
Think:

1. Is my environment healthy, stable, and consistent?
First, make sure of that.

2. Think about version conflict.
This is a complicated matter.
Too many libs, too many versions, lead to possible many conflicts.


>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


tslint: expected call-signature: ... to have a typedef

 

>PROBLEM


Using typscript and TSLint, return the following message:

  expected call-signature: 'run1' to have a typedef


>SOLUTION


>BEFORE

  async run1() {

    await mongoose.connect('mongodb://127.0.0.1');

  }

>AFTER  

  async run1(): Promise<any> {

    await mongoose.connect('mongodb://127.0.0.1');

  }


>ENV

VSCode

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


eclipse: java: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder" or Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

  >PROBLEM Using Eclipse, you try to run a simple logging test using "org.slf4j.Logger" like the sample below: package Test; im...