Beispiel #1
0
  private void playerLogEvent(IPlayer player, HookType type) {
    List<Hook> hooks = HookHandler.getHooks(type);

    if (hooks != null)
      for (Hook hook : hooks)
        if (hook.getPlayerName().equalsIgnoreCase(player.getName())) hook.execute();
  }
Beispiel #2
0
  @Override
  public void OnPlayerLeftClick(RunsafePlayerClickEvent event) {
    List<Hook> hooks = HookHandler.getHooks(HookType.LEFT_CLICK_BLOCK);

    if (hooks != null) {
      IBlock block = event.getBlock();
      Item material = block.getMaterial();
      ILocation blockLocation = block.getLocation();
      String blockWorldName = blockLocation.getWorld().getName();
      String playerName = event.getPlayer().getName();
      for (Hook hook : hooks) {
        IWorld world = hook.getWorld();
        if (world != null && !blockWorldName.equals(world.getName())) return;

        LuaTable table = new LuaTable();
        table.set("player", LuaValue.valueOf(playerName));
        table.set("world", LuaValue.valueOf(blockWorldName));
        table.set("x", LuaValue.valueOf(blockLocation.getBlockX()));
        table.set("y", LuaValue.valueOf(blockLocation.getBlockY()));
        table.set("z", LuaValue.valueOf(blockLocation.getBlockZ()));
        table.set("blockID", LuaValue.valueOf(material.getItemID()));
        table.set("blockData", LuaValue.valueOf(material.getData()));

        hook.execute(table);
      }
    }
  }
Beispiel #3
0
  @Override
  public boolean OnBlockBreak(IPlayer player, IBlock block) {
    List<Hook> hooks = HookHandler.getHooks(HookType.BLOCK_BREAK);

    if (hooks != null) {
      ILocation blockLocation = block.getLocation();
      String blockWorld = blockLocation.getWorld().getName();
      for (Hook hook : hooks) {
        IWorld world = hook.getWorld();
        if (world != null && !blockWorld.equals(world.getName())) return true;

        LuaTable table = new LuaTable();
        if (player != null) table.set("player", LuaValue.valueOf(player.getName()));

        table.set("world", LuaValue.valueOf(blockWorld));
        table.set("x", LuaValue.valueOf(blockLocation.getBlockX()));
        table.set("y", LuaValue.valueOf(blockLocation.getBlockY()));
        table.set("z", LuaValue.valueOf(blockLocation.getBlockZ()));
        table.set("blockID", LuaValue.valueOf(block.getMaterial().getItemID()));
        table.set("blockData", LuaValue.valueOf(((RunsafeBlock) block).getData()));

        hook.execute(table);
      }
    }
    return true;
  }
Beispiel #4
0
 static Method findTargetMethod(Method method)
     throws NoSuchMethodException, ClassNotFoundException {
   Hook hook = method.getAnnotation(Hook.class);
   String[] split = hook.value().split("->");
   return findTargetMethod(
       method, Class.forName(split[0]), split.length == 1 ? method.getName() : split[1]);
 }
Beispiel #5
0
  @Override
  public void OnPlayerDamage(IPlayer player, RunsafeEntityDamageEvent event) {
    List<Hook> hooks = HookHandler.getHooks(HookType.PLAYER_DAMAGE);

    if (hooks != null) {
      IWorld damageWorld = player.getWorld();

      LuaString playerName = LuaValue.valueOf(player.getName());
      LuaString damageCause = LuaValue.valueOf(event.getCause().name());
      LuaValue damage = LuaValue.valueOf(event.getDamage());

      for (Hook hook : hooks) {
        IWorld world = hook.getWorld();
        if (world == null || !world.isWorld(damageWorld)) return;

        LuaTable table = new LuaTable();
        table.set("player", playerName);
        table.set("playerHealth", player.getHealth());
        table.set("playerMaxHealth", player.getMaxHealth());
        table.set("damage", damage);
        table.set("cause", damageCause);

        hook.execute(table);
      }
    }
  }
