Beispiel #1
0
    public List<String> call() throws IOException {
      List<String> names = new ArrayList<String>();

      Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
      while (nis.hasMoreElements()) {
        NetworkInterface ni = nis.nextElement();
        LOGGER.fine("Listing up IP addresses for " + ni.getDisplayName());
        Enumeration<InetAddress> e = ni.getInetAddresses();
        while (e.hasMoreElements()) {
          InetAddress ia = e.nextElement();
          if (ia.isLoopbackAddress()) {
            LOGGER.fine(ia + " is a loopback address");
            continue;
          }

          if (!(ia instanceof Inet4Address)) {
            LOGGER.fine(ia + " is not an IPv4 address");
            continue;
          }

          LOGGER.fine(ia + " is a viable candidate");
          names.add(ia.getHostAddress());
        }
      }
      return names;
    }
  @Override
  public String toModelName(final String name) {
    final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix);

    // camelize the model name
    // phone_number => PhoneNumber
    final String camelizedName = camelize(sanitizedName);

    // model name cannot use reserved keyword, e.g. return
    if (isReservedWord(camelizedName)) {
      final String modelName = "Model" + camelizedName;
      LOGGER.warn(
          camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName);
      return modelName;
    }

    // model name starts with number
    if (name.matches("^\\d.*")) {
      final String modelName =
          "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize)
      LOGGER.warn(
          name
              + " (model name starts with number) cannot be used as model name. Renamed to "
              + modelName);
      return modelName;
    }

    return camelizedName;
  }
Beispiel #3
0
		@EventHandler(priority = EventPriority.HIGHEST)
		public void onPlayerJoin(final PlayerJoinEvent event)
		{
			final User user = ess.getUser(event.getPlayer());
			if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
			{
				return;
			}

			try
			{
				sendToJail(user, user.getJail());
			}
			catch (Exception ex)
			{
				if (ess.getSettings().isDebug())
				{
					LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
				}
				else
				{
					LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
				}
			}
			user.sendMessage(_("jailMessage"));
		}
 protected Audit waitForAuditToComplete(Audit audit) {
   LOGGER.debug(
       "WAIT FOR AUDIT TO COMPLETE:"
           + audit
           + ","
           + (long) (audit.getDateOfCreation().getTime() / 1000));
   Long token = new Date().getTime();
   this.getAuditExecutionList().put(audit, token);
   // while the audit is not seen as completed or crashed
   while (!this.getAuditCompletedList().containsKey(token)
       && !this.getAuditCrashedList().containsKey(token)) {
     try {
       Thread.sleep(500);
     } catch (InterruptedException ex) {
       LOGGER.error("", ex);
     }
   }
   if ((audit = this.getAuditCompletedList().get(token)) != null) {
     this.getAuditCompletedList().remove(token);
     return audit;
   }
   if ((audit = this.getAuditCrashedList().get(token).getKey()) != null) {
     this.getAuditCrashedList().remove(token);
     return audit;
   }
   return null;
 }
