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.<anonymous> (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() {

@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


Thursday, July 28, 2022

node.js/express: crbug/1173575, non-JS module files deprecated. ... ERR_SSL_PROTOCOL_ERROR

 

>PROBLEM

Attempt to access the site returns the following error messages:


- On browser console:

crbug/1173575, non-JS module files deprecated.


- On browser page:

ERR_SSL_PROTOCOL_ERROR

Não foi possível estabelecer uma conexão segura com este site

Not possible to establish a secure connection with the site





>SOLUTION

Probably you've tried to access the site using https where it should be http.

Ex.:

- wrong:

https://localhost:3000

- because it uses the http protocol service, so:

http://localhost:3000


>ENV

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

Monday, July 25, 2022

angular: Warning: There are multiple modules with names that only differ in casing. This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.

 

>PROBLEM


The compilation returns the follwing warning message:

  Warning: There are multiple modules with names that only differ in casing.
  This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
  Use equal casing. Compare these module identifiers:


>SOLUTION

Two things to check:

1. If working on Windows, files hasn't case sensitive approach.
So, make sure that the file pointed by the warning message matches case.
If not, remember that it doesn't help renaming the file. It is necessary to rename the file to a different one and then rename it back using the name with the right case.

2. Check the import referred by the error message that it is pointing to the path with different case.
It works on Windows but not on *nix or Mac.
Follow by the images.








Fixed: switched from "_ConfigDb"  to  "_ConfigDB"







>ENV

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



Sunday, July 24, 2022

angular: is not a known element

 

>PROBLEM

An element is not recognized, returning the following error message:

angular: is not a known element




>SOLUTION

A referencing error may lead to side effects during parsing operation.

The issue is caused by a missing reference that becomes invalid.
It is example happened because the component was deleted using the editor, but it was not able to remove the respective reference together.
It may happen also when you rename or move componets.


Removing the missing references:


the problem is gone.



NOTE:

Errors of @NgModule may lead also to another errors, for instance like NG8002.


>CHECK

>MODULE/SUB-MODULE CONFIG BY IMAGES

Follow by the images how to set up the imports using module and sub-modules through images.











>ENV

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

Thursday, July 21, 2022

angular: error NG8001: 'pagination-controls' is not a known element



>PROBLEM

 

When angular compiles, returns the following error:

Error: src/app/crud/crud-employee/crud-employee-list/crud-employee-list.component.html:28:11 - error NG8001: 'pagination-controls' is not a known element:

1. If 'pagination-controls' is an Angular component, then verify that it is part of this module.

2. If 'pagination-controls' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.


28           <pagination-controls id="employees_listing_pagination" maxSize="5" directionLinks="true" (pageChange)="page = $event"></pagination-controls>



>SOLUTION

This kind of error message happened when using ngx-bootstrap and some other kind of issue promotes a compilation errors returning eventually this message.

The most common issues were:

1. Malformed module configuration.

2. Non-visible chars resulting in unexpected combinations.

3. Components not declared.


Details at:

Window
Node.js
Angular + ngx-bootstrap

angular or another framework/language: Mysterious compilation errors suddenly appeared after restarting app

 

>PROBLEM

Mysterious compilation errors suddenly appeared after restarting app.
It may happen with any framework/language.

Context:
Everything was done right and the modifications implemented were compiled successfully. Suddenly, after restarting the app, many error messages come from nowhere and they seem not compatible with the code written.




>SOLUTION

When the compilation goes mad, indicates that something outside the project, pertaining to the O.S. system has come to the scene.

Most common causes that occurred to me:
- HD issue
- Corrupted files.
- Non-visible chars (the worst scenario) resulting in unexpected combinations..

The first two causes may be easier to find out.
The third may turn your search into hell.

Through the editor used during the project implementation may not help, because the issue in this cases usually comes transparent to it. For instance, if you are using VS Code (excellent), it will be necessary to use another one to identify the issue, for instance the Notepad++, SciTE, or another one.

In the image below, check the red arrow.
The strange char comes out.

It doesn't help correcting in the editor. The issue may persist because it may have not visible chars during the fix, and they will be still there and may cause more issues.

The best thing to do is to create a new file and retype the code.
You may risk doing just this with just the defective line.
Better if you replace all the code from another source or manually.


This kind of issue happened to me three times and the first one drove me crazy.


>VERSIONING CONTROL  SIDE EFFECTS (Git, etc.)

The versioning is also affected.
The best approach, because it is faster and more effective, is:

1. Copy the current code to a temporary folder.
2. Checkout to a previous version — the most recent state that compiles successfully.
3. Replace the differences without copying, otherwise, you may contaminate the content again.

NOTE:
Non-visible chars produce issues to the compiler and also to any other software working with the files, and that is the case of the versioning control, spoiling the merges.

>ENV

Windows
Node.js
Angular 12 and higher.



Wednesday, July 20, 2022

angular: Error: node_modules/ngx-bootstrap/modal/bs-modal.service.d.ts:7:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

 


>PROBLEM

Angular compilation throws the following error:

Error: node_modules/ngx-bootstrap/modal/bs-modal.service.d.ts:7:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

This likely means that the library (ngx-bootstrap/modal) which declares BsModalService has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.


>SOLUTION

>BEFORE (WRONG)

imports: [

BsModalService,

],

providers: [

],


>AFTER (RIGHT)

imports: [

BsModalService,

],

providers: [

BsModalService,

],




>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


angular: Error: node_modules/ngx-bootstrap/datepicker/bs-datepicker.config.d.ts:8:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

 

>PROBLEM

Angular compilation returns:

Error: node_modules/ngx-bootstrap/datepicker/bs-datepicker.config.d.ts:8:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.


This likely means that the library (ngx-bootstrap/datepicker) which declares BsDatepickerConfig has not been processed correctly by ngcc, or is not compatible with Angular Ivy. 

Check if a newer version of the library is available, and update if so. 

Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy. 



>SOLUTION


Edit app.module.ts and fix its configuration as follows:


>BEFORE (WRONG)

  imports: [

AlertConfig, 

BsDropdownConfig, 

BsDatepickerConfig

  ],

  providers: [],


>AFTER (RIGHT)

  imports: [

  ],

  providers: [AlertConfig, BsDropdownConfig, BsDatepickerConfig],



>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


Thursday, July 14, 2022

angular: ngForm: error NG8002: Can't bind to 'formControl' since it isn't a known property of 'input'.

 

>PROBLEM

After adding an implementation to bind using ngModel , for instance:

    <label for="example-ngModel">[(ngModel)]:</label>

    <input [(ngModel)]="currentItem.name" id="example-ngModel">


Running angular using ngModels, returns the error message:

error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'
Can't bind to 'formGroup' since it isn't a known property of 'form'

Error: src/app/crud/crud-employee/crud-employee-update/crud-employee-update.component.html:2:9 - error NG8002: Can't bind to 'formGroup' since it isn't a known property of 'form'.

2   <form [formGroup]="updateForm" (ngSubmit)="saveToList(updateForm)">


For instance, implementing a simple example like this:




You get:




Another example:



>SOLUTION


@NgModule is a key concern in Angular.

This NG8002 error usually comes from the @NgModule misconfiguration (missing something).
For instance, a usual occurrence may happen with these scenarios:

1. A new module is created and not registered on app.module.ts.
or

2. A new component is created and not registered in its specific module.
or

3. The selector's module is not registered in the module.

The selector is that declared in the .ts file, for instance at:
@Component({
  selector: 'app-modal-list',

Referenced in the .html file comes like this:
<app-modal-list></app-modal-list>



There are a few things to be observed.


1. Requires modules setup.

Set the required modules in app.modules.ts. Example:


import { FormsModule, ReactiveFormsModule } from "@angular/forms";

...

@NgModule({

  declarations: [
        //...
   ],

  imports: [
//...
    FormsModule,
    ReactiveFormsModule,
  ],


*** IMPORTANT NOTE:

If you are using a page under its specific module, declare in that module too.

Example:

app
+--forms-lab
+-- forms1
--- forms-lab.module.ts


Edit forms-lab.module.ts and declare both modules referred to above.


2. Make sure that you have not overwritten the angular modules: 

It is something easy to happen, for instance, if you create a module called forms, as it is:


ng g m forms


This command will generate a FormsModule that overrides the angular's module.
This conflict causes the same issue.

If it happened, delete, and recreate it with another name.


3. Check if all components are declared in its modules.ts file.

Using the example above, it would be something like this in the forms-lab.module.ts file:

import { Forms1Component } from './forms1/forms1.component';
...
@NgModule({
  declarations: [
    Forms1Component,
  ],


4. Check if there isn't naming conflict.

Sometimes, the way the components are named may cause the issue.

Check the following image:




@MORE: 

https://stackoverflow.com/questions/43220348/cant-bind-to-formcontrol-since-it-isnt-a-known-property-of-input-angular


>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


Friday, July 8, 2022

node.js: express: req.session returns "undefined"

 

>PROBLEM

node.js: express: req.session returns "undefined".

console.log(req.session)

- Returns:

undefined


>SOLUTION

The session block declaration shall come before the routing blocks.


>>BEFORE

// error handler
app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

// ...

const session = require('express-session');
app.set('trust proxy', 1) // trust first proxy
app.use(session({
    secret: ConfigSvc.configValue('sessionKey'),
    saveUninitialized:true,
    cookie: { maxAge: oneDay, secure: true },
    resave: false
}));


>>AFTER

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var todoRouter = require('./routes/todo');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

var favicon = require('serve-favicon');
const ConfigSvc = require('./utils/ConfigSvc');
app.use(favicon(__dirname + '/public/favicon.ico'));

const oneDay = 8640000;
const session = require('express-session');
app.set('trust proxy', 1) // trust first proxy
app.use(session({
    secret: ConfigSvc.configValue('sessionKey'),
    saveUninitialized:true,
    cookie: { maxAge: oneDay, secure: true },
    resave: false
}));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/todo', todoRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});


// error handler
app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});


>ENV

Node.js 16
Express
JWT

Wednesday, June 29, 2022

linux: debian: ubuntu: How to discover an application and its service to handle it


>PROBLEM

Scenario by example:
On a linux(debian, ubuntu, etc) system you want to discover the postgresql service, its version and how to stop/start.


>SOLUTION


Alternative ways to discover a service:

1. whereis

2. locate

3. ps aux 

Ex.: ps aux | grep postgres

/usr/lib/postgresql/13/bin/postgres -D /var/lib/postgresql/13/main -c config_file=/etc/postgresql/13/main/postgresql.conf

4. systemctl

returns all registerd services


Using systemctl (newer)

systemctl stop ssh

systemctl disable ssh

systemctl enable ssh

systemctl start ssh

systemctl status ssh


Using service

service  postgresql status

service  postgresql start

service  postgresql stop


>ENV

linux/debian

Thursday, June 23, 2022

docker commit lost data

 >PROBLEM

Suppose the following scenario.
 
1. You have create a container mapping to an internal directory.
Example:
docker run -it --name d10n16p11v1 -p 5000:3000 --mount "target=/home/data" d10n16p11:latest /bin/bash

2. Inside the container you created content under /home/data.
For instance:
git clone someURL

After the clone you get a new dir, for instance:
myproject

So you have:
/home/data/myproject

3. Eventually, you decide to preserve the changes and all the stuff (the full state), then you do:

docker commit d10n16p11v1 local/d10n16p11v1

- or using the CONTAINER ID:
docker commit 156e4a967258 local/d10n16p11v1

4. Using the new image, you create a container from it doing:

docker run -it --name d10n16p11v2 -p 5000:3000 --mount "target=/home/data" local/d10n16p11v1 /bin/bash

Accessing the prompt you search for your content:
ls /home/data

but unfortunately, the "myproject" downloaded on the previous container is not there — it is lost!


>SOLUTION

Before exiting the container, copy the content from under the folder that you mapped to create it, in this example is "/home/data" to a system's directory, for instance "/opt".

cp -R /home/data /opt

After, you may commit (step #3).
Next time you run the new container from the committed image, the /opt directory will contain your stuff under data.

IMPORTANT:
Before deleting the previous image or container, test your new image.

>ENV

docker
debian 10

Monday, May 2, 2022

git: hint: core.useBuiltinFSMonitor will be deprecated soon; use core.fsmonitor instead

 

>PROBLEM


On Windows, after running a git command, it is thrown the following warning:

  hint: core.useBuiltinFSMonitor will be deprecated soon; use core.fsmonitor instead

  hint: Disable this message with "git config advice.useCoreFSMonitorConfig false"



>SOLUTION


core.fsmonitor

If set to true, enable the built-in file system monitor daemon for this working directory (git-fsmonitor--daemon[1]).

Like hook-based file system monitors, the built-in file system monitor can speed up Git commands that need to refresh the Git index 

(e.g. git status) in a working directory with many files. 

The built-in monitor eliminates the need to install and maintain an external third-party tool. 


- Documentation:
https://git-scm.com/docs/git-config#Documentation/git-config.txt-corefsmonitor


Run the desired option:

git config core.fsmonitor true

or

git config core.fsmonitor false


*** IMPORTANT NOTE:

Run the command on the git's root folder.

Make sure that the git folder is not another git subdirectory of a root git folder.

Example:

+-- project

.git

myStuff

+-- project2

.git

myStuff2



>ENV

git version 2.36.0.windows.1

Windows 10


Friday, April 29, 2022

eclipse: maven: Error: Could not find or load main class antlr.debug.misc.ASTFrame

 


>PROBLEM


Attempt to run an Eclipse project returns the following error:


  Error: Could not find or load main class antlr.debug.misc.ASTFrame

  Caused by: java.lang.ClassNotFoundException: antlr.debug.misc.ASTFrame


>SOLUTION

NOTE:
If you are quite sure about your project configuration, try to go straight to the 6th step.


0. Pre-requisite: make sure your pom.xml configuration is correct.


1. On Eclipse, using the Project Explorer (or Navigator), delete the following configuration files:

  .settings

  .classpath




2. Eclipse will complaing throwing an error pop-up. Ignore closing it.


3. Using the Project Explorer (or Navigator), point to the project's root and save it again.

This will generate again the deleted files.


4. Check if there are errors and fix them.




5. Clean the project (menu, Project, Clean...).



Wait to finish. Pay attention on the bottom bar.




6.  Fix the the Eclipse's configuration to run the application.





7. Run the application again and choose the proper option for the project.
In this case is Spring Boot.




8.  Configuration fixed and application is up and running.





>ENV

maven

eclipse

java17


Monday, April 25, 2022

maven: Execution default-testResources of goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:testResources failed: Unable to load the mojo 'testResources'


 >PROBLEM


The pom.xml shows the following error message:


Execution default-testResources of goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:testResources failed: Unable to load the mojo 'testResources' 

(or one of its required components) from the plugin 'org.apache.maven.plugins:maven-resources-plugin:3.2.0' 

(org.apache.maven.plugins:maven-resources-plugin:3.2.0:testResources:default-testResources:process-test-resources)



>SOLUTION


If the pom.xml was previously working fine, just update the maven project.

If using Eclipse, do:

Point to the project root on "Project Explorer" or equivalent, choose on the context menu mave, Updata Project (or ALT+F5)


>ENV

spring

java


maven: Caused by: java.lang.ClassNotFoundException: com.drillback.sgsup.Application

>PROBLEM


Running the executable jar with dependencies generated by maven plugin fails throwing the error message:

  java -jar myApp-0.0.1-SNAPSHOT-jar-with-dependencies.jar


- Returns:

  ..Caused by: java.lang.ClassNotFoundException..



>SOLUTION


1. Check the main class path in the pom.xml file.

Note: there are alternative plugins to generate executable jars.

See more at: 
How to Create an Executable JAR with Maven


Below is shown one of the options:


<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>package.appName.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>



2. If the plugins's configuration is correct, check the dependencies included in the project's pom.
For instance, if it was included lombok as shown below, remove it and test again:

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>



>ENV


java
spring
maven

Thursday, April 14, 2022

MongoDB: Caused by: java.net.ConnectException: Connection refused: no further information at java.base/sun.nio.ch.Net.pollConnect(Native Method)


>PROBLEM

Starting a project using Maven, JEE/Spring, and MongoDB driver (mongo-java-driver) throws the following exception:

...[cluster-ClusterId{value='62586e27f362ec2cd1336bda', description='null'}-localhost:27027] # INFO  # org.mongodb.driver.cluster # method: info # Exception in monitor thread while connecting to server localhost:27027

com.mongodb.MongoSocketOpenException: Exception opening socket

...

Caused by: java.net.ConnectException: Connection refused: no further information at java.base/sun.nio.ch.Net.pollConnect(Native Method)


>SOLUTION

Although connection refusal may have many causes, this post will treat one of them that maybe it is your issue.

The "mongo-java-driver" tries to start MongoDB connection automatically as soon as the application starts if it finds MongoDB's configuration in .properties or .yml files.

It happens when we start a project using this default feature but later we decide to customize it, and there is no need for this feature anymore.

So, just remove or comment on the lines in the configuration file. 


For instance, if .yml, do this:

spring:

profiles: prod

jpa:
database: default
#  data:
#    mongodb:
#      host: localhost
#      port: 27027
#      database: mydatabase


If .properties:

#spring.data.mongodb.host=localhost
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=mydatabase


>ENV


SpriingBoot 2.X
Java 17
MongoDB 5

- pom.xml:


<dependency>

<groupId>org.springframework.data</groupId>

<artifactId>spring-data-mongodb</artifactId>

</dependency>


<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-mongodb</artifactId>

</dependency>


<dependency>

<groupId>org.mongodb</groupId>

<artifactId>mongo-java-driver</artifactId>

<version>3.12.10</version>

</dependency>


Monday, April 11, 2022

Spring Boot: web service returns with 404

 

>PROBLEM


web service returns with 404


>SOLUTION

If you have already checked the protocol, then check if the @ResponseBody annotation is missing.


- BEFORE:


@PostMapping(value = {"/reset/{token}"})

public ResponseDTO resetPassword(HttpServletRequest request, @PathVariable String token) {

ResponseDTO dto = request(request, token);

dto.setData("hello there!");

return dto;

}



- AFTER:


@PostMapping(value = {"/reset/{token}"})

@ResponseBody

public ResponseDTO resetPassword(HttpServletRequest request, @PathVariable String token) {

ResponseDTO dto = request(request, token);

dto.setData("hello there!");

return dto;

}


>ENV

spring boot 2

java 17


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...