Beispiel #6
0
  @SuppressWarnings("unchecked")
  @Override
  public void OnPlayerCustomEvent(RunsafeCustomEvent event) {
    HookType type = null;
    String eventType = event.getEvent();

    if (eventType.equals("region.enter")) type = HookType.REGION_ENTER;
    else if (eventType.equals("region.leave")) type = HookType.REGION_LEAVE;

    if (type != null) {
      List<Hook> hooks = HookHandler.getHooks(type);

      if (hooks != null) {
        for (final Hook hook : hooks) {
          Map<String, String> data = (Map<String, String>) event.getData();
          if (((String) hook.getData())
              .equalsIgnoreCase(String.format("%s-%s", data.get("world"), data.get("region")))) {
            final LuaTable table = new LuaTable();
            table.set("player", LuaValue.valueOf(event.getPlayer().getName()));

            scheduler.runNow(
                new Runnable() {
                  @Override
                  public void run() {
                    hook.execute(table);
                  }
                });
          }
        }
      }
    }
  }
 @Override
 public void visitEnd() {
   for (Hook transplant : transplants) {
     String resourceName =
         "/"
             + transplantMapper.mapResourceName(
                 classFileFormatVersion, transplant.getClassSpec() + ".class");
     transplantMethod(resourceName, transplant, cv);
   }
 }
Beispiel #8
0
  private void handleItemHook(Hook hook, IPlayer player, RunsafeMeta item) {
    IWorld hookWorld = hook.getWorld();
    if (hookWorld.isWorld(player.getWorld())) {
      LuaTable table = new LuaTable();
      table.set("player", player.getName());
      table.set("itemID", item.getItemId());
      table.set("itemName", item.hasDisplayName() ? item.getDisplayName() : item.getNormalName());

      hook.execute(table);
    }
  }
  public static void setInstance(Hook hook) {
    if (_log.isDebugEnabled()) {
      _log.debug("Set " + hook.getClass().getName());
    }

    _hook = hook;
  }
Beispiel #10
0
  @Override
  public void OnBlockRedstoneEvent(RunsafeBlockRedstoneEvent event) {
    if (event.getNewCurrent() > 0 && event.getOldCurrent() == 0) {
      List<Hook> hooks = HookHandler.getHooks(HookType.BLOCK_GAINS_CURRENT);

      if (hooks != null) {
        for (Hook hook : hooks) {
          IBlock block = event.getBlock();
          if (block != null) {
            ILocation location = block.getLocation();
            if (location.getWorld().getName().equals(hook.getLocation().getWorld().getName()))
              if (location.distance(hook.getLocation()) < 1) hook.execute();
          }
        }
      }
    }
  }
Beispiel #11
0
  @Override
  public void OnPlayerDeathEvent(RunsafePlayerDeathEvent event) {
    List<Hook> hooks = HookHandler.getHooks(HookType.PLAYER_DEATH);

    if (hooks != null) {
      IPlayer player = event.getEntity();

      for (Hook hook : hooks) {
        IWorld hookWorld = hook.getWorld();
        if (hookWorld.isWorld(player.getWorld())) {
          LuaTable table = new LuaTable();
          table.set("player", LuaValue.valueOf(player.getName()));

          hook.execute(table);
        }
      }
    }
  }
Beispiel #12
0
  @Override
  public void OnPlayerInteractEvent(RunsafePlayerInteractEvent event) {
    debug.debugFine("Interact event detected");
    List<Hook> hooks = HookHandler.getHooks(HookType.INTERACT);

    if (hooks != null) {
      debug.debugFine("Hooks not null");
      for (Hook hook : hooks) {
        debug.debugFine("Processing hook...");
        IBlock block = event.getBlock();
        if (hook.getData() != null)
          if (block == null || block.getMaterial().getItemID() != (Integer) hook.getData())
            continue;

        debug.debugFine("Block is not null");

        IWorld hookWorld = hook.getWorld();
        ILocation location = block.getLocation();
        if (hookWorld == null) {
          debug.debugFine("Hook world is null, using location");
          if (location.getWorld().getName().equals(hook.getLocation().getWorld().getName())) {
            debug.debugFine("Correct world!");
            if (location.distance(hook.getLocation()) < 1) {
              debug.debugFine("Distance is less than 1");
              LuaTable table = new LuaTable();
              if (event.getPlayer() != null)
                table.set("player", LuaValue.valueOf(event.getPlayer().getName()));

              table.set("x", LuaValue.valueOf(location.getBlockX()));
              table.set("y", LuaValue.valueOf(location.getBlockY()));
              table.set("z", LuaValue.valueOf(location.getBlockZ()));
              table.set("blockID", LuaValue.valueOf(block.getMaterial().getItemID()));
              table.set("blockData", LuaValue.valueOf((block).getData()));

              hook.execute(table);
            }
          }
        } else if (hookWorld.getName().equals(block.getWorld().getName())) {
          debug.debugFine("Hook world is null, sending location data");
          LuaTable table = new LuaTable();
          if (event.getPlayer() != null)
            table.set("player", LuaValue.valueOf(event.getPlayer().getName()));

          table.set("x", LuaValue.valueOf(location.getBlockX()));
          table.set("y", LuaValue.valueOf(location.getBlockY()));
          table.set("z", LuaValue.valueOf(location.getBlockZ()));
          table.set("blockID", LuaValue.valueOf(block.getMaterial().getItemID()));
          table.set("blockData", LuaValue.valueOf((block).getData()));

          hook.execute(table);
        }
      }
    }
  }
