public static void loadAndAssertStatusForRow(
      long downloadRowId, DownloadStatus status, boolean mockNetworkError) {
    FileDownloader loader = FileDownloader.newForDownloadRow(downloadRowId);
    if (mockNetworkError) {
      loader.connectionMock =
          new ConnectionTwitterGnuSocialMock(new ConnectionException("Mocked IO exception"));
    }
    CommandData commandData = CommandData.newCommand(CommandEnum.FETCH_AVATAR);
    loader.load(commandData);

    DownloadData data = DownloadData.fromId(downloadRowId);
    if (DownloadStatus.LOADED.equals(status)) {
      assertFalse("Loaded " + data.getUri() + "; " + data, commandData.getResult().hasError());
      assertEquals("Loaded " + data.getUri(), status, loader.getStatus());
    } else {
      assertTrue("Error loading " + data.getUri(), commandData.getResult().hasError());
    }

    if (DownloadStatus.LOADED.equals(status)) {
      assertTrue("File exists " + data.getUri(), data.getFile().exists());
    } else {
      assertFalse("File doesn't exist " + data.getUri(), data.getFile().exists());
    }

    assertEquals("Loaded " + data.getUri(), status, loader.getStatus());
  }
Esempio n. 2
0
 /** Stop {@link MyService} asynchronously */
 public static synchronized void stopService() {
   if (!MyContextHolder.get().isReady()) {
     return;
   }
   // Don't do "context.stopService", because we may lose some information and (or) get Force Close
   // This is "mild" stopping
   CommandData element = new CommandData(CommandEnum.STOP_SERVICE, "");
   MyContextHolder.get()
       .context()
       .sendBroadcast(element.toIntent(MyAction.EXECUTE_COMMAND.getIntent()));
 }
Esempio n. 3
0
 static void sendCommandEvenForUnavailable(CommandData commandData) {
   // Using explicit Service intent,
   // see
   // http://stackoverflow.com/questions/18924640/starting-android-service-using-explicit-vs-implicit-intent
   Intent serviceIntent = new Intent(MyContextHolder.get().context(), MyService.class);
   if (commandData != null) {
     serviceIntent = commandData.toIntent(serviceIntent);
   }
   MyContextHolder.get().context().startService(serviceIntent);
 }
Esempio n. 4
0
 /**
  * Starts MyService asynchronously if it is not already started and send command to it.
  *
  * @param commandData to the service or null
  */
 public static void sendCommand(CommandData commandData) {
   if (!isServiceAvailable()) {
     // Imitate a soft service error
     commandData.getResult().incrementNumIoExceptions();
     commandData.getResult().setMessage("Service is not available");
     MyServiceEventsBroadcaster.newInstance(MyContextHolder.get(), MyServiceState.STOPPED)
         .setCommandData(commandData)
         .setEvent(MyServiceEvent.AFTER_EXECUTING_COMMAND)
         .broadcast();
     return;
   }
   sendCommandEvenForUnavailable(commandData);
 }
Esempio n. 5
0
 /**
  * Returns previous service state and queries service for its current state asynchronously.
  * Doesn't start the service, so absence of the reply will mean that service is stopped @See <a
  * href="http://groups.google.com/group/android-developers/browse_thread/thread/8c4bd731681b8331/bf3ae8ef79cad75d">here</a>
  */
 public static MyServiceState getServiceState() {
   synchronized (mServiceState) {
     long time = System.nanoTime();
     if (waitingForServiceState
         && (time - stateQueuedTime)
             > java.util.concurrent.TimeUnit.SECONDS.toMillis(STATE_QUERY_TIMEOUT_SECONDS)) {
       // Timeout expired
       waitingForServiceState = false;
       mServiceState = MyServiceState.STOPPED;
     } else if (!waitingForServiceState && mServiceState == MyServiceState.UNKNOWN) {
       // State is unknown, we need to query the Service again
       waitingForServiceState = true;
       stateQueuedTime = time;
       mServiceState = MyServiceState.UNKNOWN;
       CommandData element = new CommandData(CommandEnum.BROADCAST_SERVICE_STATE, "");
       MyContextHolder.get()
           .context()
           .sendBroadcast(element.toIntent(MyAction.EXECUTE_COMMAND.getIntent()));
     }
   }
   return mServiceState;
 }
