Servlet can't send cookie for the first request by client - java

I want to create a cookie which keeps the number of visits on persistent storage on client side, my server is simple servlet which runs on Apache Tomcat 8.0,
when the client sends a cookie already initialized with counter (for example counter = 12), the server increments the counter and sends back new cookie with new counter (counter = 13) and it's saved correctly by the client on my hard drive. This works fine for me.
but when the client sends a request for the first time, so no cookie is sent to server, and the server should create new cookie with counter = 0 and sends it back to client. This case doesn't work correctly and the client doesn't receive any cookie.
Here's my code example:
Client
public class Test
{
URI uri;
HttpURLConnection httpCon;
public static String urlString = "http://localhost:8082/Test/ReverseServlet";
public Test()
{
CookieManager cookieManager = new CookieManager(new MyCookieStore(), CookiePolicy.ACCEPT_ALL);
CookieManager.setDefault(cookieManager);
try
{
try
{
uri = new URI(urlString);
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
httpCon = (HttpURLConnection) uri.toURL().openConnection();
if (cookieManager.getCookieStore().get(uri).size() > 0)
{
httpCon.setRequestProperty("Cookie", cookieManager.getCookieStore().get(uri).get(0).toString());
}
httpCon.connect();
Map<String, List<String>> headerFields = httpCon.getHeaderFields();
List<String> cookiesHeader = headerFields.get("Set-Cookie");
if (cookiesHeader != null)
{
for (String cookie : cookiesHeader)
{
cookieManager.getCookieStore().add(uri, HttpCookie.parse(cookie).get(0));
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Test();
}
}
class MyCookieStore implements CookieStore
{
CookieStore store;
Path pathCookiesStore;
URI uri;
public MyCookieStore()
{
try
{
pathCookiesStore = Paths.get("D:\\Temp\\cookies.txt");
if (!Files.exists(pathCookiesStore))
{
Files.createFile(pathCookiesStore);
}
try
{
uri = new URI(Test.urlString);
}
catch (URISyntaxException e1)
{
e1.printStackTrace();
}
List<String> cookies = Files.readAllLines(pathCookiesStore);
store = new CookieManager().getCookieStore();
if (cookies.size() > 0)
{
HttpCookie countCookie = new HttpCookie("count", cookies.get(0));
countCookie.setDomain("localhost.local");
countCookie.setMaxAge(-1);
countCookie.setPath("/Test/");
store.add(uri, countCookie);
}
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
try
{
PrintWriter pw = new PrintWriter(new OutputStreamWriter(Files.newOutputStream(pathCookiesStore, StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING)));
for (HttpCookie cookie : store.getCookies())
{
if (cookie.getName().equals("count"))
{
pw.println(cookie.getValue());
pw.flush();
pw.close();
break;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
}
catch (IOException excp)
{
excp.printStackTrace();
}
}
public void add(URI uri, HttpCookie cookie)
{
store.add(uri, cookie);
}
public List<HttpCookie> get(URI uri)
{
return store.get(uri);
}
public List<HttpCookie> getCookies()
{
return store.getCookies();
}
public List<URI> getURIs()
{
return store.getURIs();
}
public boolean remove(URI uri, HttpCookie cookie)
{
return store.remove(uri, cookie);
}
public boolean removeAll()
{
return store.removeAll();
}
}
Server
public class ReverseServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
{
int countVisits = 0;
Cookie cookies[] = req.getCookies();
if (cookies.length > 0)
{
for (Cookie cookie : cookies)
{
if (cookie.getName().equals("count"))
{
try
{
countVisits = Integer.parseInt(cookie.getValue());
countVisits++;
}
catch (NumberFormatException excp)
{
countVisits = 0;
}
break;
}
}
}
Cookie countCookie = new Cookie("count", String.valueOf(countVisits));
countCookie.setDomain("localhost.local");
countCookie.setMaxAge(-1);
countCookie.setPath("/Test/");
resp.addCookie(countCookie);
}
}

Related

Why can't my web client accept an image from my web server?

I this is my java HTTP server:
public class WebServer implements Runnable {
public static final int PORT = 80;
#Override
public void run() {
HttpServer $server;
try {
$server = HttpServer.create(new InetSocketAddress(80), 0);
} catch (IOException _e) {
throw new RuntimeException(_e);
}
$server.createContext("/", _httpExchange ->
{
String $uri = _httpExchange.getRequestURI().toString();
$uri = $uri.startsWith("/") ? $uri.replaceFirst("/", "") : $uri;
if ($uri.equals("")) {
sendFile("test.html", _httpExchange);
}
else if ($uri.matches(".*\\.[^/.]+")) {
sendFile($uri, _httpExchange);
}
else {
sendFile($uri + ".html", _httpExchange);
}
});
$server.start();
System.out.println("Server started at " + getPrivateIp() + " on port " + PORT);
}
private static String getPrivateIp() {
try (final DatagramSocket datagramSocket = new DatagramSocket()) {
datagramSocket.connect(InetAddress.getByName("8.8.8.8"), 12345);
return datagramSocket.getLocalAddress().getHostAddress();
} catch (UnknownHostException | SocketException _e) {
throw new RuntimeException(_e);
}
}
public static void sendFile(String _name, HttpExchange _exchange) throws IOException {
try {
InputStream $stream = WebServer.class.getResourceAsStream(_name);
if ($stream == null) {
_exchange.sendResponseHeaders(404, 0);
_exchange.close();
return;
}
Scanner $scanner = new Scanner($stream).useDelimiter("\\A");
String $response = $scanner.next();
_exchange.getResponseBody();
_exchange.sendResponseHeaders(200, $response.getBytes().length);
_exchange.getResponseBody().write($response.getBytes());
_exchange.close();
} catch (Exception _ex) {
throw new RuntimeException(_ex);
}
}
}
When I run it, and then open my website, everything is ok, but I cannot see any images. In the network tab, it says that the image was accepted, but it's not shown. I tried using Files.copy() in sendFile() method, but it didn't work - it didn't show the website, nor the image! (Not even when I did localhost/image.jpg).
In the network tab, it also shows that the MIME type is img/jpeg, which is correct, so it's not because of that...
Using wget, I get a normal looking .jpg file, but if I open it, it's corrupted...
Does someone know how to fix this?
Thanks.
Solved it!
You just check if the request wants .png or .jpg file (or you can just check the MIME type), and if it does, then you have to use ImageIO class
public static void sendFile(String _name, HttpExchange _exchange) {
try {
InputStream $stream = WebServer.class.getResourceAsStream(_name);
if ($stream == null) {
_exchange.sendResponseHeaders(404, 0);
_exchange.close();
return;
}
if (_name.matches(".*?\\.(png|PNG|jpg|JPG|jpeg|JPEG)")) {
BufferedImage $image = ImageIO.read($stream);
if (_name.toLowerCase().endsWith("png")) {
_exchange.sendResponseHeaders(200, getImageSize($image, "png"));
ImageIO.write($image, "png", _exchange.getResponseBody());
}
else {
_exchange.sendResponseHeaders(200, getImageSize($image,"jpeg"));
ImageIO.write($image, "jpeg", _exchange.getResponseBody());
}
$stream.close();
_exchange.close();
return;
}
Scanner $scanner = new Scanner($stream).useDelimiter("$");
String $response = $scanner.next();
_exchange.getResponseBody();
_exchange.sendResponseHeaders(200, $response.length());
_exchange.getResponseBody().write($response.getBytes());
_exchange.close();
} catch (Exception _ex) {
throw new RuntimeException(_ex);
}
}

Why does client not receive final server answer in non-blocking client-server app?

I am trying to figure out NIO in Java doing some simple client-server project.
The case is I have to concurrent clients in cached thread pool executor, who are communicating with single-threaded server using non-blocking NIO channels.
The problem is that last client cannot receive last server's sent message. It locks in infinite loop waiting for upcoming data.
ClientTask class:
public class ClientTask extends FutureTask<String> {
private Client client;
private List<String> reqList; // requests list (without last and first)
private boolean showRes; // print request results
public ClientTask(Client client, List<String> reqList, boolean showRes) {
super(() -> ClientTask.getLogWhenArrives(client, reqList, showRes));
this.client = client;
this.reqList = reqList;
this.showRes = showRes;
}
public static ClientTask create(Client c, List<String> reqList, boolean showRes) {
return new ClientTask(c, reqList, showRes);
}
private static String getLogWhenArrives(Client client, List<String> reqList, boolean showRes) {
client.connect();
String response = client.send("login " + client.getId());
if (showRes) System.out.println(response);
for (String req : reqList) {
response = client.send(req);
if (showRes) System.out.println(response);
}
String responseLog = client.send("bye and log transfer");
client.close();
return responseLog;
}
}
Client send():
public String send(String req) {
ByteBuffer reqBuffer = ByteBuffer.wrap((req + END).getBytes());
try {
channel.write(reqBuffer);
} catch (IOException e) {
e.printStackTrace();
}
return receive();
}
Client receive()
public String receive() {
StringBuilder result = new StringBuilder();
try {
inBuff.clear();
readLoop:
while (true) { // THIS LOOP WON'T END
int n = channel.read(inBuff);
if (n == -1) {
break;
}
if (n > 0) {
inBuff.flip();
CharBuffer cb = charset.decode(inBuff);
while (cb.hasRemaining()) {
char c = cb.get();
if (c == END.charAt(0)) {
break readLoop;
}
result.append(c);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
Main:
public class Main {
public static void main(String[] args) throws Exception {
String fileName = System.getProperty("user.home") + "/PassTimeServerOptions.yaml";
Options opts = Tools.createOptionsFromYaml(fileName);
String host = opts.getHost();
int port = opts.getPort();
boolean concur = opts.isConcurMode();
boolean showRes = opts.isShowSendRes();
Map<String, List<String>> clRequests = opts.getClientsMap();
ExecutorService es = Executors.newCachedThreadPool();
List<ClientTask> ctasks = new ArrayList<>();
List<String> clogs = new ArrayList<>();
Server s = new Server(host, port);
s.startServer();
// start clients
clRequests.forEach( (id, reqList) -> {
Client c = new Client(host, port, id);
if (concur) {
ClientTask ctask = ClientTask.create(c, reqList, showRes);
ctasks.add(ctask);
es.execute(ctask);
}
});
if (concur) {
ctasks.forEach( task -> {
try {
String log = task.get();
clogs.add(log);
} catch (InterruptedException | ExecutionException exc) {
System.out.println(exc);
}
});
clogs.forEach( System.out::println);
es.shutdown();
}
s.stopServer();
System.out.println("\n=== Server log ===");
System.out.println(s.getServerLog());
}
}
Server is sending all the info and channels are open and connected.

Java two threads work with the same data (one get, one set)

I'm taking my first steps with Java Sockets and Threads.
I want to try make synchonized connection with serwer where multiple threades adds their request to the queue and signle thread send all this request. In the meantime other threads wait for there resoults.
How it's work:
Client ask servert to log in by caling method
User user = logIn("sdasd");
public User logIn(String name){
System.out.println("!Log in");
//Function create request
RequestHandler<User> request = new RequestHandler<>("logIn", name, out, results);
//Request is added to queue
requestQueue.addLast(request);
RequestStatus status;
//Thread who call this function wait for request to be handle (changed status)
while (true){
status = request.getStatus();
System.out.println(status);
if (status == RequestStatus.SUCCESSFUL) {
System.out.println("Try to get result: ");
User user = request.result();
System.out.println(user.getName());
return request.result();
}
if(status == RequestStatus.FAILED) {
return null;
}
}
}
In the meantime other thread send request to server:
new Thread(new Runnable() {
#Override
public void run() {
while(isConnected()){
//is request to be handle?
if(requestQueue.size() != 0){
//remove request form queue
RequestHandler request = (RequestHandler) requestQueue.removeFirst();
//change request status
request.setStatus(RequestStatus.IN_PROGRESS);
System.out.println("!Request: ");
System.out.println(request.getStatus());
//process request
request.request();
//change request status to finished
request.setStatus(RequestStatus.SUCCESSFUL);
System.out.print("!Request end: ");
System.out.println(request.getStatus());
}
}
Iterator<Request> iterator = requestQueue.iterator();
for (Iterator<Request> it = iterator; it.hasNext(); ) {
Request request = it.next();
request.setStatus(RequestStatus.FAILED);
}
}
}).start();
Inside class RequestHandler is process this code:
#Override
public void request() {
try {
//send commend
out.writeObject(requestCommend);
//wait for result (other thread handle this functionality)
while(!results.containsKey(commend)){}
//attach result
result = (T) results.remove(commend);
} catch (IOException e) {
e.printStackTrace();
}
}
When the request is send to the server other thread wait for response for the server and add result to the HashMap:
new Thread(new Runnable() {
#Override
public void run() {
while(isConnected()) {
try {
String commend = (String) in.readObject();
if(commend.charAt(0) == '#') { // # mean its result of request
Object object = in.readObject();
//This is debug case to see everything work properly
if(object == null){
System.out.println("!I am null");
}else{
System.out.println("I am user: " +((User) object).getName());
}
System.out.println(commend);
results.put(commend, object);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}).start();
This is it. Required code for this question:
public class ServerConnection extends Socket{
public static final int PORT = 8888;
private ObjectInputStream in;
private ObjectOutputStream out;
private LinkedList<Request> requestQueue;
private ConcurrentHashMap<String, Object> results;
public ServerConnection() throws IOException{
super("localhost", PORT);
System.out.println("Connected to the server.");
in = new ObjectInputStream(getInputStream());
out = new ObjectOutputStream(getOutputStream());
requestQueue = new LinkedList<>();
results = new ConcurrentHashMap<>();
new Thread(new Runnable() {
#Override
public void run() {
while(isConnected()){
if(requestQueue.size() != 0){
RequestHandler request = (RequestHandler) requestQueue.removeFirst();
request.setStatus(RequestStatus.IN_PROGRESS);
System.out.println("!Request: ");
System.out.println(request.getStatus());
request.request();
request.setStatus(RequestStatus.SUCCESSFUL);
System.out.print("!Request end: ");
System.out.println(request.getStatus());
}
}
Iterator<Request> iterator = requestQueue.iterator();
for (Iterator<Request> it = iterator; it.hasNext(); ) {
Request request = it.next();
request.setStatus(RequestStatus.FAILED);
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
while(isConnected()) {
try {
String commend = (String) in.readObject();
if(commend.charAt(0) == '#') { // # mean its result of request
Object object = in.readObject();
//This is debug case
if(object == null){
System.out.println("!I am null");
}else{
System.out.println("I am user: " +((User) object).getName());
}
System.out.println(commend);
results.put(commend, object);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}).start();
}
public User logIn(String name){
System.out.println("!Log in");
RequestHandler<User> request = new RequestHandler<>("logIn", name, out, results);
requestQueue.addLast(request);
RequestStatus status;
while (true){
status = request.getStatus();
System.out.println(status);
if (status == RequestStatus.SUCCESSFUL) {
System.out.println("Try to get result: ");
User user = request.result();
System.out.println(user.getName());
return request.result();
}
if(status == RequestStatus.FAILED) {
return null;
}
}
}
public ArrayList<Room> getListOfRooms(){
Request<ArrayList<Room>> request = new RequestHandler<>("listOfRooms", out, results);
requestQueue.addLast(request);
while (true){
RequestStatus status = request.getStatus();
if (status == RequestStatus.SUCCESSFUL)
return request.result();
if(status == RequestStatus.FAILED) {
return null;
}
}
}
}
RequestHandler looks like this:
public class RequestHandler<T> implements Request<T>{
private T result;
private RequestStatus status = RequestStatus.NEW;
private ObjectOutputStream out;
private String commend;
private String requestCommend;
private ConcurrentHashMap<String, Object> results;
public RequestHandler(String commend, String parameters, ObjectOutputStream out, ConcurrentHashMap<String, Object> results) {
this.commend = "#" + commend;
this.requestCommend = "?" + commend + ":" + parameters;
this.out = out;
this.results = results;
}
public RequestHandler(String commend, ObjectOutputStream out, ConcurrentHashMap<String, Object> results) {
this.commend = "#" + commend;
this.requestCommend = "?" + commend;
this.out = out;
this.results = results;
}
#Override
public void request() {
try {
out.writeObject(requestCommend);
while(!results.containsKey(commend)){}
result = (T) results.remove(commend);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public T result() {
return result;
}
#Override
public RequestStatus getStatus() {
return status;
}
#Override
public void setStatus(RequestStatus status) {
this.status = status;
}
}
The output looks like this WHEN ITS WORK:
Connected to the server.
!Log in
NEW
IN_PROGRESS
...
IN_PROGRESS
!Request: IN_PROGRESS
IN_PROGRESS
...
IN_PROGRESS
I am user: sdsad
#logIn
IN_PROGRESS
IN_PROGRESS
SUCCESSFUL
!Request end: SUCCESSFUL
Try to get result:
sdsad
But when I COMMENT one debug msg I got this:
Connected to the server.
!Log in
!Request: IN_PROGRESS
I am user: dfdsfsdf4324
#logIn
!Request end: SUCCESSFUL
And the loop while(true) never end becouse I got always status IN_PROGRESS.
That's why I want to ask you why it's happen? Is Java have some weird way to optimalize output of functions to make is faster and is it thinking if it was reapet milion times so it has to be this state always?

RMI does not return response over internet

I have a simple rmi-server and rmi-client. When i run this server and client in same network, my server function returns the result properly. But my server and client are in different networks and if the process time is more than 3-4 minutes client can not get the result, although server fihishes the operation.
here is my entire server code:
public class SimpleServer {
ServerRemoteObject mRemoteObject;
public static int RMIInPort = 27550;
public static int delay = 0;
public byte[] handleEvent(byte[] mMessage) throws Exception {
String request = new String(mMessage, "UTF-8");
// if ("hearthbeat".equalsIgnoreCase(request)) {
// System.out.println("returning for hearthbeat");
// return "hearthbeat response".getBytes("UTF-8");
// }
System.out.println(request);
Thread.sleep(delay);
System.out.println("returning response");
return "this is response".getBytes("UTF-8");
}
public void bindYourself(int rmiport) {
try {
mRemoteObject = new ServerRemoteObject(this);
java.rmi.registry.Registry iRegistry = LocateRegistry.getRegistry(rmiport);
iRegistry.rebind("Server", mRemoteObject);
} catch (Exception e) {
e.printStackTrace();
mRemoteObject = null;
}
}
public static void main(String[] server) {
int rmiport = Integer.parseInt(server[0]);
RMIInPort = Integer.parseInt(server[1]);
delay = Integer.parseInt(server[2]);
System.out.println("server java:" + System.getProperty("java.version"));
System.out.println("server started on:" + rmiport + "/" + RMIInPort);
System.out.println("server delay on:" + delay);
SimpleServer iServer = new SimpleServer();
iServer.bindYourself(rmiport);
while (true) {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and here is my client code:
public class SimpleClient {
ISimpleServer iServer;
public SimpleClient(String p_strServerIp, String p_strCMName, int nRMIPort) {
try {
if (nRMIPort == 1099) {
iServer = (ISimpleServer) Naming.lookup("rmi://" + p_strServerIp + "/" + p_strCMName);
} else {
Registry rmiRegistry = null;
rmiRegistry = LocateRegistry.getRegistry(p_strServerIp, nRMIPort);
iServer = (ISimpleServer) rmiRegistry.lookup(p_strCMName);
}
} catch (Exception ex) {
ex.printStackTrace();
iServer = null;
}
}
public static void main(String... strings) {
String ip = strings[0];
int rmiport = Integer.parseInt(strings[1]);
System.out.println("client java:" + System.getProperty("java.version"));
System.out.println("client is looking for:" + ip + ":" + rmiport);
SimpleClient iClient = new SimpleClient(ip, "Server", rmiport);
try {
byte[] response = iClient.iServer.doaction("this is request".getBytes("UTF-8"));
System.out.println(new String(response, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
and here is my rmi-registry code:
public class SimpleRMI implements Runnable {
Registry mRegistry = null;
public SimpleRMI(int nPort) {
try {
mRegistry = new sun.rmi.registry.RegistryImpl(nPort);
} catch (RemoteException e1) {
e1.printStackTrace();
}
}
#Override
public void run() {
while (true) {
try {
Thread.sleep(360000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String... strings) {
int rmiport = Integer.parseInt(strings[0]);
System.out.println("rmi java:" + System.getProperty("java.version"));
System.out.println("rmi started on:" + rmiport);
SimpleRMI iRegisry = new SimpleRMI(rmiport);
Thread tThread = new Thread(iRegisry);
tThread.start();
byte[] bytes = new byte[1];
while (true) {
try {
System.in.read(bytes);
if (bytes[0] == 13) {
try {
iRegisry.listRegistry();
} catch (Exception exc2) {
exc2.printStackTrace();
}
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
private void listRegistry() {
String[] strList = null;
try {
strList = mRegistry.list();
if (strList != null) {
for (int i = 0; i < strList.length; i++) {
int j = i + 1;
String name = strList[i];
java.rmi.Remote r = mRegistry.lookup(name);
System.out.println(j + ". " + strList[i] + " -> "
+ r.toString());
}
}
System.out.println();
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
and my remote interface and remote object:
public interface ISimpleServer extends java.rmi.Remote {
public byte[] doaction(byte[] message) throws java.rmi.RemoteException;
}
#SuppressWarnings("serial")
public class ServerRemoteObject extends UnicastRemoteObject implements ISimpleServer {
SimpleServer Server = null;
public ServerRemoteObject(SimpleServer pServer) throws RemoteException {
super(SimpleServer.RMIInPort);
Server = pServer;
}
#Override
public byte[] doaction(byte[] message) throws RemoteException {
try {
return Server.handleEvent(message);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
when i run client and server in different networks. (i run client in my home network) and if delay is more than 3-4 mins server prints returning response but client still waits for the response. If delay is only 1 minute, clients gets the result properly.
Can you please help me to find where the problem is?

Why does object inside a protected method has implementation?

Its the method invokeBackend(String request, HashMap context) .
Why does it have an object named java.security.PrivilegedAction createController = new java.security.PrivilegedAction()
and it has an implementation ? I see it has a run() method which means its a thread.
Does the run method returns "controller"? It returns "controller" to what?
What kind of an implementation is this? An object having implementation code?
3.Whats the primary use of implmentation of the method invokeBackend
Also the object
java.security.PrivilegedAction processRequest = new java.security.PrivilegedAction()
Thanks a lot!
protected static String invokeBackend(String request, HashMap context)
throws CommonModelException {
if (request.equals("")) {
return null;
}
if (logger.isDebugEnabled()) {
logger.debug("request: \r\n" + request);
}
Properties clientAuthenticationEnv = CommonProperties
.getClientAuthenticationProperties();
if (wccClientId == null) {
wccClientId = clientAuthenticationEnv.getProperty(CLIENT_ID);
}
if (wccClientPassword == null) {
wccClientPassword = clientAuthenticationEnv
.getProperty(CLIENT_PASSWORD);
}
controllerHome = getControllerHome();
String response = null;
try {
if (controllerHome == null) {
throw new CommonModelException(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION));
}
if (isWASImpl) {
java.security.PrivilegedAction createController = new java.security.PrivilegedAction() {
public Object run() {
Object controller = null;
try {
controller = controllerHome.create();
} catch (RemoteException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e);
} catch (CreateException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_FAIL_GET_EJB_INSTANCE), e);
}
return controller;
}
}; // PrivilegedAction
validateSecurityToken();
final DWLServiceController controller = (DWLServiceController) WSSubject
.doAs(subject, createController);
final String req = request;
final HashMap cxt = context;
java.security.PrivilegedAction processRequest = new java.security.PrivilegedAction() {
public Object run() {
Object response = null;
try {
response = (String) controller.processRequest(cxt,
req);
} catch (com.dwl.base.exception.DWLResponseException e) {
response = e.getLocalizedMessage();
} catch (RemoteException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e);
}
return response;
}
}; // PrivilegedAction
validateSecurityToken();
response = (String) WSSubject.doAs(subject, processRequest);
} else {
// DWLServiceController controller = controllerHome.create();
// response = (String) controller.processRequest(context,
// request);
java.security.PrivilegedAction createController = new java.security.PrivilegedAction() {
public Object run() {
Object controller = null;
try {
controller = controllerHome.create();
} catch (RemoteException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e);
} catch (CreateException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_FAIL_GET_EJB_INSTANCE), e);
}
return controller;
}
}; // PrivilegedAction
//reflection invoke to avoid compile dependency on weblogic library
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class securityClazz = cl.getClass().getClassLoader().loadClass("weblogic.security.Security");
Method runAs = securityClazz.getMethod("runAs", new Class[]{Subject.class, java.security.PrivilegedAction.class});
final DWLServiceController controller = (DWLServiceController) runAs.invoke(securityClazz, new Object[]{subject, createController});
//final DWLServiceController controller = (DWLServiceController) Security.runAs(subject, createController);
final String req = request;
final HashMap cxt = context;
java.security.PrivilegedAction processRequest = new java.security.PrivilegedAction() {
public Object run() {
Object response = null;
try {
response = (String) controller.processRequest(cxt,
req);
} catch (com.dwl.base.exception.DWLResponseException e) {
response = e.getLocalizedMessage();
} catch (RemoteException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e);
}
return response;
}
}; // PrivilegedAction
response = (String)runAs.invoke(securityClazz, subject, processRequest);
//response = (String) Security.runAs(subject, processRequest);
}
} catch (Exception e) {
response = e.getLocalizedMessage();
// for non IBM WebSphere Server, we have one more chance to redo
// lookup for EJB server restart, clear the session first
controllerHome = getControllerHome();
if (controllerHome == null) {
throw new CommonModelException(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION));
}
try {
DWLServiceController controller = controllerHome.create();
response = (String) controller.processRequest(context, request);
} catch (DWLResponseException e1) {
response = e1.getLocalizedMessage();
} catch (RemoteException e1) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e1);
throw new CommonModelException(e1);
} catch (CreateException e1) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_FAIL_GET_EJB_INSTANCE), e1);
throw new CommonModelException(e1);
}
}
if (logger.isDebugEnabled()) {
logger.debug("response: \r\n" + response);
}
return response;
}
The declaration you're looking at is a local variable initialized to reference an instance of an anonymous inner class. The class implemented is PrivilegedAction. The syntax is used when you want to create a one-off implementation of an interface or class that you don't intend to use elsewhere, so there's no point in giving it a name. The code implements the run method from the interface and creates an object implementing that interface, that it assigns to the local variable.
The run method returns a controller object to whoever calls run on it. That isn't shown here, it's passed in as one of the arguments to the runAs method call on this line:
final DWLServiceController controller = (DWLServiceController) runAs.invoke(
securityClazz, new Object[]{subject, createController});
where the code used reflection to look up the runAs method on the class weblogic.security.Security.

Categories