Beispiel #13
0
  @Override
  public void OnPlayerChatEvent(RunsafePlayerChatEvent event) {
    List<Hook> hooks = HookHandler.getHooks(HookType.CHAT_MESSAGE);

    if (hooks != null) {
      IPlayer player = event.getPlayer();
      IWorld playerWorld = player.getWorld();

      if (playerWorld == null) return;

      for (Hook hook : hooks) {
        if (hook.getWorld().isWorld(player.getWorld())) {
          LuaTable table = new LuaTable();
          table.set("player", LuaValue.valueOf(player.getName()));
          table.set("message", LuaValue.valueOf(event.getMessage()));

          hook.execute(table);
        }
      }
    }
  }
  @Transactional
  @Override
  @CacheEvict(value = "hooks", allEntries = true)
  public CommandProcessingResult createHook(final JsonCommand command) {

    try {
      this.context.authenticatedUser();

      this.fromApiJsonDeserializer.validateForCreate(command.json());

      final HookTemplate template =
          retrieveHookTemplateBy(command.stringValueOfParameterNamed(nameParamName));
      final String configJson = command.jsonFragment(configParamName);
      final Set<HookConfiguration> config =
          assembleConfig(command.mapValueOfParameterNamed(configJson), template);
      final JsonArray events = command.arrayOfParameterNamed(eventsParamName);
      final Set<HookResource> allEvents = assembleSetOfEvents(events);
      Template ugdTemplate = null;
      if (command.hasParameter(templateIdParamName)) {
        final Long ugdTemplateId = command.longValueOfParameterNamed(templateIdParamName);
        ugdTemplate = this.ugdTemplateRepository.findOne(ugdTemplateId);
        if (ugdTemplate == null) {
          throw new TemplateNotFoundException(ugdTemplateId);
        }
      }
      final Hook hook = Hook.fromJson(command, template, config, allEvents, ugdTemplate);

      validateHookRules(template, config, allEvents);

      this.hookRepository.save(hook);

      return new CommandProcessingResultBuilder()
          .withCommandId(command.commandId())
          .withEntityId(hook.getId())
          .build();
    } catch (final DataIntegrityViolationException dve) {
      handleHookDataIntegrityIssues(command, dve);
      return CommandProcessingResult.empty();
    }
  }
    @Override
    public MethodVisitor visitMethod(
        int access, String name, String desc, String signature, String[] exceptions) {
      MethodVisitor visitor = super.visitMethod(access, name, desc, signature, exceptions);

      /* Remove transplant jobs where the method already exists - probably because of an earlier patch script. */ {
        Iterator<Hook> it = transplants.iterator();
        while (it.hasNext()) {
          Hook h = it.next();
          if (h.getMethodName().equals(name) && h.getMethodDescriptor().equals(desc)) it.remove();
        }
      }

      for (TargetMatcher t : targets) {
        if (t.matches(ownClassSpec, name, desc)) {
          return factory.createMethodVisitor(
              name, desc, visitor, new MethodLogistics(access, desc));
        }
      }

      return visitor;
    }
