Esempio n. 1
0
  private static boolean addDamage(Player attacker, Player victim, Double damage) {
    // mysql shit
    if (attacker == null) {
      attacker = DataUtils.getPlayer(victim).getLastAttacker();
    }
    if (damage > victim.getHealth()) {
      damage = victim.getHealth();
    }

    SmashPlayer Victim = DataUtils.getPlayer(victim);
    Victim.setLastDamage(System.currentTimeMillis());
    Victim.setLastAttacker(attacker);

    StatisticUtils.addDamageTaken(victim, damage);

    if (attacker != null) {

      StatisticUtils.addDamageDelt(attacker, damage);

      if (Victim.getDamagers().containsKey(attacker)) {
        Victim.getDamagers().put(attacker, Victim.getDamagers().get(attacker) + damage);
      } else {
        Victim.getDamagers().put(attacker, damage);
      }
    }

    return HealthUtils.addHealth(victim, damage * -1);
  }
Esempio n. 2
0
 private ByteArrayOutputStream putIndirectId(ByteArrayOutputStream id) throws IOException {
   byte[] data = id.toByteArray();
   id = new ByteArrayOutputStream();
   // indirect: 2, total len (long), blockId (long)
   id.write(2);
   DataUtils.writeVarLong(id, length(data));
   DataUtils.writeVarLong(id, writeBlock(data));
   return id;
 }
Esempio n. 3
0
 /**
  * Try to open the file.
  *
  * @param fileName the file name
  * @param readOnly whether the file should only be opened in read-only mode, even if the file is
  *     writable
  * @param encryptionKey the encryption key, or null if encryption is not used
  */
 public void open(String fileName, boolean readOnly, char[] encryptionKey) {
   if (file != null) {
     return;
   }
   if (fileName != null) {
     FilePath p = FilePath.get(fileName);
     // if no explicit scheme was specified, NIO is used
     if (p instanceof FilePathDisk && !fileName.startsWith(p.getScheme() + ":")) {
       // ensure the NIO file system is registered
       FilePathNio.class.getName();
       fileName = "nio:" + fileName;
     }
   }
   this.fileName = fileName;
   FilePath f = FilePath.get(fileName);
   FilePath parent = f.getParent();
   if (parent != null && !parent.exists()) {
     throw DataUtils.newIllegalArgumentException("Directory does not exist: {0}", parent);
   }
   if (f.exists() && !f.canWrite()) {
     readOnly = true;
   }
   this.readOnly = readOnly;
   try {
     file = f.open(readOnly ? "r" : "rw");
     if (encryptionKey != null) {
       byte[] key = FilePathEncrypt.getPasswordBytes(encryptionKey);
       encryptedFile = file;
       file = new FilePathEncrypt.FileEncrypt(fileName, key, file);
     }
     file = FilePathCache.wrap(file);
     try {
       if (readOnly) {
         fileLock = file.tryLock(0, Long.MAX_VALUE, true);
       } else {
         fileLock = file.tryLock();
       }
     } catch (OverlappingFileLockException e) {
       throw DataUtils.newIllegalStateException(
           DataUtils.ERROR_FILE_LOCKED, "The file is locked: {0}", fileName, e);
     }
     if (fileLock == null) {
       throw DataUtils.newIllegalStateException(
           DataUtils.ERROR_FILE_LOCKED, "The file is locked: {0}", fileName);
     }
     fileSize = file.size();
   } catch (IOException e) {
     throw DataUtils.newIllegalStateException(
         DataUtils.ERROR_READING_FAILED, "Could not open file {0}", fileName, e);
   }
 }
 /**
  * TODO:登录接口测试
  *
  * @author 作者:邱卫武
  * @date 创建时间:2015年9月8日
  * @param url
  * @param excelPath
  * @param sheetName
  * @throws Exception void
  */
 public void login(String url, String excelPath, String sheetName, String tablename, int datanum)
     throws Exception {
   for (int i = 1; i <= datanum; i++) {
     JSONObject response =
         JSONObject.fromString(
             request.doPost(url, sqldata.getData_login(tablename, i))); // 判断登录是否成功
     if ("false".equals(data.getResultDataBy_one(response, "IsSuccess"))) {
       String message = data.getResultDataBy_one(response, "Message");
       check.checkString(message, readexcel.readExcel13_oneValue(excelPath, sheetName, i, "预期结果"));
     } else {
       report.log("登录成功");
     }
   }
 }
