Basic Session Creation How To

NEST application creates network sessions without using HTML page request. The user application can only run with network session file in JSON data format so the NEST application must follow session creation rules.

The following example will show how to create and manage network sessions.

package com.nxstinc.nest.servlet.api;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.nxstinc.commons.tools.SimpleRsaToolSingleton;
import com.nxstinc.nest.servlet.IProcess;
import com.nxstinc.nest.servlet.NEST;
import com.nxstinc.nest.servlet.ProcessException;
import com.nxstinc.nest.servlet.Result;

@WebServlet(description = "Signup", urlPatterns = { "/Signup" })
public class Signup extends NEST implements IProcess {
	private static final long serialVersionUID = 1L;

	@Override
	public void process(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Input in = getInputAsObject(request, Input.class);

		try {
			if (in.id != null)
				throw new ProcessException(Result.UNAUTHORIZED, "id");

			// Once signup is completed, set user data
			User user = new User();
			user.id = in.id;
			user.name = "NEST";
			user.timeStamp = System.currentTimeMillis();

			Gson gson = new GsonBuilder().create();
			// To store session data the user data is encrypted
			String accessToken = SimpleRsaToolSingleton.getSimpleRsaTool().encryptToBase64String(gson.toJson(user));

			// Users data and session data is transmitted to user application
			replyResult(new Result(user), accessToken, request, response);
		} catch (ProcessException ex) {
			System.err.println("[E] " + getClass().getCanonicalName() + " " + ex.getMessage());
			replyResult(ex.getResult(), request, response);
		} catch (Throwable th) {
			// th.printStackTrace();
			System.err.println("[E] " + getClass().getCanonicalName() + " " + th.getMessage());
			replyResult(new Result(Result.SERVICE_UNAVAILABLE, "Sorry, Service Un-available"), request, response);
		}
	}

	@Override
	public Class<?> getInputSpec() {
		return Input.class;
	}

	@Override
	public Class<?> getOutputSpec() {
		return User.class;
	}

	static class Input {
		String id;
		String password;
	}

	static class User {
		String id;
		String name;
		long timeStamp;
	}
}