Beispiel #16
0
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) {
    Hook hook = new Hook();
    Method customMethod = null;
    Object[] customArgs = new Object[args.length + 1];

    // Get a string representation of this invokation.
    String key = MethodCache.getKey(this.original, method.getName(), args);

    // Look for a custom handler.
    if (this.mapping.containsKey(key)) {
      customArgs[0] = hook;
      System.arraycopy(args, 0, customArgs, 1, args.length);

      Method cached = MethodCache.getMethod(this.custom, this.mapping.get(key), customArgs);

      if (cached != null) customMethod = cached;
    }

    if (customMethod == null && !key.equals("ls.d(mw)") && !key.equals("ls.s()"))
      System.out.println(key + " => " + method);

    // Go ahead.
    Object toReturn = null;
    try {
      if (customMethod != null) toReturn = customMethod.invoke(this.custom, customArgs);
    } catch (IllegalAccessException | InvocationTargetException e) {
      e.printStackTrace();
    }

    try {
      if (!hook.isCancelled()) toReturn = method.invoke(this.original, args);
    } catch (IllegalAccessException | InvocationTargetException e) {
      e.printStackTrace();
    }

    return toReturn;
  }
  @Transactional
  @Override
  @CacheEvict(value = "hooks", allEntries = true)
  public CommandProcessingResult updateHook(final Long hookId, final JsonCommand command) {

    try {
      this.context.authenticatedUser();

      this.fromApiJsonDeserializer.validateForUpdate(command.json());

      final Hook hook = retrieveHookBy(hookId);
      final HookTemplate template = hook.getHookTemplate();
      final Map<String, Object> changes = hook.update(command);

      if (!changes.isEmpty()) {

        if (changes.containsKey(templateIdParamName)) {
          final Long ugdTemplateId = command.longValueOfParameterNamed(templateIdParamName);
          final Template ugdTemplate = this.ugdTemplateRepository.findOne(ugdTemplateId);
          if (ugdTemplate == null) {
            changes.remove(templateIdParamName);
            throw new TemplateNotFoundException(ugdTemplateId);
          }
          hook.updateUgdTemplate(ugdTemplate);
        }

        if (changes.containsKey(eventsParamName)) {
          final Set<HookResource> events =
              assembleSetOfEvents(command.arrayOfParameterNamed(eventsParamName));
          final boolean updated = hook.updateEvents(events);
          if (!updated) {
            changes.remove(eventsParamName);
          }
        }

        if (changes.containsKey(configParamName)) {
          final String configJson = command.jsonFragment(configParamName);
          final Set<HookConfiguration> config =
              assembleConfig(command.mapValueOfParameterNamed(configJson), template);
          final boolean updated = hook.updateConfig(config);
          if (!updated) {
            changes.remove(configParamName);
          }
        }

        this.hookRepository.saveAndFlush(hook);
      }

      return new CommandProcessingResultBuilder() //
          .withCommandId(command.commandId()) //
          .withEntityId(hookId) //
          .with(changes) //
          .build();
    } catch (final DataIntegrityViolationException dve) {
      handleHookDataIntegrityIssues(command, dve);
      return null;
    }
  }
Beispiel #18
0
 protected Hook project(Hook hook) {
   tempHook.start = hook.start;
   tempHook.end = hook.end;
   tempHook.state = gp.project(hook.state);
   tempHook.head = hook.head;
   tempHook.tag = hook.tag;
   tempHook.subState = gp.project(hook.subState);
   return tempHook;
 }
Beispiel #19
0
  private void doNotifyHook(final Webhook event, Hook hook, final Object payload) {
    CloseableHttpClient client = HttpClients.createDefault();

    try {
      ObjectMapper mapper = new ObjectMapper();
      String json = mapper.writeValueAsString(payload);

      HttpPost request = new HttpPost(hook.getUrl());
      request.setEntity(new StringEntity(json));

      if (hook.getSecret().isPresent()) {
        String hmac = this.hmac(hook.getSecret().get(), json);
        request.setHeader("X-Mayocat-Signature", hmac);
      }

      request.setHeader("User-Agent", "Mayocat Webhooks/1.0");
      request.setHeader("X-Mayocat-Hook", event.getName());

      CloseableHttpResponse response = client.execute(request);

    } catch (Exception e) {
      logger.error("Failed to notify hook", e);
    }
  }
  protected static void insertMethod(final Hook methodToInsert, final MethodVisitor target) {
    byte[] classData = readStream("/" + methodToInsert.getClassSpec() + ".class");

    ClassReader reader = new ClassReader(classData);
    ClassVisitor methodFinder =
        new NoopClassVisitor() {
          @Override
          public MethodVisitor visitMethod(
              int access, String name, String desc, String signature, String[] exceptions) {
            if (name.equals(methodToInsert.getMethodName())
                && desc.equals(methodToInsert.getMethodDescriptor())) {
              return new InsertBodyOfMethodIntoAnotherVisitor(target);
            }
            return null;
          }
        };
    reader.accept(methodFinder, 0);
  }
 public final void begin_scenario() throws Throwable {
   prepareScenario();
   for (Hook before : befores) {
     before.invoke("before", null);
   }
 }