Esempio n. 5
0
 /**
  * Get the map metadata as a string.
  *
  * @param name the map name (or null)
  * @return the string
  */
 public String asString(String name) {
   StringBuilder buff = new StringBuilder();
   if (name != null) {
     DataUtils.appendMap(buff, "name", name);
   }
   if (createVersion != 0) {
     DataUtils.appendMap(buff, "createVersion", createVersion);
   }
   String type = getType();
   if (type != null) {
     DataUtils.appendMap(buff, "type", type);
   }
   return buff.toString();
 }
Esempio n. 6
0
 /** Check that no write operation is in progress. */
 protected void checkConcurrentWrite() {
   if (writing) {
     // try to detect concurrent modification
     // on a best-effort basis
     throw DataUtils.newConcurrentModificationException();
   }
 }
Esempio n. 7
0
  /**
   * Constructs a test using a given data set. If a data set is provided (that is, a tabular data
   * set), fourth moment statistics can be calculated (p. 160); otherwise, it must be assumed that
   * the data are multivariate Gaussian.
   */
  public DeltaSextadTest(DataSet dataSet) {
    if (dataSet == null) {
      throw new NullPointerException();
    }

    if (!dataSet.isContinuous()) {
      throw new IllegalArgumentException();
    }

    this.cov = new CovarianceMatrix(dataSet);

    List<DataSet> data1 = new ArrayList<DataSet>();
    data1.add(dataSet);
    List<DataSet> data2 = DataUtils.center(data1);

    this.dataSet = data2.get(0);

    this.data = this.dataSet.getDoubleData().transpose().toArray();
    this.N = dataSet.getNumRows();
    this.variables = dataSet.getVariables();
    this.numVars = dataSet.getNumColumns();

    this.variablesHash = new HashMap<Node, Integer>();

    for (int i = 0; i < variables.size(); i++) {
      variablesHash.put(variables.get(i), i);
    }

    this.means = new double[numVars];

    for (int i = 0; i < numVars; i++) {
      means[i] = mean(data[i], N);
    }
  }
Esempio n. 8
0
 /**
  * Write to the file.
  *
  * @param pos the write position
  * @param src the source buffer
  */
 public void writeFully(long pos, ByteBuffer src) {
   int len = src.remaining();
   fileSize = Math.max(fileSize, pos + len);
   DataUtils.writeFully(file, pos, src);
   writeCount++;
   writeBytes += len;
 }