Beispiel #5
0
 @Override
 public void run() {
   reportStatus.setCurrentProcess(ReportStatusInfo.ReportEngineProcess.DredgeTask);
   try {
     updateCacheFromLdap();
   } catch (Exception e) {
     if (e instanceof PwmException) {
       if (((PwmException) e).getErrorInformation().getError()
           == PwmError.ERROR_DIRECTORY_UNAVAILABLE) {
         if (executorService != null) {
           LOGGER.error(
               PwmConstants.REPORTING_SESSION_LABEL,
               "directory unavailable error during background DredgeTask, will retry; error: "
                   + e.getMessage());
           executorService.schedule(new DredgeTask(), 10, TimeUnit.MINUTES);
         }
       } else {
         LOGGER.error(
             PwmConstants.REPORTING_SESSION_LABEL,
             "error during background DredgeTask: " + e.getMessage());
       }
     }
   } finally {
     reportStatus.setCurrentProcess(ReportStatusInfo.ReportEngineProcess.None);
   }
 }
  public ResPackage loadMainPkg(ResTable resTable, ExtFile apkFile) throws AndrolibException {
    LOGGER.info("Loading resource table...");
    ResPackage[] pkgs = getResPackagesFromApk(apkFile, resTable, sKeepBroken);
    ResPackage pkg = null;

    switch (pkgs.length) {
      case 1:
        pkg = pkgs[0];
        break;
      case 2:
        if (pkgs[0].getName().equals("android")) {
          LOGGER.warning("Skipping \"android\" package group");
          pkg = pkgs[1];
        } else if (pkgs[0].getName().equals("com.htc")) {
          LOGGER.warning("Skipping \"htc\" stupid package group");
          pkg = pkgs[1];
        }
        break;
    }

    if (pkg == null) {
      throw new AndrolibException("Arsc files with zero or multiple packages");
    }

    resTable.addPackage(pkg, true);
    LOGGER.info("Loaded.");
    return pkg;
  }
Beispiel #7
0
 public UserCacheRecord next() {
   try {
     UserCacheRecord returnBean = null;
     while (returnBean == null && this.storageKeyIterator.hasNext()) {
       UserCacheService.StorageKey key = this.storageKeyIterator.next();
       returnBean = userCacheService.readStorageKey(key);
       if (returnBean != null) {
         if (returnBean.getCacheTimestamp() == null) {
           LOGGER.debug(
               PwmConstants.REPORTING_SESSION_LABEL,
               "purging record due to missing cache timestamp: "
                   + JsonUtil.serialize(returnBean));
           userCacheService.removeStorageKey(key);
         } else if (TimeDuration.fromCurrent(returnBean.getCacheTimestamp())
             .isLongerThan(settings.getMaxCacheAge())) {
           LOGGER.debug(
               PwmConstants.REPORTING_SESSION_LABEL,
               "purging record due to old age timestamp: " + JsonUtil.serialize(returnBean));
           userCacheService.removeStorageKey(key);
         } else {
           return returnBean;
         }
       }
     }
   } catch (LocalDBException e) {
     throw new IllegalStateException(
         "unexpected iterator traversal error while reading LocalDB: " + e.getMessage());
   }
   return null;
 }
 private void refreshTimeoutOnEvade(User user, Server server) {
   ServerTimeout timeout =
       SafeNav.of(serverStorage.get(server.getId()))
           .next(TempServerConfig::getServerTimeouts)
           .next(ServerTimeoutStorage::getTimeouts)
           .next(timeouts -> timeouts.get(user.getId()))
           .get();
   if (timeout == null) {
     LOGGER.warn(
         "Attempted to refresh a timeout on a user who was not timed out! {} ({})",
         user.getUsername(),
         user.getId());
     return;
   }
   LOGGER.info(
       "User {} ({}) attempted to evade a timeout on {} ({})!",
       user.getUsername(),
       user.getId(),
       server.getName(),
       server.getId());
   Channel channel = apiClient.getChannelById(server.getId(), server);
   apiClient.sendMessage(
       loc.localize(
           "listener.mod.timeout.on_evasion",
           user.getId(),
           formatDuration(Duration.between(Instant.now(), timeout.getEndTime())),
           formatInstant(timeout.getEndTime())),
       channel);
   applyTimeoutRole(user, server, channel);
 }