Esempio n. 6
0
 @Override
 public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();
   if (action.equals(MyAction.SERVICE_STATE.getAction())) {
     MyContextHolder.initialize(context, this);
     synchronized (mServiceState) {
       stateQueuedTime = System.nanoTime();
       waitingForServiceState = false;
       mServiceState = MyServiceState.load(intent.getStringExtra(IntentExtra.SERVICE_STATE.key));
     }
     MyLog.d(this, "Notification received: Service state=" + mServiceState);
   } else if ("android.intent.action.BOOT_COMPLETED".equals(action)) {
     MyLog.d(this, "Trying to start service on boot");
     sendCommand(CommandData.getEmpty());
   } else if ("android.intent.action.ACTION_SHUTDOWN".equals(action)) {
     // We need this to persist unsaved data in the service
     MyLog.d(this, "Stopping service on Shutdown");
     setServiceUnavailable();
     stopService();
   }
 }
Esempio n. 7
0
  public CommandData parseCommandData(ArtifactData artifact) throws Exception {
    File source = new File(artifact.file);
    if (!source.isFile()) throw new FileNotFoundException();

    CommandData data = new CommandData();
    data.sha = artifact.sha;
    data.jpmRepoDir = repoDir.getCanonicalPath();
    JarFile jar = new JarFile(source);
    try {
      reporter.trace("Parsing %s", source);
      Manifest m = jar.getManifest();
      Attributes main = m.getMainAttributes();
      data.name = data.bsn = main.getValue("Bundle-SymbolicName");
      String version = main.getValue("Bundle-Version");
      if (version == null) data.version = Version.LOWEST;
      else data.version = new Version(version);

      data.main = main.getValue("Main-Class");
      data.description = main.getValue("Bundle-Description");
      data.title = main.getValue("JPM-Name");

      reporter.trace("name " + data.name + " " + data.main + " " + data.title);
      DependencyCollector path = new DependencyCollector(this);
      path.add(artifact);
      DependencyCollector bundles = new DependencyCollector(this);
      if (main.getValue("JPM-Classpath") != null) {
        Parameters requires = OSGiHeader.parseHeader(main.getValue("JPM-Classpath"));

        for (Map.Entry<String, Attrs> e : requires.entrySet()) {
          path.add(e.getKey(), e.getValue().get("name")); // coordinate
        }
      } else if (!artifact.local) { // No JPM-Classpath, falling back to
        // server's revision
        // Iterable<RevisionRef> closure =
        // library.getClosure(artifact.sha,
        // false);
        // System.out.println("getting closure " + artifact.url + " " +
        // Strings.join("\n",closure));

        // if (closure != null) {
        // for (RevisionRef ref : closure) {
        // path.add(Hex.toHexString(ref.revision));
        // }
        // }
      }

      if (main.getValue("JPM-Runbundles") != null) {
        Parameters jpmrunbundles = OSGiHeader.parseHeader(main.getValue("JPM-Runbundles"));

        for (Map.Entry<String, Attrs> e : jpmrunbundles.entrySet()) {
          bundles.add(e.getKey(), e.getValue().get("name"));
        }
      }

      reporter.trace("collect digests runpath");
      data.dependencies.addAll(path.getDigests());
      reporter.trace("collect digests bundles");
      data.runbundles.addAll(bundles.getDigests());

      Parameters command = OSGiHeader.parseHeader(main.getValue("JPM-Command"));
      if (command.size() > 1) reporter.error("Only one command can be specified");

      for (Map.Entry<String, Attrs> e : command.entrySet()) {
        data.name = e.getKey();

        Attrs attrs = e.getValue();

        if (attrs.containsKey("jvmargs")) data.jvmArgs = attrs.get("jvmargs");

        if (attrs.containsKey("title")) data.title = attrs.get("title");

        if (data.title != null) data.title = data.name;
      }
      return data;
    } finally {
      jar.close();
    }
  }