Esempio n. 9
0
  public String addPolicy(File policyFile) throws Exception {
    byte[] policy = DataUtils.loadFile(policyFile.getAbsolutePath());

    String policyId = getPolicyId(policy);

    String policyFileName = "file:///" + policyFile.getAbsolutePath();

    // escape any pid namespace character
    if (policyId.contains(":")) {
      policyId = policyId.replace(":", "%3A");
    }

    String pid = "demo:" + policyId;

    StringBuilder foxml = new StringBuilder();

    // basic empty object

    foxml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    foxml.append(
        "<foxml:digitalObject VERSION=\"1.1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
    foxml.append("    xmlns:foxml=\"info:fedora/fedora-system:def/foxml#\"\n");
    foxml.append(
        "           xsi:schemaLocation=\""
            + Constants.FOXML.uri
            + " "
            + Constants.FOXML1_1.xsdLocation
            + "\"");
    foxml.append("\n           PID=\"" + StreamUtility.enc(pid) + "\">\n");
    foxml.append("  <foxml:objectProperties>\n");
    foxml.append(
        "    <foxml:property NAME=\"info:fedora/fedora-system:def/model#state\" VALUE=\"A\"/>\n");
    foxml.append(
        "    <foxml:property NAME=\"info:fedora/fedora-system:def/model#label\" VALUE=\""
            + StreamUtility.enc("test policy object")
            + "\"/>\n");
    foxml.append("  </foxml:objectProperties>\n");

    foxml.append(
        "<foxml:datastream ID=\""
            + FedoraPolicyStore.POLICY_DATASTREAM
            + "\" CONTROL_GROUP=\"M\">");
    foxml.append(
        "<foxml:datastreamVersion ID=\"POLICY.0\" MIMETYPE=\"text/xml\" LABEL=\"XACML policy datastream\">");

    foxml.append("  <foxml:contentLocation REF=\"" + policyFileName + "\" TYPE=\"URL\"/>");

    // foxml.append("  <foxml:xmlContent>");
    // foxml.append(policy);
    // foxml.append("    </foxml:xmlContent>");

    foxml.append("  </foxml:datastreamVersion>");
    foxml.append("</foxml:datastream>");

    foxml.append("</foxml:digitalObject>");

    apim.ingest(foxml.toString().getBytes("UTF-8"), FOXML1_1.uri, "ingesting new foxml object");

    return policyId;
  }
Esempio n. 10
0
 /**
  * Read from the file.
  *
  * @param pos the write position
  * @param len the number of bytes to read
  * @return the byte buffer
  */
 public ByteBuffer readFully(long pos, int len) {
   ByteBuffer dst = ByteBuffer.allocate(len);
   DataUtils.readFully(file, pos, dst);
   readCount++;
   readBytes += len;
   return dst;
 }
Esempio n. 11
0
 @Override
 public int read(byte[] b, int off, int len) throws IOException {
   if (len <= 0) {
     return 0;
   }
   while (true) {
     if (buffer == null) {
       try {
         buffer = nextBuffer();
       } catch (IllegalStateException e) {
         String msg =
             DataUtils.formatMessage(
                 DataUtils.ERROR_BLOCK_NOT_FOUND,
                 "Block not found in id {0}",
                 Arrays.toString(idBuffer.array()));
         throw new IOException(msg, e);
       }
       if (buffer == null) {
         return -1;
       }
     }
     int result = buffer.read(b, off, len);
     if (result > 0) {
       pos += result;
       return result;
     }
     buffer = null;
   }
 }
Esempio n. 12
0
  public static boolean Damage(Player attacker, Player victim, Double damage) {

    if (victim.isDead()) {
      return false;
    }
    if (attacker != null && !attacker.isOnline()) {
      return false;
    }
    if (DataUtils.getPlayer(victim).isVanished()) {
      return false;
    }
    if (attacker != null && DataUtils.getPlayer(attacker).isVanished()) {
      return false;
    }

    // Multiply and reduce by team stats.

    SmashPredamageEvent event = new SmashPredamageEvent(attacker, victim, damage);
    Bukkit.getPluginManager().callEvent(event);
    if (event.isCancelled()) {
      return false;
    }
    damage = event.getDamage();

    victim.playEffect(EntityEffect.HURT);
    Location loc = victim.getLocation().add(0, 1, 0);
    ParticleUtils.SendPacket(
        ParticleUtils.createBlockPacket(
            EnumParticle.BLOCK_CRACK, 152, 0, loc, new Vector(0.1, 0.1, 0.1), 0F, 50),
        loc);
    ParticleUtils.SendPacket(
        ParticleUtils.createNormalPacket(
            EnumParticle.VILLAGER_ANGRY, victim.getEyeLocation(), new Vector(0, 0, 0), 0F, 1),
        loc);

    Double totalDamage = damage;

    damage = BarrierUtils.takeDamage(victim, damage);

    HologramUtils.displayAlertHolo(victim, "&c-" + Integer.toString(totalDamage.intValue()) + " ❤");

    boolean result = addDamage(attacker, victim, damage);

    Bukkit.getPluginManager().callEvent(new SmashDamageEvent(attacker, victim, totalDamage));

    return result;
  }
 /**
  * Return Semantic Type of the concept code passed in
  *
  * @param conceptCode
  * @return
  */
 public String getSemanticType(String conceptCode) {
   Vector<String> code_vec = new Vector<String>();
   code_vec.add(conceptCode);
   HashMap<?, ?> map =
       DataUtils.getPropertyValuesForCodes(
           Constants.CODING_SCHEME_NAME, null, code_vec, SEMANTIC_TYPE);
   return (String) map.get(conceptCode);
 }
Esempio n. 14
0
 /** Flush all changes. */
 public void sync() {
   try {
     file.force(true);
   } catch (IOException e) {
     throw DataUtils.newIllegalStateException(
         DataUtils.ERROR_WRITING_FAILED, "Could not sync file {0}", fileName, e);
   }
 }
Esempio n. 15
0
 /**
  * Get the block.
  *
  * @param key the key
  * @return the block
  */
 byte[] getBlock(long key) {
   byte[] data = map.get(key);
   if (data == null) {
     throw DataUtils.newIllegalStateException(
         DataUtils.ERROR_BLOCK_NOT_FOUND, "Block {0} not found", key);
   }
   return data;
 }
Esempio n. 16
0
 /**
  * This method is called before writing to the map. The default implementation checks whether
  * writing is allowed, and tries to detect concurrent modification.
  *
  * @throws UnsupportedOperationException if the map is read-only, or if another thread is
  *     concurrently writing
  */
 protected void beforeWrite() {
   if (readOnly) {
     checkOpen();
     throw DataUtils.newUnsupportedOperationException("This map is read-only");
   }
   checkConcurrentWrite();
   writing = true;
   store.beforeWrite();
 }
Esempio n. 17
0
 private boolean put(ByteArrayOutputStream id, InputStream in, int level) throws IOException {
   if (level > 0) {
     ByteArrayOutputStream id2 = new ByteArrayOutputStream();
     while (true) {
       boolean eof = put(id2, in, level - 1);
       if (id2.size() > maxBlockSize / 2) {
         id2 = putIndirectId(id2);
         id2.writeTo(id);
         return eof;
       } else if (eof) {
         id2.writeTo(id);
         return true;
       }
     }
   }
   byte[] readBuffer = nextBuffer.getAndSet(null);
   if (readBuffer == null) {
     readBuffer = new byte[maxBlockSize];
   }
   byte[] buff = read(in, readBuffer);
   if (buff != readBuffer) {
     // re-use the buffer if the result was shorter
     nextBuffer.set(readBuffer);
   }
   int len = buff.length;
   if (len == 0) {
     return true;
   }
   boolean eof = len < maxBlockSize;
   if (len < minBlockSize) {
     // in-place: 0, len (int), data
     id.write(0);
     DataUtils.writeVarInt(id, len);
     id.write(buff);
   } else {
     // block: 1, len (int), blockId (long)
     id.write(1);
     DataUtils.writeVarInt(id, len);
     DataUtils.writeVarLong(id, writeBlock(buff));
   }
   return eof;
 }
Esempio n. 18
0
 /**
  * Check whether the id itself contains all the data. This operation does not cause any reads in
  * the map.
  *
  * @param id the id
  * @return if the id contains the data
  */
 public boolean isInPlace(byte[] id) {
   ByteBuffer idBuffer = ByteBuffer.wrap(id);
   while (idBuffer.hasRemaining()) {
     if (idBuffer.get() != 0) {
       return false;
     }
     int len = DataUtils.readVarInt(idBuffer);
     idBuffer.position(idBuffer.position() + len);
   }
   return true;
 }
Esempio n. 19
0
  public static void Death(Player victim) {
    DeathEffectUtils.playDeathEffect(victim);
    SoundUtils.playSound(Sound.HURT_FLESH, victim.getEyeLocation(), 2F, 0F);

    Player attacker = DataUtils.getPlayer(victim).getLastAttacker();

    StatisticUtils.addDeath(victim);

    if (attacker == null) {
      TitleUtils.sendTitle(victim, "&c&lYou have died!", "&7&lMistakes were made", 10, 80, 10);
      ChatUtils.sendMessage(victim, "&7&m-----------------------------------------------------");
      ChatUtils.sendMessage(victim, "&8[&c&lDeath&8] &7Mistakes were made.");
      ChatUtils.sendMessage(victim, "&7&m-----------------------------------------------------");
    } else {

      String prefixAttacker = DataUtils.getPlayer(attacker).getPrefix();
      String colorAttacker = prefixAttacker.substring(0, 2);
      ChatUtils.sendMessage(victim, "&7&m-----------------------------------------------------");
      ChatUtils.sendMessage(
          victim,
          "&8[&c&lDeath&8] &7You have been slain by " + prefixAttacker + attacker.getDisplayName());
      ChatUtils.sendMessage(victim, "&7&m-----------------------------------------------------");
      TitleUtils.sendTitle(
          victim,
          "&c&lYou have been slain!",
          "&7&lKiller: " + colorAttacker + attacker.getDisplayName(),
          10,
          80,
          10);

      MoneyUtils.deathCoinsPayout(victim);

      StatisticUtils.addDeath(attacker);
    }
    victim.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 60, 0, true, true));

    //		victim.teleport(Main.SpawnLoc);
    // Location teleport to team spawn.
    victim.setVelocity(new Vector(0, 0, 0));
  }
