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

Wednesday, August 2, 2017

Thymeleaf: DefaultHandlerExceptionResolver : Failed to bind request





>PROBLEM

The page fails to render and returns the following error:



2017-08-02 19:41:27.258 WARN 13112 --- [nio-8080-exec-9] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to bind request
element: org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type
'br.com.setget.model.User'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed
to convert from type [java.lang.String] to type [java.lang.Long] for value 'admin@email'; nested exception is
java.lang.NumberFormatException: For input string: "admin@email"


>SOLUTION

Check the thymeleaf's html code.
HTML input tags are responsible to upload values to the server.
If the input tag is not conform to thymeleaf semantic, it may cause this kind of issue.
In this example the defective code found was:

<div>
<input type="text" placeholder="username" name="user">
</div>
<div>
<input type="password" placeholder="password" name="password">
</div>


The defective code was corrected and replaced by the following:

<div>
<input type="text" id="email" name="email" th:placeholder="email" th:field="*{email}" /></br>
</div>
<div>
<input type="password" id="password" placeholder="password or create one" name="password" th:field="*{password}">
</div>


>ENV
Spring Boot 1.5.4.RELEASE
Thymeleaf 3.0.6.RELEASE
java 8

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