Running Tomcat Automatically At Linux Startup

A potential drawback of installing Tomcat from a binary distribution instead of using a Linux-packaged version is that you’ll have to do some extra legwork to make Tomcat start automatically when Linux boots up.  To make this process easy and pain-free, follow this simple guide.

Step 1 – Create A Tomcat-Specific User and User Group

It’s a bad idea to run Tomcat as the root user, especially if you’re going to be starting Tomcat automatically.  It’s much more secure to create a new group and user specifically to run Tomcat.  You can do so with the following commands (in this example, we have created a user group named tomcat, and a user named tomcat with the password tomcat; you can certainly be more creative if you wish):

$ groupadd tomcat
$ useradd -s /sbin/nologin -g tomcat -d /path/to/tomcat tomcat

or
$ useradd -r -s /sbin/nologin tomcat

-r for system user
$ passwd tomcat

-r, –system
Create a system account.

System users will be created with no aging information in /etc/shadow, and their
numeric identifiers are chosen in the SYS_UID_MIN-SYS_UID_MAX range, defined in
/etc/login.defs, instead of UID_MIN-UID_MAX (and their GID counterparts for the
creation of groups).

Note that useradd will not create a home directory for such an user, regardless
of the default setting in /etc/login.defs (CREATE_HOME). You have to specify the
-m options if you want a home directory for a system account to be created.

-s, –shell SHELL
The name of the user’s login shell. The default is to leave this field blank,
which causes the system to select the default login shell specified by the SHELL
variable in /etc/default/useradd, or an empty string by default.

Esample:

useradd -m -d /home/thenewuser -s /bin/bash -c "the new user" -U thenewuser

-c “message” : extra information about the user.

-U thenewuser : Create a group with the same name as the user, and add the user to this group.

-N : the -N argument tells the system not to create a group having the user’s name

-m, –create-home are same: Create the user’s home directory if it does not exist.

-d, –home HOME_DIR : The new user will be created using HOME_DIR as the value for the user’s login directory.
if -d is not used the default homedirectory will be /home/thenewuser

-m -d /data/thenewuser : the -m argument creates the /data/thenewuser homedirectory, specified by the -d argument.

-M : the -M argument tells the system not to create a home directory

-s /bin/bash : the -s is used for specifing the user’s default shell, /bin/bash in this case.

-s or –shell are same.

-s /sbin/nologin : The /sbin/nologin for Fedora and /usr/sbin/nologin for Debian are two shells that return you a polite message like “this account is not available” and do not allow you to log into the system. This message can be customized.

-s /bin/false : Is an old shell used to deny a user’s login. The /bin/false exits immediatly when false exists. The user accounts with /bin/false or /bin/true as their default shells are locked.

-s /sbin/nologin belongs to unix-linux while /bin/false part of GNU Coreutils. These shells must be listed in the /etc/shells file, to work.

The users with /sbin/nologin (or /usr/sbin/nologin) can connect through ssh or ftp, but the users with /bin/false are completely locked out from the system.

with useradd -D : You can also view the default parameters set for new user to be created using

# useradd -D
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes
#

Step 2 – Adjust Ownership For New Users And Groups

Now that you have created a user to run Tomcat, you’ll need to give them access to the correct directories.  Use the following commands, substituting your own usernames and groups as necessary:

# chown -R tomcat.tomcat /path/to/tomcat
# chmod 775 /path/to/tomcat/webapps
The first gives ownership of the Tomcat directories to the Tomcat user, and the second gives the user write access for the webapps directory.

Step 3 – Relay Traffic For Non-Root Tomcat User

When running Tomcat as a user other than the root user, you will not be able to bind to port 80, which is where Tomcat listens for HTTP requests.  To get around this, you can use Netfilter, which is packaged with all major Linux distributions:

# iptables -t nat -I PREROUTING -p tcp –dport 80 -j REDIRECT –to-ports 8080
# iptables -t nat -I OUTPUT -p tcp –dport 80 -j REDIRECT –to-ports 8080
To preserve these rules through re-boot, save them with the “ip-tables-save” command, and then follow the procedure appropriate for your Linux distribution (for most distributions, this means editing the iptables init script; Debian users should load the configuration via a script called by if-up.d or pre-up.d).

Step 3 – Create A Custom init Script

To start Tomcat at Linux boot time, we’ll need to create an init script that calls the startup.sh and shutdown.sh scripts included with Tomcat.

The actual creation of this script is outside the scope of this article, but there are many useful resources available online.  All you need to know in order to use the basic init script format to call Tomcat is how the startup.sh and shutdown.sh scripts work.

For more information about these scripts, visit our Tomcat Start page, which includes a simple, step-by-step guide to Tomcat’s three start-up shell scripts.

like :

chmod 774 /opt/apache-tomcat-8.0.12-1/ -Rf

export JAVA_OPTS=”-agentlib:hprof=cpu=samples,file=/var/log/cpuTest.log”