Esempio n. 20
0
 /**
  * Get the key of the biggest block, of -1 for inline data. This method is used to garbage collect
  * orphaned blocks.
  *
  * @param id the id
  * @return the key, or -1
  */
 public long getMaxBlockKey(byte[] id) {
   long maxKey = -1;
   ByteBuffer idBuffer = ByteBuffer.wrap(id);
   while (idBuffer.hasRemaining()) {
     switch (idBuffer.get()) {
       case 0:
         // in-place: 0, len (int), data
         int len = DataUtils.readVarInt(idBuffer);
         idBuffer.position(idBuffer.position() + len);
         break;
       case 1:
         // block: 1, len (int), blockId (long)
         DataUtils.readVarInt(idBuffer);
         long k = DataUtils.readVarLong(idBuffer);
         maxKey = Math.max(maxKey, k);
         break;
       case 2:
         // indirect: 2, total len (long), blockId (long)
         DataUtils.readVarLong(idBuffer);
         long k2 = DataUtils.readVarLong(idBuffer);
         // recurse
         byte[] r = map.get(k2);
         maxKey = Math.max(maxKey, getMaxBlockKey(r));
         break;
       default:
         throw DataUtils.newIllegalArgumentException("Unsupported id {0}", Arrays.toString(id));
     }
   }
   return maxKey;
 }