Beispiel #22
0
  public void init() throws ControlFlow {
    Base.init(base);
    DefaultBehavior.init(defaultBehavior);
    Mixins.init(mixins);
    system.init();
    Runtime.initRuntime(runtime);
    message.init();
    Ground.init(iokeGround, ground);
    Origin.init(origin);
    nil.init();
    _true.init();
    _false.init();
    text.init();
    symbol.init();
    number.init();
    range.init();
    pair.init();
    tuple.init();
    dateTime.init();
    lexicalContext.init();
    list.init();
    dict.init();
    set.init();
    call.init();
    Locals.init(locals);
    Condition.init(condition);
    Rescue.init(rescue);
    Handler.init(handler);
    io.init();
    FileSystem.init(fileSystem);
    regexp.init();
    JavaGround.init(javaGround);
    JavaArray.init(javaArray);
    javaWrapper.init();

    iokeGround.mimicsWithoutCheck(defaultBehavior);
    iokeGround.mimicsWithoutCheck(base);
    ground.mimicsWithoutCheck(iokeGround);
    ground.mimicsWithoutCheck(javaGround);
    origin.mimicsWithoutCheck(ground);

    mixins.mimicsWithoutCheck(defaultBehavior);

    system.mimicsWithoutCheck(ground);
    system.mimicsWithoutCheck(defaultBehavior);
    runtime.mimicsWithoutCheck(ground);
    runtime.mimicsWithoutCheck(defaultBehavior);

    nil.mimicsWithoutCheck(origin);
    _true.mimicsWithoutCheck(origin);
    _false.mimicsWithoutCheck(origin);
    text.mimicsWithoutCheck(origin);
    symbol.mimicsWithoutCheck(origin);
    number.mimicsWithoutCheck(origin);
    range.mimicsWithoutCheck(origin);
    pair.mimicsWithoutCheck(origin);
    dateTime.mimicsWithoutCheck(origin);

    message.mimicsWithoutCheck(origin);
    method.mimicsWithoutCheck(origin);

    list.mimicsWithoutCheck(origin);
    dict.mimicsWithoutCheck(origin);
    set.mimicsWithoutCheck(origin);

    condition.mimicsWithoutCheck(origin);
    rescue.mimicsWithoutCheck(origin);
    handler.mimicsWithoutCheck(origin);

    io.mimicsWithoutCheck(origin);

    fileSystem.mimicsWithoutCheck(origin);

    regexp.mimicsWithoutCheck(origin);

    method.init();
    defaultMethod.init();
    nativeMethod.init();
    lexicalBlock.init();
    defaultMacro.init();
    lexicalMacro.init();
    defaultSyntax.init();
    arity.init();
    call.mimicsWithoutCheck(origin);

    method.mimicsWithoutCheck(origin);
    defaultMethod.mimicsWithoutCheck(method);
    nativeMethod.mimicsWithoutCheck(method);
    defaultMacro.mimicsWithoutCheck(origin);
    lexicalMacro.mimicsWithoutCheck(origin);
    defaultSyntax.mimicsWithoutCheck(origin);
    arity.mimicsWithoutCheck(origin);
    lexicalBlock.mimicsWithoutCheck(origin);

    Restart.init(restart);
    restart.mimicsWithoutCheck(origin);

    javaWrapper.mimicsWithoutCheck(origin);

    Reflector.init(this);
    Hook.init(this);

    Sequence.init(sequence);
    iteratorSequence.init();
    keyValueIteratorSequence.init();

    addBuiltinScript(
        "benchmark",
        new Builtin() {
          public IokeObject load(Runtime runtime, IokeObject context, IokeObject message)
              throws ControlFlow {
            return ioke.lang.extensions.benchmark.Benchmark.create(runtime);
          }
        });

    addBuiltinScript(
        "readline",
        new Builtin() {
          public IokeObject load(Runtime runtime, IokeObject context, IokeObject message)
              throws ControlFlow {
            return ioke.lang.extensions.readline.Readline.create(runtime);
          }
        });

    try {
      evaluateString("use(\"builtin/A05_conditions\")", message, ground);
      evaluateString("use(\"builtin/A10_defaultBehavior\")", message, ground);
      evaluateString("use(\"builtin/A15_dmacro\")", message, ground);
      evaluateString("use(\"builtin/A20_comparing\")", message, ground);
      evaluateString("use(\"builtin/A25_defaultBehavior_inspection\")", message, ground);
      evaluateString("use(\"builtin/A30_system\")", message, ground);

      evaluateString("use(\"builtin/D05_number\")", message, ground);
      evaluateString("use(\"builtin/D10_call\")", message, ground);
      evaluateString("use(\"builtin/D15_range\")", message, ground);
      evaluateString("use(\"builtin/D20_booleans\")", message, ground);
      evaluateString("use(\"builtin/D25_list\")", message, ground);
      evaluateString("use(\"builtin/D30_dict\")", message, ground);
      evaluateString("use(\"builtin/D35_pair\")", message, ground);
      evaluateString("use(\"builtin/D37_tuple\")", message, ground);
      evaluateString("use(\"builtin/D40_text\")", message, ground);
      evaluateString("use(\"builtin/D43_regexp\")", message, ground);
      evaluateString("use(\"builtin/D45_fileSystem\")", message, ground);
      evaluateString("use(\"builtin/D50_runtime\")", message, ground);

      evaluateString("use(\"builtin/F05_case\")", message, ground);
      evaluateString("use(\"builtin/F10_comprehensions\")", message, ground);
      evaluateString("use(\"builtin/F15_message\")", message, ground);
      evaluateString("use(\"builtin/F20_set\")", message, ground);
      evaluateString("use(\"builtin/F25_cond\")", message, ground);
      evaluateString("use(\"builtin/F30_enumerable\")", message, ground);
      evaluateString("use(\"builtin/F32_sequence\")", message, ground);

      evaluateString("use(\"builtin/G05_aspects\")", message, ground);
      evaluateString("use(\"builtin/G10_origin\")", message, ground);
      evaluateString("use(\"builtin/G10_arity\")", message, ground);

      evaluateString("use(\"builtin/G50_hook\")", message, ground);

      evaluateString("use(\"builtin/H10_lexicalBlock\")", message, ground);

      evaluateString("use(\"builtin/J05_javaGround\")", message, ground);
    } catch (ControlFlow cf) {
    }
  }