#/opt/apache-tomcat-8.0.12-2/bin/startup.sh
TOMCAT_OWNER=tomcat;
export TOMCAT_OWNER

CATALINA_HOME=/opt/apache-tomcat-8.0.12-2;
export CATALINA_HOME

/bin/su -s /bin/bash $TOMCAT_OWNER -c $CATALINA_HOME/bin/startup.sh

 

 

 

Spring Boot OAuth2

Traditional deployment

https://projects.spring.io/spring-security-oauth/docs/oauth2.html

Now we will describe the authorization code flow:

POST /oauth/oauth20/token

Returns an OAuth 2.0 token using HTTP POST.

To request an access token using this grant type, the client must have already obtained the Authorization Code from the authorization server. An Authorization Code is a short-lived token issued to the client application by the authorization server upon successful authentication/authorization of an end-user (resource owner). The client application then uses the authorization code to request an access token from the authorization server.

For detailed examples about the types of access tokens supported, with example for each type of access token, refer to OAuth: Client Authentication with the Platform’s OAuth Provider.

Note: there is a corresponding operation that performs the same action using HTTP GET: GET /oauth/oauth20/token. For information on why you might choose one or the other, see OAuth Operations: GET or POST?

Authorization Roles/Permissions: Anyone can run this operation.

This topic includes the following sections:

HTTP Method

POST

Back to top

URL

https://{oauth-provider-url}/oauth/oauth20/token

Back to top

Sample Request

The examples below shows token requests in an LDAP scenario, with several different grant types.

Request URL

https://{oauth-provider-url}/oauth/oauth20/token

Sample request headers

Note: In the sample request headers below, the Authorization header consist of the client’s Basic authentication header, as explained in HTTP Basic Authentication. This is one way of sending the authorization credentials. As an alternative, you can send this information in the POST body or, if you are using the GET operation, in the request parameters. For more information, see OAuth: Client Authentication with the Platform’s OAuth Provider.

POST /oauth/oauth20/token HTTP/1.1
Host: http://{oauth-provider-hostname}
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
Accept: application/json

Sample request body: authorization_code grant type

In the sample request body shown below, the client ID and client secret are included. When the Authorization header is included with the request message, as shown above, you don’t need to send the client ID and client secret in the parameters. Send them either in the header or in the parameters. The below is an example of sending these values in the POST request body if the Authorization header was not sent. Line breaks have been added for display purposes.

client_id=acmepaymentscorp-3rCEQzwEHMT9PPvuXcClpe3v
&client_secret=e5868ebb4445fc2ad9f949956c1cb9ddefa0d421
&code=T8Y2h7zvp-tviqe2gQQ_VGQKMizn8jRgxZ74hA
&redirect_uri=http%3A%2F%2Facmepaymentscorp.com%3A9900%2Fui%2Fapps%2Facmepaymentscorp%2F_VWQJeFH76RyfD6M6FRO5Svg%2Fresources%2Fconsole%2Fglobal%2Foauthclientredirect.html%3Fdynamic%3Dtrue
&grant_type=authorization_code
&scope=Scope1

Sample request body: client_credentials grant type (2-legged)

client_id=acmepaymentscorp-3rCEQzwEHMT9PPvuXcClpe3v
&client_secret=e5868ebb4445fc2ad9f949956c1cb9ddefa0d421
&grant_type=client_credentials
&scope=Scope1

Sample request body: Resource Owner Credentials grant type

client_id=atmosphere-3rCEQzwEHMT9PPvuXcClpe3v
&client_secret=e5868ebb4445fc2ad9f949956c1cb9ddefa0d421
&grant_type=password
&scope=Scope1
&username=eng100
&password=password

Back to top

Request Headers

For general information on request header values, refer to HTTP Request Headers.

HEADER DESCRIPTION
Accept application/json
Content-Type application/x-www-form-urlencoded
Authorization Optional. The Authorization request header authenticates the client with the server.

Back to top

Request Parameters

Note: the parameters below are all standard parameters defined in the OAuth 2.0, OpenID Connect, or JSON Web Token (JWT) specifications.

PARAMETER PARM TYPE DATA TYPE REQUIRED DESCRIPTION
grant_type Form String Required The OAuth grant type.

If the request is a request for a refresh token, the value must be set to refresh_token.

client_id Form String Optional Unique identifier of the client application.

Must be sent; but can be sent as Authorization header.

client_secret Form String Optional The client secret value; this value identifies the client with the provider.

Can be sent as Authorization header. Also, not needed for public client, even if Authorization header is not sent.

refresh_token Form String Optional Refresh Token grant type only: The refresh token.
scope Form String Optional OAuth 2.0: standard scope parameter. One or more scopes configured in the OAuth provider. Space separator for multiple scopes.

The scope of the access request.

code Form String Optional Authorization Code grant type only: The authorization code that was previously received by the client application.
redirect_uri Form String Optional Authorization Code grant type only: The redirect URI of the client application, where it received the authorization code.
username Form String Optional Resource Owner Password Credentials only: The resource owner’s username.
password Form String Optional Resource Owner Password Credentials only: The resource owner’s password.
client_assertion_type Form String Optional JWT Bearer Assertion grant type only:

