Wednesday, January 8, 2020

Docker: Hardware assisted virtualization and data execution protection must be enable in the BIOS


>PROBLEM

Docker fails to start, returning the following message:

Hardware assisted virtualization and data execution protection must be enabled in the BIOS
See https://docs.docker.com/docker-for-windows/troubleshoot/#virtualization-must-be-enabled







>SOLUTION

Turn on hyper-v.
As Administrator, issue the command:

   bcdedit /set hypervisorlaunchtype auto start

Restart the machine.

*** IMPORTANT NOTE:

Vagrant with VirtualBox require to turn off hyper-v:

  bcdedit /set hypervisorlaunchtype off

That way, if you have both installed, once their configurations are conflicting, it is not possible to have both working at the same time.





>ENV

Windows 10
Vagrant v2.2.6
VirtualBox 6.0

>SEE

Vagrant: The box you're attempting to add doesn't support the provider you requested

Vagrant: There was an error while executing VBoxManage, a CLI used by Vagrant for controlling VirtualBox


Vagrant: There was an error while executing VBoxManage, a CLI used by Vagrant for controlling VirtualBox


>PROBLEM

Starting vagrant:

    vagrant up

Causes the follwing issue:

There was an error while executing VBoxManage, a CLI used by Vagrant for controlling VirtualBox. 
The command and stderr is shown below.

Command: ["startvm", "01748371-61a5-4c0e-a279-9077bab91aaf", "--type", "headless"]
Stderr: VBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole


>SOLUTION

Turn off  hyper-v.
As administrator, issue the comand:

    bcdedit /set hypervisorlaunchtype off

Restart machine.


*** IMPORTANT NOTE:

Docker requires hyper-v on:

   bcdedit /set hypervisorlaunchtype auto start

So, after the environment is restarted, docker will stop working.
Docker and Vagrant/VirtualBox requires conflicting environment configuration.




Vagrant: The box you're attempting to add doesn't support the provider you requested


>PROBLEM

Starting Vagrant using VirtualBox as follows:

   vagrant up

Fails to start returning this message:

The box you're attempting to add doesn't support the provider you requested. 
Please find an alternate box or use an alternate provider. 
Double-check your requested provider to verify you didn't simply misspell it.

If you're adding a box from HashiCorp's Vagrant Cloud, make sure the box is
released.

Name: ubuntu/trusty64
Address: https://vagrantcloud.com/ubuntu/trusty64
Requested provider: [:hyperv]


If you force, using:

  vagrant up --provider virtualbox

vagrant then returns the following:

Vagrant has detected that you have a version of VirtualBox installed
that is not supported by this version of Vagrant. Please install one of
the supported versions listed below to use Vagrant:
4.0, 4.1, 4.2, 4.3, 5.0, 5.1, 5.2, 6.0

The provider 'virtualbox' that was requested to back the machine
'mongod-m103' is reporting that it isn't usable on this system. The
reason is shown below:

Vagrant has detected that you have a version of VirtualBox installed
that is not supported by this version of Vagrant. Please install one of
the supported versions listed below to use Vagrant:

4.0, 4.1, 4.2, 4.3, 5.0, 5.1, 5.2, 6.0

          A Vagrant update may also be available that adds support for the version
        you specified. Please check www.vagrantup.com/downloads.html to download
        the latest version.


>SOLUTION

Download a version of VirtualBox compatible with Vagrant's version.
For instance, if vagrant v2.2.6, use vitualbox 6.0.

