diff --git a/src/main/java/com/gw/server/Java2JupyterClientEndpoint.java b/src/main/java/com/gw/server/Java2JupyterClientEndpoint.java index a6019f759..5b6d8252c 100644 --- a/src/main/java/com/gw/server/Java2JupyterClientEndpoint.java +++ b/src/main/java/com/gw/server/Java2JupyterClientEndpoint.java @@ -26,7 +26,8 @@ import org.springframework.stereotype.Service; import com.gw.jpa.Host; -import com.gw.server.JupyterRedirectServlet.SessionPair; +import com.gw.tools.JupyterSessionPairTool; +import com.gw.tools.SessionPair; import com.gw.utils.BaseTool; /** @@ -292,7 +293,7 @@ public void onClose(Session session, CloseReason closeReason) { // this.new_ws_session_between_geoweaver_and_jupyterserver = null; // logger.debug("The connection between Javascript and Geoweaver is closed. "); - SessionPair pair = JupyterRedirectServlet.findPairByID(this.pairid); + SessionPair pair = JupyterSessionPairTool.findPairByID(this.pairid); if(!bt.isNull(pair)) { diff --git a/src/main/java/com/gw/server/JupyterHubRedirectServlet.java b/src/main/java/com/gw/server/JupyterHubRedirectServlet.java index eba73083f..33ecb2546 100644 --- a/src/main/java/com/gw/server/JupyterHubRedirectServlet.java +++ b/src/main/java/com/gw/server/JupyterHubRedirectServlet.java @@ -20,9 +20,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import com.gw.jpa.Host; import com.gw.tools.HostTool; +import com.gw.tools.JupyterSessionPairTool; +import com.gw.tools.SessionPair; import com.gw.utils.BaseTool; import com.gw.utils.BeanTool; @@ -46,13 +49,14 @@ public class JupyterHubRedirectServlet{ // @Autowired // Java2JupyterClientEndpoint client; - public static List pairs = new ArrayList(); + // public static List pairs = new ArrayList(); -// @Autowired + // @Autowired HostTool ht; -// @Autowired + // @Autowired BaseTool bt; + public JupyterHubRedirectServlet() { @@ -60,118 +64,6 @@ public JupyterHubRedirectServlet() { } - /** - * First session is between browser and geoweaver - * @param b2gsession - * @return - */ - public static SessionPair findPairBy1stSession(Session b2gsession) { - - SessionPair pair = null; - - for(SessionPair p : pairs) { - - if(p.getBrowse_geoweaver_session()==b2gsession) { - - pair = p; - - break; - - } - - } - - return pair; - - } - - public static SessionPair findPairByID(String pairid) { - - SessionPair pair = null; - - for(SessionPair p : pairs) { - - if(p.getId().equals(pairid)) { - - pair = p; - - break; - - } - - } - - return pair; - - } - - /** - * 2nd session is between geoweaver and jupyter - * @param b2gsession - * @return - */ - public static SessionPair findPairBy2ndSession(Java2JupyterClientEndpoint g2jclient) { - - SessionPair pair = null; - - for(SessionPair p : pairs) { - - if(p.getGeoweaver_jupyter_client()==g2jclient) { - - pair = p; - - break; - - } - - } - - return pair; - - } - - public static void removeClosedPair() { - - for(SessionPair p : pairs) { - - if(!p.getBrowse_geoweaver_session().isOpen() ) { - - System.out.println("Detected one browser_geoweaver_session is closed. Removing it..."); - - pairs.remove(p); - - } - - if(!p.getGeoweaver_jupyter_client().getNew_ws_session_between_geoweaver_and_jupyterserver().isOpen()) { - - System.out.println("Detected one geoweaver jupyter session is closed. Removing it..."); - - pairs.remove(p); - - } - - } - - } - - public static void removePairByID(String id) { - - for(SessionPair p : pairs) { - - if(p.getId().equals(id)) { - - System.out.println("Detected one session pair is closed on one of the websocket session. Removing it..."); - - pairs.remove(p); - - break; - - } - - } - - } - private void init(Session b2gsession) { if(ht==null) { @@ -187,7 +79,7 @@ private void init(Session b2gsession) { } // SessionPair pair = findPairBy1stSession(b2gsession); - SessionPair pair = this.findPairByID(b2gsession.getQueryString()); + SessionPair pair = JupyterSessionPairTool.findPairByID(b2gsession.getQueryString()); if(bt.isNull(pair)) { @@ -201,7 +93,7 @@ private void init(Session b2gsession) { pair.setGeoweaver_jupyter_client(client); - pairs.add(pair); + JupyterSessionPairTool.pairs.add(pair); logger.debug("New Pair is created: ID: " + pair.getId()); @@ -258,7 +150,7 @@ public void open(Session session, // client = new Java2JupyterClientEndpoint(new URI(trueurl), session, headers, h); - SessionPair pair = this.findPairByID(session.getQueryString()); + SessionPair pair = JupyterSessionPairTool.findPairByID(session.getQueryString()); // pair.getGeoweaver_jupyter_client().init(new URI(trueurl), session, headers, h, pair.getId()); @@ -294,7 +186,7 @@ public void echo(String message, @PathParam("uuid1") String uuid1, Session sessi // SessionPair pair = findPairBy1stSession(session); - SessionPair pair = this.findPairByID(session.getQueryString()); + SessionPair pair = JupyterSessionPairTool.findPairByID(session.getQueryString()); if(bt.isNull(pair)) { @@ -333,13 +225,13 @@ public void close(final Session session) { logger.error("Channel closed."); // SessionPair pair = findPairBy1stSession(session); - SessionPair pair = this.findPairByID(session.getQueryString()); + SessionPair pair = JupyterSessionPairTool.findPairByID(session.getQueryString()); if(!bt.isNull(pair)) { pair.getGeoweaver_jupyter_client().getNew_ws_session_between_geoweaver_and_jupyterserver().close(); //close websocket connection - pairs.remove(pair); + JupyterSessionPairTool.pairs.remove(pair); // client.getNew_ws_session_between_geoweaver_and_jupyterserver().close(); @@ -358,68 +250,4 @@ public void close(final Session session) { - public class SessionPair{ - - String id; - - Session browse_geoweaver_session; - - Java2JupyterClientEndpoint geoweaver_jupyter_client; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public Session findOpenSession() { - - Set sessionset = browse_geoweaver_session.getOpenSessions(); - - Iterator it = sessionset.iterator(); - - Session session = browse_geoweaver_session; - - while(it.hasNext()){ -// System.out.println(it.next()); - - Session cs = (Session)it.next(); - - if(id.equals(cs.getQueryString())) { - - session = cs; - - break; - - } - - } - - return session; - - } - - public Session getBrowse_geoweaver_session() { - - return findOpenSession(); - } - - public void setBrowse_geoweaver_session(Session browse_geoweaver_session) { - - this.browse_geoweaver_session = browse_geoweaver_session; - - } - - public Java2JupyterClientEndpoint getGeoweaver_jupyter_client() { - return geoweaver_jupyter_client; - } - - public void setGeoweaver_jupyter_client(Java2JupyterClientEndpoint geoweaver_jupyter_client) { - this.geoweaver_jupyter_client = geoweaver_jupyter_client; - } - - } - } diff --git a/src/main/java/com/gw/server/JupyterRedirectServlet.java b/src/main/java/com/gw/server/JupyterRedirectServlet.java index 98422d982..412133b6b 100644 --- a/src/main/java/com/gw/server/JupyterRedirectServlet.java +++ b/src/main/java/com/gw/server/JupyterRedirectServlet.java @@ -23,6 +23,8 @@ import com.gw.jpa.Host; import com.gw.tools.HostTool; +import com.gw.tools.JupyterSessionPairTool; +import com.gw.tools.SessionPair; import com.gw.utils.BaseTool; import com.gw.utils.BeanTool; @@ -46,12 +48,12 @@ public class JupyterRedirectServlet { // @Autowired // Java2JupyterClientEndpoint client; - public static List pairs = new ArrayList(); + // public static List pairs = new ArrayList(); -// @Autowired + // @Autowired HostTool ht; -// @Autowired + // @Autowired BaseTool bt; public JupyterRedirectServlet() { @@ -60,117 +62,117 @@ public JupyterRedirectServlet() { } - /** - * First session is between browser and geoweaver - * @param b2gsession - * @return - */ - public static SessionPair findPairBy1stSession(Session b2gsession) { + // /** + // * First session is between browser and geoweaver + // * @param b2gsession + // * @return + // */ + // public static SessionPair findPairBy1stSession(Session b2gsession) { - SessionPair pair = null; + // SessionPair pair = null; - for(SessionPair p : pairs) { + // for(SessionPair p : pairs) { - if(p.getBrowse_geoweaver_session()==b2gsession) { + // if(p.getBrowse_geoweaver_session()==b2gsession) { - pair = p; + // pair = p; - break; + // break; - } + // } - } + // } - return pair; + // return pair; - } + // } - public static SessionPair findPairByID(String pairid) { + // public static SessionPair findPairByID(String pairid) { - SessionPair pair = null; + // SessionPair pair = null; - for(SessionPair p : pairs) { + // for(SessionPair p : pairs) { - if(p.getId().equals(pairid)) { + // if(p.getId().equals(pairid)) { - pair = p; + // pair = p; - break; + // break; - } + // } - } + // } - return pair; + // return pair; - } + // } - /** - * 2nd session is between geoweaver and jupyter - * @param b2gsession - * @return - */ - public static SessionPair findPairBy2ndSession(Java2JupyterClientEndpoint g2jclient) { + // /** + // * 2nd session is between geoweaver and jupyter + // * @param b2gsession + // * @return + // */ + // public static SessionPair findPairBy2ndSession(Java2JupyterClientEndpoint g2jclient) { - SessionPair pair = null; + // SessionPair pair = null; - for(SessionPair p : pairs) { + // for(SessionPair p : pairs) { - if(p.getGeoweaver_jupyter_client()==g2jclient) { + // if(p.getGeoweaver_jupyter_client()==g2jclient) { - pair = p; + // pair = p; - break; + // break; - } + // } - } + // } - return pair; + // return pair; - } + // } - public static void removeClosedPair() { + // public static void removeClosedPair() { - for(SessionPair p : pairs) { + // for(SessionPair p : pairs) { - if(!p.getBrowse_geoweaver_session().isOpen() ) { + // if(!p.getBrowse_geoweaver_session().isOpen() ) { - System.out.println("Detected one browser_geoweaver_session is closed. Removing it..."); + // System.out.println("Detected one browser_geoweaver_session is closed. Removing it..."); - pairs.remove(p); + // pairs.remove(p); - } + // } - if(!p.getGeoweaver_jupyter_client().getNew_ws_session_between_geoweaver_and_jupyterserver().isOpen()) { + // if(!p.getGeoweaver_jupyter_client().getNew_ws_session_between_geoweaver_and_jupyterserver().isOpen()) { - System.out.println("Detected one geoweaver jupyter session is closed. Removing it..."); + // System.out.println("Detected one geoweaver jupyter session is closed. Removing it..."); - pairs.remove(p); + // pairs.remove(p); - } + // } - } + // } - } + // } - public static void removePairByID(String id) { + // public static void removePairByID(String id) { - for(SessionPair p : pairs) { + // for(SessionPair p : pairs) { - if(p.getId().equals(id)) { + // if(p.getId().equals(id)) { - System.out.println("Detected one session pair is closed on one of the websocket session. Removing it..."); + // System.out.println("Detected one session pair is closed on one of the websocket session. Removing it..."); - pairs.remove(p); + // pairs.remove(p); - break; + // break; - } + // } - } + // } - } + // } private void init(Session b2gsession) { @@ -187,7 +189,7 @@ private void init(Session b2gsession) { } // SessionPair pair = findPairBy1stSession(b2gsession); - SessionPair pair = this.findPairByID(b2gsession.getQueryString()); + SessionPair pair = JupyterSessionPairTool.findPairByID(b2gsession.getQueryString()); if(bt.isNull(pair)) { @@ -201,7 +203,7 @@ private void init(Session b2gsession) { pair.setGeoweaver_jupyter_client(client); - pairs.add(pair); + JupyterSessionPairTool.pairs.add(pair); logger.debug("New Pair is created: ID: " + pair.getId()); @@ -250,7 +252,7 @@ public void open(Session session, @PathParam("hostid") String hostid, @PathParam // client = new Java2JupyterClientEndpoint(new URI(trueurl), session, headers, h); - SessionPair pair = this.findPairByID(session.getQueryString()); + SessionPair pair = JupyterSessionPairTool.findPairByID(session.getQueryString()); // pair.getGeoweaver_jupyter_client().init(new URI(trueurl), session, headers, h, pair.getId()); @@ -286,7 +288,7 @@ public void echo(String message, @PathParam("uuid1") String uuid1, Session sessi // SessionPair pair = findPairBy1stSession(session); - SessionPair pair = this.findPairByID(session.getQueryString()); + SessionPair pair = JupyterSessionPairTool.findPairByID(session.getQueryString()); if(bt.isNull(pair)) { @@ -325,13 +327,13 @@ public void close(final Session session) { logger.error("Channel closed."); // SessionPair pair = findPairBy1stSession(session); - SessionPair pair = this.findPairByID(session.getQueryString()); + SessionPair pair = JupyterSessionPairTool.findPairByID(session.getQueryString()); if(!bt.isNull(pair)) { pair.getGeoweaver_jupyter_client().getNew_ws_session_between_geoweaver_and_jupyterserver().close(); //close websocket connection - pairs.remove(pair); + JupyterSessionPairTool.pairs.remove(pair); // client.getNew_ws_session_between_geoweaver_and_jupyterserver().close(); @@ -350,69 +352,69 @@ public void close(final Session session) { - public class SessionPair{ +// public class SessionPair{ - String id; +// String id; - Session browse_geoweaver_session; +// Session browse_geoweaver_session; - Java2JupyterClientEndpoint geoweaver_jupyter_client; +// Java2JupyterClientEndpoint geoweaver_jupyter_client; - public String getId() { - return id; - } +// public String getId() { +// return id; +// } - public void setId(String id) { - this.id = id; - } +// public void setId(String id) { +// this.id = id; +// } - public Session findOpenSession() { +// public Session findOpenSession() { - Set sessionset = browse_geoweaver_session.getOpenSessions(); +// Set sessionset = browse_geoweaver_session.getOpenSessions(); - Iterator it = sessionset.iterator(); +// Iterator it = sessionset.iterator(); - Session session = browse_geoweaver_session; +// Session session = browse_geoweaver_session; - while(it.hasNext()){ -// System.out.println(it.next()); +// while(it.hasNext()){ +// // System.out.println(it.next()); - Session cs = (Session)it.next(); +// Session cs = (Session)it.next(); - if(id.equals(cs.getQueryString())) { +// if(id.equals(cs.getQueryString())) { - session = cs; +// session = cs; - break; +// break; - } +// } - } +// } - return session; +// return session; - } +// } - public Session getBrowse_geoweaver_session() { +// public Session getBrowse_geoweaver_session() { - return findOpenSession(); - } +// return findOpenSession(); +// } - public void setBrowse_geoweaver_session(Session browse_geoweaver_session) { +// public void setBrowse_geoweaver_session(Session browse_geoweaver_session) { - this.browse_geoweaver_session = browse_geoweaver_session; +// this.browse_geoweaver_session = browse_geoweaver_session; - } +// } - public Java2JupyterClientEndpoint getGeoweaver_jupyter_client() { - return geoweaver_jupyter_client; - } +// public Java2JupyterClientEndpoint getGeoweaver_jupyter_client() { +// return geoweaver_jupyter_client; +// } - public void setGeoweaver_jupyter_client(Java2JupyterClientEndpoint geoweaver_jupyter_client) { - this.geoweaver_jupyter_client = geoweaver_jupyter_client; - } +// public void setGeoweaver_jupyter_client(Java2JupyterClientEndpoint geoweaver_jupyter_client) { +// this.geoweaver_jupyter_client = geoweaver_jupyter_client; +// } - } +// } } diff --git a/src/main/java/com/gw/server/WebsocketMessageHandler.java b/src/main/java/com/gw/server/WebsocketMessageHandler.java index 8ab3652df..8bb782faf 100644 --- a/src/main/java/com/gw/server/WebsocketMessageHandler.java +++ b/src/main/java/com/gw/server/WebsocketMessageHandler.java @@ -5,7 +5,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.gw.server.JupyterRedirectServlet.SessionPair; +import com.gw.tools.JupyterSessionPairTool; +import com.gw.tools.SessionPair; /** * WebSocket Message Handler @@ -35,7 +36,7 @@ public void onMessage(String message) { // logger.debug(pairid + "Message from Jupyter: " + message); - SessionPair pair = JupyterRedirectServlet.findPairByID(pairid); + SessionPair pair = JupyterSessionPairTool.findPairByID(pairid); if(pair==null) { @@ -44,41 +45,41 @@ public void onMessage(String message) { // throw new RuntimeException("The pair is null " + pairid); logger.debug("the pair is null " + pairid); - }else { - - jssession = pair.getBrowse_geoweaver_session(); + return; + } - synchronized(jssession) { + jssession = pair.getBrowse_geoweaver_session(); + + synchronized(jssession) { + - - + // logger.debug("send this message back to the client"); - - if(jssession!=null && jssession.isOpen() && message!=null) { - - jssession.getBasicRemote().sendText(message); - + + if(jssession!=null && jssession.isOpen() && message!=null) { + + jssession.getBasicRemote().sendText(message); + // logger.debug(pair.getId() + " transferred to browser"); - - }else { - - logger.warn(pair.getId() + "The websocket between browser and geoweaver is null or closed"); - - } - - + + }else { + + logger.warn(pair.getId() + "The websocket between browser and geoweaver is null or closed"); + + } + + // if(!bt.isNull(window)) { // // window.writeServerMessage(message); // // } // session.getBasicRemote().sendText("Got message from " + session.getId() + "\n" + message); - + - } - } + } catch (Exception ex) { ex.printStackTrace(); diff --git a/src/main/java/com/gw/ssh/SecurityConfiguration.java b/src/main/java/com/gw/ssh/SecurityConfiguration.java index cbdfcf6bf..75f3733e1 100644 --- a/src/main/java/com/gw/ssh/SecurityConfiguration.java +++ b/src/main/java/com/gw/ssh/SecurityConfiguration.java @@ -66,6 +66,8 @@ protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable(); http.headers().frameOptions().disable(); + + http.headers().disable(); //this must be turned off to make the JupyterHub work super.configure(http); // http diff --git a/src/main/java/com/gw/tools/JupyterSessionPairTool.java b/src/main/java/com/gw/tools/JupyterSessionPairTool.java new file mode 100644 index 000000000..2cefa550b --- /dev/null +++ b/src/main/java/com/gw/tools/JupyterSessionPairTool.java @@ -0,0 +1,158 @@ +package com.gw.tools; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.websocket.EndpointConfig; +import javax.websocket.OnClose; +import javax.websocket.OnError; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import com.gw.jpa.Host; +import com.gw.server.Java2JupyterClientEndpoint; +import com.gw.tools.HostTool; +import com.gw.utils.BaseTool; +import com.gw.utils.BeanTool; + + +public class JupyterSessionPairTool { + + static Logger logger = LoggerFactory.getLogger(JupyterSessionPairTool.class); + +// Session wsSession; + +// @Autowired +// Java2JupyterClientEndpoint client; + + public static List pairs = new ArrayList(); + + + /** + * First session is between browser and geoweaver + * @param b2gsession + * @return + */ + public static SessionPair findPairBy1stSession(Session b2gsession) { + + SessionPair pair = null; + + for(SessionPair p : pairs) { + + if(p.getBrowse_geoweaver_session()==b2gsession) { + + pair = p; + + break; + + } + + } + + return pair; + + } + + public static SessionPair findPairByID(String pairid) { + + SessionPair pair = null; + + for(SessionPair p : pairs) { + + if(p.getId().equals(pairid)) { + + pair = p; + + break; + + } + + } + + return pair; + + } + + /** + * 2nd session is between geoweaver and jupyter + * @param b2gsession + * @return + */ + public static SessionPair findPairBy2ndSession(Java2JupyterClientEndpoint g2jclient) { + + SessionPair pair = null; + + for(SessionPair p : pairs) { + + if(p.getGeoweaver_jupyter_client()==g2jclient) { + + pair = p; + + break; + + } + + } + + return pair; + + } + + public static void removeClosedPair() { + + for(SessionPair p : pairs) { + + if(!p.getBrowse_geoweaver_session().isOpen() ) { + + System.out.println("Detected one browser_geoweaver_session is closed. Removing it..."); + + pairs.remove(p); + + } + + if(!p.getGeoweaver_jupyter_client().getNew_ws_session_between_geoweaver_and_jupyterserver().isOpen()) { + + System.out.println("Detected one geoweaver jupyter session is closed. Removing it..."); + + pairs.remove(p); + + } + + } + + } + + public static void removePairByID(String id) { + + for(SessionPair p : pairs) { + + if(p.getId().equals(id)) { + + System.out.println("Detected one session pair is closed on one of the websocket session. Removing it..."); + + pairs.remove(p); + + break; + + } + + } + + } + + + +} diff --git a/src/main/java/com/gw/tools/SessionPair.java b/src/main/java/com/gw/tools/SessionPair.java new file mode 100644 index 000000000..dc2bb28d5 --- /dev/null +++ b/src/main/java/com/gw/tools/SessionPair.java @@ -0,0 +1,93 @@ +package com.gw.tools; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.websocket.EndpointConfig; +import javax.websocket.OnClose; +import javax.websocket.OnError; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import com.gw.jpa.Host; +import com.gw.server.Java2JupyterClientEndpoint; +import com.gw.tools.HostTool; +import com.gw.utils.BaseTool; +import com.gw.utils.BeanTool; + +public class SessionPair{ + + String id; + + Session browse_geoweaver_session; + + Java2JupyterClientEndpoint geoweaver_jupyter_client; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Session findOpenSession() { + + Set sessionset = browse_geoweaver_session.getOpenSessions(); + + Iterator it = sessionset.iterator(); + + Session session = browse_geoweaver_session; + + while(it.hasNext()){ +// System.out.println(it.next()); + + Session cs = (Session)it.next(); + + if(id.equals(cs.getQueryString())) { + + session = cs; + + break; + + } + + } + + return session; + + } + + public Session getBrowse_geoweaver_session() { + + return findOpenSession(); + } + + public void setBrowse_geoweaver_session(Session browse_geoweaver_session) { + + this.browse_geoweaver_session = browse_geoweaver_session; + + } + + public Java2JupyterClientEndpoint getGeoweaver_jupyter_client() { + return geoweaver_jupyter_client; + } + + public void setGeoweaver_jupyter_client(Java2JupyterClientEndpoint geoweaver_jupyter_client) { + this.geoweaver_jupyter_client = geoweaver_jupyter_client; + } + + } \ No newline at end of file diff --git a/src/main/java/com/gw/utils/BaseTool.java b/src/main/java/com/gw/utils/BaseTool.java index 62dba8735..5931ccf0a 100644 --- a/src/main/java/com/gw/utils/BaseTool.java +++ b/src/main/java/com/gw/utils/BaseTool.java @@ -527,14 +527,14 @@ public String[] parseJupyterURL(String url) { URL aURL = new URL(url); -// logger.debug("protocol = " + aURL.getProtocol()); -// logger.debug("authority = " + aURL.getAuthority()); -// logger.debug("host = " + aURL.getHost()); -// logger.debug("port = " + aURL.getPort()); -// logger.debug("path = " + aURL.getPath()); -// logger.debug("query = " + aURL.getQuery()); -// logger.debug("filename = " + aURL.getFile()); -// logger.debug("ref = " + aURL.getRef()); + // logger.debug("protocol = " + aURL.getProtocol()); + // logger.debug("authority = " + aURL.getAuthority()); + // logger.debug("host = " + aURL.getHost()); + // logger.debug("port = " + aURL.getPort()); + // logger.debug("path = " + aURL.getPath()); + // logger.debug("query = " + aURL.getQuery()); + // logger.debug("filename = " + aURL.getFile()); + // logger.debug("ref = " + aURL.getRef()); cc[0] = aURL.getProtocol(); cc[1] = aURL.getHost(); diff --git a/src/main/java/com/gw/utils/MyHttpUtils.java b/src/main/java/com/gw/utils/MyHttpUtils.java index d920fdd9e..eb9b67ad2 100644 --- a/src/main/java/com/gw/utils/MyHttpUtils.java +++ b/src/main/java/com/gw/utils/MyHttpUtils.java @@ -1,6 +1,8 @@ package com.gw.utils; import java.net.*; +import java.util.Map; + import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpClient; @@ -12,7 +14,7 @@ import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.log4j.Logger; -import sun.util.logging.resources.logging; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.*; /** @@ -399,6 +401,211 @@ public static String doGetWithCookies(String url, String cookie_str) throws Exce return buf.toString(); } + + /** + * Login request only returns headers without body + * @param request_headers + * @param body + * @return + */ + public static org.springframework.http.ResponseEntity login_jupyterhub(String target_url, org.springframework.http.HttpEntity requestentity, String hostid){ + + org.springframework.http.ResponseEntity resp = null; + + try{ + + java.net.http.HttpClient client = java.net.http.HttpClient.newHttpClient(); + + // Host: geoweaver2.eastus.cloudapp.azure.com:8000 + // User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0 + // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 + // Accept-Language: en-US,en;q=0.5 + // Accept-Encoding: gzip, deflate + // Content-Type: application/x-www-form-urlencoded + // Content-Length: 34 + // Origin: http://geoweaver2.eastus.cloudapp.azure.com:8000 + // DNT: 1 + // Connection: keep-alive + // Referer: http://geoweaver2.eastus.cloudapp.azure.com:8000/hub/login + // Cookie: _xsrf=2|c0891671|6a2f9feb3275ae40b57960c55db32f51|1615354056 + // Upgrade-Insecure-Requests: 1 + // create a request + System.out.println("Testing JupyterHub Request.."); + + // ObjectMapper objectMapper = new ObjectMapper(); + // String requestBody = objectMapper.writeValueAsString(values); + org.springframework.http.HttpHeaders headers = requestentity.getHeaders(); + + Map header_vm = headers.toSingleValueMap(); + + java.net.http.HttpRequest.Builder builder = java.net.http.HttpRequest.newBuilder(URI.create(target_url)); + + for (java.util.Map.Entry mapElement : header_vm.entrySet()) { + + String key = (String)mapElement.getKey(); + + String value = (String)mapElement.getValue(); + + System.out.println(key + " : " + value); + + String lowkey = key.toLowerCase(); + + if(lowkey.equals("host") || lowkey.equals("connection") || lowkey.equals("content-length")){ + + continue; + + } + + builder = builder.header(key, value); + + } + + java.net.http.HttpRequest request = builder + // .header("Cache-Control", "max-age=0") + // .header("Upgrade-Insecure-Requests", "1") + // .header("Content-Type", "application/x-www-form-urlencoded") + // .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36") + // .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9") + // .header("Sec-Fetch-Site", "same-origin") + // .header("Sec-Fetch-Mode", "navigate") + // .header("Sec-Fetch-User", "?1") + // .header("Sec-Fetch-Dest", "document") + // .header("Cookie", "_xsrf=2|c0891671|6a2f9feb3275ae40b57960c55db32f51|1615354056") + // .header("Upgrade-Insecure-Requests", "1") + .version(java.net.http.HttpClient.Version.HTTP_1_1) + .POST(java.net.http.HttpRequest.BodyPublishers.ofString(String.valueOf(requestentity.getBody()))) + .build(); + + System.out.println(request.headers().map()); + + java.net.http.HttpResponse response = client.send(request, java.net.http.HttpResponse.BodyHandlers.ofString()); + + java.net.http.HttpHeaders respheaders = response.headers(); + + respheaders.map().forEach((k, v) -> System.out.println(k + ":" + v)); + + // print status code + System.out.println(response.statusCode()); + + // print response body + System.out.println(response.body()); + + // org.springframework.http.HttpHeaders respheaders = ; + + +// MultiValueMap headers =new LinkedMultiValueMap(); + + org.springframework.http.HttpHeaders newresponseheaders = new org.springframework.http.HttpHeaders(); + +// logger.info("Redirection: " + newresponseheaders); + + System.out.println("Response: " + response.body()); + +// responseEntity = restTemplate.exchange(uri, method, requestentity, String.class); + +// responseEntity.getHeaders().compute("Location", (k, v) -> {v.clear(); v.add("/Geoweaver/web/jupyter-proxy/tree?");}); + +// responseEntity.getHeaders().set("Location", "/Geoweaver/web/jupyter-proxy/tree?"); + +// respheaders.set("Location", "/Geoweaver/web/jupyter-proxy/tree?"); + +// respheaders.setLocation(new URI("/Geoweaver/web/jupyter-proxy/tree?")); + +// respheaders.add("Test", "Test Value"); + + respheaders.map().forEach((key, value) -> { + + if(key.toLowerCase().equals("location")) { + + newresponseheaders.set(key, "/Geoweaver/jupyter-proxy/" + hostid + value.get(0)); + + }else { + + newresponseheaders.set(key, value.get(0)); + + } + + }); + + resp = new org.springframework.http.ResponseEntity( + response.body(), + newresponseheaders, + response.statusCode()); + + + }catch(Exception e){ + + e.printStackTrace(); + + } + + return resp; + + } + + public static void testJupyterHubLogin(){ + + try{ + + java.net.http.HttpClient client = java.net.http.HttpClient.newHttpClient(); + // Host: geoweaver2.eastus.cloudapp.azure.com:8000 + // User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0 + // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 + // Accept-Language: en-US,en;q=0.5 + // Accept-Encoding: gzip, deflate + // Content-Type: application/x-www-form-urlencoded + // Content-Length: 34 + // Origin: http://geoweaver2.eastus.cloudapp.azure.com:8000 + // DNT: 1 + // Connection: keep-alive + // Referer: http://geoweaver2.eastus.cloudapp.azure.com:8000/hub/login + // Cookie: _xsrf=2|c0891671|6a2f9feb3275ae40b57960c55db32f51|1615354056 + // Upgrade-Insecure-Requests: 1 + // create a request + System.out.println("Testing JupyterHub Request.."); + + java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder(URI.create("http://geoweaver2.eastus.cloudapp.azure.com:8000/hub/login?next=")) + // .headers(headers) + .header("Cache-Control", "max-age=1") + .header("Upgrade-Insecure-Requests", "1") + .header("Content-Type", "application/x-www-form-urlencoded") + .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36") + .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9") + .header("Sec-Fetch-Site", "same-origin") + .header("Sec-Fetch-Mode", "navigate") + .header("Sec-Fetch-User", "?1") + .header("Sec-Fetch-Dest", "document") + .header("Cookie", "_xsrf=2|c0891671|6a2f9feb3275ae40b57960c55db32f51|1615354056") + .header("Upgrade-Insecure-Requests", "1") + .version(java.net.http.HttpClient.Version.HTTP_1_1) + .POST(java.net.http.HttpRequest.BodyPublishers.ofString("username=%%%%%%%%%%%%%&password=###########################")) + .build(); + + System.out.println(request.headers().map()); + + // use the client to send the request + java.net.http.HttpResponse response = client.send(request, java.net.http.HttpResponse.BodyHandlers.ofString()); + + + java.net.http.HttpHeaders respheaders = response.headers(); + + respheaders.map().forEach((k, v) -> System.out.println(k + ":" + v)); + + // print status code + System.out.println(response.statusCode()); + + // print response body + System.out.println(response.body()); + + + + }catch(Exception e){ + + e.printStackTrace(); + + } + + } public static void main(String[] args){ @@ -412,9 +619,12 @@ public static void main(String[] args){ // theLogger.info("Response: " + resp); try { - String resp = MyHttpUtils.doGet("http://ows.dev.52north.org:8080/wps/WebProcessingService?request=GetCapabilities&service=WPS&version=2.0.0"); + // String resp = MyHttpUtils.doGet("http://ows.dev.52north.org:8080/wps/WebProcessingService?request=GetCapabilities&service=WPS&version=2.0.0"); - theLogger.debug("Response:" + resp); + // theLogger.debug("Response:" + resp); + + MyHttpUtils.testJupyterHubLogin(); + } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); diff --git a/src/main/java/com/gw/web/JupyterController.java b/src/main/java/com/gw/web/JupyterController.java index f249a0b9f..5bce1c150 100644 --- a/src/main/java/com/gw/web/JupyterController.java +++ b/src/main/java/com/gw/web/JupyterController.java @@ -16,6 +16,7 @@ import org.apache.commons.httpclient.methods.GetMethod; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpHead; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.json.simple.JSONObject; @@ -110,7 +111,9 @@ public RestTemplate getRestTemplate() { .setDefaultRequestConfig(RequestConfig.custom() .setCookieSpec(CookieSpecs.STANDARD) - .setCircularRedirectsAllowed(true) + + // .setCircularRedirectsAllowed(false) + .setRedirectsEnabled(false) .build()) .build(); @@ -120,8 +123,6 @@ public RestTemplate getRestTemplate() { restTemplate1.setRequestFactory(requestFactory); - - logger.info("A new restTemplate is created"); return restTemplate1; @@ -224,6 +225,9 @@ String addURLProxy(String resp, String hostid) { .replace("'/user/", "'/Geoweaver/jupyter-proxy/"+hostid+"/user/") .replace("data-base-url=\"/user/", "data-base-url=\"/Geoweaver/jupyter-proxy/"+hostid+"/user/") + //for jupyterlab + .replace("\"baseUrl\": \"/\"", "\"baseUrl\": \"/Geoweaver/jupyter-proxy/"+hostid+"/\"") + ; return resp; @@ -319,6 +323,8 @@ private HttpHeaders updateHeaderReferer(HttpHeaders oldheaders, Host h, String r newheaders.set("origin", hosturl); + newheaders.set("target_url", URLDecoder.decode(uri.toString(), "utf-8")); + newheaders.set("referer", URLDecoder.decode(uri.toString(), "utf-8")); } catch (Exception e) { @@ -370,8 +376,10 @@ private ResponseEntity processUtil(HttpEntity entity, HttpMethod method, HttpSer HttpEntity newentity = new HttpEntity(entity.getBody(), newheaders); // logger.debug("URL: " + newheaders.get("referer").get(0)); + + String target_url = getRealTargetURL(newheaders.get("target_url").get(0)); - ResponseEntity responseEntity = restTemplate.exchange(getRealTargetURL(newheaders.get("referer").get(0)), method, newentity, String.class); + ResponseEntity responseEntity = restTemplate.exchange(target_url, method, newentity, String.class); String newbody = addURLProxy(responseEntity.getBody(), hostid); @@ -512,7 +520,7 @@ private ResponseEntity processPatch(HttpEntity entity, HttpMethod method, HttpSe // logger.debug("URL: " + newheaders.get("referer").get(0)); - ResponseEntity responseEntity = restTemplate.exchange(getRealTargetURL(newheaders.get("referer").get(0)), method, newentity, String.class); + ResponseEntity responseEntity = restTemplate.exchange(getRealTargetURL(newheaders.get("target_url").get(0)), method, newentity, String.class); resp = new ResponseEntity( addURLProxy(responseEntity.getBody(), hostid), @@ -660,8 +668,10 @@ private ResponseEntity processDelete(HttpEntity entity, HttpMethod method, HttpS HttpHeaders newheaders = getHeaders(entity.getHeaders(), method, request, hostid); HttpEntity newentity = new HttpEntity(entity.getBody(), newheaders); + + String target_url = getRealTargetURL(newheaders.get("target_url").get(0)); - ResponseEntity responseEntity = restTemplate.exchange(getRealTargetURL(newheaders.get("referer").get(0)), method, newentity, String.class); + ResponseEntity responseEntity = restTemplate.exchange(target_url, method, newentity, String.class); resp = new ResponseEntity( addURLProxy(responseEntity.getBody(), hostid), @@ -738,16 +748,22 @@ private ResponseEntity processPost(RequestEntity reqentity, HttpMethod method, H HttpHeaders newheaders = getHeaders(reqentity.getHeaders(), method, request, hostid); HttpEntity newentity = new HttpEntity(reqentity.getBody(), newheaders); + + String target_url = getRealTargetURL(newheaders.get("target_url").get(0)); - ResponseEntity responseEntity = restTemplate.exchange(getRealTargetURL(newheaders.get("referer").get(0)), method, newentity, String.class); + ResponseEntity responseEntity = restTemplate.exchange(target_url, method, newentity, String.class); // if(realurl.indexOf("auth")!=-1) // // logger.info("Response Body: " + responseEntity.getBody()); + String newbody = addURLProxy(responseEntity.getBody(), hostid); + + HttpHeaders newrespheaders = updateHeader(responseEntity.getHeaders(), newbody, hostid); + resp = new ResponseEntity( - addURLProxy(responseEntity.getBody(), hostid), - responseEntity.getHeaders(), + newbody, + newrespheaders, responseEntity.getStatusCode()); }catch (HttpStatusCodeException ex) { @@ -800,128 +816,125 @@ private ResponseEntity processGET(RequestEntity reqentity, HttpMethod met logger.debug("=============="); -// logger.debug("This is a GET request..."); + // logger.debug("This is a GET request..."); - logger.debug("Request URI: " + request.getRequestURI()); + logger.debug("Request URI: " + reqentity.getUrl().toString()); boolean ishub = false; if(request.getRequestURI().contains("user")) ishub = true; -// logger.info("Query String: " + request.getQueryString()); - -// String realurl = this.getRealRequestURL(request.getRequestURI()); -// -// Host h = HostTool.getHostById(hostid); -// -// String[] ss = h.parseJupyterURL(); -// -// URI uri = new URI(ss[0], null, ss[1], Integer.parseInt(ss[2]), realurl, request.getQueryString(), null); -// -// logger.info("URL: " + uri.toString()); -// -// logger.info("HTTP Method: " + method.toString()); -// - -// -//// HttpEntity entity = new HttpEntity(headers); -// -// HttpHeaders newheaders = this.updateHeaderReferer(reqentity.getHeaders(), h, realurl, request.getQueryString()); - -// if(ishub)logger.info("Old HTTP Headers: " + reqentity.getHeaders().toString()); + // if(ishub)logger.info("Old Request HTTP Headers: " + reqentity.getHeaders().toString()); HttpHeaders newheaders = getHeaders(reqentity.getHeaders(), method, request, hostid); HttpEntity newentity = new HttpEntity(reqentity.getBody(), newheaders); - String targeturl = getRealTargetURL(newheaders.get("referer").get(0)); //using referer as the target url is not right + String targeturl = getRealTargetURL(newheaders.get("target_url").get(0)); //using referer as the target url is not right + // String targeturl = getRealTargetURL(reqentity.getUrl().toString()); -// logger.info("New target url: " + targeturl); + // logger.info("New target url: " + targeturl); -// if(ishub)logger.info("New HTTP Headers: " + newheaders.toString()); + // if(ishub)logger.info("New Request HTTP Headers: " + newheaders.toString()); // String sec_fetch_type = getHeaderProperty(reqentity.getHeaders(), "Sec-Fetch-Dest"); // logger.debug(URLDecoder.decode(newheaders.get("referer").get(0),"UTF-8")); // ((SimpleClientHttpRequestFactory)restTemplate.getRequestFactory()).setConnectTimeout(TIMEOUT); + + ResponseEntity responseEntity = restTemplate.exchange(targeturl, method, newentity, byte[].class); + + String contenttype = getHeaderProperty(responseEntity.getHeaders(), "Content-Type"); + + byte[] newbody = null; + + if(!bt.isNull(responseEntity.getBody()) && !targeturl.contains(".png") && !targeturl.contains(".woff") + && !(!bt.isNull(contenttype) && (contenttype.contains("image") || contenttype.contains("font"))) ){ + + newbody = addURLProxy(new String(responseEntity.getBody()), hostid).getBytes(); + + }else{ + + newbody = responseEntity.getBody(); + + } + + // if(ishub) logger.debug("Old Response Header: " + responseEntity.getHeaders().toString()); + + HttpHeaders headers = updateHeader(responseEntity.getHeaders(), newbody, hostid); - if(targeturl.contains(".png") || targeturl.contains(".woff")) { + // if(ishub) logger.debug("New Response Header: " + headers.toString()); + + resp = new ResponseEntity( + newbody, + headers, + responseEntity.getStatusCode()); + + +// if(targeturl.contains(".png") || targeturl.contains(".woff")) { - ResponseEntity responseEntity = restTemplate.exchange(targeturl, method, newentity, byte[].class); -// -// String newbody = new String(responseEntity.getBody()); -// -// HttpHeaders headers = updateHeader(responseEntity.getHeaders(), newbody, hostid); -// -// resp = new ResponseEntity( -// responseEntity.getBody(), -// headers, -// responseEntity.getStatusCode());; +// ResponseEntity responseEntity = restTemplate.exchange(targeturl, method, newentity, byte[].class); +// // +// // String newbody = new String(responseEntity.getBody()); +// // +// // HttpHeaders headers = updateHeader(responseEntity.getHeaders(), newbody, hostid); +// // +// // resp = new ResponseEntity( +// // responseEntity.getBody(), +// // headers, +// // responseEntity.getStatusCode());; - resp = responseEntity; +// resp = responseEntity; - }else { +// }else { - ResponseEntity responseEntity = restTemplate.exchange(targeturl, method, newentity, String.class); +// ResponseEntity responseEntity = restTemplate.exchange(targeturl, method, newentity, String.class); -// if(ishub)logger.debug("Response Header: " + responseEntity.getHeaders()); -//// -// if(ishub)logger.debug("Response HTTP Code: " + responseEntity.getStatusCode()); - String newbody = responseEntity.getBody(); +// String newbody = responseEntity.getBody(); - String contenttype = getHeaderProperty(responseEntity.getHeaders(), "Content-Type"); +// String contenttype = getHeaderProperty(responseEntity.getHeaders(), "Content-Type"); -// - if(bt.isNull(newbody)|| ( !bt.isNull(contenttype) && (contenttype.contains("image") - || contenttype.contains("font")) )) { - -// HttpHeaders headers = updateHeader(responseEntity.getHeaders(), newbody, hostid); -// -// resp = new ResponseEntity( -// bt.isNull(newbody)?null:newbody.getBytes("UTF-8"), -// headers, -// responseEntity.getStatusCode());; - - resp = restTemplate.exchange(targeturl, method, newentity, byte[].class); +// // if(bt.isNull(newbody)|| ( !bt.isNull(contenttype) && (contenttype.contains("image") +// // || contenttype.contains("font")) )) { +// if( !bt.isNull(contenttype) && (contenttype.contains("image") || contenttype.contains("font")) ) { +// // HttpHeaders headers = updateHeader(responseEntity.getHeaders(), newbody, hostid); +// // +// // resp = new ResponseEntity( +// // bt.isNull(newbody)?null:newbody.getBytes("UTF-8"), +// // headers, +// // responseEntity.getStatusCode());; +// // find a way not send the same request twice just because the type is not byte for image/font files +// resp = restTemplate.exchange(targeturl, method, newentity, byte[].class); -// resp = responseEntity; +// // resp = responseEntity; - }else { - - newbody = addURLProxy(responseEntity.getBody(), hostid); - -// if(ishub) logger.debug("Response Body: " + newbody); - - -// if(responseEntity.getHeaders().getContentType().equals(MediaType.TEXT_HTML) -// || responseEntity.getHeaders().getContentType()) +// }else { - - HttpHeaders headers = updateHeader(responseEntity.getHeaders(), newbody, hostid); - -// if(targeturl.contains("static/tree/js")) { - - -// logger.info("Response Body: " + newbody); - - +// if(bt.isNull(responseEntity.getBody())){ +// resp = new ResponseEntity( +// null, +// headers, +// responseEntity.getStatusCode()); +// }else{ -// headers.set("Content-Length", String.valueOf(newbody.getBytes().length)); - -// } - - resp = new ResponseEntity( - newbody.getBytes("UTF-8"), - headers, - responseEntity.getStatusCode()); +// newbody = addURLProxy(responseEntity.getBody(), hostid); + +// HttpHeaders headers = updateHeader(responseEntity.getHeaders(), newbody, hostid); + +// resp = new ResponseEntity( +// newbody.getBytes("UTF-8"), +// headers, +// responseEntity.getStatusCode()); +// } + - } -// +// } +// // - } +// } @@ -953,52 +966,131 @@ private ResponseEntity processGET(RequestEntity reqentity, HttpMethod met return resp; } - + /** - * Update Header Length and Origin and location + * * @param oldheaders - * @param returnbody + * @param bodylength * @param hostid * @return */ - HttpHeaders updateHeader(HttpHeaders oldheaders, String returnbody, String hostid) { + HttpHeaders updateHeader(HttpHeaders oldheaders, int bodylength, String hostid) { HttpHeaders newheaders = new HttpHeaders(); - oldheaders.forEach((key, value) -> { - if(key.toLowerCase().equals("location")) { + try { + + String lowkey = key.toLowerCase(); + + if(lowkey.equals("location")) { - newheaders.set(key, "/Geoweaver/jupyter-proxy/" + hostid + value.get(0)); + newheaders.set(lowkey, "/Geoweaver/jupyter-proxy/" + hostid + value.get(0)); - }else if(key.toLowerCase().equals("transfer-encoding") && value.get(0).equals("chunked")){ + }else if(lowkey.equals("transfer-encoding") && value.get(0).equals("chunked")){ logger.info("skip the header property of transfer encoding and value is chunked"); - - }else if (key.toLowerCase().equals("content-length")){ + + // }else if(lowkey.equals("cache-control")){ + + // logger.info("remove cache control"); + + }else if (lowkey.equals("content-length")){ // logger.debug("Old Content Length: " + value); - if(!bt.isNull(returnbody)) - try { - newheaders.set(key, String.valueOf(returnbody.getBytes("UTF-8").length)); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); + newheaders.set(lowkey, String.valueOf(bodylength)); + + }else if(lowkey.equals("set-cookie")){ + + List newvalues = new ArrayList(); + + for(String singleval : value){ + + String newsingleval = singleval.replace("Path=", "Path="+"/Geoweaver/jupyter-proxy/" + hostid ); + String newsingleval_socket = singleval.replace("Path=", "Path="+"/Geoweaver/jupyter-socket/" + hostid ); + + newvalues.add(newsingleval); + newvalues.add(newsingleval_socket); + + // jupyterhub-user-zsun-oauth-state-uypLrTlm=""; expires=Mon, 16 Mar 2020 03:08:07 GMT; Path=/Geoweaver/jupyter-proxy/urlwti/user/zsun/ + + if(singleval.contains("-oauth-state-") && singleval.contains("=\"\";")){ + + int first_break = singleval.indexOf("-oauth-state-") + 12 ; + int second_break = singleval.indexOf("=\"\""); + singleval = singleval.substring(0, first_break) + singleval.substring(second_break); + + newsingleval = singleval.replace("Path=", "Path="+"/Geoweaver/jupyter-proxy/" + hostid ); + newsingleval_socket = singleval.replace("Path=", "Path="+"/Geoweaver/jupyter-socket/" + hostid ); + + newvalues.add(newsingleval); + newvalues.add(newsingleval_socket); + } - + + // newvalues.add(singleval.replace("Path=", "Path="+"/Geoweaver/jupyter-socket/" + hostid )); + + } + + newheaders.addAll(lowkey, newvalues); + }else { - newheaders.set(key, value.get(0)); + // newheaders.set(lowkey, value.get(0)); + newheaders.addAll(lowkey, value); } + } catch (Exception e) { + e.printStackTrace(); + } }); return newheaders; } + + /** + * Update Header Length and Origin and location + * @param oldheaders + * @param returnbody + * @param hostid + * @return + */ + HttpHeaders updateHeader(HttpHeaders oldheaders, byte[] returnbody, String hostid) { + + int bodylength = 0; + + if(!bt.isNull(returnbody)) + bodylength = returnbody.length; + + return updateHeader(oldheaders, bodylength, hostid); + + } + + /** + * Update Header Length and Origin and location + * @deprecated + * @param oldheaders + * @param returnbody + * @param hostid + * @return + */ + HttpHeaders updateHeader(HttpHeaders oldheaders, String returnbody, String hostid) { + + int bodylength = 0; + if(!bt.isNull(returnbody)) + try { + bodylength = returnbody.getBytes("UTF-8").length; + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return updateHeader(oldheaders, bodylength, hostid); + + } @RequestMapping(value="/jupyter-proxy/{hostid}/hub/login", method = RequestMethod.POST) public ResponseEntity jupyterhub_login( HttpMethod method, @PathVariable("hostid") String hostid, @@ -1021,22 +1113,6 @@ public ResponseEntity jupyterhub_login( HttpMethod method, @PathVariable("hostid logger.debug("Request URI: " + request.getRequestURI()); -// logger.info("Query String: " + request.getQueryString()); - -// logger.info("Original Request String: " + request.getParameterMap()); - -// String realurl = this.getRealRequestURL(request.getRequestURI()); -// -// Host h = HostTool.getHostById(hostid); -// -// String[] ss = h.parseJupyterURL(); -// -// int current_port = Integer.parseInt(ss[2]); -// -// URI uri = new URI(ss[0], null, ss[1], current_port, realurl, request.getQueryString(), null); -// -// logger.info("URL: " + uri.toString()); -// logger.info("HTTP Method: " + method.toString()); HttpHeaders newheaders = getHeaders(httpheaders, method, request, hostid); @@ -1069,62 +1145,67 @@ public ResponseEntity jupyterhub_login( HttpMethod method, @PathVariable("hostid // HttpHeaders newheaders = this.updateHeaderReferer(httpheaders, h, realurl, request.getQueryString()); HttpEntity requestentity = new HttpEntity(reqstr.toString(), newheaders); + + // RestTemplate restTemplate1 = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); + // List interceptors = new ArrayList<>(); + // interceptors.add(new LoggingRequestInterceptor()); + // restTemplate1.setInterceptors(interceptors); + + String target_url = getRealTargetURL(newheaders.get("target_url").get(0)); - logger.info("Body: " + requestentity.getBody()); - - logger.info("Headers: " + requestentity.getHeaders()); - - ResponseEntity responseEntity = restTemplate.exchange(getRealTargetURL(newheaders.get("referer").get(0)), method, requestentity, String.class); + ResponseEntity responseEntity = restTemplate.exchange(target_url, method, requestentity, String.class); - HttpHeaders respheaders = responseEntity.getHeaders(); + HttpHeaders respheaders = updateHeader(responseEntity.getHeaders(), responseEntity.getBody(), hostid); + +// HttpHeaders respheaders = responseEntity.getHeaders(); - if(responseEntity.getStatusCode()==HttpStatus.FOUND) { +// if(responseEntity.getStatusCode()==HttpStatus.FOUND) { -// MultiValueMap headers =new LinkedMultiValueMap(); +// // MultiValueMap headers =new LinkedMultiValueMap(); - HttpHeaders newresponseheaders = new HttpHeaders(); +// HttpHeaders newresponseheaders = new HttpHeaders(); -// logger.info("Redirection: " + newresponseheaders); -// - logger.info("Response: " + responseEntity.getBody()); +// // logger.info("Redirection: " + newresponseheaders); +// // +// logger.info("Response: " + responseEntity.getBody()); -// responseEntity = restTemplate.exchange(uri, method, requestentity, String.class); +// // responseEntity = restTemplate.exchange(uri, method, requestentity, String.class); -// responseEntity.getHeaders().compute("Location", (k, v) -> {v.clear(); v.add("/Geoweaver/web/jupyter-proxy/tree?");}); +// // responseEntity.getHeaders().compute("Location", (k, v) -> {v.clear(); v.add("/Geoweaver/web/jupyter-proxy/tree?");}); -// responseEntity.getHeaders().set("Location", "/Geoweaver/web/jupyter-proxy/tree?"); +// // responseEntity.getHeaders().set("Location", "/Geoweaver/web/jupyter-proxy/tree?"); -// respheaders.set("Location", "/Geoweaver/web/jupyter-proxy/tree?"); +// // respheaders.set("Location", "/Geoweaver/web/jupyter-proxy/tree?"); -// respheaders.setLocation(new URI("/Geoweaver/web/jupyter-proxy/tree?")); +// // respheaders.setLocation(new URI("/Geoweaver/web/jupyter-proxy/tree?")); -// respheaders.add("Test", "Test Value"); +// // respheaders.add("Test", "Test Value"); - respheaders.forEach((key, value) -> { +// // respheaders.forEach((key, value) -> { - if(key.toLowerCase().equals("location")) { +// // if(key.toLowerCase().equals("location")) { - newresponseheaders.set(key, "/Geoweaver/jupyter-proxy/" + hostid + value.get(0)); +// // newresponseheaders.set(key, "/Geoweaver/jupyter-proxy/" + hostid + value.get(0)); - }else { +// // }else { - newresponseheaders.set(key, value.get(0)); +// // newresponseheaders.set(key, value.get(0)); - } +// // } - }); +// // }); - respheaders = newresponseheaders; +// respheaders = newresponseheaders; -// Set ent = respheaders.entrySet(); +// // Set ent = respheaders.entrySet(); - logger.info(respheaders.toString()); +// logger.info(respheaders.toString()); - }else if(responseEntity.getStatusCode()==HttpStatus.UNAUTHORIZED) { +// }else if(responseEntity.getStatusCode()==HttpStatus.UNAUTHORIZED) { - logger.error("Login Unauthorized"); +// logger.error("Login Unauthorized"); - } +// } // resp = new ResponseEntity(null, respheaders, resp.getStatusCode()); @@ -1237,13 +1318,13 @@ public ResponseEntity jupyter_login( HttpMethod method, @PathVariable("hostid") } - if(key.equals("_xsrf")) { + // if(key.equals("_xsrf")) { - newheaders.set("cookie", "_xsrf="+value); + // newheaders.set("cookie", "_xsrf="+value); - logger.info("Cookie XSRF: " + value); + // logger.info("Cookie XSRF: " + value); - } + // } reqstr.append(key).append("=").append(value); @@ -1257,12 +1338,14 @@ public ResponseEntity jupyter_login( HttpMethod method, @PathVariable("hostid") logger.info("New Headers: " + requestentity.getHeaders()); - RestTemplate restTemplate1 = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); - List interceptors = new ArrayList<>(); - interceptors.add(new LoggingRequestInterceptor()); - restTemplate1.setInterceptors(interceptors); + // RestTemplate restTemplate1 = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); + // List interceptors = new ArrayList<>(); + // interceptors.add(new LoggingRequestInterceptor()); + // restTemplate1.setInterceptors(interceptors); + + String target_url = getRealTargetURL(newheaders.get("target_url").get(0)); - ResponseEntity responseEntity = restTemplate1.exchange(getRealTargetURL(newheaders.get("referer").get(0)), method, requestentity, String.class); + ResponseEntity responseEntity = restTemplate.exchange(target_url, method, requestentity, String.class); HttpHeaders respheaders = responseEntity.getHeaders(); @@ -1296,7 +1379,7 @@ public ResponseEntity jupyter_login( HttpMethod method, @PathVariable("hostid") }else { - newresponseheaders.set(key, value.get(0)); + newresponseheaders.addAll(key, value); }