The format of the assertion as identified by the Authorization Server. The value must be set to urn:ietf:params:oauth:client-assertion-type:jwt-bearer.

client_assertion Form String Optional JWT Bearer Assertion grant type only: The assertion being used to authenticate the client. Only JWT compact serialization is allowed.
assertion Form String Optional JWT Bearer Assertion grant type only: The JWT Bearer Assertion.

Back to top

Response

If successful, this operation returns HTTP status code 200, with the access token.

Back to top

Sample Response

The sample response below shows successful completion of this operation.

Sample response headers: application/json

HTTP/1.1 200 OK
Content-Type: application/json
Sample response body: application/json

Sample response body #1

{
  "access_token": "SlAV32hkKG",
  "token_type": "Bearer",
  "refresh_token": "8xLOxBtZp8",
  "expires_in": 3600,
  "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjFlOWdkazcifQ.ewogImlzc
    yI6ICJodHRwOi8vc2VydmVyLmV4YW1wbGUuY29tIiwKICJzdWIiOiAiMjQ4Mjg5
    NzYxMDAxIiwKICJhdWQiOiAiczZCaGRSa3F0MyIsCiAibm9uY2UiOiAibi0wUzZ
    fV3pBMk1qIiwKICJleHAiOiAxMzExMjgxOTcwLAogImlhdCI6IDEzMTEyODA5Nz
    AKfQ.ggW8hZ1EuVLuxNuuIJKX_V8a_OMXzR0EHR9R6jgdqrOOF4daGU96Sr_P6q
    Jp6IcmD3HP99Obi1PRs-cwh3LO-p146waJ8IhehcwL7F09JdijmBqkvPeB2T9CJ
    NqeGpe-gccMg4vfKjkM8FcGvnzZUN4_KSP0aAp1tOJ1zZwgjxqGByKHiOtX7Tpd
    QyHE5lcMiKPXfEIQILVq0pc_E2DzL7emopWoaoZTF_m0_N0YzFC6g6EJbOEoRoS
    K5hoDalrcvRYLSrQAZZKflyuVCyixEoV9GfNQC3_osjzw2PAithfubEEBLuVVk4
    XUVrWOLrLl0nx7RkKU8NXNHq-rvKMzqg"
}

Sample response body: authorization_code grant type

{
  "access_token" : "d50d9fd00acf797ac409d5890fcc76669b727e63",
  "token_type" : "Bearer",
  "expires_in" : 1295998,
  "refresh_token" : "TZzj2yvtWlNP6BvG6UC5UKHXY2Ey6eEo80FSYax6Yv8"
}

Sample response body: Client Credentials grant type (2-legged)

{
  "access_token" : "4484e52dc4744374aced826a4543cd28948816ff",
  "token_type" : "Bearer",
  "expires_in" : 1295999
}

Sample response body: Resource Owner Credentials grant type

{
  "access_token" : "49fad390491a5b547d0f782309b6a5b33f7ac087",
  "token_type" : "Bearer",
  "expires_in" : 1295999,
  "refresh_token" : "USrAgmSf5MJ8N_RLQODa7rZ3zNs1Sj1GkSIsTsb4n-Y"
}

Sample response body: Error scenario

Note: in the example below, the state parameter is included in the error response. This would be the case in any scenario where it was included in the request.

{
  error=invalid_request,
  error_description=Unsupported%20response_type%20value,
  state=af0ifjsldkj
}

Back to top

Response Headers

For general information on response header values, refer to HTTP Response Headers.

HEADER DESCRIPTION
Content-Type application/json

Back to top

Response Body: Success

NAME TYPE DESCRIPTION
AccessTokenResponse AccessTokenResponse Contains information about the response to a request for an OAuth Access Token. Used by the token endpoint.

Response Body: Error Scenario

NAME TYPE DESCRIPTION
AccessTokenErrorResponse AccessTokenErrorResponse Contains information about an error response returned by the OAuth Token Endpoint in response to a request for an OAuth 2.0 access token.

Back to top

Error Codes/Messages

If the call is unsuccessful an error code/message is returned. One or more examples of possible errors for this operation are shown below.

ITEM VALUE
500 An error occurred processing the call.

More information about Enterprise API Platform API error messages.

Back to top

Lambda Expression in Java

Java Lambda Example

package it;

public class TypeInterfaceExample {

public static void main(String[] args) {

        StringLambdaString myLambda1 = (String s) -> s.length();

        StringLambdaString myLambda2 = (s) -> s.length();

        StringLambdaString myLambda3 = s -> s.length();

        printLambda(myLambda3);

        //OR

        printLambda(s -> s.length());//here directly the definition of the

        implemention of the method getLength

}

public static void printLambda(StringLambdaString l) {

        System.out.println(l.getLength(“Hello Lambda”));

}

        interface StringLambdaString {

               int getLength(String s);

        }

}

Thanks to Brains