Esempio n. 8
0
  private static void executeCommand(SkypeMessage chat, CommandData data, Matcher m) {
    if (data.getCommand().admin()) {
      try {
        if (!Arrays.asList(Resource.GROUP_ADMINS).contains(chat.getSender().getUsername())) {
          Resource.sendMessage(chat, "Access Denied!");
          return;
        }
      } catch (Exception ignored) {
        return;
      }
    }

    try {
      if (data.getCommand().cooldown() > 0
          && !Arrays.asList(Resource.GROUP_ADMINS).contains(chat.getSender().getUsername())) {
        if (!SkypeBot.getInstance().getCooldownHandler().canUse(data.getCommand())) {
          return;
        }
      }

      long difference = System.currentTimeMillis() - lastCommand;

      if (difference <= 5000L) {
        return;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    List<Object> a = new ArrayList<>();
    a.add(chat);

    if (m.groupCount() > 0) {
      for (int i = 1; i <= m.groupCount(); i++) {
        String g = m.group(i);
        if (g.contains(".") && Utils.isDouble(g)) {
          a.add(Double.parseDouble(g));
        } else if (Utils.isInteger(g)) {
          a.add(Integer.parseInt(g));
        } else {
          a.add(g);
        }
      }
    }

    if (a.size() < data.getMethod().getParameterCount()) {
      for (int i = a.size(); i < data.getMethod().getParameterCount(); i++) {
        if (data.getMethod().getParameters()[i].getType().equals(String.class)) {
          a.add(null);
        } else {
          a.add(0);
        }
      }
    }

    MethodAccessor methodAccessor = null;
    try {
      Field methodAccessorField = Method.class.getDeclaredField("methodAccessor");
      methodAccessorField.setAccessible(true);
      methodAccessor = (MethodAccessor) methodAccessorField.get(data.getMethod());

      if (methodAccessor == null) {
        Method acquireMethodAccessorMethod =
            Method.class.getDeclaredMethod("acquireMethodAccessor", null);
        acquireMethodAccessorMethod.setAccessible(true);
        methodAccessor =
            (MethodAccessor) acquireMethodAccessorMethod.invoke(data.getMethod(), null);

        lastCommand = System.currentTimeMillis();
      }
    } catch (NoSuchFieldException
        | InvocationTargetException
        | IllegalAccessException
        | NoSuchMethodException e) {
      Resource.sendMessage(chat, "Failed... (" + ExceptionUtils.getStackTrace(e) + ")");
    }

    try {
      methodAccessor.invoke(null, a.toArray());
    } catch (Exception e) {
      Resource.sendMessage(
          chat, "Failed... (" + Utils.upload(ExceptionUtils.getStackTrace(e)) + ")");
    }
  }
Esempio n. 9
0
  public static void parseText(SkypeMessage chat) {
    String command;
    String originalCommand;
    try {
      command = chat.getMessage();
      originalCommand = command;
    } catch (Exception ignored) {
      System.out.println("Skype exception occurred");
      return;
    }

    if (command == null) {
      System.out.println("Command is null");
      return;
    }

    System.out.println("Received chat message: " + command);

    if (command.length() < 1) {
      System.out.println("low command length");
      return;
    }

    if (command.startsWith(Resource.COMMAND_PREFIX)) {
      command = command.substring(1);
    }

    String[] commandSplit = command.split(" ");

    if (commandSplit.length == 0) {
      System.out.println("nothing");
      return;
    }

    for (Map.Entry<String, CommandData> s : allCommands.entrySet()) {
      String match = s.getKey();
      if (!s.getValue().getParameterRegex(false).equals("")) {
        match += " " + s.getValue().getParameterRegex(false);
      }

      if (s.getValue().getCommand().command()) {
        match = Resource.COMMAND_PREFIX + match;
      }

      if (s.getValue().getCommand().exact()) {
        match = "^" + match + "$";
      }

      Pattern r = Pattern.compile(match);
      Matcher m = r.matcher(originalCommand);

      if (m.find()) {
        executeCommand(chat, s.getValue(), m);
        System.out.println("executed command");
        return;
      } else if (!s.getValue()
          .getParameterRegex(false)
          .equals(s.getValue().getParameterRegex(true))) {
        match = s.getKey();
        if (!s.getValue().getParameterRegex(true).equals("")) {
          match += " " + s.getValue().getParameterRegex(true);
        }

        if (s.getValue().getCommand().command()) {
          match = Resource.COMMAND_PREFIX + match;
        }

        if (s.getValue().getCommand().exact()) {
          match = "^" + match + "$";
        }

        r = Pattern.compile(match);
        m = r.matcher(originalCommand);
        if (m.find()) {
          executeCommand(chat, s.getValue(), m);
          return;
        }
      }
    }

    if (allCommands.containsKey(commandSplit[0].toLowerCase())) {
      CommandData d = allCommands.get(commandSplit[0].toLowerCase());
      Command c = d.getCommand();

      String correct = commandSplit[0];
      if (!d.getParameterNames().equals("")) {
        correct += " " + d.getParameterNames();
      }

      if (c.command()) {
        if (!originalCommand.startsWith(Resource.COMMAND_PREFIX)) {
          return;
        }

        correct = Resource.COMMAND_PREFIX + correct;
      }

      Resource.sendMessage(chat, "Incorrect syntax: " + correct);

      return;
    }
  }
Esempio n. 10
0
 public static void sendForegroundCommand(CommandData commandData) {
   sendCommand(commandData.setInForeground(true));
 }
Esempio n. 11
0
 public static void sendManualForegroundCommand(CommandData commandData) {
   sendForegroundCommand(commandData.setManuallyLaunched(true));
 }