Beispiel #23
0
  public static void registerHook(Hook hook) {
    HookType type = hook.getType();
    if (!HookHandler.hooks.containsKey(type)) HookHandler.hooks.put(type, new ArrayList<Hook>());

    HookHandler.hooks.get(type).add(hook);
  }
Beispiel #24
0
  public RState(int uid, String restrictionName, String methodName, Version version) {
    mUid = uid;
    mRestrictionName = restrictionName;
    mMethodName = methodName;

    int userId = Util.getUserId(Process.myUid());

    // Get if on demand
    boolean onDemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true);
    if (onDemand)
      onDemand = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingOnDemand, false);

    boolean allRestricted = true;
    boolean someRestricted = false;
    boolean allAsk = true;
    boolean someAsk = false;

    if (methodName == null) {
      if (restrictionName == null) {
        // Examine the category state
        someAsk = onDemand;
        for (String rRestrictionName : PrivacyManager.getRestrictions()) {
          PRestriction query = PrivacyManager.getRestrictionEx(uid, rRestrictionName, null);
          allRestricted = (allRestricted && query.restricted);
          someRestricted = (someRestricted || query.restricted);
          allAsk = (allAsk && !query.asked);
          someAsk = (someAsk || !query.asked);
        }
        asked = !onDemand;
      } else {
        // Examine the category/method states
        PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, null);
        someRestricted = query.restricted;
        someAsk = !query.asked;
        for (PRestriction restriction : PrivacyManager.getRestrictionList(uid, restrictionName)) {
          Hook hook = PrivacyManager.getHook(restrictionName, restriction.methodName);
          if (version != null
              && hook != null
              && hook.getFrom() != null
              && version.compareTo(hook.getFrom()) < 0) continue;

          allRestricted = (allRestricted && restriction.restricted);
          someRestricted = (someRestricted || restriction.restricted);
          if (hook == null || hook.canOnDemand()) {
            allAsk = (allAsk && !restriction.asked);
            someAsk = (someAsk || !restriction.asked);
          }
        }
        asked = query.asked;
      }
    } else {
      // Examine the method state
      PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, methodName);
      allRestricted = query.restricted;
      someRestricted = false;
      asked = query.asked;
    }

    boolean isApp = PrivacyManager.isApplication(uid);
    boolean odSystem =
        PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemandSystem, false);

    restricted = (allRestricted || someRestricted);
    asked = (!onDemand || !(isApp || odSystem) || asked);
    partialRestricted = (!allRestricted && someRestricted);
    partialAsk = (onDemand && (isApp || odSystem) && !allAsk && someAsk);
  }