Esempio n. 21
0
 /**
  * Calculate the number of data bytes for the given id. As the length is encoded in the id, this
  * operation does not cause any reads in the map.
  *
  * @param id the id
  * @return the length
  */
 public long length(byte[] id) {
   ByteBuffer idBuffer = ByteBuffer.wrap(id);
   long length = 0;
   while (idBuffer.hasRemaining()) {
     switch (idBuffer.get()) {
       case 0:
         // in-place: 0, len (int), data
         int len = DataUtils.readVarInt(idBuffer);
         idBuffer.position(idBuffer.position() + len);
         length += len;
         break;
       case 1:
         // block: 1, len (int), blockId (long)
         length += DataUtils.readVarInt(idBuffer);
         DataUtils.readVarLong(idBuffer);
         break;
       case 2:
         // indirect: 2, total len (long), blockId (long)
         length += DataUtils.readVarLong(idBuffer);
         DataUtils.readVarLong(idBuffer);
         break;
       default:
         throw DataUtils.newIllegalArgumentException("Unsupported id {0}", Arrays.toString(id));
     }
   }
   return length;
 }
Esempio n. 22
0
 /**
  * Remove all stored blocks for the given id.
  *
  * @param id the id
  */
 public void remove(byte[] id) {
   ByteBuffer idBuffer = ByteBuffer.wrap(id);
   while (idBuffer.hasRemaining()) {
     switch (idBuffer.get()) {
       case 0:
         // in-place: 0, len (int), data
         int len = DataUtils.readVarInt(idBuffer);
         idBuffer.position(idBuffer.position() + len);
         break;
       case 1:
         // block: 1, len (int), blockId (long)
         DataUtils.readVarInt(idBuffer);
         long k = DataUtils.readVarLong(idBuffer);
         map.remove(k);
         break;
       case 2:
         // indirect: 2, total len (long), blockId (long)
         DataUtils.readVarLong(idBuffer);
         long k2 = DataUtils.readVarLong(idBuffer);
         // recurse
         remove(map.get(k2));
         map.remove(k2);
         break;
       default:
         throw DataUtils.newIllegalArgumentException("Unsupported id {0}", Arrays.toString(id));
     }
   }
 }
