You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by mi...@apache.org on 2012/09/08 03:24:27 UTC
[3/6] CLOUDSTACK-61 Console proxy has plenty of files with CRLF line
ending.
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/ConsoleProxySecureServerFactoryImpl.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/ConsoleProxySecureServerFactoryImpl.java b/console-proxy/src/com/cloud/consoleproxy/ConsoleProxySecureServerFactoryImpl.java
index 42d069f..ee0ee13 100644
--- a/console-proxy/src/com/cloud/consoleproxy/ConsoleProxySecureServerFactoryImpl.java
+++ b/console-proxy/src/com/cloud/consoleproxy/ConsoleProxySecureServerFactoryImpl.java
@@ -14,8 +14,8 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy;
-
+package com.cloud.consoleproxy;
+
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
@@ -35,111 +35,111 @@ import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsParameters;
import com.sun.net.httpserver.HttpsServer;
-
-public class ConsoleProxySecureServerFactoryImpl implements ConsoleProxyServerFactory {
- private static final Logger s_logger = Logger.getLogger(ConsoleProxySecureServerFactoryImpl.class);
-
- private SSLContext sslContext = null;
-
- public ConsoleProxySecureServerFactoryImpl() {
- }
-
- @Override
- public void init(byte[] ksBits, String ksPassword) {
- s_logger.info("Start initializing SSL");
- if(ksBits == null) {
- try {
- s_logger.info("Initializing SSL from built-in default certificate");
-
- char[] passphrase = "vmops.com".toCharArray();
- KeyStore ks = KeyStore.getInstance("JKS");
-
- ks.load(new FileInputStream("certs/realhostip.keystore"), passphrase);
- // ks.load(ConsoleProxy.class.getResourceAsStream("/realhostip.keystore"), passphrase);
-
- s_logger.info("SSL certificate loaded");
-
- KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
- kmf.init(ks, passphrase);
- s_logger.info("Key manager factory is initialized");
+public class ConsoleProxySecureServerFactoryImpl implements ConsoleProxyServerFactory {
+ private static final Logger s_logger = Logger.getLogger(ConsoleProxySecureServerFactoryImpl.class);
+
+ private SSLContext sslContext = null;
+
+ public ConsoleProxySecureServerFactoryImpl() {
+ }
+
+ @Override
+ public void init(byte[] ksBits, String ksPassword) {
+ s_logger.info("Start initializing SSL");
+
+ if(ksBits == null) {
+ try {
+ s_logger.info("Initializing SSL from built-in default certificate");
+
+ char[] passphrase = "vmops.com".toCharArray();
+ KeyStore ks = KeyStore.getInstance("JKS");
+
+ ks.load(new FileInputStream("certs/realhostip.keystore"), passphrase);
+ // ks.load(ConsoleProxy.class.getResourceAsStream("/realhostip.keystore"), passphrase);
+
+ s_logger.info("SSL certificate loaded");
+
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
+ kmf.init(ks, passphrase);
+ s_logger.info("Key manager factory is initialized");
+
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
+ tmf.init(ks);
+ s_logger.info("Trust manager factory is initialized");
+
+ sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+ s_logger.info("SSL context is initialized");
+ } catch (Exception ioe) {
+ s_logger.error(ioe.toString(), ioe);
+ }
+
+ } else {
+ char[] passphrase = ksPassword != null ? ksPassword.toCharArray() : null;
+ try {
+ s_logger.info("Initializing SSL from passed-in certificate");
+
+ KeyStore ks = KeyStore.getInstance("JKS");
+ ks.load(new ByteArrayInputStream(ksBits), passphrase);
+
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
+ kmf.init(ks, passphrase);
+ s_logger.info("Key manager factory is initialized");
+
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
+ tmf.init(ks);
+ s_logger.info("Trust manager factory is initialized");
+
+ sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+ s_logger.info("SSL context is initialized");
+ } catch(Exception e) {
+ s_logger.error("Unable to init factory due to exception ", e);
+ }
+ }
+
+ }
+
+ public HttpServer createHttpServerInstance(int port) throws IOException {
+ try {
+ HttpsServer server = HttpsServer.create(new InetSocketAddress(port), 5);
+ server.setHttpsConfigurator (new HttpsConfigurator(sslContext) {
+ @Override
+ public void configure (HttpsParameters params) {
+
+ // get the remote address if needed
+ InetSocketAddress remote = params.getClientAddress();
+ SSLContext c = getSSLContext();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
- tmf.init(ks);
- s_logger.info("Trust manager factory is initialized");
+ // get the default parameters
+ SSLParameters sslparams = c.getDefaultSSLParameters();
- sslContext = SSLContext.getInstance("TLS");
- sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
- s_logger.info("SSL context is initialized");
- } catch (Exception ioe) {
- s_logger.error(ioe.toString(), ioe);
- }
-
- } else {
- char[] passphrase = ksPassword != null ? ksPassword.toCharArray() : null;
- try {
- s_logger.info("Initializing SSL from passed-in certificate");
-
- KeyStore ks = KeyStore.getInstance("JKS");
- ks.load(new ByteArrayInputStream(ksBits), passphrase);
-
- KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
- kmf.init(ks, passphrase);
- s_logger.info("Key manager factory is initialized");
-
- TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
- tmf.init(ks);
- s_logger.info("Trust manager factory is initialized");
-
- sslContext = SSLContext.getInstance("TLS");
- sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
- s_logger.info("SSL context is initialized");
- } catch(Exception e) {
- s_logger.error("Unable to init factory due to exception ", e);
- }
- }
-
- }
-
- public HttpServer createHttpServerInstance(int port) throws IOException {
- try {
- HttpsServer server = HttpsServer.create(new InetSocketAddress(port), 5);
- server.setHttpsConfigurator (new HttpsConfigurator(sslContext) {
- @Override
- public void configure (HttpsParameters params) {
-
- // get the remote address if needed
- InetSocketAddress remote = params.getClientAddress();
- SSLContext c = getSSLContext();
-
- // get the default parameters
- SSLParameters sslparams = c.getDefaultSSLParameters();
-
- params.setSSLParameters(sslparams);
- // statement above could throw IAE if any params invalid.
- // eg. if app has a UI and parameters supplied by a user.
- }
- });
-
- s_logger.info("create HTTPS server instance on port: " + port);
- return server;
- } catch (Exception ioe) {
- s_logger.error(ioe.toString(), ioe);
- }
- return null;
- }
-
- public SSLServerSocket createSSLServerSocket(int port) throws IOException {
- try {
- SSLServerSocket srvSock = null;
- SSLServerSocketFactory ssf = sslContext.getServerSocketFactory();
- srvSock = (SSLServerSocket) ssf.createServerSocket(port);
-
- s_logger.info("create SSL server socket on port: " + port);
- return srvSock;
- } catch (Exception ioe) {
- s_logger.error(ioe.toString(), ioe);
- }
- return null;
- }
-}
+ params.setSSLParameters(sslparams);
+ // statement above could throw IAE if any params invalid.
+ // eg. if app has a UI and parameters supplied by a user.
+ }
+ });
+
+ s_logger.info("create HTTPS server instance on port: " + port);
+ return server;
+ } catch (Exception ioe) {
+ s_logger.error(ioe.toString(), ioe);
+ }
+ return null;
+ }
+
+ public SSLServerSocket createSSLServerSocket(int port) throws IOException {
+ try {
+ SSLServerSocket srvSock = null;
+ SSLServerSocketFactory ssf = sslContext.getServerSocketFactory();
+ srvSock = (SSLServerSocket) ssf.createServerSocket(port);
+
+ s_logger.info("create SSL server socket on port: " + port);
+ return srvSock;
+ } catch (Exception ioe) {
+ s_logger.error(ioe.toString(), ioe);
+ }
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyServerFactory.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyServerFactory.java b/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyServerFactory.java
index 9d65c00..7e0e5c7 100644
--- a/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyServerFactory.java
+++ b/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyServerFactory.java
@@ -14,16 +14,16 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy;
-
+package com.cloud.consoleproxy;
+
import java.io.IOException;
import javax.net.ssl.SSLServerSocket;
import com.sun.net.httpserver.HttpServer;
-
+
public interface ConsoleProxyServerFactory {
- void init(byte[] ksBits, String ksPassword);
- HttpServer createHttpServerInstance(int port) throws IOException;
- SSLServerSocket createSSLServerSocket(int port) throws IOException;
-}
+ void init(byte[] ksBits, String ksPassword);
+ HttpServer createHttpServerInstance(int port) throws IOException;
+ SSLServerSocket createSSLServerSocket(int port) throws IOException;
+}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyThumbnailHandler.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyThumbnailHandler.java b/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyThumbnailHandler.java
index 82d45b7..6d34d3b 100644
--- a/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyThumbnailHandler.java
+++ b/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyThumbnailHandler.java
@@ -14,199 +14,199 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy;
-
-import java.awt.Color;
-import java.awt.Font;
-import java.awt.FontMetrics;
-import java.awt.Graphics2D;
-import java.awt.Image;
-import java.awt.image.BufferedImage;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.HashMap;
-import java.util.Map;
-
+package com.cloud.consoleproxy;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Graphics2D;
+import java.awt.Image;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.HashMap;
+import java.util.Map;
+
import com.cloud.consoleproxy.util.Logger;
-import com.sun.net.httpserver.Headers;
-import com.sun.net.httpserver.HttpExchange;
-import com.sun.net.httpserver.HttpHandler;
-
-public class ConsoleProxyThumbnailHandler implements HttpHandler {
- private static final Logger s_logger = Logger.getLogger(ConsoleProxyThumbnailHandler.class);
-
- public ConsoleProxyThumbnailHandler() {
- }
-
- public void handle(HttpExchange t) throws IOException {
- try {
- Thread.currentThread().setName("JPG Thread " +
- Thread.currentThread().getId() + " " + t.getRemoteAddress());
-
- if(s_logger.isDebugEnabled())
- s_logger.debug("ScreenHandler " + t.getRequestURI());
-
- long startTick = System.currentTimeMillis();
- doHandle(t);
-
- if(s_logger.isDebugEnabled())
- s_logger.debug(t.getRequestURI() + "Process time " + (System.currentTimeMillis() - startTick) + " ms");
- } catch (IllegalArgumentException e) {
- String response = "Bad query string";
- s_logger.error(response + ", request URI : " + t.getRequestURI());
- t.sendResponseHeaders(200, response.length());
- OutputStream os = t.getResponseBody();
- os.write(response.getBytes());
- os.close();
- } catch(OutOfMemoryError e) {
- s_logger.error("Unrecoverable OutOfMemory Error, exit and let it be re-launched");
- System.exit(1);
- } catch (Throwable e) {
- s_logger.error("Unexpected exception while handing thumbnail request, ", e);
-
- String queries = t.getRequestURI().getQuery();
- Map<String, String> queryMap = getQueryMap(queries);
- int width = 0;
- int height = 0;
- String ws = queryMap.get("w");
- String hs = queryMap.get("h");
- try {
- width = Integer.parseInt(ws);
- height = Integer.parseInt(hs);
- } catch (NumberFormatException ex) {
- }
- width = Math.min(width, 800);
- height = Math.min(height, 600);
-
- BufferedImage img = generateTextImage(width, height, "Cannot Connect");
- ByteArrayOutputStream bos = new ByteArrayOutputStream(8196);
- javax.imageio.ImageIO.write(img, "jpg", bos);
- byte[] bs = bos.toByteArray();
- Headers hds = t.getResponseHeaders();
- hds.set("Content-Type", "image/jpeg");
- hds.set("Cache-Control", "no-cache");
- hds.set("Cache-Control", "no-store");
- t.sendResponseHeaders(200, bs.length);
- OutputStream os = t.getResponseBody();
- os.write(bs);
- os.close();
- s_logger.error("Cannot get console, sent error JPG response for " + t.getRequestURI());
- return;
- } finally {
- t.close();
- }
- }
-
- private void doHandle(HttpExchange t) throws Exception, IllegalArgumentException {
- String queries = t.getRequestURI().getQuery();
- Map<String, String> queryMap = getQueryMap(queries);
- int width = 0;
- int height = 0;
- int port = 0;
- String ws = queryMap.get("w");
- String hs = queryMap.get("h");
- String host = queryMap.get("host");
- String portStr = queryMap.get("port");
- String sid = queryMap.get("sid");
- String tag = queryMap.get("tag");
- String ticket = queryMap.get("ticket");
- String console_url = queryMap.get("consoleurl");
- String console_host_session = queryMap.get("sessionref");
+import com.sun.net.httpserver.Headers;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+
+public class ConsoleProxyThumbnailHandler implements HttpHandler {
+ private static final Logger s_logger = Logger.getLogger(ConsoleProxyThumbnailHandler.class);
+
+ public ConsoleProxyThumbnailHandler() {
+ }
+
+ public void handle(HttpExchange t) throws IOException {
+ try {
+ Thread.currentThread().setName("JPG Thread " +
+ Thread.currentThread().getId() + " " + t.getRemoteAddress());
+
+ if(s_logger.isDebugEnabled())
+ s_logger.debug("ScreenHandler " + t.getRequestURI());
+
+ long startTick = System.currentTimeMillis();
+ doHandle(t);
+
+ if(s_logger.isDebugEnabled())
+ s_logger.debug(t.getRequestURI() + "Process time " + (System.currentTimeMillis() - startTick) + " ms");
+ } catch (IllegalArgumentException e) {
+ String response = "Bad query string";
+ s_logger.error(response + ", request URI : " + t.getRequestURI());
+ t.sendResponseHeaders(200, response.length());
+ OutputStream os = t.getResponseBody();
+ os.write(response.getBytes());
+ os.close();
+ } catch(OutOfMemoryError e) {
+ s_logger.error("Unrecoverable OutOfMemory Error, exit and let it be re-launched");
+ System.exit(1);
+ } catch (Throwable e) {
+ s_logger.error("Unexpected exception while handing thumbnail request, ", e);
+
+ String queries = t.getRequestURI().getQuery();
+ Map<String, String> queryMap = getQueryMap(queries);
+ int width = 0;
+ int height = 0;
+ String ws = queryMap.get("w");
+ String hs = queryMap.get("h");
+ try {
+ width = Integer.parseInt(ws);
+ height = Integer.parseInt(hs);
+ } catch (NumberFormatException ex) {
+ }
+ width = Math.min(width, 800);
+ height = Math.min(height, 600);
+
+ BufferedImage img = generateTextImage(width, height, "Cannot Connect");
+ ByteArrayOutputStream bos = new ByteArrayOutputStream(8196);
+ javax.imageio.ImageIO.write(img, "jpg", bos);
+ byte[] bs = bos.toByteArray();
+ Headers hds = t.getResponseHeaders();
+ hds.set("Content-Type", "image/jpeg");
+ hds.set("Cache-Control", "no-cache");
+ hds.set("Cache-Control", "no-store");
+ t.sendResponseHeaders(200, bs.length);
+ OutputStream os = t.getResponseBody();
+ os.write(bs);
+ os.close();
+ s_logger.error("Cannot get console, sent error JPG response for " + t.getRequestURI());
+ return;
+ } finally {
+ t.close();
+ }
+ }
+
+ private void doHandle(HttpExchange t) throws Exception, IllegalArgumentException {
+ String queries = t.getRequestURI().getQuery();
+ Map<String, String> queryMap = getQueryMap(queries);
+ int width = 0;
+ int height = 0;
+ int port = 0;
+ String ws = queryMap.get("w");
+ String hs = queryMap.get("h");
+ String host = queryMap.get("host");
+ String portStr = queryMap.get("port");
+ String sid = queryMap.get("sid");
+ String tag = queryMap.get("tag");
+ String ticket = queryMap.get("ticket");
+ String console_url = queryMap.get("consoleurl");
+ String console_host_session = queryMap.get("sessionref");
+
+ if(tag == null)
+ tag = "";
+
+ if (ws == null || hs == null || host == null || portStr == null || sid == null ) {
+ throw new IllegalArgumentException();
+ }
+ try {
+ width = Integer.parseInt(ws);
+ height = Integer.parseInt(hs);
+ port = Integer.parseInt(portStr);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(e);
+ }
- if(tag == null)
- tag = "";
-
- if (ws == null || hs == null || host == null || portStr == null || sid == null ) {
- throw new IllegalArgumentException();
- }
- try {
- width = Integer.parseInt(ws);
- height = Integer.parseInt(hs);
- port = Integer.parseInt(portStr);
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException(e);
- }
+ ConsoleProxyClientParam param = new ConsoleProxyClientParam();
+ param.setClientHostAddress(host);
+ param.setClientHostPort(port);
+ param.setClientHostPassword(sid);
+ param.setClientTag(tag);
+ param.setTicket(ticket);
+ param.setClientTunnelUrl(console_url);
+ param.setClientTunnelSession(console_host_session);
+
+ ConsoleProxyClient viewer = ConsoleProxy.getVncViewer(param);
+
+ if (!viewer.isHostConnected()) {
+ // use generated image instead of static
+ BufferedImage img = generateTextImage(width, height, "Connecting");
+ ByteArrayOutputStream bos = new ByteArrayOutputStream(8196);
+ javax.imageio.ImageIO.write(img, "jpg", bos);
+ byte[] bs = bos.toByteArray();
+ Headers hds = t.getResponseHeaders();
+ hds.set("Content-Type", "image/jpeg");
+ hds.set("Cache-Control", "no-cache");
+ hds.set("Cache-Control", "no-store");
+ t.sendResponseHeaders(200, bs.length);
+ OutputStream os = t.getResponseBody();
+ os.write(bs);
+ os.close();
+
+ if(s_logger.isInfoEnabled())
+ s_logger.info("Console not ready, sent dummy JPG response");
+ return;
+ }
+
+ {
+ Image scaledImage = viewer.getClientScaledImage(width, height);
+ BufferedImage bufferedImage = new BufferedImage(width, height,
+ BufferedImage.TYPE_3BYTE_BGR);
+ Graphics2D bufImageGraphics = bufferedImage.createGraphics();
+ bufImageGraphics.drawImage(scaledImage, 0, 0, null);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream(8196);
+ javax.imageio.ImageIO.write(bufferedImage, "jpg", bos);
+ byte[] bs = bos.toByteArray();
+ Headers hds = t.getResponseHeaders();
+ hds.set("Content-Type", "image/jpeg");
+ hds.set("Cache-Control", "no-cache");
+ hds.set("Cache-Control", "no-store");
+ t.sendResponseHeaders(200, bs.length);
+ OutputStream os = t.getResponseBody();
+ os.write(bs);
+ os.close();
+ }
+ }
+
+ public static BufferedImage generateTextImage(int w, int h, String text) {
+ BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
+ Graphics2D g = img.createGraphics();
+ g.setColor(Color.BLACK);
+ g.fillRect(0, 0, w, h);
+ g.setColor(Color.WHITE);
+ try {
+ g.setFont(new Font(null, Font.PLAIN, 12));
+ FontMetrics fm = g.getFontMetrics();
+ int textWidth = fm.stringWidth(text);
+ int startx = (w-textWidth) / 2;
+ if(startx < 0)
+ startx = 0;
+ g.drawString(text, startx, h/2);
+ } catch (Throwable e) {
+ s_logger.warn("Problem in generating text to thumnail image, return blank image");
+ }
+ return img;
+ }
- ConsoleProxyClientParam param = new ConsoleProxyClientParam();
- param.setClientHostAddress(host);
- param.setClientHostPort(port);
- param.setClientHostPassword(sid);
- param.setClientTag(tag);
- param.setTicket(ticket);
- param.setClientTunnelUrl(console_url);
- param.setClientTunnelSession(console_host_session);
-
- ConsoleProxyClient viewer = ConsoleProxy.getVncViewer(param);
-
- if (!viewer.isHostConnected()) {
- // use generated image instead of static
- BufferedImage img = generateTextImage(width, height, "Connecting");
- ByteArrayOutputStream bos = new ByteArrayOutputStream(8196);
- javax.imageio.ImageIO.write(img, "jpg", bos);
- byte[] bs = bos.toByteArray();
- Headers hds = t.getResponseHeaders();
- hds.set("Content-Type", "image/jpeg");
- hds.set("Cache-Control", "no-cache");
- hds.set("Cache-Control", "no-store");
- t.sendResponseHeaders(200, bs.length);
- OutputStream os = t.getResponseBody();
- os.write(bs);
- os.close();
-
- if(s_logger.isInfoEnabled())
- s_logger.info("Console not ready, sent dummy JPG response");
- return;
- }
-
- {
- Image scaledImage = viewer.getClientScaledImage(width, height);
- BufferedImage bufferedImage = new BufferedImage(width, height,
- BufferedImage.TYPE_3BYTE_BGR);
- Graphics2D bufImageGraphics = bufferedImage.createGraphics();
- bufImageGraphics.drawImage(scaledImage, 0, 0, null);
- ByteArrayOutputStream bos = new ByteArrayOutputStream(8196);
- javax.imageio.ImageIO.write(bufferedImage, "jpg", bos);
- byte[] bs = bos.toByteArray();
- Headers hds = t.getResponseHeaders();
- hds.set("Content-Type", "image/jpeg");
- hds.set("Cache-Control", "no-cache");
- hds.set("Cache-Control", "no-store");
- t.sendResponseHeaders(200, bs.length);
- OutputStream os = t.getResponseBody();
- os.write(bs);
- os.close();
- }
- }
-
- public static BufferedImage generateTextImage(int w, int h, String text) {
- BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
- Graphics2D g = img.createGraphics();
- g.setColor(Color.BLACK);
- g.fillRect(0, 0, w, h);
- g.setColor(Color.WHITE);
- try {
- g.setFont(new Font(null, Font.PLAIN, 12));
- FontMetrics fm = g.getFontMetrics();
- int textWidth = fm.stringWidth(text);
- int startx = (w-textWidth) / 2;
- if(startx < 0)
- startx = 0;
- g.drawString(text, startx, h/2);
- } catch (Throwable e) {
- s_logger.warn("Problem in generating text to thumnail image, return blank image");
- }
- return img;
- }
-
- public static Map<String, String> getQueryMap(String query) {
- String[] params = query.split("&");
- Map<String, String> map = new HashMap<String, String>();
- for (String param : params) {
- String name = param.split("=")[0];
- String value = param.split("=")[1];
- map.put(name, value);
- }
- return map;
- }
-}
+ public static Map<String, String> getQueryMap(String query) {
+ String[] params = query.split("&");
+ Map<String, String> map = new HashMap<String, String>();
+ for (String param : params) {
+ String name = param.split("=")[0];
+ String value = param.split("=")[1];
+ map.put(name, value);
+ }
+ return map;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/InputEventType.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/InputEventType.java b/console-proxy/src/com/cloud/consoleproxy/InputEventType.java
index b0bf8eb..4a5aff1 100644
--- a/console-proxy/src/com/cloud/consoleproxy/InputEventType.java
+++ b/console-proxy/src/com/cloud/consoleproxy/InputEventType.java
@@ -14,45 +14,45 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy;
-
-public enum InputEventType {
- MOUSE_MOVE(1),
- MOUSE_DOWN(2),
- MOUSE_UP(3),
- KEY_PRESS(4),
- KEY_DOWN(5),
- KEY_UP(6),
- MOUSE_DBLCLICK(8);
-
- int eventCode;
- private InputEventType(int eventCode) {
- this.eventCode = eventCode;
- }
-
- public int getEventCode() {
- return eventCode;
- }
-
- public static InputEventType fromEventCode(int eventCode) {
- switch(eventCode) {
- case 1 :
- return MOUSE_MOVE;
- case 2 :
- return MOUSE_DOWN;
- case 3 :
- return MOUSE_UP;
- case 4 :
- return KEY_PRESS;
- case 5 :
- return KEY_DOWN;
- case 6 :
- return KEY_UP;
- case 8 :
- return MOUSE_DBLCLICK;
- default :
- break;
- }
- throw new IllegalArgumentException("Unsupport event code: " + eventCode);
- }
-}
+package com.cloud.consoleproxy;
+
+public enum InputEventType {
+ MOUSE_MOVE(1),
+ MOUSE_DOWN(2),
+ MOUSE_UP(3),
+ KEY_PRESS(4),
+ KEY_DOWN(5),
+ KEY_UP(6),
+ MOUSE_DBLCLICK(8);
+
+ int eventCode;
+ private InputEventType(int eventCode) {
+ this.eventCode = eventCode;
+ }
+
+ public int getEventCode() {
+ return eventCode;
+ }
+
+ public static InputEventType fromEventCode(int eventCode) {
+ switch(eventCode) {
+ case 1 :
+ return MOUSE_MOVE;
+ case 2 :
+ return MOUSE_DOWN;
+ case 3 :
+ return MOUSE_UP;
+ case 4 :
+ return KEY_PRESS;
+ case 5 :
+ return KEY_DOWN;
+ case 6 :
+ return KEY_UP;
+ case 8 :
+ return MOUSE_DBLCLICK;
+ default :
+ break;
+ }
+ throw new IllegalArgumentException("Unsupport event code: " + eventCode);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/util/ITileScanListener.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/util/ITileScanListener.java b/console-proxy/src/com/cloud/consoleproxy/util/ITileScanListener.java
index 547b13c..2ff82d7 100644
--- a/console-proxy/src/com/cloud/consoleproxy/util/ITileScanListener.java
+++ b/console-proxy/src/com/cloud/consoleproxy/util/ITileScanListener.java
@@ -14,12 +14,12 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy.util;
-
-import java.awt.Rectangle;
-import java.util.List;
-
-public interface ITileScanListener {
- boolean onTileChange(Rectangle rowMergedRect, int row, int col);
- void onRegionChange(List<Region> regionList);
-}
+package com.cloud.consoleproxy.util;
+
+import java.awt.Rectangle;
+import java.util.List;
+
+public interface ITileScanListener {
+ boolean onTileChange(Rectangle rowMergedRect, int row, int col);
+ void onRegionChange(List<Region> regionList);
+}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/util/ImageHelper.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/util/ImageHelper.java b/console-proxy/src/com/cloud/consoleproxy/util/ImageHelper.java
index 42fb59e..bb7373e 100644
--- a/console-proxy/src/com/cloud/consoleproxy/util/ImageHelper.java
+++ b/console-proxy/src/com/cloud/consoleproxy/util/ImageHelper.java
@@ -14,19 +14,19 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy.util;
-
-import java.awt.image.BufferedImage;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
-public class ImageHelper {
- public static byte[] jpegFromImage(BufferedImage image) throws IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream(128000);
- javax.imageio.ImageIO.write(image, "jpg", bos);
-
- byte[] jpegBits = bos.toByteArray();
- bos.close();
- return jpegBits;
- }
-}
+package com.cloud.consoleproxy.util;
+
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+public class ImageHelper {
+ public static byte[] jpegFromImage(BufferedImage image) throws IOException {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream(128000);
+ javax.imageio.ImageIO.write(image, "jpg", bos);
+
+ byte[] jpegBits = bos.toByteArray();
+ bos.close();
+ return jpegBits;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/util/Logger.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/util/Logger.java b/console-proxy/src/com/cloud/consoleproxy/util/Logger.java
index 2392a98..f4357bd 100644
--- a/console-proxy/src/com/cloud/consoleproxy/util/Logger.java
+++ b/console-proxy/src/com/cloud/consoleproxy/util/Logger.java
@@ -14,210 +14,210 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy.util;
-
-// logger facility for dynamic switch between console logger used in Applet and log4j based logger
-public class Logger {
- private static LoggerFactory factory = null;
-
- public static final int LEVEL_TRACE = 1;
- public static final int LEVEL_DEBUG = 2;
- public static final int LEVEL_INFO = 3;
- public static final int LEVEL_WARN = 4;
- public static final int LEVEL_ERROR = 5;
-
- private Class<?> clazz;
- private Logger logger;
-
- private static int level = LEVEL_INFO;
-
- public static Logger getLogger(Class<?> clazz) {
- return new Logger(clazz);
- }
-
- public static void setFactory(LoggerFactory f) {
- factory = f;
- }
-
- public static void setLevel(int l) {
- level = l;
- }
-
- public Logger(Class<?> clazz) {
- this.clazz = clazz;
- }
-
- protected Logger() {
- }
-
- public boolean isTraceEnabled() {
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- return logger.isTraceEnabled();
- }
- return level <= LEVEL_TRACE;
- }
-
- public boolean isDebugEnabled() {
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- return logger.isDebugEnabled();
- }
- return level <= LEVEL_DEBUG;
- }
-
- public boolean isInfoEnabled() {
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- return logger.isInfoEnabled();
- }
- return level <= LEVEL_INFO;
- }
-
- public void trace(Object message) {
-
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- logger.trace(message);
- } else {
- if(level <= LEVEL_TRACE)
- System.out.println(message);
- }
- }
-
- public void trace(Object message, Throwable exception) {
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- logger.trace(message, exception);
- } else {
- if(level <= LEVEL_TRACE) {
- System.out.println(message);
- if (exception != null) {
- exception.printStackTrace(System.out);
- }
- }
- }
- }
-
- public void info(Object message) {
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- logger.info(message);
- } else {
- if(level <= LEVEL_INFO)
- System.out.println(message);
- }
- }
-
- public void info(Object message, Throwable exception) {
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- logger.info(message, exception);
- } else {
- if(level <= LEVEL_INFO) {
- System.out.println(message);
- if (exception != null) {
- exception.printStackTrace(System.out);
- }
- }
- }
- }
-
- public void debug(Object message) {
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- logger.debug(message);
- } else {
- if(level <= LEVEL_DEBUG)
- System.out.println(message);
- }
- }
-
- public void debug(Object message, Throwable exception) {
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- logger.debug(message, exception);
- } else {
- if(level <= LEVEL_DEBUG) {
- System.out.println(message);
- if (exception != null) {
- exception.printStackTrace(System.out);
- }
- }
- }
- }
-
- public void warn(Object message) {
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- logger.warn(message);
- } else {
- if(level <= LEVEL_WARN)
- System.out.println(message);
- }
- }
-
- public void warn(Object message, Throwable exception) {
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- logger.warn(message, exception);
- } else {
- if(level <= LEVEL_WARN) {
- System.out.println(message);
- if (exception != null) {
- exception.printStackTrace(System.out);
- }
- }
- }
- }
-
- public void error(Object message) {
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- logger.error(message);
- } else {
- if(level <= LEVEL_ERROR)
- System.out.println(message);
- }
- }
-
- public void error(Object message, Throwable exception) {
- if(factory != null) {
- if(logger == null)
- logger = factory.getLogger(clazz);
-
- logger.error(message, exception);
- } else {
- if(level <= LEVEL_ERROR) {
- System.out.println(message);
- if (exception != null) {
- exception.printStackTrace(System.out);
- }
- }
- }
- }
-}
+package com.cloud.consoleproxy.util;
+
+// logger facility for dynamic switch between console logger used in Applet and log4j based logger
+public class Logger {
+ private static LoggerFactory factory = null;
+
+ public static final int LEVEL_TRACE = 1;
+ public static final int LEVEL_DEBUG = 2;
+ public static final int LEVEL_INFO = 3;
+ public static final int LEVEL_WARN = 4;
+ public static final int LEVEL_ERROR = 5;
+
+ private Class<?> clazz;
+ private Logger logger;
+
+ private static int level = LEVEL_INFO;
+
+ public static Logger getLogger(Class<?> clazz) {
+ return new Logger(clazz);
+ }
+
+ public static void setFactory(LoggerFactory f) {
+ factory = f;
+ }
+
+ public static void setLevel(int l) {
+ level = l;
+ }
+
+ public Logger(Class<?> clazz) {
+ this.clazz = clazz;
+ }
+
+ protected Logger() {
+ }
+
+ public boolean isTraceEnabled() {
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ return logger.isTraceEnabled();
+ }
+ return level <= LEVEL_TRACE;
+ }
+
+ public boolean isDebugEnabled() {
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ return logger.isDebugEnabled();
+ }
+ return level <= LEVEL_DEBUG;
+ }
+
+ public boolean isInfoEnabled() {
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ return logger.isInfoEnabled();
+ }
+ return level <= LEVEL_INFO;
+ }
+
+ public void trace(Object message) {
+
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ logger.trace(message);
+ } else {
+ if(level <= LEVEL_TRACE)
+ System.out.println(message);
+ }
+ }
+
+ public void trace(Object message, Throwable exception) {
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ logger.trace(message, exception);
+ } else {
+ if(level <= LEVEL_TRACE) {
+ System.out.println(message);
+ if (exception != null) {
+ exception.printStackTrace(System.out);
+ }
+ }
+ }
+ }
+
+ public void info(Object message) {
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ logger.info(message);
+ } else {
+ if(level <= LEVEL_INFO)
+ System.out.println(message);
+ }
+ }
+
+ public void info(Object message, Throwable exception) {
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ logger.info(message, exception);
+ } else {
+ if(level <= LEVEL_INFO) {
+ System.out.println(message);
+ if (exception != null) {
+ exception.printStackTrace(System.out);
+ }
+ }
+ }
+ }
+
+ public void debug(Object message) {
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ logger.debug(message);
+ } else {
+ if(level <= LEVEL_DEBUG)
+ System.out.println(message);
+ }
+ }
+
+ public void debug(Object message, Throwable exception) {
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ logger.debug(message, exception);
+ } else {
+ if(level <= LEVEL_DEBUG) {
+ System.out.println(message);
+ if (exception != null) {
+ exception.printStackTrace(System.out);
+ }
+ }
+ }
+ }
+
+ public void warn(Object message) {
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ logger.warn(message);
+ } else {
+ if(level <= LEVEL_WARN)
+ System.out.println(message);
+ }
+ }
+
+ public void warn(Object message, Throwable exception) {
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ logger.warn(message, exception);
+ } else {
+ if(level <= LEVEL_WARN) {
+ System.out.println(message);
+ if (exception != null) {
+ exception.printStackTrace(System.out);
+ }
+ }
+ }
+ }
+
+ public void error(Object message) {
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ logger.error(message);
+ } else {
+ if(level <= LEVEL_ERROR)
+ System.out.println(message);
+ }
+ }
+
+ public void error(Object message, Throwable exception) {
+ if(factory != null) {
+ if(logger == null)
+ logger = factory.getLogger(clazz);
+
+ logger.error(message, exception);
+ } else {
+ if(level <= LEVEL_ERROR) {
+ System.out.println(message);
+ if (exception != null) {
+ exception.printStackTrace(System.out);
+ }
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/util/LoggerFactory.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/util/LoggerFactory.java b/console-proxy/src/com/cloud/consoleproxy/util/LoggerFactory.java
index fa0d3cf..121411a 100644
--- a/console-proxy/src/com/cloud/consoleproxy/util/LoggerFactory.java
+++ b/console-proxy/src/com/cloud/consoleproxy/util/LoggerFactory.java
@@ -14,8 +14,8 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy.util;
-
-public interface LoggerFactory {
- Logger getLogger(Class<?> clazz);
-}
+package com.cloud.consoleproxy.util;
+
+public interface LoggerFactory {
+ Logger getLogger(Class<?> clazz);
+}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/util/RawHTTP.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/util/RawHTTP.java b/console-proxy/src/com/cloud/consoleproxy/util/RawHTTP.java
index eeba345..c77b551 100644
--- a/console-proxy/src/com/cloud/consoleproxy/util/RawHTTP.java
+++ b/console-proxy/src/com/cloud/consoleproxy/util/RawHTTP.java
@@ -14,236 +14,236 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.Socket;
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.SecureRandom;
-import java.security.cert.X509Certificate;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.net.SocketFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-
-//
-// This file is originally from XenConsole with modifications
-//
-
-/**
- * Send an HTTP CONNECT or PUT request to a XenAPI host with a Session ID,
- * return the connected socket and the Task ID. Used for tunnelling VNC
- * connections and import/export operations.
- */
-public final class RawHTTP {
- private static final Logger s_logger = Logger.getLogger(RawHTTP.class);
-
- private static final Pattern END_PATTERN = Pattern.compile("^\r\n$");
- private static final Pattern HEADER_PATTERN = Pattern
- .compile("^([A-Z_a-z0-9-]+):\\s*(.*)\r\n$");
- private static final Pattern HTTP_PATTERN = Pattern
- .compile("^HTTP/\\d+\\.\\d+ (\\d*) (.*)\r\n$");
-
- /**
- * @uml.property name="command"
- */
- private final String command;
- /**
- * @uml.property name="host"
- */
- private final String host;
- /**
- * @uml.property name="port"
- */
- private final int port;
- /**
- * @uml.property name="path"
- */
- private final String path;
- /**
- * @uml.property name="session"
- */
- private final String session;
- /**
- * @uml.property name="useSSL"
- */
- private final boolean useSSL;
-
- /**
- * @uml.property name="responseHeaders"
- * @uml.associationEnd qualifier="group:java.lang.String java.lang.String"
- */
- private final Map<String, String> responseHeaders = new HashMap<String, String>();
-
- /**
- * @uml.property name="ic"
- */
- private InputStream ic;
- /**
- * @uml.property name="oc"
- */
- private OutputStream oc;
- /**
- * @uml.property name="s"
- */
- private Socket s;
-
- public InputStream getInputStream() {
- return ic;
- }
-
- public OutputStream getOutputStream() {
- return oc;
- }
-
- public Socket getSocket() {
- return s;
- }
-
- public RawHTTP(String command, String host, int port, String path,
- String session, boolean useSSL) {
- this.command = command;
- this.host = host;
- this.port = port;
- this.path = path;
- this.session = session;
- this.useSSL = useSSL;
- }
-
- private static final TrustManager[] trustAllCerts = new TrustManager[] {
- new X509TrustManager() {
- public X509Certificate[] getAcceptedIssuers() {
- return null;
- }
-
- public void checkClientTrusted(X509Certificate[] certs, String authType) {
- }
-
- public void checkServerTrusted(X509Certificate[] certs, String authType) {
- }
- }
- };
-
- private Socket _getSocket() throws IOException {
- if (useSSL) {
- SSLContext context = getClientSSLContext();
- if(context == null)
- throw new IOException("Unable to setup SSL context");
-
- SSLSocket ssl = null;
- try {
- context.init(null, trustAllCerts, new SecureRandom());
- SocketFactory factory = context.getSocketFactory();
- ssl = (SSLSocket) factory.createSocket(host, port);
- /* ssl.setSSLParameters(context.getDefaultSSLParameters()); */
- } catch (IOException e) {
- s_logger.error("IOException: " + e.getMessage(), e);
- throw e;
- } catch (KeyManagementException e) {
- s_logger.error("KeyManagementException: " + e.getMessage(), e);
- }
- return ssl;
- } else {
- return new Socket(host, port);
- }
- }
-
- public Socket connect() throws IOException {
- String[] headers = makeHeaders();
- s = _getSocket();
- try {
- oc = s.getOutputStream();
- for (String header : headers) {
- oc.write(header.getBytes());
- oc.write("\r\n".getBytes());
- }
- oc.flush();
- ic = s.getInputStream();
- while (true) {
- String line = readline(ic);
-
- Matcher m = END_PATTERN.matcher(line);
- if (m.matches()) {
- return s;
- }
-
- m = HEADER_PATTERN.matcher(line);
- if (m.matches()) {
- responseHeaders.put(m.group(1), m.group(2));
- continue;
- }
-
- m = HTTP_PATTERN.matcher(line);
- if (m.matches()) {
- String status_code = m.group(1);
- String reason_phrase = m.group(2);
- if (!"200".equals(status_code)) {
- throw new IOException("HTTP status " + status_code
- + " " + reason_phrase);
- }
- } else {
- throw new IOException("Unknown HTTP line " + line);
- }
- }
- } catch (IOException exn) {
- s.close();
- throw exn;
- } catch (RuntimeException exn) {
- s.close();
- throw exn;
- }
- }
-
- public Map<String, String> getResponseHeaders() {
- return responseHeaders;
- }
-
- private String[] makeHeaders() {
- String[] headers = { String.format("%s %s HTTP/1.0", command, path),
- String.format("Host: %s", host),
- String.format("Cookie: session_id=%s", session), "" };
- return headers;
- }
-
- private static String readline(InputStream ic) throws IOException {
- String result = "";
- while (true) {
- try {
- int c = ic.read();
-
- if (c == -1) {
- return result;
- }
- result = result + (char) c;
- if (c == 0x0a /* LF */) {
- return result;
- }
- } catch (IOException e) {
- ic.close();
- throw e;
- }
- }
- }
-
- private SSLContext getClientSSLContext() {
- SSLContext sslContext = null;
- try {
- sslContext = SSLContext.getInstance("SSL", "SunJSSE");
- } catch (NoSuchAlgorithmException e) {
- s_logger.error("Unexpected exception ", e);
- } catch (NoSuchProviderException e) {
- s_logger.error("Unexpected exception ", e);
- }
- return sslContext;
- }
-}
+package com.cloud.consoleproxy.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.SecureRandom;
+import java.security.cert.X509Certificate;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.net.SocketFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+//
+// This file is originally from XenConsole with modifications
+//
+
+/**
+ * Send an HTTP CONNECT or PUT request to a XenAPI host with a Session ID,
+ * return the connected socket and the Task ID. Used for tunnelling VNC
+ * connections and import/export operations.
+ */
+public final class RawHTTP {
+ private static final Logger s_logger = Logger.getLogger(RawHTTP.class);
+
+ private static final Pattern END_PATTERN = Pattern.compile("^\r\n$");
+ private static final Pattern HEADER_PATTERN = Pattern
+ .compile("^([A-Z_a-z0-9-]+):\\s*(.*)\r\n$");
+ private static final Pattern HTTP_PATTERN = Pattern
+ .compile("^HTTP/\\d+\\.\\d+ (\\d*) (.*)\r\n$");
+
+ /**
+ * @uml.property name="command"
+ */
+ private final String command;
+ /**
+ * @uml.property name="host"
+ */
+ private final String host;
+ /**
+ * @uml.property name="port"
+ */
+ private final int port;
+ /**
+ * @uml.property name="path"
+ */
+ private final String path;
+ /**
+ * @uml.property name="session"
+ */
+ private final String session;
+ /**
+ * @uml.property name="useSSL"
+ */
+ private final boolean useSSL;
+
+ /**
+ * @uml.property name="responseHeaders"
+ * @uml.associationEnd qualifier="group:java.lang.String java.lang.String"
+ */
+ private final Map<String, String> responseHeaders = new HashMap<String, String>();
+
+ /**
+ * @uml.property name="ic"
+ */
+ private InputStream ic;
+ /**
+ * @uml.property name="oc"
+ */
+ private OutputStream oc;
+ /**
+ * @uml.property name="s"
+ */
+ private Socket s;
+
+ public InputStream getInputStream() {
+ return ic;
+ }
+
+ public OutputStream getOutputStream() {
+ return oc;
+ }
+
+ public Socket getSocket() {
+ return s;
+ }
+
+ public RawHTTP(String command, String host, int port, String path,
+ String session, boolean useSSL) {
+ this.command = command;
+ this.host = host;
+ this.port = port;
+ this.path = path;
+ this.session = session;
+ this.useSSL = useSSL;
+ }
+
+ private static final TrustManager[] trustAllCerts = new TrustManager[] {
+ new X509TrustManager() {
+ public X509Certificate[] getAcceptedIssuers() {
+ return null;
+ }
+
+ public void checkClientTrusted(X509Certificate[] certs, String authType) {
+ }
+
+ public void checkServerTrusted(X509Certificate[] certs, String authType) {
+ }
+ }
+ };
+
+ private Socket _getSocket() throws IOException {
+ if (useSSL) {
+ SSLContext context = getClientSSLContext();
+ if(context == null)
+ throw new IOException("Unable to setup SSL context");
+
+ SSLSocket ssl = null;
+ try {
+ context.init(null, trustAllCerts, new SecureRandom());
+ SocketFactory factory = context.getSocketFactory();
+ ssl = (SSLSocket) factory.createSocket(host, port);
+ /* ssl.setSSLParameters(context.getDefaultSSLParameters()); */
+ } catch (IOException e) {
+ s_logger.error("IOException: " + e.getMessage(), e);
+ throw e;
+ } catch (KeyManagementException e) {
+ s_logger.error("KeyManagementException: " + e.getMessage(), e);
+ }
+ return ssl;
+ } else {
+ return new Socket(host, port);
+ }
+ }
+
+ public Socket connect() throws IOException {
+ String[] headers = makeHeaders();
+ s = _getSocket();
+ try {
+ oc = s.getOutputStream();
+ for (String header : headers) {
+ oc.write(header.getBytes());
+ oc.write("\r\n".getBytes());
+ }
+ oc.flush();
+ ic = s.getInputStream();
+ while (true) {
+ String line = readline(ic);
+
+ Matcher m = END_PATTERN.matcher(line);
+ if (m.matches()) {
+ return s;
+ }
+
+ m = HEADER_PATTERN.matcher(line);
+ if (m.matches()) {
+ responseHeaders.put(m.group(1), m.group(2));
+ continue;
+ }
+
+ m = HTTP_PATTERN.matcher(line);
+ if (m.matches()) {
+ String status_code = m.group(1);
+ String reason_phrase = m.group(2);
+ if (!"200".equals(status_code)) {
+ throw new IOException("HTTP status " + status_code
+ + " " + reason_phrase);
+ }
+ } else {
+ throw new IOException("Unknown HTTP line " + line);
+ }
+ }
+ } catch (IOException exn) {
+ s.close();
+ throw exn;
+ } catch (RuntimeException exn) {
+ s.close();
+ throw exn;
+ }
+ }
+
+ public Map<String, String> getResponseHeaders() {
+ return responseHeaders;
+ }
+
+ private String[] makeHeaders() {
+ String[] headers = { String.format("%s %s HTTP/1.0", command, path),
+ String.format("Host: %s", host),
+ String.format("Cookie: session_id=%s", session), "" };
+ return headers;
+ }
+
+ private static String readline(InputStream ic) throws IOException {
+ String result = "";
+ while (true) {
+ try {
+ int c = ic.read();
+
+ if (c == -1) {
+ return result;
+ }
+ result = result + (char) c;
+ if (c == 0x0a /* LF */) {
+ return result;
+ }
+ } catch (IOException e) {
+ ic.close();
+ throw e;
+ }
+ }
+ }
+
+ private SSLContext getClientSSLContext() {
+ SSLContext sslContext = null;
+ try {
+ sslContext = SSLContext.getInstance("SSL", "SunJSSE");
+ } catch (NoSuchAlgorithmException e) {
+ s_logger.error("Unexpected exception ", e);
+ } catch (NoSuchProviderException e) {
+ s_logger.error("Unexpected exception ", e);
+ }
+ return sslContext;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/util/Region.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/util/Region.java b/console-proxy/src/com/cloud/consoleproxy/util/Region.java
index a5860f3..a5d1751 100644
--- a/console-proxy/src/com/cloud/consoleproxy/util/Region.java
+++ b/console-proxy/src/com/cloud/consoleproxy/util/Region.java
@@ -14,77 +14,77 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy.util;
-
-import java.awt.Rectangle;
-import java.util.ArrayList;
-import java.util.List;
-
-public class Region {
- private Rectangle bound;
- private List<Rectangle> rectList;
-
- public Region() {
- bound = new Rectangle(0, 0, 0, 0);
- rectList = new ArrayList<Rectangle>();
- }
-
- public Region(Rectangle rect) {
- bound = new Rectangle(rect.x, rect.y, rect.width, rect.height);
- rectList = new ArrayList<Rectangle>();
- rectList.add(rect);
- }
-
- public Rectangle getBound() {
- return bound;
- }
-
- public void clearBound() {
- assert(rectList.size() == 0);
- bound.x = bound.y = bound.width = bound.height = 0;
- }
-
- public List<Rectangle> getRectangles() {
- return rectList;
- }
-
- public boolean add(Rectangle rect) {
- if(bound.isEmpty()) {
- assert(rectList.size() == 0);
- bound.x = rect.x;
- bound.y = rect.y;
- bound.width = rect.width;
- bound.height = rect.height;
-
- rectList.add(rect);
- return true;
- }
-
- Rectangle rcInflated = new Rectangle(rect.x - 1, rect.y- 1, rect.width + 2, rect.height + 2);
- if(!bound.intersects(rcInflated))
- return false;
-
- for(Rectangle r : rectList) {
- if(r.intersects(rcInflated)) {
- if(!r.contains(rect)) {
- enlargeBound(rect);
- rectList.add(rect);
- return true;
- }
- }
- }
- return false;
- }
-
- private void enlargeBound(Rectangle rect) {
- int boundLeft = Math.min(bound.x, rect.x);
- int boundTop = Math.min(bound.y, rect.y);
- int boundRight = Math.max(bound.x + bound.width, rect.x + rect.width);
- int boundBottom = Math.max(bound.y + bound.height, rect.y + rect.height);
-
- bound.x = boundLeft;
- bound.y = boundTop;
- bound.width = boundRight - boundLeft;
- bound.height = boundBottom - boundTop;
- }
-}
+package com.cloud.consoleproxy.util;
+
+import java.awt.Rectangle;
+import java.util.ArrayList;
+import java.util.List;
+
+public class Region {
+ private Rectangle bound;
+ private List<Rectangle> rectList;
+
+ public Region() {
+ bound = new Rectangle(0, 0, 0, 0);
+ rectList = new ArrayList<Rectangle>();
+ }
+
+ public Region(Rectangle rect) {
+ bound = new Rectangle(rect.x, rect.y, rect.width, rect.height);
+ rectList = new ArrayList<Rectangle>();
+ rectList.add(rect);
+ }
+
+ public Rectangle getBound() {
+ return bound;
+ }
+
+ public void clearBound() {
+ assert(rectList.size() == 0);
+ bound.x = bound.y = bound.width = bound.height = 0;
+ }
+
+ public List<Rectangle> getRectangles() {
+ return rectList;
+ }
+
+ public boolean add(Rectangle rect) {
+ if(bound.isEmpty()) {
+ assert(rectList.size() == 0);
+ bound.x = rect.x;
+ bound.y = rect.y;
+ bound.width = rect.width;
+ bound.height = rect.height;
+
+ rectList.add(rect);
+ return true;
+ }
+
+ Rectangle rcInflated = new Rectangle(rect.x - 1, rect.y- 1, rect.width + 2, rect.height + 2);
+ if(!bound.intersects(rcInflated))
+ return false;
+
+ for(Rectangle r : rectList) {
+ if(r.intersects(rcInflated)) {
+ if(!r.contains(rect)) {
+ enlargeBound(rect);
+ rectList.add(rect);
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private void enlargeBound(Rectangle rect) {
+ int boundLeft = Math.min(bound.x, rect.x);
+ int boundTop = Math.min(bound.y, rect.y);
+ int boundRight = Math.max(bound.x + bound.width, rect.x + rect.width);
+ int boundBottom = Math.max(bound.y + bound.height, rect.y + rect.height);
+
+ bound.x = boundLeft;
+ bound.y = boundTop;
+ bound.width = boundRight - boundLeft;
+ bound.height = boundBottom - boundTop;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/util/RegionClassifier.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/util/RegionClassifier.java b/console-proxy/src/com/cloud/consoleproxy/util/RegionClassifier.java
index c4d9b82..9faa04e 100644
--- a/console-proxy/src/com/cloud/consoleproxy/util/RegionClassifier.java
+++ b/console-proxy/src/com/cloud/consoleproxy/util/RegionClassifier.java
@@ -14,45 +14,45 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy.util;
-
-import java.awt.Rectangle;
-import java.util.ArrayList;
-import java.util.List;
-
-public class RegionClassifier {
- private List<Region> regionList;
-
- public RegionClassifier() {
- regionList = new ArrayList<Region>();
- }
-
- public void add(Rectangle rect) {
- boolean newRegion = true;
- Rectangle rcInflated = new Rectangle(rect.x - 1, rect.y - 1, rect.width + 2, rect.height + 2);
- for(Region region : regionList) {
- if(region.getBound().intersects(rcInflated)) {
- newRegion = false;
- break;
- }
- }
-
- if(newRegion) {
- regionList.add(new Region(rect));
- } else {
- for(Region region : regionList) {
- if(region.add(rect))
- return;
- }
- regionList.add(new Region(rect));
- }
- }
-
- public List<Region> getRegionList() {
- return regionList;
- }
-
- public void clear() {
- regionList.clear();
- }
-}
+package com.cloud.consoleproxy.util;
+
+import java.awt.Rectangle;
+import java.util.ArrayList;
+import java.util.List;
+
+public class RegionClassifier {
+ private List<Region> regionList;
+
+ public RegionClassifier() {
+ regionList = new ArrayList<Region>();
+ }
+
+ public void add(Rectangle rect) {
+ boolean newRegion = true;
+ Rectangle rcInflated = new Rectangle(rect.x - 1, rect.y - 1, rect.width + 2, rect.height + 2);
+ for(Region region : regionList) {
+ if(region.getBound().intersects(rcInflated)) {
+ newRegion = false;
+ break;
+ }
+ }
+
+ if(newRegion) {
+ regionList.add(new Region(rect));
+ } else {
+ for(Region region : regionList) {
+ if(region.add(rect))
+ return;
+ }
+ regionList.add(new Region(rect));
+ }
+ }
+
+ public List<Region> getRegionList() {
+ return regionList;
+ }
+
+ public void clear() {
+ regionList.clear();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/util/TileInfo.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/util/TileInfo.java b/console-proxy/src/com/cloud/consoleproxy/util/TileInfo.java
index 728f07a..933a55a 100644
--- a/console-proxy/src/com/cloud/consoleproxy/util/TileInfo.java
+++ b/console-proxy/src/com/cloud/consoleproxy/util/TileInfo.java
@@ -14,42 +14,42 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy.util;
-
-import java.awt.Rectangle;
-
-public class TileInfo {
- private int row;
- private int col;
- private Rectangle tileRect;
-
- public TileInfo(int row, int col, Rectangle tileRect) {
- this.row = row;
- this.col = col;
- this.tileRect = tileRect;
- }
-
- public int getRow() {
- return row;
- }
-
- public void setRow(int row) {
- this.row = row;
- }
-
- public int getCol() {
- return col;
- }
-
- public void setCol(int col) {
- this.col = col;
- }
-
- public Rectangle getTileRect() {
- return tileRect;
- }
-
- public void setTileRect(Rectangle tileRect) {
- this.tileRect = tileRect;
- }
-}
+package com.cloud.consoleproxy.util;
+
+import java.awt.Rectangle;
+
+public class TileInfo {
+ private int row;
+ private int col;
+ private Rectangle tileRect;
+
+ public TileInfo(int row, int col, Rectangle tileRect) {
+ this.row = row;
+ this.col = col;
+ this.tileRect = tileRect;
+ }
+
+ public int getRow() {
+ return row;
+ }
+
+ public void setRow(int row) {
+ this.row = row;
+ }
+
+ public int getCol() {
+ return col;
+ }
+
+ public void setCol(int col) {
+ this.col = col;
+ }
+
+ public Rectangle getTileRect() {
+ return tileRect;
+ }
+
+ public void setTileRect(Rectangle tileRect) {
+ this.tileRect = tileRect;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/0bf8c5a1/console-proxy/src/com/cloud/consoleproxy/util/TileTracker.java
----------------------------------------------------------------------
diff --git a/console-proxy/src/com/cloud/consoleproxy/util/TileTracker.java b/console-proxy/src/com/cloud/consoleproxy/util/TileTracker.java
index 350eebf..b3facb2 100644
--- a/console-proxy/src/com/cloud/consoleproxy/util/TileTracker.java
+++ b/console-proxy/src/com/cloud/consoleproxy/util/TileTracker.java
@@ -14,256 +14,256 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-package com.cloud.consoleproxy.util;
-
-import java.awt.Rectangle;
-import java.util.ArrayList;
-import java.util.List;
-
-public class TileTracker {
-
- // 2 dimension tile status snapshot, a true value means the corresponding tile has been invalidated
- private boolean[][] snapshot;
-
- private int tileWidth = 0;
- private int tileHeight = 0;
- private int trackWidth = 0;
- private int trackHeight = 0;
-
- public TileTracker() {
- }
-
- public int getTileWidth() {
- return tileWidth;
- }
-
- public void setTileWidth(int tileWidth) {
- this.tileWidth = tileWidth;
- }
-
- public int getTileHeight() {
- return tileHeight;
- }
-
- public void setTileHeight(int tileHeight) {
- this.tileHeight = tileHeight;
- }
-
- public int getTrackWidth() {
- return trackWidth;
- }
-
- public void setTrackWidth(int trackWidth) {
- this.trackWidth = trackWidth;
- }
-
- public int getTrackHeight() {
- return trackHeight;
- }
-
- public void setTrackHeight(int trackHeight) {
- this.trackHeight = trackHeight;
- }
-
- public void initTracking(int tileWidth, int tileHeight, int trackWidth, int trackHeight) {
- assert(tileWidth > 0);
- assert(tileHeight > 0);
- assert(trackWidth > 0);
- assert(trackHeight > 0);
- assert(tileWidth <= trackWidth);
- assert(tileHeight <= trackHeight);
-
- this.tileWidth = tileWidth;
- this.tileHeight = tileHeight;
- this.trackWidth = trackWidth;
- this.trackHeight = trackHeight;
-
- int cols = getTileCols();
- int rows = getTileRows();
- snapshot = new boolean[rows][cols];
- for(int i = 0; i < rows; i++)
- for(int j = 0; j < cols; j++)
- snapshot[i][j] = false;
- }
-
- public synchronized void resize(int trackWidth, int trackHeight) {
- assert(tileWidth > 0);
- assert(tileHeight > 0);
- assert(trackWidth > 0);
- assert(trackHeight > 0);
-
- this.trackWidth = trackWidth;
- this.trackHeight = trackHeight;
-
- int cols = getTileCols();
- int rows = getTileRows();
- snapshot = new boolean[rows][cols];
- for(int i = 0; i < rows; i++)
- for(int j = 0; j < cols; j++)
- snapshot[i][j] = true;
- }
-
- public void invalidate(Rectangle rect) {
- setTileFlag(rect, true);
- }
-
- public void validate(Rectangle rect) {
- setTileFlag(rect, false);
- }
-
- public List<TileInfo> scan(boolean init) {
- List<TileInfo> l = new ArrayList<TileInfo>();
-
- synchronized(this) {
- for(int i = 0; i < getTileRows(); i++) {
- for(int j = 0; j < getTileCols(); j++) {
- if(init || snapshot[i][j]) {
- Rectangle rect = new Rectangle();
- rect.y = i*tileHeight;
- rect.x = j*tileWidth;
- rect.width = Math.min(trackWidth - rect.x, tileWidth);
- rect.height = Math.min(trackHeight - rect.y, tileHeight);
-
- l.add(new TileInfo(i, j, rect));
- snapshot[i][j] = false;
- }
- }
- }
-
- return l;
- }
- }
-
- public boolean hasFullCoverage() {
- synchronized(this) {
- for(int i = 0; i < getTileRows(); i++) {
- for(int j = 0; j < getTileCols(); j++) {
- if(!snapshot[i][j])
- return false;
- }
- }
- }
- return true;
- }
-
-
-
- public void initCoverageTest() {
- synchronized(this) {
- for(int i = 0; i < getTileRows(); i++) {
- for(int j = 0; j < getTileCols(); j++) {
- snapshot[i][j] = false;
- }
- }
- }
- }
-
- // listener will be called while holding the object lock, use it
- // with care to avoid deadlock condition being formed
- public synchronized void scan(int nStartRow, int nStartCol, ITileScanListener listener) {
- assert(listener != null);
-
- int cols = getTileCols();
- int rows = getTileRows();
-
- nStartRow = nStartRow % rows;
- nStartCol = nStartCol % cols;
-
- int nPos = nStartRow*cols + nStartCol;
- int nUnits = rows*cols;
- int nStartPos = nPos;
- int nRow;
- int nCol;
- do {
- nRow = nPos / cols;
- nCol = nPos % cols;
-
- if(snapshot[nRow][nCol]) {
- int nEndCol = nCol;
- for(; nEndCol < cols && snapshot[nRow][nEndCol]; nEndCol++) {
- snapshot[nRow][nEndCol] = false;
- }
-
- Rectangle rect = new Rectangle();
- rect.y = nRow*tileHeight;
- rect.height = tileHeight;
- rect.x = nCol*tileWidth;
- rect.width = (nEndCol - nCol)*tileWidth;
-
- if(!listener.onTileChange(rect, nRow, nEndCol))
- break;
- }
-
- nPos = (nPos + 1) % nUnits;
- } while(nPos != nStartPos);
- }
-
- public void capture(ITileScanListener listener) {
- assert(listener != null);
-
- int cols = getTileCols();
- int rows = getTileRows();
-
- RegionClassifier classifier = new RegionClassifier();
- int left, top, right, bottom;
-
- synchronized(this) {
- for(int i = 0; i < rows; i++) {
- top = i*tileHeight;
- bottom = Math.min(top + tileHeight, trackHeight);
- for(int j = 0; j < cols; j++) {
- left = j*tileWidth;
- right = Math.min(left + tileWidth, trackWidth);
-
- if(snapshot[i][j]) {
- snapshot[i][j] = false;
- classifier.add(new Rectangle(left, top, right - left, bottom - top));
- }
- }
- }
- }
- listener.onRegionChange(classifier.getRegionList());
- }
-
- private synchronized void setTileFlag(Rectangle rect, boolean flag) {
- int nStartTileRow;
- int nStartTileCol;
- int nEndTileRow;
- int nEndTileCol;
-
- int cols = getTileCols();
- int rows = getTileRows();
-
- if(rect != null) {
- nStartTileRow = Math.min(getTileYPos(rect.y), rows - 1);
- nStartTileCol = Math.min(getTileXPos(rect.x), cols - 1);
- nEndTileRow = Math.min(getTileYPos(rect.y + rect.height - 1), rows -1);
- nEndTileCol = Math.min(getTileXPos(rect.x + rect.width - 1), cols -1);
- } else {
- nStartTileRow = 0;
- nStartTileCol = 0;
- nEndTileRow = rows - 1;
- nEndTileCol = cols - 1;
- }
-
- for(int i = nStartTileRow; i <= nEndTileRow; i++)
- for(int j = nStartTileCol; j <= nEndTileCol; j++)
- snapshot[i][j] = flag;
- }
-
- private int getTileRows() {
- return (trackHeight + tileHeight - 1) / tileHeight;
- }
-
- private int getTileCols() {
- return (trackWidth + tileWidth - 1) / tileWidth;
- }
-
- private int getTileXPos(int x) {
- return x / tileWidth;
- }
-
- public int getTileYPos(int y) {
- return y / tileHeight;
- }
-}
+package com.cloud.consoleproxy.util;
+
+import java.awt.Rectangle;
+import java.util.ArrayList;
+import java.util.List;
+
+public class TileTracker {
+
+ // 2 dimension tile status snapshot, a true value means the corresponding tile has been invalidated
+ private boolean[][] snapshot;
+
+ private int tileWidth = 0;
+ private int tileHeight = 0;
+ private int trackWidth = 0;
+ private int trackHeight = 0;
+
+ public TileTracker() {
+ }
+
+ public int getTileWidth() {
+ return tileWidth;
+ }
+
+ public void setTileWidth(int tileWidth) {
+ this.tileWidth = tileWidth;
+ }
+
+ public int getTileHeight() {
+ return tileHeight;
+ }
+
+ public void setTileHeight(int tileHeight) {
+ this.tileHeight = tileHeight;
+ }
+
+ public int getTrackWidth() {
+ return trackWidth;
+ }
+
+ public void setTrackWidth(int trackWidth) {
+ this.trackWidth = trackWidth;
+ }
+
+ public int getTrackHeight() {
+ return trackHeight;
+ }
+
+ public void setTrackHeight(int trackHeight) {
+ this.trackHeight = trackHeight;
+ }
+
+ public void initTracking(int tileWidth, int tileHeight, int trackWidth, int trackHeight) {
+ assert(tileWidth > 0);
+ assert(tileHeight > 0);
+ assert(trackWidth > 0);
+ assert(trackHeight > 0);
+ assert(tileWidth <= trackWidth);
+ assert(tileHeight <= trackHeight);
+
+ this.tileWidth = tileWidth;
+ this.tileHeight = tileHeight;
+ this.trackWidth = trackWidth;
+ this.trackHeight = trackHeight;
+
+ int cols = getTileCols();
+ int rows = getTileRows();
+ snapshot = new boolean[rows][cols];
+ for(int i = 0; i < rows; i++)
+ for(int j = 0; j < cols; j++)
+ snapshot[i][j] = false;
+ }
+
+ public synchronized void resize(int trackWidth, int trackHeight) {
+ assert(tileWidth > 0);
+ assert(tileHeight > 0);
+ assert(trackWidth > 0);
+ assert(trackHeight > 0);
+
+ this.trackWidth = trackWidth;
+ this.trackHeight = trackHeight;
+
+ int cols = getTileCols();
+ int rows = getTileRows();
+ snapshot = new boolean[rows][cols];
+ for(int i = 0; i < rows; i++)
+ for(int j = 0; j < cols; j++)
+ snapshot[i][j] = true;
+ }
+
+ public void invalidate(Rectangle rect) {
+ setTileFlag(rect, true);
+ }
+
+ public void validate(Rectangle rect) {
+ setTileFlag(rect, false);
+ }
+
+ public List<TileInfo> scan(boolean init) {
+ List<TileInfo> l = new ArrayList<TileInfo>();
+
+ synchronized(this) {
+ for(int i = 0; i < getTileRows(); i++) {
+ for(int j = 0; j < getTileCols(); j++) {
+ if(init || snapshot[i][j]) {
+ Rectangle rect = new Rectangle();
+ rect.y = i*tileHeight;
+ rect.x = j*tileWidth;
+ rect.width = Math.min(trackWidth - rect.x, tileWidth);
+ rect.height = Math.min(trackHeight - rect.y, tileHeight);
+
+ l.add(new TileInfo(i, j, rect));
+ snapshot[i][j] = false;
+ }
+ }
+ }
+
+ return l;
+ }
+ }
+
+ public boolean hasFullCoverage() {
+ synchronized(this) {
+ for(int i = 0; i < getTileRows(); i++) {
+ for(int j = 0; j < getTileCols(); j++) {
+ if(!snapshot[i][j])
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+
+
+ public void initCoverageTest() {
+ synchronized(this) {
+ for(int i = 0; i < getTileRows(); i++) {
+ for(int j = 0; j < getTileCols(); j++) {
+ snapshot[i][j] = false;
+ }
+ }
+ }
+ }
+
+ // listener will be called while holding the object lock, use it
+ // with care to avoid deadlock condition being formed
+ public synchronized void scan(int nStartRow, int nStartCol, ITileScanListener listener) {
+ assert(listener != null);
+
+ int cols = getTileCols();
+ int rows = getTileRows();
+
+ nStartRow = nStartRow % rows;
+ nStartCol = nStartCol % cols;
+
+ int nPos = nStartRow*cols + nStartCol;
+ int nUnits = rows*cols;
+ int nStartPos = nPos;
+ int nRow;
+ int nCol;
+ do {
+ nRow = nPos / cols;
+ nCol = nPos % cols;
+
+ if(snapshot[nRow][nCol]) {
+ int nEndCol = nCol;
+ for(; nEndCol < cols && snapshot[nRow][nEndCol]; nEndCol++) {
+ snapshot[nRow][nEndCol] = false;
+ }
+
+ Rectangle rect = new Rectangle();
+ rect.y = nRow*tileHeight;
+ rect.height = tileHeight;
+ rect.x = nCol*tileWidth;
+ rect.width = (nEndCol - nCol)*tileWidth;
+
+ if(!listener.onTileChange(rect, nRow, nEndCol))
+ break;
+ }
+
+ nPos = (nPos + 1) % nUnits;
+ } while(nPos != nStartPos);
+ }
+
+ public void capture(ITileScanListener listener) {
+ assert(listener != null);
+
+ int cols = getTileCols();
+ int rows = getTileRows();
+
+ RegionClassifier classifier = new RegionClassifier();
+ int left, top, right, bottom;
+
+ synchronized(this) {
+ for(int i = 0; i < rows; i++) {
+ top = i*tileHeight;
+ bottom = Math.min(top + tileHeight, trackHeight);
+ for(int j = 0; j < cols; j++) {
+ left = j*tileWidth;
+ right = Math.min(left + tileWidth, trackWidth);
+
+ if(snapshot[i][j]) {
+ snapshot[i][j] = false;
+ classifier.add(new Rectangle(left, top, right - left, bottom - top));
+ }
+ }
+ }
+ }
+ listener.onRegionChange(classifier.getRegionList());
+ }
+
+ private synchronized void setTileFlag(Rectangle rect, boolean flag) {
+ int nStartTileRow;
+ int nStartTileCol;
+ int nEndTileRow;
+ int nEndTileCol;
+
+ int cols = getTileCols();
+ int rows = getTileRows();
+
+ if(rect != null) {
+ nStartTileRow = Math.min(getTileYPos(rect.y), rows - 1);
+ nStartTileCol = Math.min(getTileXPos(rect.x), cols - 1);
+ nEndTileRow = Math.min(getTileYPos(rect.y + rect.height - 1), rows -1);
+ nEndTileCol = Math.min(getTileXPos(rect.x + rect.width - 1), cols -1);
+ } else {
+ nStartTileRow = 0;
+ nStartTileCol = 0;
+ nEndTileRow = rows - 1;
+ nEndTileCol = cols - 1;
+ }
+
+ for(int i = nStartTileRow; i <= nEndTileRow; i++)
+ for(int j = nStartTileCol; j <= nEndTileCol; j++)
+ snapshot[i][j] = flag;
+ }
+
+ private int getTileRows() {
+ return (trackHeight + tileHeight - 1) / tileHeight;
+ }
+
+ private int getTileCols() {
+ return (trackWidth + tileWidth - 1) / tileWidth;
+ }
+
+ private int getTileXPos(int x) {
+ return x / tileWidth;
+ }
+
+ public int getTileYPos(int y) {
+ return y / tileHeight;
+ }
+}