Beispiel #9
0
  /**
   * This method tries to compute the name of the host that's reachable by all the other nodes.
   *
   * <p>Since it's possible that the slave is not reachable from the master (it may be behind a
   * firewall, connecting to master via JNLP), this method may return null.
   *
   * <p>It's surprisingly tricky for a machine to know a name that other systems can get to,
   * especially between things like DNS search suffix, the hosts file, and YP.
   *
   * <p>So the technique here is to compute possible interfaces and names on the slave, then try to
   * ping them from the master, and pick the one that worked.
   *
   * <p>The computation may take some time, so it employs caching to make the successive lookups
   * faster.
   *
   * @since 1.300
   * @return null if the host name cannot be computed (for example because this computer is offline,
   *     because the slave is behind the firewall, etc.)
   */
  public String getHostName() throws IOException, InterruptedException {
    if (hostNameCached)
      // in the worst case we end up having multiple threads computing the host name simultaneously,
      // but that's not harmful, just wasteful.
      return cachedHostName;

    VirtualChannel channel = getChannel();
    if (channel == null) return null; // can't compute right now

    for (String address : channel.call(new ListPossibleNames())) {
      try {
        InetAddress ia = InetAddress.getByName(address);
        if (!(ia instanceof Inet4Address)) {
          LOGGER.fine(address + " is not an IPv4 address");
          continue;
        }
        if (!ComputerPinger.checkIsReachable(ia, 3)) {
          LOGGER.fine(address + " didn't respond to ping");
          continue;
        }
        cachedHostName = ia.getCanonicalHostName();
        hostNameCached = true;
        return cachedHostName;
      } catch (IOException e) {
        // if a given name fails to parse on this host, we get this error
        LOGGER.log(Level.FINE, "Failed to parse " + address, e);
      }
    }

    // allow the administrator to manually specify the host name as a fallback. HUDSON-5373
    cachedHostName = channel.call(new GetFallbackName());
    hostNameCached = true;
    return cachedHostName;
  }
 public void onTimeoutExpire(User user, Server server) {
   String serverId = server.getId();
   TempServerConfig serverConfig = serverStorage.get(serverId);
   if (serverConfig == null) {
     serverConfig = new TempServerConfig(serverId);
     serverStorage.put(serverId, serverConfig);
   }
   ServerTimeoutStorage storage = serverConfig.getServerTimeouts();
   if (storage != null) {
     ServerTimeout timeout = storage.getTimeouts().remove(user.getId());
     if (timeout != null) {
       saveServerConfig(serverConfig);
       LOGGER.info(
           "Expiring timeout for {} ({}) in {} ({})",
           user.getUsername(),
           user.getId(),
           server.getName(),
           server.getId());
       if (apiClient.getUserById(user.getId(), server) != NO_USER) {
         apiClient.sendMessage(
             loc.localize("message.mod.timeout.expire", user.getId()), server.getId());
       }
       removeTimeoutRole(user, server, apiClient.getChannelById(server.getId()));
       return;
     }
   }
   LOGGER.warn(
       "Unable to expire: find server or timeout entry for {} ({}) in {} ({})",
       user.getUsername(),
       user.getId(),
       server.getName(),
       server.getId());
 }
 public boolean applyTimeout(
     User issuingUser, Channel noticeChannel, Server server, User user, Duration duration) {
   String serverId = server.getId();
   if (duration != null && !duration.isNegative() && !duration.isZero()) {
     ServerTimeout timeout =
         new ServerTimeout(
             duration,
             Instant.now(),
             user.getId(),
             serverId,
             user.getUsername(),
             issuingUser.getId());
     TempServerConfig serverConfig = serverStorage.get(serverId);
     if (serverConfig == null) {
       serverConfig = new TempServerConfig(serverId);
       serverStorage.put(serverId, serverConfig);
     }
     ServerTimeoutStorage storage = serverConfig.getServerTimeouts();
     if (storage == null) {
       storage = new ServerTimeoutStorage();
       serverConfig.setServerTimeouts(storage);
     }
     if (applyTimeoutRole(user, server, noticeChannel)) {
       storage.getTimeouts().put(user.getId(), timeout);
       ScheduledFuture future =
           timeoutService.schedule(
               () -> onTimeoutExpire(user, server), duration.getSeconds(), TimeUnit.SECONDS);
       timeout.setTimerFuture(future);
       saveServerConfig(serverConfig);
       String durationStr = formatDuration(duration);
       String instantStr = formatInstant(timeout.getEndTime());
       String msg =
           loc.localize(
               "commands.mod.timeout.response",
               user.getUsername(),
               user.getId(),
               durationStr,
               instantStr);
       apiClient.sendMessage(msg, noticeChannel);
       LOGGER.info(
           "[{}] '{}': Timing out {} ({}) for {} (until {}), issued by {} ({})",
           serverId,
           server.getName(),
           user.getUsername(),
           user.getId(),
           durationStr,
           instantStr,
           issuingUser.getUsername(),
           issuingUser.getId());
     }
     //  No else with error - applyTimeoutRole does that for us
     return true;
   } else {
     LOGGER.warn("Invalid duration format");
   }
   return false;
 }
  /** Called when a module build that corresponds to this module set build has completed. */
  /* package */ void notifyModuleBuild(IvyBuild newBuild) {
    try {
      // update module set build number
      getParent().updateNextBuildNumber();

      // update actions
      Map<IvyModule, List<IvyBuild>> moduleBuilds = getModuleBuilds();

      // actions need to be replaced atomically especially
      // given that two builds might complete simultaneously.
      synchronized (this) {
        boolean modified = false;

        List<Action> actions = getActions();
        Set<Class<? extends AggregatableAction>> individuals =
            new HashSet<Class<? extends AggregatableAction>>();
        for (Action a : actions) {
          if (a instanceof IvyAggregatedReport) {
            IvyAggregatedReport mar = (IvyAggregatedReport) a;
            mar.update(moduleBuilds, newBuild);
            individuals.add(mar.getIndividualActionType());
            modified = true;
          }
        }

        // see if the new build has any new aggregatable action that we
        // haven't seen.
        for (AggregatableAction aa : newBuild.getActions(AggregatableAction.class)) {
          if (individuals.add(aa.getClass())) {
            // new AggregatableAction
            IvyAggregatedReport mar = aa.createAggregatedAction(this, moduleBuilds);
            mar.update(moduleBuilds, newBuild);
            actions.add(mar);
            modified = true;
          }
        }

        if (modified) {
          save();
          getProject().updateTransientActions();
        }
      }

      // symlink to this module build
      String moduleFsName = newBuild.getProject().getModuleName().toFileSystemName();
      Util.createSymlink(
          getRootDir(),
          "../../modules/" + moduleFsName + "/builds/" + newBuild.getId() /*ugly!*/,
          moduleFsName,
          StreamTaskListener.NULL);
    } catch (IOException e) {
      LOGGER.log(Level.WARNING, "Failed to update " + this, e);
    } catch (InterruptedException e) {
      LOGGER.log(Level.WARNING, "Failed to update " + this, e);
    }
  }
 public void loadServerConfigFiles() {
   if (!Files.exists(serverStorageDir)) {
     LOGGER.info("Server storage directory doesn't exist, not loading anything");
     return;
   }
   try (Stream<Path> files = Files.list(serverStorageDir)) {
     files
         .filter(p -> p.getFileName().toString().endsWith(".json"))
         .forEach(this::loadServerConfig);
   } catch (IOException e) {
     LOGGER.warn("Unable to load server storage files", e);
     return;
   }
 }