Esempio n. 23
0
 /**
  * Truncate the file.
  *
  * @param size the new file size
  */
 public void truncate(long size) {
   try {
     writeCount++;
     file.truncate(size);
     fileSize = Math.min(fileSize, size);
   } catch (IOException e) {
     throw DataUtils.newIllegalStateException(
         DataUtils.ERROR_WRITING_FAILED,
         "Could not truncate file {0} to size {1}",
         fileName,
         size,
         e);
   }
 }
Esempio n. 24
0
 /** Close this store. */
 public void close() {
   try {
     if (fileLock != null) {
       fileLock.release();
       fileLock = null;
     }
     file.close();
     freeSpace.clear();
   } catch (Exception e) {
     throw DataUtils.newIllegalStateException(
         DataUtils.ERROR_WRITING_FAILED, "Closing failed for file {0}", fileName, e);
   } finally {
     file = null;
   }
 }
Esempio n. 25
0
 /**
  * Open an old version for the given map.
  *
  * @param version the version
  * @return the map
  */
 public MVMap<K, V> openVersion(long version) {
   if (readOnly) {
     throw DataUtils.newUnsupportedOperationException(
         "This map is read-only - need to call the method on the writable map");
   }
   DataUtils.checkArgument(
       version >= createVersion,
       "Unknown version {0}; this map was created in version is {1}",
       version,
       createVersion);
   Page newest = null;
   // need to copy because it can change
   Page r = root;
   if (version >= r.getVersion()
       && (version == store.getCurrentVersion()
           || r.getVersion() >= 0
           || version <= createVersion
           || store.getFile() == null)) {
     newest = r;
   } else {
     // find the newest page that has a getVersion() <= version
     int i = searchRoot(version);
     if (i < 0) {
       // not found
       if (i == -1) {
         // smaller than all in-memory versions
         return store.openMapVersion(version, id, this);
       }
       i = -i - 2;
     }
     newest = oldRoots.get(i);
   }
   MVMap<K, V> m = openReadOnly();
   m.root = newest;
   return m;
 }
Esempio n. 26
0
 /**
  * Add or replace a key-value pair.
  *
  * @param key the key (may not be null)
  * @param value the value (may not be null)
  * @return the old value if the key existed, or null otherwise
  */
 @SuppressWarnings("unchecked")
 public V put(K key, V value) {
   DataUtils.checkArgument(value != null, "The value may not be null");
   beforeWrite();
   try {
     long writeVersion = store.getCurrentVersion();
     Page p = copyOnWrite(root, writeVersion);
     p = splitRootIfNeeded(p, writeVersion);
     Object result = put(p, writeVersion, key, value);
     newRoot(p);
     return (V) result;
   } finally {
     afterWrite();
   }
 }
Esempio n. 27
0
 private ByteArrayInputStream nextBuffer() {
   while (idBuffer.hasRemaining()) {
     switch (idBuffer.get()) {
       case 0:
         {
           int len = DataUtils.readVarInt(idBuffer);
           if (skip >= len) {
             skip -= len;
             idBuffer.position(idBuffer.position() + len);
             continue;
           }
           int p = (int) (idBuffer.position() + skip);
           int l = (int) (len - skip);
           idBuffer.position(p + l);
           return new ByteArrayInputStream(idBuffer.array(), p, l);
         }
       case 1:
         {
           int len = DataUtils.readVarInt(idBuffer);
           long key = DataUtils.readVarLong(idBuffer);
           if (skip >= len) {
             skip -= len;
             continue;
           }
           byte[] data = store.getBlock(key);
           int s = (int) skip;
           skip = 0;
           return new ByteArrayInputStream(data, s, data.length - s);
         }
       case 2:
         {
           long len = DataUtils.readVarLong(idBuffer);
           long key = DataUtils.readVarLong(idBuffer);
           if (skip >= len) {
             skip -= len;
             continue;
           }
           byte[] k = store.getBlock(key);
           ByteBuffer newBuffer =
               ByteBuffer.allocate(k.length + idBuffer.limit() - idBuffer.position());
           newBuffer.put(k);
           newBuffer.put(idBuffer);
           newBuffer.flip();
           idBuffer = newBuffer;
           return nextBuffer();
         }
       default:
         throw DataUtils.newIllegalArgumentException(
             "Unsupported id {0}", Arrays.toString(idBuffer.array()));
     }
   }
   return null;
 }
 private void updateEventNameIfEmpty(EventData eventData) {
   if (StringUtils.isEmpty(eventData.getEventName()) && eventData.getContext() != null) {
     Map<String, String> guessedAttributes = DataUtils.guessEventName(eventData.getContext());
     if (guessedAttributes != null) {
       if (guessedAttributes.get("event_name") != null) {
         eventData.setEventName(guessedAttributes.get("event_name"));
       }
       if (guessedAttributes.get("parent_gooru_id") != null
           && eventData.getParentGooruId() == null) {
         eventData.setParentGooruId(guessedAttributes.get("parent_gooru_id"));
       }
       if (guessedAttributes.get("content_gooru_id") != null
           && eventData.getContentGooruId() == null) {
         eventData.setContentGooruId(guessedAttributes.get("content_gooru_id"));
       }
     }
   }
 }
  private void updateEventNameForConsistency(EventData eventData) {
    // Handle event naming convention inconsistency - ensure event map is not empty
    String eventName = DataUtils.makeEventNameConsistent(eventData.getEventName());

    if (eventName != null) {
      if (eventName.equalsIgnoreCase("collection-play")
          && !StringUtils.isEmpty(eventData.getParentGooruId())) {
        // This is actually collection-resource-play event, coming up disguised as collection-play.
        // Change.
        eventName = "collection-resource-play";
      }
      if (eventName.equalsIgnoreCase("collection-resource-play-dots")
          && eventData.getAttemptStatus() != null) {
        // This is used to remove collection resource play from server side logs
        eventName = "collection-question-resource-play-dots";
      }
    }
    eventData.setEventName(eventName);
  }
Esempio n. 30
0
  /**
   * Delete {@code books} from Realm, along with any {@link RBookListItem}s which may exist for
   * them, and their cover images if they have them. Optionally delete the real files they were
   * imported from as well.
   *
   * @param realm Instance of Realm to use.
   * @param books Books to delete.
   * @param deleteRealFiles If true, also delete the books' corresponding files.
   */
  public static void deleteBooks(Realm realm, Collection<RBook> books, boolean deleteRealFiles) {
    // Null checks.
    if (books == null || books.isEmpty()) return;

    // If deleteRealFiles is true, check permissions before doing anything.
    if (deleteRealFiles
        && !Util.checkForStoragePermAndFireEventIfNeeded(R.id.action_execute_deferred)) {
      //noinspection unchecked    Defer this action while we ask for permission.
      setDeferredAction(params -> deleteBooks(realm, (Collection<RBook>) params[0], true), books);
      return;
    }

    List<String> relPaths = new ArrayList<>(books.size());
    // Delete what we created.
    realm.executeTransaction(
        tRealm -> {
          for (RBook book : books) {
            // Delete any RBookListItems which may exist for these books.
            tRealm
                .where(RBookListItem.class)
                .contains("book.relPath", book.relPath)
                .findAll()
                .deleteAllFromRealm();
            // Get the relative path of the book, in case we wish to delete the real files too.
            String relPath = book.relPath;
            relPaths.add(relPath);
            // Be sure to delete the cover file, if we have one.
            if (book.hasCoverImage) DataUtils.deleteCoverImage(relPath);
            // Delete the actual RBook from Realm.
            book.deleteFromRealm();
          }
        });

    // If the user wants us to, also try to delete the corresponding files from the device.
    if (deleteRealFiles) {
      for (String relPath : relPaths) {
        File file = Util.getFileFromRelPath(relPath);
        if (file != null) // noinspection ResultOfMethodCallIgnored
        file.delete();
      }
    }
  }