Beispiel #25
0
 @Override
 public void run() {
   for (Hook hook : hooks) {
     hook.shutdown();
   }
 }
Beispiel #26
0
  /*
   * (non-Javadoc)
   *
   * @see net.sf.javailp.Solver#solve(net.sf.javailp.Problem)
   */
  public Result solve(Problem problem) {
    Map<IloNumVar, Object> numToVar = new HashMap<IloNumVar, Object>();
    Map<Object, IloNumVar> varToNum = new HashMap<Object, IloNumVar>();

    try {
      IloCplex cplex = new IloCplex();

      initWithParameters(cplex);

      for (Object variable : problem.getVariables()) {
        VarType varType = problem.getVarType(variable);
        Number lowerBound = problem.getVarLowerBound(variable);
        Number upperBound = problem.getVarUpperBound(variable);

        double lb = (lowerBound != null ? lowerBound.doubleValue() : Double.NEGATIVE_INFINITY);
        double ub = (upperBound != null ? upperBound.doubleValue() : Double.POSITIVE_INFINITY);

        final IloNumVarType type;
        switch (varType) {
          case BOOL:
            type = IloNumVarType.Bool;
            break;
          case INT:
            type = IloNumVarType.Int;
            break;
          default: // REAL
            type = IloNumVarType.Float;
            break;
        }

        IloNumVar num = cplex.numVar(lb, ub, type);

        numToVar.put(num, variable);
        varToNum.put(variable, num);
      }

      for (Constraint constraint : problem.getConstraints()) {
        IloLinearNumExpr lin = cplex.linearNumExpr();
        Linear linear = constraint.getLhs();
        convert(linear, lin, varToNum);

        double rhs = constraint.getRhs().doubleValue();

        switch (constraint.getOperator()) {
          case LE:
            cplex.addLe(lin, rhs);
            break;
          case GE:
            cplex.addGe(lin, rhs);
            break;
          default: // EQ
            cplex.addEq(lin, rhs);
        }
      }

      if (problem.getObjective() != null) {
        IloLinearNumExpr lin = cplex.linearNumExpr();
        Linear objective = problem.getObjective();
        convert(objective, lin, varToNum);

        if (problem.getOptType() == OptType.MIN) {
          cplex.addMinimize(lin);
        } else {
          cplex.addMaximize(lin);
        }
      }

      for (Hook hook : hooks) {
        hook.call(cplex, varToNum);
      }

      if (!cplex.solve()) {
        cplex.end();
        return null;
      }

      final Result result;
      if (problem.getObjective() != null) {
        Linear objective = problem.getObjective();
        result = new ResultImpl(objective);
      } else {
        result = new ResultImpl();
      }

      for (Entry<Object, IloNumVar> entry : varToNum.entrySet()) {
        Object variable = entry.getKey();
        IloNumVar num = entry.getValue();
        VarType varType = problem.getVarType(variable);

        double value = cplex.getValue(num);
        if (varType.isInt()) {
          int v = (int) Math.round(value);
          result.putPrimalValue(variable, v);
        } else {
          result.putPrimalValue(variable, value);
        }
      }

      cplex.end();

      return result;

    } catch (IloException e) {
      e.printStackTrace();
    }

    return null;
  }
 public final void end_scenario() throws Throwable {
   for (Hook after : afters) {
     after.invoke("after", null);
   }
   cleanupScenario();
 }