Download here (change the url's version suffix for the one desired):

https://www.virtualbox.org/wiki/Download_Old_Builds_6_0


>ENV

Windows 10
Vagrant v2.2.6
VirtualBox 6.0

Sunday, January 5, 2020

git Changes not staged for commit remove message



>PROBLEM

git status command returns the following message:

  git Changes not staged for commit remove message


>SOLUTION

This kind of problem may be originated when a folder is added to .gitignore without adding and committing the repository before .gitignore inclusion and committing after.
A straightway is to move the folder that contains the inconsistency to a temporary folder. Then add and commit again.

Example, supposing the following project structure:

+-- myProjectRoot
+--folder1
+--folder2
+--folderWithIssue

To fix, do:

cd /home/myProjectRoot
- windows:
cd C:\myProjectRoot

git add *
git commit -am "my message here"

mv /home/myProjectRoot/folderWithIssue /home/temp
- windows:
move folderWithIssue C:\temp

git add *
git commit -am "my message here"
git push

mv /home/temp/folderWithIssue .
- windows:
move C:\temp\folderWithIssue .

git add *
git commit -am "my message here"
git push


node.js: morgan deprecated default format: use combined format



>PROBLEM

The server throws the following server's message:
  morgan deprecated default format: use combined format

>SOLUTIONS

>>POSSIBILITY #1 ----------------------------------

BEFORE:
app.use(logger);


AFTER:
app.use(logger('combined'));


@FROM:
stackoverflow.com/questions/36397812/morgan-deprecated-expressjs/36398066


>>POSSIBILITY #2 ----------------------------------

BEFORE:
app.use(logger(process.env.AMBIENTE));
...
require('dotenv').config();


AFTER:
require('dotenv').config();
..
app.use(logger(process.env.AMBIENTE));

Friday, December 27, 2019

WordPress fails to update plugins, Posts or Sign in


NOTE: 
Although the examples concern to Linux env, an analogy may be done to other environments converting the commands and paths.
In the examples below, replace "mysite" by the name of your site folder.

>ATTEMPT #1 - FILES' PERMISSION

Check the owner of your data, if www-data, do:

chown www-data -R /home/mySite/public_html
chgrp www-data -R /home/mySite/public_html

>ATTEMPT #2 - PLUGIN'S ISSUE

CHECKING ONE BY ONE BEGINNING BY THE LAST ONES

If the issue happens after plugins' update or a new plugin installation, it is necessary to identify the plugin that causes the issue.
In this case, just remove the plugin by moving its code to a temporary folder.
If the issue disappears, the last removal indicates the responsible.
Example:

mv /home/mysite/public_html/wp-content/plugins/do-something /home/temp/plugins


REMOVING ALL AND REINSERTING ONE BY ONE 

Another method removes all and insert one by one (or small groups) until the issue comes up, identifying the cause.
Example reinserting a group of three:

mv /home/mysite/public_html/wp-content/plugins /home/temp
mkdir /home/mysite/public_html/wp-content/plugins
mv /home/temp/plugins/do-something /home/mysite/public_html/wp-content/plugins
mv /home/temp/plugins/do-something2 /home/mysite/public_html/wp-content/plugins
mv /home/temp/plugins/do-something3 /home/mysite/public_html/wp-content/plugins
chown www-data -R /home/mySite/public_html/plugins
chgrp www-data -R /home/mySite/public_html/plugins
#Go to the site, menu, plugins and activate the inserted plugins, then test.
#If the issue returns, one of the new three plugins is the responsible.
#To discover the one, repeate the operation removing the three ones and inserting one by one.
More details at:


>ATTEMPT #2 - WORDPRESS FILES' ISSUE

If the attempt one is ineffective, then it may be a major problem like Wordpress corruption, considering that any other procedure above was successful.

>PROBLEM

The site fails to update post.
Attempt to update a plugin works differently, redirecting to another page retuning a detailed log like wordpress upgrade - unusual since upgrade is done on the same page - the plugins' page.
After log off, login also fails.
The problem comes apparently from nothing.

>SOLUTION

Rename the current site to preserve its content.
Performed a new Wordpress installation but preserving its current database.
The new installation is connected to the previous database.
The configurations and contents from the previous installation are copied to the new one, including plugins, uploads and other key folders.

Example:

- database backup, just in case:
  mysqldump --all-databases --routines  --triggers -uroot -proot > dump.sql

- creating a new mysite directory to install a new wordpress:
  mv /home/mysite /home/mysite_
  mkdir /home/mysite
  chown root:root -R /home/mysite
  chmod 755 -R /home/mysite
  mkdir /home/mysite/public_html

- set permissions required by wordpress running by apache2:
  chown www-data -R /home/mysite/public_html

- create log dir:
  mkdir /home/mysite/public_html/logs

- installing the new site:
  cd /home/backup/wordpress
  unzip wordpress-5.3.2-en_GB.zip
  mv wordpress/* /home/mysite/public_html
  chown www-data -R /home/mysite/public_html
  chmod 755 -R /home/mysite/public_html

- create a symlink on apache2's /var/www folder:
  cd /var/www
  ln -s /home/ipstuff/public-html mysite

- point to mysite:  
  http://ultering.com/mysite/

- get the database information
database name: mysite
username: mysite
password: secret
host: localhost

- after the initial login, the key folders are copied from previous intallation to preserve configuration and content:

  rm -Rf /home/mysite/public_html/wp-content/plugins
  cp -R /home/temp/mysite/plugins /home/mysite/public_html/wp-content
  chown www-data -R /home/mysite/public_html
  chmod 755 -R /home/mysite/public_html

  cp -R /home/mysite_/public_html/wp-content/themes/* /home/mysite/public_html/wp-content/themes

   cd /home/mysite

- backup from previous content, just in case:   
   tar czvf itstuf_temp.tar.gz /home/mysite/public_html

- copying key folders containing content and configuration:
  cp -R /home/mysite_/public_html/wp-content/uploads /home/mysite/public_html/wp-content
  cp -R /home/mysite_/public_html/wp-content/w3tc-config /home/mysite/public_html/wp-content
  cp -R /home/mysite_/public_html/wp-content/wflogs /home/mysite/public_html/wp-content
  cp -R /home/mysite_/public_html/wp-content/nfwlog /home/mysite/public_html/wp-content
  cp -R /home/mysite_/public_html/wp-content/.tmb /home/mysite/public_html/wp-content
  cp -R /home/mysite_/public_html/wp-content/.quarantine /home/mysite/public_html/wp-content
  cp -R /home/mysite_/public_html/wp-content/mu-plugins /home/mysite/public_html/wp-content
  cp -R /home/mysite_/public_html/wp-content/wp-link-status-salt.php /home/mysite/public_html/wp-content
  cp -R /home/mysite_/public_html/wp-content/index.php /home/mysite/public_html/wp-content

- moving the backup to a temp dir to be downloaded and removed:  
  mv /home/mysite/public_html/wp-content/uploads /home/temp



Tuesday, August 20, 2019

ECLIPSE - Cannot change version of project facet Dynamic Web Module to 3.1




>PROBLEM

Attempt to switch Web Module version in "Project Facets" is denied, not allowed, returning a message like this:

Cannot change version of project facet Dynamic Web Module to 3.1. sisgit2 line 1 Maven Java EE Configuration Problem



>SOLUTION

Go to the eclipse's project root directory at:

$ECLIPSE_PROJECT_ROOT\.settings\org.eclipse.wst.common.project.facet.core.xml


Change here:
From:
<installed facet="wst.jsdt.web" version="1.0"></installed>
To:
<installed facet="jst.web" version="3.1"></installed>

>ENV

Windows 10
Eclipse 2019


@FROM:
stackoverflow.com/questions/18122336/cannot-change-version-of-project-facet-dynamic-web-module-to-3-0

Sunday, August 18, 2019

VSCODE: EDITOR: Number of Opened Tabs Setup


To set the number of opened tabs on the editor, go to the menu, File, Preferences, Settings.
Follow by the images, yellow arrows.






Sunday, August 11, 2019

node.js: flash: a req.session is required!



>PROBLEM


a req.session is required!
AssertionError [ERR_ASSERTION]: a req.session is required!
    at L:\work\devcli_\javascript\node\projects\tellme4\tellme4\node_modules\flash\index.js:6:5
    at Layer.handle [as handle_request] (L:\work\devcli_\javascript\node\projects\tellme4\tellme4\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (L:\work\devcli_\javascript\node\projects\tellme4\tellme4\node_modules\express\lib\router\index.js:317:13)
    at L:\work\devcli_\javascript\node\projects\tellme4\tellme4\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (L:\work\devcli_\javascript\node\projects\tellme4\tellme4\node_modules\express\lib\router\index.js:335:12)
    at next (L:\work\devcli_\javascript\node\projects\tellme4\tellme4\node_modules\express\lib\router\index.js:275:10)
    at logger (L:\work\devcli_\javascript\node\projects\tellme4\tellme4\node_modules\morgan\index.js:144:5)
    at Layer.handle [as handle_request] (L:\work\devcli_\javascript\node\projects\tellme4\tellme4\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (L:\work\devcli_\javascript\node\projects\tellme4\tellme4\node_modules\express\lib\router\index.js:317:13)
    at L:\work\devcli_\javascript\node\projects\tellme4\tellme4\node_modules\express\lib\router\index.js:284:7


>SOLUTION

>>WRONG:

//*** wrong place of flash configuration, before session:

app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(session({
  secret: "fd34s@!@dfa453f3DF#$D&W",
  resave: false,
  saveUninitialized: true,
  cookie: { secure: !true }
}));


>>RIGHT:

app.use(passport.initialize());
app.use(passport.session());
app.use(session({
  secret: "fd34s@!@dfa453f3DF#$D&W",
  resave: false,
  saveUninitialized: true,
  cookie: { secure: !true }
}));
//*** right place after session:
app.use(flash());


>ENV
w10
node.js

Tuesday, September 11, 2018

Spring: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ...: Unsatisfied dependency expressed through field


>PROBLEM
Starting the application, it stops working throwing the following exception:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ulteringController': Unsatisfied dependency expressed through field 'stateSvc'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'estadoSvc': Unsatisfied dependency expressed through field 'estadoRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'estadoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Could not create query metamodel for method public abstract br.com.ultering.model.State br.com.ultering.model.repository.EstadoRepository.findBySigla(java.lang.String)!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]


>SOLUTION

@Autowired
private StateSvc stateSvc;

ORIGINAL

@Service("estadoSvc")
@Transactional
public class StateSvcImpl extends AbstractSvc implements StateSvc {

FIXED

@Service("stateSvc")
@Transactional
public class StateSvcImpl extends AbstractSvc implements StateSvc {


>ENV
Windows
Spring Boot

Saturday, June 16, 2018

git: Resolving .gitignore issue in a messy project

PROBLEM
There many different .gitignore files into your project.
The ".gitignore" seams not working at all.
Your pull like commands comes with "ignored files".
SOLUTION
  1. Create a .gitignore pattern.
  2. Fix your repository's .gitignore file into master, at least.
    Same to develop or another very used branch.
  3. After updating or merging your local stuff, check the .gitignore content.
    If the local .gitignore file is not like the pattern, just overwrite it with the pattern file.
    If your project is too messy,  simply overwrite local using the pattern as a "just after procedure", to make sure.
  4. Avoid having more than one .gitignore file.
    Set just one under the project's root dir.
    In most of all usual cases, is enough.

.gitignore Example of a Java Project With Sonar and Docker files.

# Add any directories, files, or patterns you don't want to be tracked by version control
# ECLIPSE'S
**/target
**/.settings
**/.apt_generated
**/.metadata
*.classpath
*.factorypath
*.project
*.class
*.tern-project
# PROJECT'S STUFF
*.Jenkinsfile
*.JenkinsfileTeste
*.arquivoPdf.txt
*.arquivoPng.txt
*.arquivoXls.txt
*.axis.log
# TO BE USED TO LOG REPORTS AND MAINTENANCE

#WHY .GITIGNORE SEEMS TO FAIL

Follow the figures below.




After fixing .gitignore file:




Another reason when .gitignore fails is caused by a "conflicting state".



*.log.out
 @FROM: my alternative site

Wednesday, April 25, 2018

Maven exception "Fatal error compiling: invalid target release:..."

>PROBLEM
When running "mvn clean install" you get:
  Fatal error compiling: invalid target release:


>SOLUTION
Set JAVA_HOME envvar or include it into the script which runs maven.
  export JAVA_HOME="/home/portables_d/jdk1.8.0_144"

>ENV
linux/debian

Maven fails to load spring references



>PROBLEM
Maven fails to load spring references

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.6
Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.6

Failure to transfer org.apache.maven.plugins:maven-resources-plugin:pom:2.6 from http://maven.repository.redhat.com/ga/ was cached in the local repository, resolution will not be reattempted until the update 
 interval of redhat-ga-repository has elapsed or updates are forced. Original error: Could not transfer artifact org.apache.maven.plugins:maven-resources-plugin:pom:2.6 from/to redhat-ga-repository (http://
 maven.repository.redhat.com/ga/): maven.repository.redhat.com





>SOLUTION
Check the repository location into ".m2\settings.xml".

For instance:
C:\Users\YourLogin\.m2\settings.xml

In this case the localRepository was configured with linux's location and not windows as it was supposed to be:

***WRONG:
/home/portables_d/mvnlibs

+++RIGHT:
${env.LOCAL}\portables_d\mvnlibs



>ENV
windows
eclipse
java8

Tuesday, March 6, 2018

Remove dashboard bar to a profile from WordPress site


METHOD #1 - Plugin

Suppose that you have a site that you desire to supress the dashboard bar and admin bar to the users except the administrators.

Use "Editor Menu And Widget Access" plugin and just set the configuration like this:




-----------------------------------------------------------------------------------------------------------
METHOD #2 - Coding

@DEPRECATED:
In recent versions using others themes, the solution was not effective anymore, requiring more code digging. A better alternative solution was adopted above.


Suppose that you have a site that you desire to supress the dashboard bar and admin bar to the "subscriber" profile.
Follow the example.

1. Go to the themes' function.php file.
For instance, if the active theme is named "vale", edit:
$SITE_DIR/public_html/wp-content/themes/vale/function.php

2. Add the following

// This file is not called from WordPress. We don't like that.
! defined( 'ABSPATH' ) and exit;

add_action( 'init', 'fb_remove_admin_bar', 0 );
function fb_remove_admin_bar() {
if ( current_user_can('subscriber') || current_user_can('assinante') ) {
wp_deregister_script( 'admin-bar' );
wp_deregister_style( 'admin-bar' );
remove_action( 'init', '_wp_admin_bar_init' );
remove_action( 'wp_footer', 'wp_admin_bar_render', 1000 );
remove_action( 'admin_footer', 'wp_admin_bar_render', 1000 );
// maybe also: 'wp_head'
foreach ( array( 'admin_head' ) as $hook ) {
add_action(
$hook,
create_function(
'',
"echo '';"
)
);
}
}
}


Adapted from:
https://wordpress.stackexchange.com/questions/77639/disable-the-admin-bar/77648#77648

Remove excert from WordPress standard search



The standard search box generates by default a list of titles and excerpts.

The bold text is the title, the other (smaller characters) is the excerpt.

To exclude the excerpt from the default search, check the theme the site is using.
In this example is TwentyFifteen.
Go to the theme's folder and follow the procedure below.



1. Edit content-search.php.
This file is at:

/home/mynumbers/public_html/wp-content/themes/twentyfifteen/content-search.php


2. Remove the entry in orange:

 <header class="entry-header">
  <?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>
 </header><!-- .entry-header -->

 <div class="entry-summary">
  <?php the_excerpt(); ?>
 </div><!-- .entry-summary -->

 <?php if ( 'post' == get_post_type() ) : ?>
NOTE: always take note of a reference from where the code was remove in order to rollback, just in case.

After this procedure, just the bold title shall appear.


Saturday, November 25, 2017

MySQL server fails to start

>PROBLEM

After server reboot MySQL fails to start.
For instance:
  /etc/init.d/mysql restart
or
  service mysql stop
  service mysql start
 
Returns "failed" message.


>SOLUTION

1. Create data backup:
  cp -R /var/lib/mysql /var/lib/mysql_171115

2. Run the following cmds:
  chown -R mysql:mysql /var/lib/mysql
  mysql_install_db --user=mysql -ldata=/var/lib/mysql/

The last cmd output may show you the reason.
- Example:
  root@setgetsrv:/home/alsdias/dev/scripts# mysql_install_db --user=mysql -ldata=/var/lib/mysql/
  Installing MySQL system tables...
  171125 12:02:54 [Warning] The syntax '--log' is deprecated and will be removed in a future release. Please use '--general-log'/'--general-log-file' instead.
  171125 12:02:54 [Warning] The syntax '--log' is deprecated and will be removed in a future release. Please use '--general-log'/'--general-log-file' instead.
  171125 12:02:54 [Note] Ignoring --secure-file-priv value as server is running with --bootstrap.
  171125 12:02:54 [Note] /usr/sbin/mysqld (mysqld 5.5.55-0+deb7u1-log) starting as process 12458 ...
  171125 12:02:54 [ERROR] /usr/sbin/mysqld: unknown variable 'log_slow_verbosity=query_plan'
  171125 12:02:54 [ERROR] Aborting

3. Solving.
- The output shows issue with:
log_slow_verbosity = query_plan
- then, comment the line:
#log_slow_verbosity = query_plan

>ENV
debian whezzy
MySQL 5.X

Friday, October 13, 2017

Spring Boot: the client fails to find the service returning 404.


>PROBLEM

The application starts successfully, but the client fails to access the service getting 404.

Controller's original code:
@RestController
@RequestMapping("/api")
@CrossOrigin("*")
public class HelloController {

    @Autowired
    IHelloRepository helloRepository;

    @GetMapping("/hellos")
    public List getAllHellos() {
        Sort sortByCreatedAtDesc = new Sort(Sort.Direction.DESC, "createdAt");
        return helloRepository.findAll(sortByCreatedAtDesc);
    }



>SOLUTION

***WRONG:     @GetMapping("/hellos")
***RIGHT:        @GetMapping("/hellos/")

@RestController
@RequestMapping("/api")
@CrossOrigin("*")
public class HelloController {

    @Autowired
    IHelloRepository helloRepository;

    @GetMapping("/hellos/")
    public List getAllHellos() {
        Sort sortByCreatedAtDesc = new Sort(Sort.Direction.DESC, "createdAt");
        return helloRepository.findAll(sortByCreatedAtDesc);
    }


>ENV

Java 1.8
SpringBoot 1.5.6

Sunday, October 1, 2017

node.js: Error: Cannot find module .. bin/www


>PROBLEM

When the server is started using:
  npm start app.js
it returns the following error message:

  Error: Cannot find module 'L:\work\devcli_\javascript\node\work\ndprj01\ndprj01\bin\www'
      at Function.Module._resolveFilename (module.js:489:15)
      at Function.Module._load (module.js:439:25)
      at Function.Module.runMain (module.js:609:10)
      at startup (bootstrap_node.js:158:16)
      at bootstrap_node.js:598:3
  npm ERR! code ELIFECYCLE
  npm ERR! errno 1
  npm ERR! ndprj01@0.0.0 start: `node ./bin/www "app500c6sql"`
  npm ERR! Exit status 1
  npm ERR!
  npm ERR! Failed at the ndprj01@0.0.0 start script.
  npm ERR! This is probably not a problem with npm. There is likely additional logging output above.


>SOLUTION

Edit "package.json" file.
The error tell at:
  Error: Cannot find module 'L:\work\devcli_\javascript\node\work\ndprj01\ndprj01\bin\www'
that it is a problem concerning "bin\www".
Find "bin\www" and take it out.

- Before:

{
  "name": "ndprj01",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "async": "^2.5.0",
    "bluebird": "^3.5.0",

- After:
{
  "name": "ndprj01",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node "
  },
  "dependencies": {
    "async": "^2.5.0",
    "bluebird": "^3.5.0",






>ENV
windows
node.js

Saturday, September 30, 2017

node and npm: cleaning message "requires a peer of..."


>PROBLEM

Working with node, you perform some installation which not fulfill full installation.
Some unmet dependency keeps hanging a boring warning.
In this examples was:

npm WARN grunt-execute@0.2.2 requires a peer of grunt@~0.4.1 but none was installed.



>SOLUTION

Try to clean the unmet dependency manually.
Open the file package.json and remove the respective package.

In this case was "grunt-execute: 0.2.2".



After removal:



Results:




>ENV

Windows
node





Friday, August 25, 2017

node enoent: no such file or directory package.json



>PROBLEM

The package description is missing.
When it is not found, returns this message:
... ENOENT: no such file or directory ... package.json

npm WARN enoent ENOENT: no such file or directory, open '$HOMEDIR\package.json'


>SOLUTION

Use "npm init" create the package description.
This command asks some questions.
  npm init

To avoid interactive questions, use:
  npm init -y
  npm will assume some default values.

>>Example using the interactive mode with Git

1. Before executing the command, get your git's repository path, do:
  git remote -v

The output as example:
$git remote -v
origin  J:\git\dev\javascript (fetch)
origin  J:\git\dev\javascript (push)


2. Issue init.
The output was copied here as example:
$npm init

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ˆC at any time to quit.
package name: (bin714)
version: (1.0.0)
description: lab project based on bin714
entry point: (app.js)
test command: appt
git repository: J:\git\dev\javascript
keywords: node,http,server,example,template
author: alsdias plus others
license: (ISC)
About to write to L:\work\devcli_\javascript\node\work\bin714\package.json:

{
  "name": "bin714",
  "version": "1.0.0",
  "description": "lab project based on bin714 ",
  "main": "app.js",
  "scripts": {
    "test": "appt"
  },
  "repository": {
    "type": "git",
    "url": "J:\\git\\dev\\javascript"
  },
  "keywords": [
    "node",
    "http",
    "server",
    "example",
    "template"
  ],
  "author": "alsdias plus others",
  "license": "ISC"
}


Is this ok? (yes)
yes

>ENV
windows
node.js

Friday, August 18, 2017

Using an existing x509 certificate and private key to generate Java keystore to deploy https apps using SSL/TLS


>PROBLEM
You have the certificates and key generated by a CA and need to generate a keystore file to run a java application.


>SOLUTION

This example uses the certificates generated by sslforfree.

1. create a sandbox subfolder to generate the keystore file under the CA's folder where the certificates are stored.
  mkdir certificates\ssforfree\mysandbox


2. copy the CA's key and the certificate to the sandbox.
  cd certificates\ssforfree
  cp mysite_certificate.crt mysandbox
  cp mysite_private.key mysandbox
  cd certificates\ssforfree\mysandbox
  
  openssl pkcs12 -export -out keystore.p12 -name "myAlias" -inkey mysite_private.key -in mysite_certificate.crt
password?: mypass (the same pass used to generate the CA's certificates and key)
  
  where name = alias, the spring boot keyAlias value, the openssl friendly name.


3. set the application property file under the spring boot project.

Example using application.yml:

server:
  port: 8443 #default HTTPS
  ssl:
    #enabled: true
    key-store: keystore.p12
    keyStoreType: PKCS12
    keyAlias: myAlias 
    key-store-password: MY_PASSWORD_USED_WHEN_GENERATED_THE_CERTIFICATES_AT_CA_SITE


4. compile the spring boot project.
  mvn clean install
  

5. copy the keystore.p12 generated at "step 2" to the spring boot project's target folder.
  cp certificates\ssforfree\mysandbox\keystore.p12 myproject\target


6. run the application.
  cd target
  java -jar myapp-1.0.war
  

Saturday, August 5, 2017

How to download a project subdirectory from GitHub



This page contains the procedures which really worked for me, collected during my researches.
The snippets are real code which may be used to check the procedure in your environment.


1. using SVN

1.1. For URLs containg tree/master

If the URL contains "tree/master"
  https://github.com/eugenp/tutorials/tree/master/spring-boot

then replace it for "trunk":
  https://github.com/eugenp/tutorials/trunk/spring-boot

1.1.1. To downlod without the ".svn" subdir, use:
  
  svn export https://github.com/eugenp/tutorials/trunk/spring-boot

Final result:



1.1.2. To downlod with the ".svn" subdir, use:
  
  svn checkout https://github.com/eugenp/tutorials/trunk/spring-boot

Final result:





2. Using chrome extension

Install "GitZip for github" extension.

Why Should I use Angular 2 , or not?








When writing code I usually think about the following issues, among others:

- Is it a sensitive code?

- Where should it be processed?

- Is it a "light code" not requiring resources intensively that could decrease considerably the service performance like  memory/throughput/CPU processing usages?
(the old and famous triad performance requirements)

JavaScript is gorgeous and its main "purpose" was born for client processing using a browser.
Asynchronous calling is widely used to reduce heavy roundtrips where the full page is processed by a server returning its full content, instead it is processed just the minimum stuff required.
Very clever! Very necessary!

We, developers, started programming widely using the client's power processing, asynchronous callings and callbacks, and such intense activity leads us to skip accidentally about some concerns like, for instance, security.

Considering that standard JavaScript model process its code on client, it is not recommended to expose sensitive code, but due to constant coding habits, sometimes some sensitive code leaks to layers where it shouldn't be.

Angular 2, or later versions like Angular 4, uses a client-server architecture, usually supported by Node.js.
That way, this practice may help you avoiding the issue commented above, but you still have to remember that a client-server communication has its security considerations.
You may get some additional comments about this pointing to this link.

On the other side, Angular 1 carries the standard way of JavaScript programming, which makes easier to leak information, while Angular 2 or later, using annotations, requires the server side necessarily on the purpose of its injection resources.

This advantage has a setback, since nothing is totally good or bad.
If working with another server, not Node.js, it will be required two servers.

Well, this additional requirement may be compensated by reducing traffic on the main server, since part of the callings will be attended by the other one processing Angular 2 code.

On the other side, sometimes it is desired simplicity, lower processing, like avoiding additional steps like transpilation, injection, etc. In such cases, Angular 1 may fit like a glove, since sensitive codes are not exposed into client-processed scripts.

So, it is just a question of what is more recommended for each case.
Remember, since there are no miracles, when something does an extra thing it also requires extra resources.

Eventually, a last concern still remaining.
Sometimes, you may have sensitive code but that it doesn't mean that you really need Angular 2.
If the respective feature (use case) that code belongs to has low usage frequency, it may be used the traditional approach (full roundtrip) to spare project time and server resources without major issues about performance and etc. There is still another possibility. You may use the traditional asynchronous call by Angular 1 to process the sensitive code on the server.
If the page rendered on the client is compatible with the target devices, like mobile's platforms, the solution becomes another possible alternative.

Project design is a matter of weighing pros and cons considering possible refactoring costs in the future and cross-platform issues.




Thursday, August 3, 2017

Spring Boot: HTTPS and HTTP with Redirection Configuration (SSL/TLS)





To enable an application using Spring Boot to use secure connection, follow the steps described
below.


1. Generate the certificate.

Use Java's keytool utility to generate a self-signed certificate or by one.
For self-signed certificate, do:

  keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650


This command generates the file keystore.p12, a PKCS12 keystore containing the certificate in it and using "tomcat" as alias.

Output example:

$ keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
Password?: tomcat Again: tomcat Your first and last names? [Unknown]: john doe Organizational unit? [Unknown]: unitOne Your company's name? [Unknown]: myEnterprise Your city or locality? [Unknown]: Rio de Janeiro Your state? [Unknown]: RJ Your country - two letters? [Unknown]: BR

This command generates a PKCS12 keystore, denoted by keystore.p12.
Move the generated file to project's root dir.
Example:
- windows:
move keystore.p12 $PROJECT_ROOTDIR
- *nix:
mv keystore.p12 $PROJECT_ROOTDIR


2. Set project's configuration file.
If using yaml and MySQL, it could be something like shown below, otherwise, if using ".properties" just convert to its notation using dots ('.').  Example: server.contextPath=/

server:
  contextPath: /
spring:
  profiles: 
    active: dev  #if using profile
---
spring:
  profiles: dev, default
server:
  port: 8443 #default HTTPS
  ssl:
    key-store: keystore.p12
    key-store-password: tomcat
    keyStoreType: PKCS12
    keyAlias: tomcat
datasource:
  setget:
    url: jdbc:mysql://localhost:3306/myproject
    username: adminName
    password: myPass
#    driverClassName: org.gjt.mm.mysql.Driver
    driverClassName: com.mysql.jdbc.Driver
    defaultSchema: mySchema
    maxPoolSize: 20
    hibernate:
#      dialect: org.hibernate.dialect.MySQLDialect
      dialect: org.hibernate.dialect.MySQL5Dialect
      hbm2ddl.method: update
      show_sql: true
      format_sql: true


3. Create a @SpringBootApplication class:

br.com.setget.control.TomcatTwoConnectorsApplication

package br.com.setget.control;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class TomcatTwoConnectorsApplication {

@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
return tomcat;
}

private Connector initiateHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}

}

3b. If it is used a not proper configuration class, the application may fail to start.
In such cases, it may return a message file when the http redirection fails, for instance, like this:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate 
[org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; 
nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling


This procedure was created based on the documentation below wich may be used as complementary searching source.
Thanks to the authors.

https://drissamri.be/blog/java/enable-https-in-spring-boot/

https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors

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