Beispiel #14
0
    protected ConfigSaveState updatePartial(String xmlPartial, final String md5) throws Exception {
      LOGGER.debug("[Config Save] Updating partial");
      org.dom4j.Document document = documentRoot();
      Element root = document.getRootElement();

      Element configElement = ((Element) root.selectSingleNode(getXpath()));
      List nodes = configElement.getParent().content();
      int index = nodes.indexOf(configElement);

      LOGGER.debug("[Config Save] Converting to object");
      Element newConfigElement = reader.read(new StringReader(xmlPartial)).getRootElement();
      nodes.set(index, newConfigElement);

      return saveConfig(document.asXML(), md5);
    }
 /**
  * Removes the timeout role from the given user. This does NOT create or manage any
  * storage/persistence, it only sets the user's roles
  *
  * @param user The user to remove the timeout role
  * @param server The server on which to remove the user from the timeout role
  * @param invocationChannel The channel to send messages on error
  */
 public boolean removeTimeoutRole(User user, Server server, Channel invocationChannel) {
   String serverId = server.getId();
   TempServerConfig serverConfig = serverStorage.get(serverId);
   if (serverConfig == null) {
     serverConfig = new TempServerConfig(serverId);
     serverStorage.put(serverId, serverConfig);
   }
   ServerTimeoutStorage storage = serverConfig.getServerTimeouts();
   String serverName = server.getName();
   if (storage != null && storage.getTimeoutRoleId() != null) {
     String timeoutRoleId = storage.getTimeoutRoleId();
     Role timeoutRole = apiClient.getRole(timeoutRoleId, server);
     if (timeoutRole != NO_ROLE) {
       //  Get roles
       Set<Role> userRoles =
           apiClient.getMemberRoles(apiClient.getUserMember(user, server), server);
       //  Delete the ban role
       LinkedHashSet<String> newRoles = new LinkedHashSet<>(userRoles.size() - 1);
       userRoles
           .stream()
           .map(Role::getId)
           .filter(s -> !timeoutRoleId.equals(s))
           .forEach(newRoles::add);
       //  Update
       apiClient.updateRoles(user, server, newRoles);
       return userRoles.size() == newRoles.size();
     } else {
       LOGGER.warn(
           "Timeout role ID {} for server {} ({}) does not exist",
           timeoutRoleId,
           serverName,
           serverId);
       apiClient.sendMessage(
           loc.localize("message.mod.timeout.bad_role", timeoutRoleId), invocationChannel);
     }
   } else {
     storage = new ServerTimeoutStorage();
     serverConfig.setServerTimeouts(storage);
     serverStorage.put(serverId, serverConfig);
     LOGGER.warn(
         "Timeout role for server {} ({}) is not configured",
         storage.getTimeoutRoleId(),
         serverName,
         serverId);
     apiClient.sendMessage(loc.localize("message.mod.timeout.not_configured"), invocationChannel);
   }
   return false;
 }
  public boolean buildManifest(ExtFile appDir, Map<String, Object> usesFramework)
      throws BrutException {
    try {
      if (!new File(appDir, "AndroidManifest.xml").exists()) {
        return false;
      }
      if (!apkOptions.forceBuildAll) {
        LOGGER.info("Checking whether resources has changed...");
      }

      File apkDir = new File(appDir, APK_DIRNAME);

      if (apkOptions.debugMode) {
        mAndRes.remove_application_debug(new File(apkDir, "AndroidManifest.xml").getAbsolutePath());
      }

      if (apkOptions.forceBuildAll
          || isModified(
              newFiles(APK_MANIFEST_FILENAMES, appDir), newFiles(APK_MANIFEST_FILENAMES, apkDir))) {
        LOGGER.info("Building AndroidManifest.xml...");

        File apkFile = File.createTempFile("APKTOOL", null);
        apkFile.delete();

        File ninePatch = new File(appDir, "9patch");
        if (!ninePatch.exists()) {
          ninePatch = null;
        }

        mAndRes.aaptPackage(
            apkFile,
            new File(appDir, "AndroidManifest.xml"),
            null,
            ninePatch,
            null,
            parseUsesFramework(usesFramework));

        Directory tmpDir = new ExtFile(apkFile).getDirectory();
        tmpDir.copyToDir(apkDir, APK_MANIFEST_FILENAMES);
      }
      return true;
    } catch (IOException | DirectoryException ex) {
      throw new AndrolibException(ex);
    } catch (AndrolibException ex) {
      LOGGER.warning("Parse AndroidManifest.xml failed, treat it as raw file.");
      return buildManifestRaw(appDir);
    }
  }
 public void decodeSourcesSmali(
     File apkFile,
     File outDir,
     String filename,
     boolean debug,
     String debugLinePrefix,
     boolean bakdeb,
     int api)
     throws AndrolibException {
   try {
     File smaliDir;
     if (filename.equalsIgnoreCase("classes.dex")) {
       smaliDir = new File(outDir, SMALI_DIRNAME);
     } else {
       smaliDir =
           new File(outDir, SMALI_DIRNAME + "_" + filename.substring(0, filename.indexOf(".")));
     }
     OS.rmdir(smaliDir);
     smaliDir.mkdirs();
     LOGGER.info("Baksmaling " + filename + "...");
     SmaliDecoder.decode(apkFile, smaliDir, filename, debug, debugLinePrefix, bakdeb, api);
   } catch (BrutException ex) {
     throw new AndrolibException(ex);
   }
 }
Beispiel #18
0
 public void run() {
   try {
     publishStatisticsToCloud();
   } catch (Exception e) {
     LOGGER.error("error publishing statistics to cloud: " + e.getMessage());
   }
 }
 private void stopTimeout(MessageContext context, String args) {
   if (args.isEmpty()) {
     apiClient.sendMessage(
         loc.localize("commands.mod.stoptimeout.response.invalid"), context.getChannel());
     return;
   }
   String uid = args;
   if (uid.length() > 4) {
     if (uid.startsWith("<@")) {
       uid = uid.substring(2, uid.length() - 1);
     }
     Server server = context.getServer();
     User user = apiClient.getUserById(uid, server);
     if (user == NO_USER) {
       user = new User("UNKNOWN", uid, "", null);
     }
     LOGGER.info(
         "{} ({}) is attempting to cancel timeout for {} ({}) in {} ({})",
         context.getAuthor().getUsername(),
         context.getAuthor().getId(),
         user.getUsername(),
         user.getId(),
         server.getName(),
         server.getId());
     cancelTimeout(user, server, context.getChannel());
   } else {
     apiClient.sendMessage(
         loc.localize("commands.mod.stoptimeout.response.invalid"), context.getChannel());
   }
 }
Beispiel #20
0
 @Override
 public void run() {
   try {
     initTempData();
   } catch (LocalDBException | PwmUnrecoverableException e) {
     LOGGER.error(
         PwmConstants.REPORTING_SESSION_LABEL, "error during initialization: " + e.getMessage());
     status = STATUS.CLOSED;
     return;
   }
   final long secondsUntilNextDredge =
       settings.getJobOffsetSeconds()
           + TimeDuration.fromCurrent(Helper.nextZuluZeroTime()).getTotalSeconds();
   executorService.scheduleAtFixedRate(
       new DredgeTask(),
       secondsUntilNextDredge,
       TimeDuration.DAY.getTotalSeconds(),
       TimeUnit.SECONDS);
   executorService.scheduleAtFixedRate(
       new RolloverTask(),
       secondsUntilNextDredge + 1,
       TimeDuration.DAY.getTotalSeconds(),
       TimeUnit.SECONDS);
   executorService.submit(new RolloverTask());
 }
  public void build(ExtFile appDir, File outFile) throws BrutException {
    LOGGER.info("Using Apktool " + Androlib.getVersion());

    Map<String, Object> meta = readMetaFile(appDir);
    Object t1 = meta.get("isFrameworkApk");
    apkOptions.isFramework = (t1 == null ? false : (Boolean) t1);
    apkOptions.resourcesAreCompressed =
        meta.get("compressionType") == null
            ? false
            : Boolean.valueOf(meta.get("compressionType").toString());

    mAndRes.setSdkInfo((Map<String, String>) meta.get("sdkInfo"));
    mAndRes.setPackageId((Map<String, String>) meta.get("packageInfo"));
    mAndRes.setPackageInfo((Map<String, String>) meta.get("packageInfo"));
    mAndRes.setVersionInfo((Map<String, String>) meta.get("versionInfo"));

    if (outFile == null) {
      String outFileName = (String) meta.get("apkFileName");
      outFile =
          new File(
              appDir, "dist" + File.separator + (outFileName == null ? "out.apk" : outFileName));
    }

    new File(appDir, APK_DIRNAME).mkdirs();
    buildSources(appDir);
    buildNonDefaultSources(appDir);
    buildResources(appDir, (Map<String, Object>) meta.get("usesFramework"));
    buildLib(appDir);
    buildCopyOriginalFiles(appDir);
    buildApk(appDir, outFile);

    // we must go after the Apk is built, and copy the files in via Zip
    // this is because Aapt won't add files it doesn't know (ex unknown files)
    buildUnknownFiles(appDir, outFile, meta);
  }
 @Override
 public void auditCrashed(Audit audit, Exception exception) {
   String url = "";
   if (audit.getSubject() != null) {
     url = audit.getSubject().getURL();
   }
   LOGGER.error(
       "AUDIT CRASHED:"
           + audit
           + ","
           + url
           + ","
           + (long) (audit.getDateOfCreation().getTime() / 1000),
       exception);
   Audit auditCrashed = null;
   for (Audit auditRunning : this.auditExecutionList.keySet()) {
     if (auditRunning.getId().equals(audit.getId())
         && (long) (auditRunning.getDateOfCreation().getTime() / 1000)
             == (long) (audit.getDateOfCreation().getTime() / 1000)) {
       auditCrashed = auditRunning;
       break;
     }
   }
   if (auditCrashed != null) {
     Long token = this.auditExecutionList.get(auditCrashed);
     this.auditExecutionList.remove(auditCrashed);
     this.auditCrashedList.put(token, new AbstractMap.SimpleImmutableEntry<>(audit, exception));
     this.exception = exception;
   }
 }
 public void run() {
   try {
     reduceWordDB();
   } catch (LocalDBException e) {
     LOGGER.error("error during old record purge: " + e.getMessage());
   }
 }
 public void buildSources(File appDir) throws AndrolibException {
   if (!buildSourcesRaw(appDir, "classes.dex")
       && !buildSourcesSmali(appDir, "smali", "classes.dex")
       && !buildSourcesJava(appDir)) {
     LOGGER.warning("Could not find sources");
   }
 }
 public boolean buildSourcesJava(File appDir) throws AndrolibException {
   File javaDir = new File(appDir, "src");
   if (!javaDir.exists()) {
     return false;
   }
   File dex = new File(appDir, APK_DIRNAME + "/classes.dex");
   if (!apkOptions.forceBuildAll) {
     LOGGER.info("Checking whether sources has changed...");
   }
   if (apkOptions.forceBuildAll || isModified(javaDir, dex)) {
     LOGGER.info("Building java sources...");
     dex.delete();
     new AndrolibJava().build(javaDir, dex);
   }
   return true;
 }
 @Override
 public void auditCompleted(Audit audit) {
   LOGGER.debug(
       "AUDIT COMPLETED:"
           + audit
           + ","
           + audit.getSubject().getURL()
           + ","
           + (long) (audit.getDateOfCreation().getTime() / 1000)
           + audit.getId());
   Audit auditCompleted = null;
   for (Audit auditRunning : this.auditExecutionList.keySet()) {
     if (auditRunning.getId().equals(audit.getId())
         && (long) (auditRunning.getDateOfCreation().getTime() / 1000)
             == (long) (audit.getDateOfCreation().getTime() / 1000)) {
       auditCompleted = auditRunning;
       break;
     }
   }
   if (auditCompleted != null) {
     Long token = this.auditExecutionList.get(auditCompleted);
     this.auditExecutionList.remove(auditCompleted);
     this.auditCompletedList.put(token, audit);
   }
 }
    public void process(WatchedEvent event) {
      LOGGER.debug(
          "Watcher fired on path: "
              + event.getPath()
              + " state: "
              + event.getState()
              + " type "
              + event.getType());

      latchIfNoChange.countDown();

      // ignore any children except valid children for a queue
      if (keyHandler.hasValidName(ZkUtils.getPathEnd(event.getPath()))) {

        if (highestPriorityChanged == null) {
          highestPriorityChanged = keyHandler.getPriority(event.getPath());
        } else {
          synchronized (highestPriorityChanged) {
            PRIORITY changedPriority = keyHandler.getPriority(event.getPath());
            if (changedPriority != null && changedPriority.compareTo(highestPriorityChanged) < 0) {
              highestPriorityChanged = changedPriority;
            }
          }
        }
      }
    }
  public void decodeManifest(ResTable resTable, ExtFile apkFile, File outDir)
      throws AndrolibException {

    Duo<ResFileDecoder, AXmlResourceParser> duo = getManifestFileDecoder();
    ResFileDecoder fileDecoder = duo.m1;

    // Set ResAttrDecoder
    duo.m2.setAttrDecoder(new ResAttrDecoder());
    ResAttrDecoder attrDecoder = duo.m2.getAttrDecoder();

    // Fake ResPackage
    attrDecoder.setCurrentPackage(new ResPackage(resTable, 0, null));

    Directory inApk, out;
    try {
      inApk = apkFile.getDirectory();
      out = new FileDirectory(outDir);

      LOGGER.info("Decoding AndroidManifest.xml with only framework resources...");
      fileDecoder.decodeManifest(inApk, "AndroidManifest.xml", out, "AndroidManifest.xml");

    } catch (DirectoryException ex) {
      throw new AndrolibException(ex);
    }
  }
 @Override
 protected void onActTerminated(Act act, Audit audit) {
   super.onActTerminated(act, audit);
   if (getException() == null) {
     sendAuditResultEmail(act, getLocale());
   }
   LOGGER.info("Audit scenario terminated on " + this.scenarioName);
 }
  public void decode(ResTable resTable, ExtFile apkFile, File outDir) throws AndrolibException {
    Duo<ResFileDecoder, AXmlResourceParser> duo = getResFileDecoder();
    ResFileDecoder fileDecoder = duo.m1;
    ResAttrDecoder attrDecoder = duo.m2.getAttrDecoder();

    attrDecoder.setCurrentPackage(resTable.listMainPackages().iterator().next());

    Directory inApk, in = null, out;
    try {
      inApk = apkFile.getDirectory();
      out = new FileDirectory(outDir);

      LOGGER.info("Decoding AndroidManifest.xml with resources...");

      fileDecoder.decodeManifest(inApk, "AndroidManifest.xml", out, "AndroidManifest.xml");

      if (inApk.containsDir("res")) {
        in = inApk.getDir("res");
      }
      out = out.createDir("res");
    } catch (DirectoryException ex) {
      throw new AndrolibException(ex);
    }

    ExtMXSerializer xmlSerializer = getResXmlSerializer();
    for (ResPackage pkg : resTable.listMainPackages()) {
      attrDecoder.setCurrentPackage(pkg);

      LOGGER.info("Decoding file-resources...");
      for (ResResource res : pkg.listFiles()) {
        fileDecoder.decode(res, in, out);
      }

      LOGGER.info("Decoding values */* XMLs...");
      for (ResValuesFile valuesFile : pkg.listValuesFiles()) {
        generateValuesFile(valuesFile, out, xmlSerializer);
      }
      generatePublicXml(pkg, out, xmlSerializer);
      LOGGER.info("Done.");
    }

    AndrolibException decodeError = duo.m2.getFirstError();
    if (decodeError != null) {
      throw decodeError;
    }
  }