org.tizen.web.livereload_2.0.0.201311011708

16:50:42.408 INFO  jd.cli.Main - Decompiling org.tizen.web.livereload_2.0.0.201311011708.jar
package org.tizen.web.livereload;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractResourceProvider
  extends Observable
  implements IResourceProvider
{
  protected final Logger logger = LoggerFactory.getLogger(getClass());
  protected IResourceProvider parent;
  protected final ArrayList<Observer> observers = new ArrayList();
  
  public void setParent(IResourceProvider parent)
  {
    this.parent = parent;
  }
  
  public void addObserver(Observer observer)
  {
    super.addObserver(observer);
    observers.add(observer);
  }
  
  public long getSize(String path)
    throws IOException
  {
    byte[] bytes = get(path);
    if (bytes == null) {
      return -1L;
    }
    return bytes.length;
  }
  
  public InputStream getContents(String path)
    throws IOException
  {
    byte[] bytes = get(path);
    if (bytes == null) {
      return null;
    }
    return new ByteArrayInputStream(bytes);
  }
  
  protected abstract byte[] get(String paramString)
    throws IOException;
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.AbstractResourceProvider
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload;

import java.io.IOException;
import java.io.InputStream;
import java.util.Observer;

public abstract interface IResourceProvider
{
  public abstract void setParent(IResourceProvider paramIResourceProvider);
  
  public abstract void addObserver(Observer paramObserver);
  
  public abstract long getSize(String paramString)
    throws IOException;
  
  public abstract InputStream getContents(String paramString)
    throws IOException;
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.IResourceProvider
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload;

import java.io.IOException;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.util.resource.Resource;

class LiveReload$1
  extends DefaultServlet
{
  private static final long serialVersionUID = 2320825957794195737L;
  
  LiveReload$1(LiveReload paramLiveReload) {}
  
  public Resource getResource(String pathInContext)
  {
    try
    {
      Resource resource = this$0.getVirtualResource(pathInContext);
      if (resource == null) {
        return super.getResource(pathInContext);
      }
      return resource;
    }
    catch (IOException localIOException) {}
    return super.getResource(pathInContext);
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.LiveReload.1
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload;

import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Observable;
import java.util.Observer;
import javax.servlet.Servlet;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.util.resource.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tizen.common.util.CollectionUtil;
import org.tizen.common.util.FilenameUtil;
import org.tizen.common.util.IOUtil;
import org.tizen.web.livereload.daemon.WebServer;
import org.tizen.web.livereload.servlet.LiveReloadSocketManager;
import org.tizen.web.livereload.servlet.VirtualResource;
import org.tizen.web.livereload.servlet.WebSocketMessage;
import org.tizen.web.livereload.util.CompositeInputStream;

public class LiveReload
  implements Observer, Closeable
{
  protected static final byte[] INJECTION = "<script>\nport = (location.port || location.host.split(':')[1] );\nif ( !port || port.length == 0 ) { portStr = ''; } else { portStr = ':' + port; }code = '<script src=\"http://'\n + (location.host || 'localhost').split(':')[0]\n + portStr  + '/livereload.js?snipver=1\"><\\/script>';\nconsole.log( code );\ndocument.write( code );\n</script>\n<style type=\"text/css\">[tizen-ide-status='selected'] {\n-moz-box-shadow:    inset 0 0 10px #000000;\n-webkit-box-shadow: inset 0 0 10px #000000;\nbox-shadow:         inset 0 0 10px #000000;\n}</style>"
  
    .getBytes();
  protected final Logger logger = LoggerFactory.getLogger(getClass());
  protected boolean bEnabled = true;
  protected WebServer webServer;
  protected DefaultServlet servlet = new DefaultServlet()
  {
    private static final long serialVersionUID = 2320825957794195737L;
    
    public Resource getResource(String pathInContext)
    {
      try
      {
        Resource resource = getVirtualResource(pathInContext);
        if (resource == null) {
          return super.getResource(pathInContext);
        }
        return resource;
      }
      catch (IOException localIOException) {}
      return super.getResource(pathInContext);
    }
  };
  protected byte[] livereload;
  protected HashSet<String> loaded = new HashSet();
  protected final LiveReloadSocketManager webSocketManager = new LiveReloadSocketManager();
  protected IResourceProvider resourceProvider;
  
  public synchronized byte[] getLiveReload()
    throws IOException
  {
    if (livereload == null)
    {
      String path = getClass().getPackage().getName().replace('.', '/') + "/livereload.js";
      InputStream in = getClass().getClassLoader().getResourceAsStream(path);
      livereload = IOUtil.getBytes(in, true);
    }
    return livereload;
  }
  
  public byte[] getLiveReloadInjection()
  {
    return INJECTION;
  }
  
  public WebServer getWebServer()
  {
    return webServer;
  }
  
  public void setWebServer(WebServer webServer)
  {
    this.webServer = webServer;
  }
  
  public LiveReloadSocketManager getSocketManager()
  {
    return webSocketManager;
  }
  
  public Servlet getServlet()
  {
    return servlet;
  }
  
  public void setEnabled(boolean bEnabled)
  {
    this.bEnabled = bEnabled;
  }
  
  public void update(Observable o, Object arg)
  {
    logger.trace("Observable: {}, Arg: {}", o, arg);
    if ((arg instanceof WebSocketMessage))
    {
      try
      {
        webSocketManager.broadcast((WebSocketMessage)arg);
      }
      catch (IOException e)
      {
        logger.error("Can't send request", e);
      }
      return;
    }
    if (arg == null)
    {
      loaded.clear();
      reload(null);
      return;
    }
    Collection<String> changed = (Collection)arg;
    
    logger.debug("changed :{}", changed);
    
    logger.debug("Before :{}", loaded);
    int before = loaded.size();
    for (String change : changed) {
      loaded.remove(FilenameUtil.getCanonicalForm(change));
    }
    logger.debug("After: {}", loaded);
    int after = loaded.size();
    if (before == after)
    {
      logger.info("No changed");
      return;
    }
    if (1 == changed.size()) {
      reload((String)CollectionUtil.pickupFirst(changed));
    } else {
      reload(null);
    }
  }
  
  public void reload(String path)
  {
    try
    {
      webSocketManager.reload(path);
      logger.info("Send reload request via websocket");
    }
    catch (IOException e)
    {
      logger.error("Can't send request", e);
    }
  }
  
  public Resource getVirtualResource(String path)
    throws IOException
  {
    logger.trace("Path :{}", path);
    if ("/livereload.js".equals(path))
    {
      logger.trace("Injection mode");
      return new VirtualResource(null, new ByteArrayInputStream(getLiveReload()), getLiveReload().length);
    }
    InputStream in = getVirtualResourceAsStream(path);
    
    loaded.add(FilenameUtil.getCanonicalForm(path));
    logger.debug("Added {}", path);
    if (in == null)
    {
      logger.debug("Resource[{}] not found", path);
      return null;
    }
    logger.debug("Resource[{}] found", path);
    if (path.endsWith(".html"))
    {
      byte[] suffix = bEnabled ? getLiveReloadInjection() : "".getBytes();
      return new VirtualResource(
        null, 
        new CompositeInputStream(Arrays.asList(new InputStream[] {
        in, new ByteArrayInputStream(suffix) })), 
        
        getVirtualResourceSize(path) + suffix.length);
    }
    return new VirtualResource(null, in, getVirtualResourceSize(path));
  }
  
  protected InputStream getVirtualResourceAsStream(String path)
    throws IOException
  {
    return resourceProvider.getContents(path);
  }
  
  protected long getVirtualResourceSize(String path)
    throws IOException
  {
    return Math.max(0L, resourceProvider.getSize(path));
  }
  
  public IResourceProvider getResourceProvider()
  {
    return resourceProvider;
  }
  
  public void setResourceProvider(IResourceProvider resourceProvider)
  {
    this.resourceProvider = resourceProvider;
    logger.info("Resource provider: {}", resourceProvider);
  }
  
  public void close()
    throws IOException
  {
    IOUtil.tryClose(
      new Object[] { webSocketManager });
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.LiveReload
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload;

import org.tizen.web.livereload.servlet.LiveReloadSocket;

public class LiveReloadEvent
{
  protected LiveReloadSocket socket;
  protected String magic;
  protected String message;
  
  public LiveReloadEvent(String magic, LiveReloadSocket socket, String message)
  {
    this.magic = magic;
    this.socket = socket;
    this.message = message;
  }
  
  public LiveReloadSocket getSocket()
  {
    return socket;
  }
  
  public void setSocket(LiveReloadSocket socket)
  {
    this.socket = socket;
  }
  
  public String getMagic()
  {
    return magic;
  }
  
  public void setMagic(String magic)
  {
    this.magic = magic;
  }
  
  public String getMessage()
  {
    return message;
  }
  
  public void setMessage(String message)
  {
    this.message = message;
  }
  
  public String toString()
  {
    return socket + ":" + magic + "-" + message;
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.LiveReloadEvent
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload;

import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.websocket.WebSocketFactory;
import org.tizen.common.FactoryWithArgument;
import org.tizen.web.livereload.daemon.WebServer;
import org.tizen.web.livereload.servlet.FrameInjector;

public class LiveReloadFactory
  implements FactoryWithArgument<LiveReload, IResourceProvider>
{
  public LiveReload create(IResourceProvider resources)
  {
    LiveReload livereload = new LiveReload();
    FrameInjector injector = new FrameInjector(new WebSocketFactory(livereload.getSocketManager()));
    livereload.setResourceProvider(resources);
    resources.addObserver(livereload);
    Resource.setDefaultUseCaches(false);
    
    injector.setContextPath("/");
    injector.addServlet(new ServletHolder(livereload.getServlet()), "/*");
    WebServer server = new WebServer(injector);
    livereload.setWebServer(server);
    return livereload;
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.LiveReloadFactory
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload;

public abstract interface LiveReloadListener
{
  public abstract void onAccepted(LiveReloadEvent paramLiveReloadEvent);
  
  public abstract void onConnected(LiveReloadEvent paramLiveReloadEvent);
  
  public abstract void onMessage(LiveReloadEvent paramLiveReloadEvent);
  
  public abstract void onDisconnect(LiveReloadEvent paramLiveReloadEvent);
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.LiveReloadListener
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload.daemon;

class DirectoryObserver$FileInfo
{
  long loadedTime;
  long size;
  
  DirectoryObserver$FileInfo(DirectoryObserver paramDirectoryObserver) {}
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.daemon.DirectoryObserver.FileInfo
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload.daemon;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Observer;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.tizen.common.daemon.AbstractServer;
import org.tizen.common.daemon.ServerException;
import org.tizen.common.util.FilenameUtil;
import org.tizen.common.util.ThreadUtil;
import org.tizen.web.livereload.IResourceProvider;

public class DirectoryObserver
  extends AbstractServer
  implements IResourceProvider
{
  protected static final long INTERVAL = 500L;
  protected static final long TIMEOUT = 1000L;
  protected IResourceProvider parent;
  protected final File root;
  protected HashMap<File, FileInfo> file2contents = new HashMap();
  protected Set<Observer> observers = new HashSet();
  
  public DirectoryObserver(File root)
  {
    super("Direcotry Monitor");
    this.root = root;
  }
  
  public void setParent(IResourceProvider parent)
  {
    this.parent = parent;
  }
  
  protected void initialize()
    throws ServerException
  {
    logger.info("File monitoring start");
  }
  
  protected void check(File file, Set<File> checked, Set<File> modified)
  {
    checked.add(file);
    if (file.isDirectory())
    {
      long fileModifiedTime = file.lastModified();
      FileInfo info = (FileInfo)file2contents.get(file);
      if (!file.equals(root)) {
        if (info == null)
        {
          info = new FileInfo();
          loadedTime = fileModifiedTime;
          file2contents.put(file, info);
          modified.add(file);
        }
        else if (loadedTime < fileModifiedTime)
        {
          loadedTime = fileModifiedTime;
          modified.add(file);
        }
      }
      File[] arrayOfFile;
      int j = (arrayOfFile = file.listFiles()).length;
      for (int i = 0; i < j; i++)
      {
        File child = arrayOfFile[i];
        
        check(child, checked, modified);
      }
    }
    else
    {
      long fileModifiedTime = file.lastModified();
      FileInfo info = (FileInfo)file2contents.get(file);
      if (info == null)
      {
        info = new FileInfo();
        loadedTime = fileModifiedTime;
        file2contents.put(file, info);
        modified.add(file);
      }
      else if (loadedTime < fileModifiedTime)
      {
        loadedTime = fileModifiedTime;
        modified.add(file);
      }
    }
  }
  
  protected void process()
    throws Exception
  {
    logger.trace("File monitoring start");
    
    HashSet<File> checked = new HashSet();
    HashSet<File> modified = new HashSet();
    
    check(root, checked, modified);
    
    HashSet<File> deleted = new HashSet(file2contents.keySet());
    deleted.removeAll(checked);
    for (File f : deleted) {
      file2contents.remove(f);
    }
    modified.addAll(deleted);
    if (modified.isEmpty()) {
      return;
    }
    TreeSet<String> changed = new TreeSet();
    String rootPath = root.getCanonicalPath();
    for (File f : modified)
    {
      String path = f.getCanonicalPath();
      if (rootPath != path) {
        changed.add(FilenameUtil.getRelativePath(rootPath, path));
      }
    }
    logger.debug("Change :\n{}", changed);
    notifyChanged(changed);
    
    ThreadUtil.trySleep(500L);
  }
  
  public long getSize(String path)
    throws IOException
  {
    logger.trace("Path :{}", path);
    
    File file = new File(root, path);
    FileInfo info = (FileInfo)file2contents.get(file);
    logger.debug("File info :{}", info);
    if (info != null) {
      return size;
    }
    logger.debug("File {} - exist :{}, readability :{}, file :{}", new Object[] { file, Boolean.valueOf(file.exists()), Boolean.valueOf(file.canRead()), Boolean.valueOf(file.isFile()) });
    long end = System.currentTimeMillis() + 1000L;
    while ((!file.exists()) || (!file.canRead()))
    {
      if (System.currentTimeMillis() < end) {
        return -1L;
      }
      ThreadUtil.trySleep(100L);
    }
    if (file.isDirectory())
    {
      file = new File(file, "index.html");
      if ((!file.exists()) || (!file.isFile())) {
        return file.length();
      }
    }
    info = new FileInfo();
    loadedTime = file.lastModified();
    size = file.length();
    file2contents.put(file, info);
    
    return size;
  }
  
  public synchronized InputStream getContents(String path)
    throws IOException
  {
    logger.trace("Path :{}", path);
    
    File file = new File(root, path);
    FileInfo info = (FileInfo)file2contents.get(file);
    logger.debug("File info :{}", info);
    
    logger.debug("File {} - exist :{}, readability :{}, file :{}", new Object[] { file, Boolean.valueOf(file.exists()), Boolean.valueOf(file.canRead()), Boolean.valueOf(file.isFile()) });
    long end = System.currentTimeMillis() + 1000L;
    while ((!file.exists()) || (!file.canRead()))
    {
      if (System.currentTimeMillis() < end) {
        return null;
      }
      ThreadUtil.trySleep(100L);
    }
    if (file.isDirectory())
    {
      file = new File(file, "index.html");
      if ((!file.exists()) || (!file.isFile())) {
        return null;
      }
    }
    info = new FileInfo();
    loadedTime = file.lastModified();
    size = file.length();
    file2contents.put(file, info);
    
    return new FileInputStream(file);
  }
  
  protected void terminate() {}
  
  public void addObserver(Observer observer)
  {
    observers.add(observer);
  }
  
  protected void notifyChanged(Collection<String> modified)
  {
    for (Observer observer : observers) {
      observer.update(null, modified);
    }
    logger.info("Changed notified to {} observers", Integer.valueOf(observers.size()));
  }
  
  class FileInfo
  {
    long loadedTime;
    long size;
    
    FileInfo() {}
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.daemon.DirectoryObserver
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload.daemon;

import java.util.concurrent.locks.Lock;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.component.LifeCycle.Listener;
import org.slf4j.Logger;
import org.tizen.common.daemon.AbstractServer;
import org.tizen.common.daemon.ServerException;

public class WebServer
  extends AbstractServer
  implements org.tizen.common.daemon.Server, LifeCycle.Listener
{
  protected Connector connector;
  protected org.eclipse.jetty.server.Server server;
  protected int port = 0;
  protected Handler handler;
  
  public WebServer(Handler handler)
  {
    this.handler = handler;
    logger.info("Handler :{}", this.handler);
  }
  
  public int getPort()
  {
    lock.lock();
    try
    {
      int i;
      if ((connector != null) && (connector.isStarted())) {
        return connector.getLocalPort();
      }
      return port;
    }
    finally
    {
      lock.unlock();
    }
  }
  
  /* Error */
  public void setPort(int port)
  {
    // Byte code:
    //   0: aload_0
    //   1: getfield 45	org/tizen/web/livereload/daemon/WebServer:lock	Ljava/util/concurrent/locks/Lock;
    //   4: invokeinterface 49 1 0
    //   9: aload_0
    //   10: iconst_1
    //   11: anewarray 72	org/tizen/common/daemon/ServerState
    //   14: dup
    //   15: iconst_0
    //   16: getstatic 74	org/tizen/common/daemon/ServerState:Terminated	Lorg/tizen/common/daemon/ServerState;
    //   19: aastore
    //   20: invokevirtual 78	org/tizen/web/livereload/daemon/WebServer:isState	([Lorg/tizen/common/daemon/ServerState;)Z
    //   23: ifne +11 -> 34
    //   26: new 82	java/lang/IllegalStateException
    //   29: dup
    //   30: invokespecial 84	java/lang/IllegalStateException:<init>	()V
    //   33: athrow
    //   34: aload_0
    //   35: iload_1
    //   36: putfield 23	org/tizen/web/livereload/daemon/WebServer:port	I
    //   39: aload_0
    //   40: getfield 27	org/tizen/web/livereload/daemon/WebServer:logger	Lorg/slf4j/Logger;
    //   43: ldc 85
    //   45: iload_1
    //   46: invokestatic 87	java/lang/Integer:valueOf	(I)Ljava/lang/Integer;
    //   49: invokeinterface 33 3 0
    //   54: goto +15 -> 69
    //   57: astore_2
    //   58: aload_0
    //   59: getfield 45	org/tizen/web/livereload/daemon/WebServer:lock	Ljava/util/concurrent/locks/Lock;
    //   62: invokeinterface 64 1 0
    //   67: aload_2
    //   68: athrow
    //   69: aload_0
    //   70: getfield 45	org/tizen/web/livereload/daemon/WebServer:lock	Ljava/util/concurrent/locks/Lock;
    //   73: invokeinterface 64 1 0
    //   78: return
    // Line number table:
    //   Java source line #131	-> byte code offset #0
    //   Java source line #134	-> byte code offset #9
    //   Java source line #136	-> byte code offset #26
    //   Java source line #139	-> byte code offset #34
    //   Java source line #140	-> byte code offset #39
    //   Java source line #143	-> byte code offset #57
    //   Java source line #144	-> byte code offset #58
    //   Java source line #145	-> byte code offset #67
    //   Java source line #144	-> byte code offset #69
    //   Java source line #147	-> byte code offset #78
    // Local variable table:
    //   start	length	slot	name	signature
    //   0	79	0	this	WebServer
    //   0	79	1	port	int
    //   57	11	2	localObject	Object
    // Exception table:
    //   from	to	target	type
    //   9	57	57	finally
  }
  
  public Handler getHandler()
  {
    return handler;
  }
  
  protected void initialize()
    throws ServerException
  {
    try
    {
      connector = new SelectChannelConnector();
      connector.setPort(port);
      server = new org.eclipse.jetty.server.Server();
      server.addLifeCycleListener(this);
      server.setConnectors(new Connector[] { connector });
      
      server.setHandler(handler);
      server.start();
      while (!server.isRunning()) {
        synchronized (this)
        {
          wait(1000L);
        }
      }
      logger.info("webserver initialized");
    }
    catch (Exception e)
    {
      throw new ServerException(e);
    }
  }
  
  protected void process()
    throws Exception
  {}
  
  protected void terminate()
  {
    try
    {
      server.stop();
      logger.info("webserver terminated");
    }
    catch (Exception e)
    {
      logger.trace(e.getMessage());
    }
  }
  
  public void lifeCycleStarting(LifeCycle paramLifeCycle)
  {
    logger.debug("lifecycle starting");
    synchronized (this)
    {
      notifyAll();
    }
  }
  
  public void lifeCycleStarted(LifeCycle paramLifeCycle)
  {
    logger.debug("lifecycle started");
    synchronized (this)
    {
      notifyAll();
    }
  }
  
  public void lifeCycleFailure(LifeCycle lifeCycle, Throwable throwable)
  {
    logger.debug("lifecycle failure", throwable);
    synchronized (this)
    {
      notifyAll();
    }
  }
  
  public void lifeCycleStopping(LifeCycle lifeCycle)
  {
    logger.debug("lifecycle stopping");
    synchronized (this)
    {
      notifyAll();
    }
  }
  
  public void lifeCycleStopped(LifeCycle lifeCycle)
  {
    logger.debug("lifecycle stopped");
    synchronized (this)
    {
      notifyAll();
    }
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.daemon.WebServer
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload.servlet;

import java.io.IOException;
import java.util.HashSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.websocket.WebSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FrameInjector
  extends ServletContextHandler
{
  protected final Logger logger = LoggerFactory.getLogger(getClass());
  protected final WebSocketFactory factory;
  protected final HashSet<String> loaded = new HashSet();
  
  public FrameInjector(WebSocketFactory factory)
  {
    super(0);
    
    this.factory = factory;
  }
  
  public void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
  {
    if ((factory.acceptWebSocket(request, response)) || (response.isCommitted()))
    {
      logger.info("Accept connection: {}", request.getPathInfo());
      baseRequest.setHandled(true);
      return;
    }
    String path = request.getPathInfo();
    if ((path.endsWith(".html")) || (path.endsWith(".htm"))) {
      response.setContentType("text/html");
    }
    super.doHandle(target, baseRequest, request, response);
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.servlet.FrameInjector
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload.servlet;

import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.eclipse.jetty.websocket.WebSocket.Connection;
import org.eclipse.jetty.websocket.WebSocket.OnTextMessage;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tizen.web.livereload.LiveReloadEvent;
import org.tizen.web.livereload.LiveReloadListener;

public class LiveReloadSocket
  implements WebSocket.OnTextMessage, Closeable
{
  protected final Logger logger = LoggerFactory.getLogger(getClass());
  protected final LiveReloadSocketManager manager;
  protected WebSocket.Connection con;
  protected ObjectMapper mapper = new ObjectMapper();
  protected String magic;
  
  public LiveReloadSocket(LiveReloadSocketManager manager)
  {
    Assert.assertNotNull(manager);
    this.manager = manager;
  }
  
  public void onOpen(WebSocket.Connection con)
  {
    logger.info("Connected :{}", con);
    manager.add(this);
    this.con = con;
  }
  
  public void onClose(int code, String message)
  {
    logger.info("Closed :{} - {}", Integer.valueOf(code), message);
    manager.remove(this, magic);
  }
  
  public void onMessage(String message)
  {
    try
    {
      logger.debug("Message :{}", message);
      
      JsonNode req = mapper.readTree(message);
      JsonNode commandNode = req.path("command");
      if (commandNode == null) {
        return;
      }
      LiveReloadEvent event;
      if ("hello".equals(commandNode.getTextValue()))
      {
        JsonNode magicNode = req.path("magic");
        magic = magicNode.getTextValue();
        
        logger.debug("Magic: {}", magic);
        WebSocketMessage res = new WebSocketMessage();
        res.setCommand("hello");
        res.setProtocols(Arrays.asList(new String[] { "http://livereload.com/protocols/official-7" }));
        res.setServerName("tizen-pic");
        send(res);
        manager.initialize(this);
        
        event = new LiveReloadEvent(magic, this, null);
        logger.debug(
          "Event: {}, Manager: {}, Listeners: {}", 
          new Object[] { event, manager, manager.listeners });
        for (LiveReloadListener listener : manager.listeners) {
          listener.onConnected(event);
        }
      }
      else
      {
        LiveReloadEvent event = new LiveReloadEvent(magic, this, message);
        for (LiveReloadListener listener : manager.listeners) {
          listener.onMessage(event);
        }
      }
    }
    catch (JsonParseException e)
    {
      logger.error("Exception occured:", e);
    }
    catch (JsonMappingException e)
    {
      logger.error("Exception occured:", e);
    }
    catch (IOException e)
    {
      logger.error("Exception occured:", e);
    }
  }
  
  public void send(WebSocketMessage message)
    throws IOException
  {
    send(mapper.writeValueAsString(message));
  }
  
  public void send(String message)
    throws IOException
  {
    logger.info("Send message :{}", message);
    con.sendMessage(message);
  }
  
  public void close()
    throws IOException
  {
    if (con != null) {
      con.close();
    }
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.servlet.LiveReloadSocket
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload.servlet;

import org.tizen.common.util.IOUtil;
import org.tizen.common.util.IteratingRunner;

class LiveReloadSocketManager$1
  implements IteratingRunner<LiveReloadSocket>
{
  LiveReloadSocketManager$1(LiveReloadSocketManager paramLiveReloadSocketManager) {}
  
  public void run(LiveReloadSocket socket)
  {
    IOUtil.tryClose(
      new Object[] { socket });
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.servlet.LiveReloadSocketManager.1
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload.servlet;

import org.tizen.common.util.IOUtil;
import org.tizen.common.util.IteratingRunner;

class LiveReloadSocketManager$2
  implements IteratingRunner<LiveReloadSocket>
{
  LiveReloadSocketManager$2(LiveReloadSocketManager paramLiveReloadSocketManager) {}
  
  public void run(LiveReloadSocket socket)
  {
    IOUtil.tryClose(
      new Object[] { socket });
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.servlet.LiveReloadSocketManager.2
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload.servlet;

import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import javax.servlet.http.HttpServletRequest;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketFactory.Acceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tizen.common.util.CollectionUtil;
import org.tizen.common.util.FilenameUtil;
import org.tizen.common.util.IOUtil;
import org.tizen.common.util.IteratingRunner;
import org.tizen.web.livereload.LiveReloadEvent;
import org.tizen.web.livereload.LiveReloadListener;

public class LiveReloadSocketManager
  implements WebSocketFactory.Acceptor, Closeable
{
  protected final Logger logger = LoggerFactory.getLogger(getClass());
  protected final HashSet<LiveReloadSocket> uninitializedSockets = new HashSet();
  protected final HashSet<LiveReloadSocket> sockets = new HashSet();
  protected final ObjectMapper mapper = new ObjectMapper();
  protected final ArrayList<LiveReloadListener> listeners = new ArrayList();
  
  public WebSocket doWebSocketConnect(HttpServletRequest req, String protocol)
  {
    logger.trace("Connection requested :{}, {}", req, protocol);
    LiveReloadSocket webSocket = new LiveReloadSocket(this);
    return webSocket;
  }
  
  public boolean checkOrigin(HttpServletRequest req, String protocol)
  {
    logger.trace("Check origin :{}, {}", req, protocol);
    return true;
  }
  
  synchronized void add(LiveReloadSocket socket)
  {
    logger.trace("Socket for livereload: {}", socket);
    uninitializedSockets.add(socket);
    
    LiveReloadEvent event = new LiveReloadEvent(null, socket, null);
    for (LiveReloadListener listener : listeners) {
      listener.onAccepted(event);
    }
  }
  
  synchronized void initialize(LiveReloadSocket socket)
  {
    if (uninitializedSockets.remove(socket)) {
      sockets.add(socket);
    }
  }
  
  void remove(LiveReloadSocket socket, String magic)
  {
    sockets.remove(socket);
    
    LiveReloadEvent event = new LiveReloadEvent(magic, socket, null);
    for (LiveReloadListener listener : listeners) {
      listener.onDisconnect(event);
    }
  }
  
  public Collection<LiveReloadSocket> getSockets()
  {
    return Collections.unmodifiableCollection(sockets);
  }
  
  public void reload(String path)
    throws JsonGenerationException, JsonMappingException, IOException
  {
    WebSocketMessage message = new WebSocketMessage();
    message.setCommand("reload");
    if (path != null) {
      message.setPath(FilenameUtil.getCanonicalForm(path));
    }
    message.setLiveCSS(true);
    message.setLiveJS(true);
    
    broadcast(message);
  }
  
  public void broadcast(WebSocketMessage message)
    throws IOException
  {
    for (LiveReloadSocket socket : sockets) {
      socket.send(message);
    }
  }
  
  public void addListener(LiveReloadListener listener)
  {
    listeners.add(listener);
    logger.info("{} added", listener);
  }
  
  public boolean removeListener(LiveReloadListener listener)
  {
    boolean bResult = listeners.remove(listener);
    
    logger.info("{} removed", listener);
    return bResult;
  }
  
  public void close()
    throws IOException
  {
    try
    {
      CollectionUtil.iterate(sockets, new IteratingRunner()
      {
        public void run(LiveReloadSocket socket)
        {
          IOUtil.tryClose(
            new Object[] { socket });
        }
      });
      CollectionUtil.iterate(uninitializedSockets, new IteratingRunner()
      {
        public void run(LiveReloadSocket socket)
        {
          IOUtil.tryClose(
            new Object[] { socket });
        }
      });
    }
    catch (InvocationTargetException e)
    {
      throw new IOException(e.getCause());
    }
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.servlet.LiveReloadSocketManager
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.eclipse.jetty.util.resource.Resource;

public class VirtualResource
  extends Resource
{
  protected final String name;
  protected final InputStream in;
  protected final long size;
  
  public VirtualResource(String name, InputStream in, long size)
  {
    this.name = name;
    this.in = in;
    this.size = size;
  }
  
  public boolean isContainedIn(Resource paramResource)
    throws MalformedURLException
  {
    return false;
  }
  
  public void release() {}
  
  public boolean exists()
  {
    return true;
  }
  
  public boolean isDirectory()
  {
    return false;
  }
  
  public long lastModified()
  {
    return -1L;
  }
  
  public long length()
  {
    return size;
  }
  
  public URL getURL()
  {
    return null;
  }
  
  public File getFile()
    throws IOException
  {
    return null;
  }
  
  public String getName()
  {
    return name;
  }
  
  public InputStream getInputStream()
    throws IOException
  {
    return in;
  }
  
  public OutputStream getOutputStream()
    throws IOException, SecurityException
  {
    return null;
  }
  
  public boolean delete()
    throws SecurityException
  {
    return false;
  }
  
  public boolean renameTo(Resource paramResource)
    throws SecurityException
  {
    return false;
  }
  
  public String[] list()
  {
    return null;
  }
  
  public Resource addPath(String paramString)
    throws IOException, MalformedURLException
  {
    return null;
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.servlet.VirtualResource
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload.servlet;

import java.util.List;

public class WebSocketMessage
{
  protected String command;
  protected List<String> protocols;
  protected String serverName;
  protected String magic;
  protected String path;
  protected String location;
  protected boolean liveCSS;
  protected boolean liveJS;
  
  public WebSocketMessage() {}
  
  public WebSocketMessage(String command)
  {
    this.command = command;
  }
  
  public String getCommand()
  {
    return command;
  }
  
  public void setCommand(String command)
  {
    this.command = command;
  }
  
  public List<String> getProtocols()
  {
    return protocols;
  }
  
  public void setProtocols(List<String> protocols)
  {
    this.protocols = protocols;
  }
  
  public String getServerName()
  {
    return serverName;
  }
  
  public void setServerName(String serverName)
  {
    this.serverName = serverName;
  }
  
  public String getPath()
  {
    return path;
  }
  
  public void setPath(String path)
  {
    this.path = path;
  }
  
  public String getLocation()
  {
    return location;
  }
  
  public void setLocation(String location)
  {
    this.location = location;
  }
  
  public boolean isLiveCSS()
  {
    return liveCSS;
  }
  
  public void setLiveCSS(boolean liveCSS)
  {
    this.liveCSS = liveCSS;
  }
  
  public boolean isLiveJS()
  {
    return liveJS;
  }
  
  public void setLiveJS(boolean liveJS)
  {
    this.liveJS = liveJS;
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.servlet.WebSocketMessage
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.tizen.web.livereload.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import org.tizen.common.util.IOUtil;

public class CompositeInputStream
  extends InputStream
{
  protected final Iterator<InputStream> iterator;
  protected InputStream in;
  
  public CompositeInputStream(InputStream... inputs)
  {
    this(Arrays.asList(inputs));
  }
  
  public CompositeInputStream(Collection<InputStream> collection)
  {
    this(collection.iterator());
  }
  
  public CompositeInputStream(Iterator<InputStream> iterator)
  {
    this.iterator = iterator;
  }
  
  public int read()
    throws IOException
  {
    if (iterator == null) {
      return -1;
    }
    while ((in != null) || (iterator.hasNext()))
    {
      if (in == null) {
        in = ((InputStream)iterator.next());
      }
      int ch = in.read();
      if (ch >= 0) {
        return ch;
      }
      IOUtil.tryClose(new Object[] {in });
      in = null;
    }
    return -1;
  }
  
  public void close()
    throws IOException
  {
    IOUtil.tryClose(
    
      new Object[] { in });
    if (iterator != null) {
      while (iterator.hasNext()) {
        IOUtil.tryClose(new Object[] {iterator.next() });
      }
    }
    super.close();
  }
}

/* Location:
 * Qualified Name:     org.tizen.web.livereload.util.CompositeInputStream
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
1

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd