org.tizen.common.sdblib_2.0.0.201310241620

16:49:52.382 INFO  jd.cli.Main - Decompiling org.tizen.common.sdblib_2.0.0.201310241620.jar
package org.tizen.sdblib;

public enum Arch
{
  X86(
  
    "86"),  ARM(
  
    "arm");
  
  private String arch;
  
  private Arch(String arch)
  {
    this.arch = arch;
  }
  
  public String getArch()
  {
    return arch;
  }
}

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

import java.io.IOException;
import java.nio.channels.AsynchronousCloseException;
import org.tizen.sdblib.command.Argument;
import org.tizen.sdblib.command.CommandFactory;
import org.tizen.sdblib.command.ICommandWithArgument;
import org.tizen.sdblib.command.ICommandWithArgument2;
import org.tizen.sdblib.command.Matcher;
import org.tizen.sdblib.command.MatcherFactory;
import org.tizen.sdblib.command.PatternExtractor;
import org.tizen.sdblib.daemon.ServerState;
import org.tizen.sdblib.exception.SdbCommandRejectedException;
import org.tizen.sdblib.exception.ServerException;
import org.tizen.sdblib.exception.ShellCommandUnresponsiveException;
import org.tizen.sdblib.exception.TimeoutException;
import org.tizen.sdblib.service.FileEntry;
import org.tizen.sdblib.service.FileEntryType;
import org.tizen.sdblib.service.SyncService;
import org.tizen.sdblib.util.Assert;
import org.tizen.sdblib.util.FilenameUtil;
import org.tizen.sdblib.util.ObjectUtil;
import org.tizen.sdblib.util.SdbShellProcess;
import org.tizen.sdblib.util.StreamGobbler;
import org.tizen.sdblib.util.StringUtil;

public class Device
  implements IDevice
{
  protected final DeviceMonitor monitor;
  protected final String serialNumber;
  protected DeviceState state;
  protected String deviceName;
  protected Arch arch = Arch.ARM;
  protected boolean bEmulator = false;
  protected String installPath;
  protected FileEntry root;
  
  Device(DeviceMonitor monitor, String serialNumber, DeviceState state)
  {
    this(monitor, serialNumber, state, null);
  }
  
  Device(DeviceMonitor monitor, String serialNumber, DeviceState state, String deviceName)
  {
    Assert.notNull(monitor);
    Assert.notNull(serialNumber);
    this.monitor = monitor;
    this.serialNumber = serialNumber;
    this.state = state;
    this.deviceName = deviceName;
  }
  
  public String getSerialNumber()
  {
    return serialNumber;
  }
  
  public String getDeviceName()
  {
    return deviceName;
  }
  
  public DeviceState getState()
  {
    return state;
  }
  
  void setState(DeviceState state)
  {
    this.state = state;
  }
  
  public Arch getArch()
  {
    return arch;
  }
  
  public boolean isEmulator()
  {
    return bEmulator;
  }
  
  public boolean isRoot()
  {
    return ((Boolean)CommandFactory.execute("whoami").in(this, MatcherFactory.equals("root"))).booleanValue();
  }
  
  public SyncService getSyncService()
    throws IOException
  {
    return new SyncService(SmartDevelopmentBridge.getBridge(), this);
  }
  
  public FileEntry getRoot()
  {
    if (root != null) {
      return root;
    }
    return root = new FileEntry(this, null, getDeviceName(), isEmulator() ? FileEntryType.RootEmulator : FileEntryType.RootDevice, null, null, null, null, null, null, null, null);
  }
  
  public FileEntry getFileEntry(String path)
  {
    return getCommonFileEntry(FilenameUtil.getCanonicalFragments(path));
  }
  
  public FileEntry getSimpleFileEntry(String path)
  {
    return getCommonFileEntry(FilenameUtil.getSimpleCanonicalFragments(path));
  }
  
  private FileEntry getCommonFileEntry(String[] fragments)
  {
    FileEntry iter = getRoot();
    String[] arrayOfString;
    int j = (arrayOfString = fragments).length;
    for (int i = 0; i < j; i++)
    {
      String fragment = arrayOfString[i];
      
      FileEntry[] children = iter.getChildren();
      boolean bFound = false;
      FileEntry[] arrayOfFileEntry1;
      int m = (arrayOfFileEntry1 = children).length;
      for (int k = 0; k < m; k++)
      {
        FileEntry child = arrayOfFileEntry1[k];
        if (fragment.equals(child.getName()))
        {
          iter = child;
          bFound = true;
          break;
        }
      }
      if (!bFound) {
        iter = new FileEntry(null, iter, fragment, FileEntryType.Unknown, null, null, null, null, null, null, null, null);
      }
    }
    return iter;
  }
  
  public void executeLaunchCommand(String command, IShellOutputReceiver receiver)
    throws IOException
  {
    executeHostCommand(" launch" + (command == null ? "" : new StringBuilder(" ").append(command).toString()), receiver);
  }
  
  public void executeHostCommand(String command, IShellOutputReceiver receiver)
    throws IOException
  {
    SmartDevelopmentBridge sdb = SmartDevelopmentBridge.getBridge();
    if (sdb == null) {
      return;
    }
    String sdbPath = sdb.getSdbOsLocation();
    if (sdbPath == null) {
      return;
    }
    if (StringUtil.isEmpty(command)) {
      return;
    }
    String sdbShellCmd = sdbPath + " -s " + serialNumber + " " + command;
    Process pSdb = Runtime.getRuntime().exec(sdbShellCmd);
    SdbShellProcess process = new SdbShellProcess(pSdb, "launch");
    try
    {
      StreamGobbler inputGobbler = new StreamGobbler(process.getInputStream());
      inputGobbler.boot();
      
      StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream());
      errorGobbler.boot();
      
      inputGobbler.waitState(new ServerState[] { ServerState.Terminated });
      errorGobbler.waitState(new ServerState[] { ServerState.Terminated });
      
      receiver.append(inputGobbler.getResult());
      receiver.append(errorGobbler.getResult());
      receiver.close();
    }
    catch (ServerException e)
    {
      throw new IOException(e);
    }
  }
  
  public SdbShellProcess executeShellCommand(String command)
    throws IOException
  {
    return (SdbShellProcess)executeShellCommand(command, true);
  }
  
  public Process executeShellCommand(String command, boolean prompt)
    throws IOException
  {
    SmartDevelopmentBridge sdb = SmartDevelopmentBridge.getBridge();
    if (sdb == null) {
      return null;
    }
    String sdbPath = sdb.getSdbOsLocation();
    if (sdbPath == null) {
      return null;
    }
    String sdbShellCmd = sdbPath + " -s " + serialNumber + " shell";
    if (!prompt) {
      sdbShellCmd = sdbShellCmd + " " + command;
    }
    Process pSdb = Runtime.getRuntime().exec(sdbShellCmd);
    if (!prompt) {
      return pSdb;
    }
    return new SdbShellProcess(pSdb, command);
  }
  
  public void executeShellCommand(String command, IShellOutputReceiver receiver)
    throws TimeoutException, SdbCommandRejectedException, ShellCommandUnresponsiveException, IOException
  {
    CommandFactory.execute(command).in(this, receiver);
  }
  
  public void executeShellCommand(String command, IShellOutputReceiver receiver, int maxTimeToOutputResponse)
    throws TimeoutException, SdbCommandRejectedException, ShellCommandUnresponsiveException, IOException
  {
    CommandFactory.execute(command).with(Argument.MaxTimeToRespond, Integer.valueOf(maxTimeToOutputResponse)).in(this, receiver);
  }
  
  public void createForward(int localPort, int remotePort)
    throws TimeoutException, SdbCommandRejectedException, IOException
  {
    SdbHelper.createForward(SmartDevelopmentBridge.getBridge(), this, localPort, remotePort);
  }
  
  public void removeForward(int localPort, int remotePort)
    throws TimeoutException, SdbCommandRejectedException, IOException
  {
    SdbHelper.removeForward(SmartDevelopmentBridge.getBridge(), this, localPort, remotePort);
  }
  
  void update(int changeMask)
  {
    monitor.getServer().deviceChanged(this, changeMask);
  }
  
  void update(int changeMask, String name)
  {
    deviceName = name;
    getRoot().setName(name);
    update(changeMask);
  }
  
  public void initialize()
    throws AsynchronousCloseException
  {
    Matcher<?> arm = MatcherFactory.containsIgnoreCase(Arch.ARM.getArch());
    Matcher<?> x86 = MatcherFactory.containsIgnoreCase(Arch.X86.getArch());
    Object arch = CommandFactory.execute("uname -m").in(this, MatcherFactory.matchers(new Matcher[] { arm, x86 }));
    if (arm.equals(arch)) {
      this.arch = Arch.ARM;
    } else if (x86.equals(arch)) {
      this.arch = Arch.X86;
    } else {
      throw new AsynchronousCloseException();
    }
    bEmulator = ((Boolean)CommandFactory.execute("ls -al /dev/samsung_sdb 2>/dev/null | wc -l ").in(this, MatcherFactory.equals("0"))).booleanValue();
  }
  
  public String getAppInstallPath()
  {
    if (StringUtil.isEmpty(installPath)) {
      installPath = ((String)CommandFactory.execute("/usr/bin/pkgcmd -a").in(this, new PatternExtractor("^Tizen Application Installation Path: (.*)")));
    }
    return installPath;
  }
  
  public String toString()
  {
    return serialNumber;
  }
  
  public boolean equals(Object obj)
  {
    if (this == obj) {
      return true;
    }
    if (!(obj instanceof IDevice)) {
      return false;
    }
    IDevice device = (IDevice)obj;
    return ObjectUtil.equals(getSerialNumber(), device.getSerialNumber());
  }
  
  public boolean setRootUser(boolean isOn)
    throws TimeoutException, SdbCommandRejectedException, IOException
  {
    String msg = String.format("root:%s", new Object[] { isOn ? "on" : "off" });
    
    byte[] reqBytes = SdbHelper.sendServiceRequest(SmartDevelopmentBridge.getBridge(), this, msg);
    
    String str = SdbHelper.replyToString(reqBytes);
    if (!str.startsWith("Permission denied")) {
      return true;
    }
    return false;
  }
}

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

public class DeviceConstants
{
  public static final String LOG_TAG = "device";
  static final String CMD_ARCHITECTURE_INFO = "uname -m";
  static final String CMD_DEVICE_TYPE = "ls -al /dev/samsung_sdb 2>/dev/null | wc -l ";
  static final String RESULT_DEVICE_TYPE_EMULATOR = "0";
  static final String CMD_USER_TYPE = "whoami";
  static final String RESULT_USER_TYPE_ROOT = "root";
  static final String CMD_PKG_TOOL_INSTALL_PATH = "/usr/bin/pkgcmd -a";
}

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

import java.io.IOException;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import org.tizen.sdblib.daemon.AbstractServer;
import org.tizen.sdblib.daemon.ServerState;
import org.tizen.sdblib.exception.ServerException;
import org.tizen.sdblib.exception.TimeoutException;
import org.tizen.sdblib.util.DeviceUtil;
import org.tizen.sdblib.util.Log;
import org.tizen.sdblib.util.ThreadUtil;

class DeviceMonitor
  extends AbstractServer
{
  protected final SmartDevelopmentBridge bridge;
  protected ArrayList<Device> devices = null;
  private SocketChannel mMainSdbConnection = null;
  private boolean mMonitoring = false;
  private int mRestartAttemptCount = 0;
  private boolean mDeviceListInitialized = false;
  
  DeviceMonitor(SmartDevelopmentBridge bridge)
  {
    super("Devices Monitor");
    this.bridge = bridge;
  }
  
  boolean isMonitoring()
  {
    return mMonitoring;
  }
  
  int getRestartAttemptCount()
  {
    return mRestartAttemptCount;
  }
  
  boolean isDeviceListInitialized()
  {
    return mDeviceListInitialized;
  }
  
  public synchronized Device[] getDevices()
  {
    while (devices == null) {
      try
      {
        wait();
      }
      catch (InterruptedException localInterruptedException) {}
    }
    return (Device[])devices.toArray(new Device[devices.size()]);
  }
  
  protected synchronized void removeDevice(Device device)
  {
    devices.remove(device);
  }
  
  SmartDevelopmentBridge getServer()
  {
    return bridge;
  }
  
  private void handleExpectioninMonitorLoop(Exception e)
  {
    if (isState(new ServerState[] { ServerState.Running }))
    {
      if ((e instanceof TimeoutException)) {
        Log.e("DeviceMonitor", "sdb connection Error: timeout");
      } else {
        Log.e("DeviceMonitor", "sdb connection Error:" + e.getMessage());
      }
      mMonitoring = false;
      if (mMainSdbConnection != null)
      {
        try
        {
          mMainSdbConnection.close();
        }
        catch (IOException ioe)
        {
          Log.e("sdb", "close main sdb connection failed:" + ioe);
        }
        mMainSdbConnection = null;
      }
    }
  }
  
  private SocketChannel openSdbConnection()
  {
    Log.d("DeviceMonitor", "connecting to sdb for Device List Monitoring...");
    try
    {
      SocketChannel channel = SmartDevelopmentBridge.getBridge().openChannel();
      bridge.setStarted(true);
      return channel;
    }
    catch (IOException e)
    {
      Log.e("DeviceMonitor", "Failed to open socket channel");
      Log.e("DeviceMonitor", e);
    }
    return null;
  }
  
  private boolean sendDeviceListMonitoringRequest()
    throws TimeoutException, IOException
  {
    byte[] request = SdbHelper.formSdbRequest("host:track-devices");
    Log.d("DeviceMonitor", "send monitoring request");
    try
    {
      SdbHelper.write(mMainSdbConnection, request);
      
      SdbResponse resp = SdbHelper.readSdbResponse(mMainSdbConnection);
      if (!okay) {
        Log.e("DeviceMonitor", "sdb refused request: " + message);
      }
      return okay;
    }
    catch (IOException e)
    {
      Log.e("DeviceMonitor", "sending tracking request failed!");
      mMainSdbConnection.close();
      throw e;
    }
  }
  
  private void processIncomingDeviceData(int length)
    throws IOException
  {
    ArrayList<Device> list = new ArrayList();
    if (length > 0)
    {
      byte[] buffer = new byte[length];
      String result = SdbHelper.readAsString(mMainSdbConnection, buffer);
      
      String[] devices = result.split("\n");
      String[] arrayOfString1;
      int j = (arrayOfString1 = devices).length;
      for (int i = 0; i < j; i++)
      {
        String d = arrayOfString1[i];
        Log.d("DeviceMonitor", "deviceData: " + d);
        String[] param = d.split("\t");
        if (param.length == 3)
        {
          Device device = new Device(this, param[0].trim(), DeviceState.getState(param[1].trim()), 
            param[2].trim());
          
          list.add(device);
          Log.d("DeviceMonitor", "deviceData: " + device.getSerialNumber() + " added to list");
        }
      }
    }
    updateDevices(list);
  }
  
  protected void updateDevices(ArrayList<Device> newList)
    throws AsynchronousCloseException
  {
    synchronized ()
    {
      ArrayList<Device> devicesToQuery = new ArrayList();
      if (devices == null) {
        devices = new ArrayList();
      }
      synchronized (this)
      {
        Device device;
        for (int d = 0; d < devices.size();)
        {
          device = (Device)devices.get(d);
          int count = newList.size();
          boolean foundMatch = false;
          for (int dd = 0; dd < count; dd++)
          {
            Device newDevice = (Device)newList.get(dd);
            if (newDevice.getSerialNumber().equals(device.getSerialNumber()))
            {
              foundMatch = true;
              if (!device.getDeviceName().equals(newDevice.getDeviceName())) {
                device.update(3, newDevice.getDeviceName());
              }
              if (device.getState() != newDevice.getState())
              {
                device.setState(newDevice.getState());
                if (device.getState() == DeviceState.ONLINE)
                {
                  device.initialize();
                  Log.d("DeviceMonitor", "updateDevices: " + device.getSerialNumber() + " onlined");
                  device.update(1, newDevice.getDeviceName());
                }
              }
              newList.remove(dd);
              break;
            }
          }
          if (!foundMatch)
          {
            removeDevice(device);
            bridge.deviceDisconnected(device);
            Log.d("DeviceMonitor", "updateDevices: " + device.getSerialNumber() + " off-lined");
          }
          else
          {
            d++;
          }
        }
        for (Device newDevice : newList)
        {
          if (DeviceUtil.isOnline(newDevice)) {
            newDevice.initialize();
          }
          devices.add(newDevice);
          if (DeviceUtil.isOnline(newDevice))
          {
            devicesToQuery.add(newDevice);
            bridge.deviceConnected(newDevice);
            Log.d("DeviceMonitor", "updateDevices: " + newDevice.getSerialNumber() + " newly connected.");
          }
        }
        notifyAll();
      }
    }
    newList.clear();
  }
  
  private int readLength(SocketChannel socket)
    throws IOException
  {
    String msg = SdbHelper.readAsString(socket, new byte[4]);
    try
    {
      return Integer.parseInt(msg, 16);
    }
    catch (NumberFormatException nfe)
    {
      Log.e("sdb", "parse integer failed:" + nfe);
      throw new IOException("Unable to read length");
    }
  }
  
  protected void initialize()
    throws ServerException
  {
    Log.d("DeviceMonitor", "start monitoring");
  }
  
  protected void process()
    throws Exception
  {
    try
    {
      if (mMainSdbConnection == null)
      {
        Log.d("DeviceMonitor", "opening sdb connection");
        mMainSdbConnection = openSdbConnection();
        if (mMainSdbConnection == null)
        {
          Log.d("DeviceMonitor", "start sdb");
          if (!bridge.startSdb())
          {
            synchronized (bridge)
            {
              bridge.notifyAll();
            }
            mRestartAttemptCount += 1;
            Log.e("DeviceMonitor", "sdb restart attempts: " + mRestartAttemptCount);
          }
          ThreadUtil.trySleep(1000L);
        }
        else
        {
          Log.d("DeviceMonitor", "connected to sdb for device monitoring");
        }
      }
      if ((mMainSdbConnection != null) && (!mMonitoring)) {
        mMonitoring = sendDeviceListMonitoringRequest();
      }
      if (mMonitoring)
      {
        int length = readLength(mMainSdbConnection);
        if (length >= 0)
        {
          processIncomingDeviceData(length);
          
          mDeviceListInitialized = true;
        }
      }
    }
    catch (AsynchronousCloseException localAsynchronousCloseException)
    {
      Log.e("DeviceMonitor", "sdb closed by the other");
    }
    catch (TimeoutException ioe)
    {
      handleExpectioninMonitorLoop(ioe);
    }
    catch (IOException ioe)
    {
      handleExpectioninMonitorLoop(ioe);
    }
    ThreadUtil.trySleep(100L);
  }
  
  protected void terminate()
  {
    Log.d("DeviceMonitor", "stop monitoring");
    try
    {
      if (mMainSdbConnection != null) {
        mMainSdbConnection.close();
      }
    }
    catch (IOException e)
    {
      Log.e("sdb", "close main sdb connection failed:" + e);
    }
  }
}

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

public enum DeviceState
{
  OFFLINE(
  
    "offline"),  ONLINE("device");
  
  private String state;
  
  private DeviceState(String state)
  {
    this.state = state;
  }
  
  public static DeviceState getState(String state)
  {
    DeviceState[] arrayOfDeviceState;
    int j = (arrayOfDeviceState = values()).length;
    for (int i = 0; i < j; i++)
    {
      DeviceState deviceState = arrayOfDeviceState[i];
      if (state.equals(state)) {
        return deviceState;
      }
    }
    return null;
  }
}

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

public abstract interface ICrashReportServiceListener
{
  public abstract void fileCreated(IDevice paramIDevice, String paramString);
}

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

public abstract interface IDebugBridgeChangeListener
{
  public abstract void bridgeChanged(SmartDevelopmentBridge paramSmartDevelopmentBridge);
}

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

import java.io.IOException;
import org.tizen.sdblib.exception.SdbCommandRejectedException;
import org.tizen.sdblib.exception.TimeoutException;
import org.tizen.sdblib.service.FileEntry;
import org.tizen.sdblib.service.SyncService;
import org.tizen.sdblib.util.SdbShellProcess;

public abstract interface IDevice
{
  public static final int CHANGE_STATE = 1;
  public static final int CHANGE_CLIENT_LIST = 2;
  public static final int CHANGE_NAME = 3;
  public static final int CHANGE_BUILD_INFO = 4;
  
  public abstract String getSerialNumber();
  
  public abstract String getDeviceName();
  
  public abstract DeviceState getState();
  
  public abstract Arch getArch();
  
  public abstract boolean isEmulator();
  
  public abstract boolean isRoot();
  
  public abstract SyncService getSyncService()
    throws IOException;
  
  public abstract FileEntry getRoot();
  
  public abstract FileEntry getFileEntry(String paramString);
  
  public abstract SdbShellProcess executeShellCommand(String paramString)
    throws IOException;
  
  public abstract Process executeShellCommand(String paramString, boolean paramBoolean)
    throws IOException;
  
  public abstract void executeShellCommand(String paramString, IShellOutputReceiver paramIShellOutputReceiver)
    throws IOException;
  
  public abstract void executeShellCommand(String paramString, IShellOutputReceiver paramIShellOutputReceiver, int paramInt)
    throws IOException;
  
  public abstract void createForward(int paramInt1, int paramInt2)
    throws IOException;
  
  public abstract void removeForward(int paramInt1, int paramInt2)
    throws TimeoutException, SdbCommandRejectedException, IOException;
  
  public abstract String getAppInstallPath();
  
  public abstract void executeLaunchCommand(String paramString, IShellOutputReceiver paramIShellOutputReceiver)
    throws IOException;
  
  public abstract void executeHostCommand(String paramString, IShellOutputReceiver paramIShellOutputReceiver)
    throws IOException;
  
  public abstract boolean setRootUser(boolean paramBoolean)
    throws TimeoutException, SdbCommandRejectedException, IOException;
}

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

public abstract interface IDeviceChangeListener
{
  public abstract void onConnected(IDevice paramIDevice);
  
  public abstract void onDisconnected(IDevice paramIDevice);
  
  public abstract void onChanged(IDevice paramIDevice, int paramInt);
}

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

import java.io.Closeable;
import java.io.Flushable;

public abstract interface IShellOutputReceiver
  extends Appendable, Flushable, Closeable
{
  public abstract boolean isCancelled();
}

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

import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

class SdbHelper$1
  extends TimerTask
{
  SdbHelper$1(AtomicBoolean paramAtomicBoolean) {}
  
  public synchronized void run()
  {
    val$running.set(false);
  }
}

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

import java.io.EOFException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import org.tizen.sdblib.exception.SdbCommandRejectedException;
import org.tizen.sdblib.exception.TimeoutException;
import org.tizen.sdblib.util.IOUtil;
import org.tizen.sdblib.util.Log;
import org.tizen.sdblib.util.Preferences;
import org.tizen.sdblib.util.ThreadUtil;

public class SdbHelper
{
  public static final int WAIT_TIME = 50;
  public static final String DEFAULT_ENCODING = "ISO-8859-1";
  public static final String UTF_DECODING = "UTF-8";
  public static final String OUTPUT_DECODING = "UTF-8";
  public static final Charset UTF_CHARSET = Charset.forName("UTF-8");
  
  public static byte[] string2bytes(String str)
    throws UnsupportedEncodingException
  {
    return str.getBytes(UTF_CHARSET);
  }
  
  public static String bytes2string(byte[] bytes)
  {
    return new String(bytes, UTF_CHARSET);
  }
  
  public static boolean check(byte[] bytes1, int start1, byte[] bytes2, int start2, int length)
  {
    if ((bytes1 == null) || (start1 < 0) || (bytes1.length < start1 + length)) {
      return false;
    }
    if ((bytes2 == null) || (start2 < 0) || (bytes2.length < start2 + length)) {
      return false;
    }
    for (int i = 0; i < length; i++) {
      if (bytes1[(start1++)] != bytes2[(start2++)]) {
        return false;
      }
    }
    return true;
  }
  
  public static byte[] formSdbRequest(String req)
  {
    try
    {
      byte[] reqByte = string2bytes(req);
      
      byte[] lengthByte = String.format("%04X", new Object[] { Integer.valueOf(reqByte.length) }).getBytes();
      
      byte[] result = new byte[reqByte.length + 4];
      System.arraycopy(lengthByte, 0, result, 0, 4);
      System.arraycopy(reqByte, 0, result, 4, reqByte.length);
      
      return result;
    }
    catch (UnsupportedEncodingException uee)
    {
      Log.e("Unsupported encoding. ", uee);
    }
    return null;
  }
  
  public static SdbResponse readSdbResponse(SocketChannel chan)
    throws IOException
  {
    SdbResponse resp = new SdbResponse();
    
    byte[] reply = new byte[4];
    read(chan, reply);
    if (check(SmartDevelopmentBridgetConstants.ID_OKAY, 0, reply, 0, 4))
    {
      okay = true;
      
      return resp;
    }
    okay = false;
    
    byte[] lenBuf = new byte[4];
    read(chan, lenBuf);
    
    String lenStr = replyToString(lenBuf);
    try
    {
      len = Integer.parseInt(lenStr, 16);
    }
    catch (NumberFormatException localNumberFormatException)
    {
      int len;
      Log.w("sdb", "Expected digits, got '" + lenStr + "': " + 
        lenBuf[0] + " " + lenBuf[1] + " " + lenBuf[2] + " " + 
        lenBuf[3]);
      Log.w("sdb", "reply was " + replyToString(reply));
      return resp;
    }
    int len;
    byte[] msg = new byte[len];
    read(chan, msg);
    
    message = replyToString(msg);
    Log.v("sdb", "Got reply '" + replyToString(reply) + "', diag='" + message + "'");
    
    return resp;
  }
  
  public static void createForward(SmartDevelopmentBridge sdb, Device device, int local, int remote)
    throws IOException
  {
    SocketChannel sdbChan = null;
    try
    {
      sdbChan = sdb.openChannel();
      
      byte[] request = formSdbRequest(String.format(
        "host-serial:%1$s:forward:tcp:%2$d;tcp:%3$d", new Object[] {
        device.getSerialNumber(), Integer.valueOf(local), Integer.valueOf(remote) }));
      
      write(sdbChan, request);
      
      SdbResponse resp = readSdbResponse(sdbChan);
      if (!okay)
      {
        Log.w("create-forward", "Error creating forward: " + message);
        throw new SdbCommandRejectedException(message);
      }
    }
    finally
    {
      IOUtil.tryClose(sdbChan);
    }
    IOUtil.tryClose(sdbChan);
  }
  
  public static void removeForward(SmartDevelopmentBridge sdb, Device device, int local, int remote)
    throws TimeoutException, SdbCommandRejectedException, IOException
  {
    SocketChannel sdbChan = null;
    try
    {
      sdbChan = sdb.openChannel();
      
      byte[] request = formSdbRequest(String.format(
        "host-serial:%1$s:killforward:tcp:%2$d;tcp:%3$d", new Object[] {
        device.getSerialNumber(), Integer.valueOf(local), Integer.valueOf(remote) }));
      
      write(sdbChan, request);
      
      SdbResponse resp = readSdbResponse(sdbChan);
      if (!okay)
      {
        Log.w("remove-forward", "Error creating forward: " + message);
        throw new SdbCommandRejectedException(message);
      }
    }
    finally
    {
      IOUtil.tryClose(sdbChan);
    }
    IOUtil.tryClose(sdbChan);
  }
  
  public static String replyToString(byte[] reply)
  {
    try
    {
      return new String(reply, "ISO-8859-1");
    }
    catch (UnsupportedEncodingException uee)
    {
      Log.e("Unsupported encoding.", uee);
    }
    return "";
  }
  
  static void read(SocketChannel chan, byte[] data)
    throws IOException
  {
    read(chan, data, -1, Preferences.getTimeOut());
  }
  
  public static void read(SocketChannel chan, byte[] data, int length, int timeout)
    throws IOException
  {
    ByteBuffer buf = ByteBuffer.wrap(data, 0, length >= 0 ? length : data.length);
    long startTime = System.currentTimeMillis();
    while (buf.position() != buf.limit())
    {
      int count = chan.read(buf);
      if (count < 0)
      {
        Log.d("sdb", "read: channel EOF");
        throw new EOFException();
      }
      if (count == 0)
      {
        if ((timeout > 0) && (System.currentTimeMillis() - startTime > timeout))
        {
          Log.d("sdb", "read: timeout");
          throw new TimeoutException();
        }
        ThreadUtil.trySleep(50L);
      }
      else
      {
        startTime = System.currentTimeMillis();
      }
    }
  }
  
  public static String readAsString(SocketChannel socket, byte[] buffer)
    throws IOException
  {
    read(socket, buffer);
    return new String(buffer, "ISO-8859-1");
  }
  
  public static void write(SocketChannel chan, byte[] data)
    throws IOException
  {
    write(chan, data, -1, Preferences.getTimeOut());
  }
  
  public static void write(SocketChannel chan, byte[] data, int length, int timeout)
    throws IOException
  {
    ByteBuffer buf = ByteBuffer.wrap(data, 0, length < 0 ? data.length : length);
    AtomicBoolean running = new AtomicBoolean(true);
    Timer timer = null;
    if (timeout > 0)
    {
      timer = new Timer();
      timer.schedule(new TimerTask()
      {
        public synchronized void run()
        {
          set(false);
        }
      }, timeout);
    }
    while ((buf.position() != buf.limit()) && (running.get()))
    {
      int count = chan.write(buf);
      if (count < 0)
      {
        Log.d("sdb", "write: channel EOF");
        throw new IOException("channel EOF");
      }
      if (count == 0) {
        ThreadUtil.trySleep(50L);
      }
    }
    if (buf.position() == buf.limit())
    {
      if (timer != null) {
        timer.cancel();
      }
      return;
    }
    Log.d("sdb", "write: Timeout");
    throw new TimeoutException();
  }
  
  public static void initializeDevice(SocketChannel channel, String serialNumber)
    throws TimeoutException, SdbCommandRejectedException, IOException
  {
    String msg = "host:transport:" + serialNumber;
    byte[] deviceQuery = formSdbRequest(msg);
    
    write(channel, deviceQuery);
    
    SdbResponse resp = readSdbResponse(channel);
    if (!okay) {
      throw new SdbCommandRejectedException(message);
    }
  }
  
  /* Error */
  public static byte[] sendServiceRequest(SmartDevelopmentBridge sdb, Device device, String req)
    throws TimeoutException, SdbCommandRejectedException, IOException
  {
    // Byte code:
    //   0: aconst_null
    //   1: astore_3
    //   2: sipush 256
    //   5: newarray <illegal type>
    //   7: astore 4
    //   9: aload_0
    //   10: invokevirtual 190	org/tizen/sdblib/SmartDevelopmentBridge:openChannel	()Ljava/nio/channels/SocketChannel;
    //   13: astore_3
    //   14: aload_3
    //   15: aload_1
    //   16: invokevirtual 198	org/tizen/sdblib/Device:getSerialNumber	()Ljava/lang/String;
    //   19: invokestatic 352	org/tizen/sdblib/SdbHelper:initializeDevice	(Ljava/nio/channels/SocketChannel;Ljava/lang/String;)V
    //   22: aload_2
    //   23: invokestatic 203	org/tizen/sdblib/SdbHelper:formSdbRequest	(Ljava/lang/String;)[B
    //   26: astore 5
    //   28: aload_3
    //   29: aload 5
    //   31: invokestatic 205	org/tizen/sdblib/SdbHelper:write	(Ljava/nio/channels/SocketChannel;[B)V
    //   34: aload_3
    //   35: invokestatic 208	org/tizen/sdblib/SdbHelper:readSdbResponse	(Ljava/nio/channels/SocketChannel;)Lorg/tizen/sdblib/SdbResponse;
    //   38: astore 6
    //   40: aload 6
    //   42: getfield 121	org/tizen/sdblib/SdbResponse:okay	Z
    //   45: ifne +53 -> 98
    //   48: ldc_w 354
    //   51: new 134	java/lang/StringBuilder
    //   54: dup
    //   55: ldc_w 355
    //   58: invokespecial 138	java/lang/StringBuilder:<init>	(Ljava/lang/String;)V
    //   61: aload_2
    //   62: invokevirtual 141	java/lang/StringBuilder:append	(Ljava/lang/String;)Ljava/lang/StringBuilder;
    //   65: ldc_w 357
    //   68: invokevirtual 141	java/lang/StringBuilder:append	(Ljava/lang/String;)Ljava/lang/StringBuilder;
    //   71: aload 6
    //   73: getfield 162	org/tizen/sdblib/SdbResponse:message	Ljava/lang/String;
    //   76: invokevirtual 141	java/lang/StringBuilder:append	(Ljava/lang/String;)Ljava/lang/StringBuilder;
    //   79: invokevirtual 152	java/lang/StringBuilder:toString	()Ljava/lang/String;
    //   82: invokestatic 156	org/tizen/sdblib/util/Log:w	(Ljava/lang/String;Ljava/lang/String;)V
    //   85: new 214	org/tizen/sdblib/exception/SdbCommandRejectedException
    //   88: dup
    //   89: aload 6
    //   91: getfield 162	org/tizen/sdblib/SdbResponse:message	Ljava/lang/String;
    //   94: invokespecial 216	org/tizen/sdblib/exception/SdbCommandRejectedException:<init>	(Ljava/lang/String;)V
    //   97: athrow
    //   98: aload_3
    //   99: aload 4
    //   101: invokestatic 110	org/tizen/sdblib/SdbHelper:read	(Ljava/nio/channels/SocketChannel;[B)V
    //   104: goto +29 -> 133
    //   107: pop
    //   108: ldc_w 354
    //   111: ldc_w 359
    //   114: invokestatic 361	org/tizen/sdblib/util/Log:i	(Ljava/lang/String;Ljava/lang/String;)V
    //   117: aload_3
    //   118: invokestatic 217	org/tizen/sdblib/util/IOUtil:tryClose	(Ljava/io/Closeable;)V
    //   121: goto +16 -> 137
    //   124: astore 7
    //   126: aload_3
    //   127: invokestatic 217	org/tizen/sdblib/util/IOUtil:tryClose	(Ljava/io/Closeable;)V
    //   130: aload 7
    //   132: athrow
    //   133: aload_3
    //   134: invokestatic 217	org/tizen/sdblib/util/IOUtil:tryClose	(Ljava/io/Closeable;)V
    //   137: aload 4
    //   139: areturn
    // Line number table:
    //   Java source line #515	-> byte code offset #0
    //   Java source line #516	-> byte code offset #2
    //   Java source line #518	-> byte code offset #9
    //   Java source line #519	-> byte code offset #14
    //   Java source line #521	-> byte code offset #22
    //   Java source line #522	-> byte code offset #28
    //   Java source line #524	-> byte code offset #34
    //   Java source line #525	-> byte code offset #40
    //   Java source line #526	-> byte code offset #48
    //   Java source line #527	-> byte code offset #85
    //   Java source line #529	-> byte code offset #98
    //   Java source line #530	-> byte code offset #107
    //   Java source line #532	-> byte code offset #108
    //   Java source line #534	-> byte code offset #117
    //   Java source line #533	-> byte code offset #124
    //   Java source line #534	-> byte code offset #126
    //   Java source line #535	-> byte code offset #130
    //   Java source line #534	-> byte code offset #133
    //   Java source line #537	-> byte code offset #137
    // Local variable table:
    //   start	length	slot	name	signature
    //   0	140	0	sdb	SmartDevelopmentBridge
    //   0	140	1	device	Device
    //   0	140	2	req	String
    //   1	133	3	sdbChan	SocketChannel
    //   7	131	4	msg	byte[]
    //   26	4	5	request	byte[]
    //   38	52	6	resp	SdbResponse
    //   124	7	7	localObject	Object
    //   107	1	8	localEOFException	EOFException
    // Exception table:
    //   from	to	target	type
    //   9	104	107	java/io/EOFException
    //   9	117	124	finally
  }
}

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

public class SdbResponse
{
  public boolean okay;
  public String message = "";
}

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

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.channels.SocketChannel;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.tizen.sdblib.exception.ServerException;
import org.tizen.sdblib.util.DeviceUtil;
import org.tizen.sdblib.util.Log;
import org.tizen.sdblib.util.ParsingUtil;
import org.tizen.sdblib.util.StreamGobbler;
import org.tizen.sdblib.util.StringUtil;

public final class SmartDevelopmentBridge
{
  private static final String TAG_SDB = "sdb";
  private static final String TAG_SDBLIB = "sdblib";
  private static InetSocketAddress socketAddr;
  private static SmartDevelopmentBridge instance;
  private String mSdbOsLocation = null;
  protected Lock lock = new ReentrantLock();
  private boolean mStarted = false;
  private DeviceMonitor deviceMonitor;
  private static final ArrayList<IDebugBridgeChangeListener> sBridgeListeners = new ArrayList();
  private static final ArrayList<IDeviceChangeListener> sDeviceListeners = new ArrayList();
  private static final Object sLock = sBridgeListeners;
  
  protected static void init()
  {
    try
    {
      int sdbPort = ParsingUtil.parseInt(System.getenv("SDB_SERVER_PORT"), 26099);
      if (sdbPort <= 0) {
        throw new IllegalArgumentException("env var SDB_SERVER_PORT: must be >=0, got " + System.getenv("SDB_SERVER_PORT"));
      }
      socketAddr = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), sdbPort);
    }
    catch (NumberFormatException localNumberFormatException)
    {
      throw new IllegalArgumentException("env var SDB_SERVER_PORT: illegal value '" + System.getenv("SDB_SERVER_PORT") + "'");
    }
    catch (SecurityException localSecurityException)
    {
      Log.w("sdblib", 
        "No access to env variables allowed by current security manager. If you've set SDB_SERVER_PORT: it's being ignored.");
    }
    catch (UnknownHostException e)
    {
      Log.e("sdb", "init socket failed:" + e);
    }
  }
  
  public static void terminate()
  {
    if ((instance != null) && (instancedeviceMonitor != null))
    {
      instancedeviceMonitor.down();
      instancedeviceMonitor = null;
    }
  }
  
  public SocketChannel openChannel()
    throws IOException
  {
    SocketChannel channel = SocketChannel.open(socketAddr);
    channel.configureBlocking(false);
    
    return channel;
  }
  
  public static SmartDevelopmentBridge createBridge(String location, boolean bForce)
  {
    
    synchronized (sLock)
    {
      if (instance != null)
      {
        if ((instancemSdbOsLocation != null) && (instancemSdbOsLocation.equals(location)) && 
          (!bForce)) {
          return instance;
        }
        instance.stop();
      }
      instance = new SmartDevelopmentBridge(location);
      instance.start();
      
      fireBridgetChanged(instance);
      return instance;
1 2 3 4 5 6 7

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