Example #1
0
  public static int adjustVideoScoreForLanguage(
      int currentScore,
      SearchResult searchResult,
      Language wantedAudioLanguage,
      Language wantedSubtitlesLanguage) {

    int score = currentScore;

    if (wantedAudioLanguage != null && wantedAudioLanguage.getSubTokens() != null) {
      for (String subToken : wantedAudioLanguage.getSubTokens()) {
        if (StringUtils.containsIgnoreCase(searchResult.getTitle(), subToken)) {
          score -= 10;
          break;
        }
      }
    }

    if ((wantedAudioLanguage != null && wantedAudioLanguage != Language.FR)
        && StringUtils.containsIgnoreCase(searchResult.getTitle(), "FRENCH")) {
      score -= 10;
    }

    if (wantedSubtitlesLanguage != null && wantedSubtitlesLanguage.getSubTokens() != null) {
      for (String subToken : wantedSubtitlesLanguage.getSubTokens()) {
        if (StringUtils.containsIgnoreCase(searchResult.getTitle(), subToken)) {
          score += 5; // already subtitled in the language we want
          break;
        }
      }
    }

    return score;
  }
  public static HashSet<String> getExternalMounts() {
    final HashSet<String> out = new HashSet<String>();
    String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4|fuse).*rw.*";
    String s = "";
    try {
      final Process process =
          new ProcessBuilder().command("mount").redirectErrorStream(true).start();
      process.waitFor();
      final InputStream is = process.getInputStream();
      final byte[] buffer = new byte[1024];
      while (is.read(buffer) != -1) {
        s = s + new String(buffer);
      }
      is.close();
    } catch (final Exception e) {

    }

    final String[] lines = s.split("\n");
    for (String line : lines) {
      if (StringUtils.containsIgnoreCase(line, "secure")) continue;
      if (StringUtils.containsIgnoreCase(line, "asec")) continue;
      if (line.matches(reg)) {
        String[] parts = line.split(" ");
        for (String part : parts) {
          if (part.startsWith("/"))
            if (!StringUtils.containsIgnoreCase(part, "vold")) out.add(part);
        }
      }
    }
    return out;
  }
Example #3
0
 private static boolean isCounter(final String url) {
   for (String entry : BLOCKED) {
     if (StringUtils.containsIgnoreCase(url, entry)) {
       return true;
     }
   }
   return false;
 }
Example #4
0
 public static String resolveTrackArtist(String trackArtist) {
   if (StringUtils.containsIgnoreCase(trackArtist, "feat.")) {
     String[] strings = StringUtils.splitByWholeSeparator(trackArtist.toLowerCase(), "feat.");
     if (strings.length > 1) {
       return strings[2].trim();
     }
   }
   return trackArtist;
 }
Example #5
0
  @Override
  public List<Event> getEventsByTitle(String title, int pageSize, int pageNum) {
    final List<Event> resultEvents =
        inMemoryStorage
            .getAllEvents()
            .stream()
            .filter(event -> StringUtils.containsIgnoreCase(event.getTitle(), title))
            .collect(Collectors.toList());

    return (List<Event>) DaoUtil.getPage(pageSize, pageNum, resultEvents);
  }
 protected String findIsbn(String page) {
   String result = null;
   if (StringUtils.containsIgnoreCase(page, "ISBN")) {
     String isbn = extractISBN(page);
     if (isbn.isEmpty()) {
       result = null;
     } else {
       result = isbn;
     }
   }
   return result;
 }
 @Bean
 public DataSource dataSource() {
   boolean hsql = StringUtils.containsIgnoreCase(hibernateDialect, "hsql");
   boolean mysql = StringUtils.containsIgnoreCase(hibernateDialect, "mysql");
   if (hsql) {
     EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
     builder.setType(EmbeddedDatabaseType.HSQL);
     builder.addScript(embeddedDatabaseSchemaSQL);
     builder.addScript(embeddedDatabaseDataSQL);
     return builder.build();
   } else if (mysql) {
     DriverManagerDataSource dataSource = new DriverManagerDataSource();
     dataSource.setDriverClassName("com.mysql.jdbc.Driver");
     dataSource.setUrl("jdbc:mysql://localhost:3306/aj");
     dataSource.setUsername(user);
     dataSource.setPassword(password);
     return dataSource;
   } else {
     throw new IllegalStateException();
   }
 }
  /*
   * Overriding this to only return the currently Active version of a proposal
   */
  @Override
  public List<? extends BusinessObject> getSearchResults(Map<String, String> fieldValues) {

    checkIsLookupForProposalCreation();
    List<ProposalLog> results = (List<ProposalLog>) super.getSearchResults(fieldValues);
    String returnLocation = fieldValues.get(BACK_LOCATION);
    List<ProposalLog> searchList = filterForPermissions(results);
    if (StringUtils.containsIgnoreCase(returnLocation, NEGOTIATION_NEGOTIATION)) {
      return cleanSearchResultsForNegotiationLookup(searchList);
    } else {
      return searchList;
    }
  }
Example #9
0
  /**
   * Returns if the given {@code seq} contains any of the given {@code searchSeqs}. The search is
   * case insensitive.
   *
   * <pre>
   * containsAny(null, null) → false
   * containsAny(*, null) → false
   * containsAny(null, *) → false
   * containsAny("abc", "a") → true
   * containsAny("abc", "abcd", "efg") → false
   * containsAny("abc", "aB") → true
   * containsAny("abc", "aBk") → false
   * containsAny("abc", "aBk", "abC") → true
   * </pre>
   *
   * @param seq The sequence.
   * @param searchSeqs The search sequence(s).
   * @return {@code true} if the given {@code seq} contains any of the given {@code searchSeqs},
   *     {@code false} otherwise.
   */
  private static boolean containsAny(final String seq, final String... searchSeqs) {

    if (seq == null || searchSeqs == null) {
      return false;
    }

    for (final String searchSeq : searchSeqs) {
      if (StringUtils.containsIgnoreCase(seq, searchSeq)) {
        return true;
      }
    }

    return false;
  }
 /**
  * Op.
  *
  * @param op1 the op1
  * @param op2 the op2
  * @return true, if successful
  */
 protected final boolean op(final String op1, final String op2) {
   switch (this.getOperator()) {
     case CONTAINS_IC:
       return StringUtils.containsIgnoreCase(op1, op2);
     case CONTAINS:
       return StringUtils.contains(op1, op2);
     case EQUALS:
       return op1.equals(op2);
     case EQUALS_IC:
       return op1.equalsIgnoreCase(op2);
     default:
       return false;
   }
 }
    public SoftwareVersion(String versionString) {

      // This can happen when running in debug
      if (versionString.charAt(0) == '@') {
        this.major = 0;
        this.minor = 0;
        this.revision = 0;
        this.patch = 0;
        this.isAlpha = false;
        this.isBeta = false;
        return;
      }

      assert versionString != null;
      assert versionString.length() > 0;

      isAlpha = StringUtils.containsIgnoreCase(versionString, "ALPHA");
      if (isAlpha) versionString = StringUtils.remove(versionString, "ALPHA");

      isBeta = StringUtils.containsIgnoreCase(versionString, "BETA");
      if (isBeta) versionString = StringUtils.remove(versionString, "BETA");

      final String[] parts = StringUtils.split(versionString, ".");
      final int numComponents = parts.length;

      assert numComponents >= 3;

      this.major = Integer.parseInt(parts[0]);
      this.minor = Integer.parseInt(parts[1]);
      this.revision = Integer.parseInt(parts[2]);
      if (numComponents == 4) {
        this.patch = Integer.parseInt(parts[3]);
      } else {
        this.patch = 0;
      }
    }
Example #12
0
 @Override
 protected boolean filenameBelongsToList(final String filename) {
   if (super.filenameBelongsToList(filename)) {
     if (StringUtils.endsWithIgnoreCase(filename, GPXImporter.ZIP_FILE_EXTENSION)) {
       for (IConnector connector : ConnectorFactory.getConnectors()) {
         if (connector.isZippedGPXFile(filename)) {
           return true;
         }
       }
       return false;
     }
     // filter out waypoint files
     return !StringUtils.containsIgnoreCase(filename, GPXImporter.WAYPOINTS_FILE_SUFFIX);
   }
   return false;
 }
  public HtmlElement getItinerarySubSection(ItineraryRows subSection) {
    if (table_rows.size() == 0) {
      table_rows = itineraryCompareTable().findElements(By.tagName("tr"));
    }
    for (HtmlElement row : table_rows) {
      String text = row.findElement(By.tagName("th")).getText();
      String textContent = row.getWrappedElement().getAttribute("textContent");
      if (StringUtils.startsWithIgnoreCase(text, subSection.name())) {
        row.scrollIntoView(false);
        return row;
      } else if (StringUtils.containsIgnoreCase(textContent, subSection.name())) {
        row.scrollIntoView(false);
        return row;
      }
    }

    return null;
  }
Example #14
0
  public int evaluateResultForSeries(ManagedSeries series, SearchResult searchResult) {

    int score = 0;

    score =
        adjustVideoScoreForLanguage(
            score, searchResult, series.getAudioLanguage(), series.getSubtitleLanguage());

    VideoQuality resultQuality = VideoNameParser.getQuality(searchResult.getTitle());
    for (VideoQuality quality : series.getQualities()) {
      if (quality.equals(resultQuality)) {
        score += 5; // requested quality
      }
    }

    if (StringUtils.containsIgnoreCase(searchResult.getTitle(), "PROPER")) {
      score += 1;
    }

    return score;
  }
  /*
   * We want to allow users to query on principal name instead of person id,
   * so we need to translate before performing the lookup.
   */
  @SuppressWarnings("unchecked")
  @Override
  public Collection performLookup(LookupForm lookupForm, Collection resultTable, boolean bounded) {
    String userName = (String) lookupForm.getFieldsForLookup().get(USERNAME_FIELD);
    lookupForm.getFieldsForLookup().remove(FOR_INSTITUTIONAL_PROPOSAL);

    if (!StringUtils.isBlank(userName)) {
      KcPerson person = getKcPersonService().getKcPersonByUserName(userName);
      if (person != null) {
        lookupForm.getFieldsForLookup().put(PI_ID, person.getPersonId());
      }
      lookupForm.getFieldsForLookup().remove(USERNAME_FIELD);
    }
    List<ProposalLog> results =
        (List<ProposalLog>) super.performLookup(lookupForm, resultTable, bounded);
    if (StringUtils.containsIgnoreCase(lookupForm.getBackLocation(), NEGOTIATION_NEGOTIATION)) {
      return cleanSearchResultsForNegotiationLookup(results);
    } else {
      return results;
    }
  }
Example #16
0
 @Override
 public boolean apply(MinerRank input) {
   return StringUtils.containsIgnoreCase(I18n.format(input.getUnlocalizedName()), filter)
       || StringUtils.containsIgnoreCase(input.getName(), filter);
 }
Example #17
0
  public Query buildQuery(Integer type, T example, String... orden) {
    StringBuilder qry;
    List<String> ids = new ArrayList<String>();
    if (type == 1) {
      qry = new StringBuilder(SELECT_COUNT);
      qry.append(example.getClass().getSimpleName());
    } else {
      qry = new StringBuilder(SELECT);
      qry.append(example.getClass().getSimpleName());
      ids = this.obtenerId(example);
    }
    qry.append(FROM);
    qry.append(WHERE);
    List<Object> parametros = new ArrayList();
    Criterio criterio = new Criterio();
    Map<String, Object> propiedades = this.obtenerPropiedades(example);
    criterio.contruccion(propiedades);
    Set<String> igualdad = criterio.igualdad.keySet();
    Integer idx = 1;
    for (String key : igualdad) {
      if (idx > 1) {
        qry.append(AND);
      }
      qry.append(OBJ);
      qry.append(key);
      qry.append(EQ);
      qry.append(idx);
      parametros.add(criterio.igualdad.get(key));
      idx++;
    }

    Set<String> likeKeys = criterio.like.keySet();
    for (String key : likeKeys) {
      if (idx > 1) {
        qry.append(AND);
      }
      Object valor = criterio.like.get(key);
      if (valor instanceof String) {
        qry.append(LOWER);
        qry.append(OBJ);
        qry.append(key);
        qry.append(")");
        qry.append(LIKE);
        qry.append(idx);
        parametros.add(((String) valor).toLowerCase());
      } else {
        qry.append(OBJ);
        qry.append(key);
        qry.append(LIKE);
        qry.append(idx);
        parametros.add(valor);
      }
      idx++;
    }

    Set<String> compositeKeys = criterio.compuesto.keySet();
    for (String key : compositeKeys) {
      Object value = criterio.compuesto.get(key);
      try {
        if (value.toString().startsWith("class java.util")) {
          continue;
        } else if (StringUtils.containsIgnoreCase(key, "pk")) {
          Map<String, Object> propsComposites = this.obtenerPropiedades(value, key);
          Criterio criterioCompuesto = new Criterio();
          criterioCompuesto.contruccion(propsComposites);
          if (!criterioCompuesto.igualdad.isEmpty()) {
            Set<String> eqKeysPK = criterioCompuesto.igualdad.keySet();
            for (String keyPK : eqKeysPK) {
              if (idx > 1) {
                qry.append(AND);
              }
              qry.append(OBJ);
              qry.append(keyPK);
              qry.append(EQ);
              qry.append(idx);
              parametros.add(criterioCompuesto.igualdad.get(keyPK));
              idx++;
            }
          }
          if (!criterioCompuesto.like.isEmpty()) {
            Set<String> likeKeysPK = criterioCompuesto.like.keySet();
            for (String keyPK : likeKeysPK) {
              if (idx > 1) {
                qry.append(AND);
              }
              Object valor = criterioCompuesto.like.get(keyPK);
              if (valor instanceof String) {
                qry.append(LOWER);
                qry.append(OBJ);
                qry.append(keyPK);
                qry.append(")");
                qry.append(LIKE);
                qry.append(idx);
                parametros.add(((String) valor).toLowerCase());
              } else {
                qry.append(OBJ);
                qry.append(keyPK);
                qry.append(LIKE);
                qry.append(idx);
                parametros.add(valor);
              }
              idx++;
            }
          }
        } else {
          Map<String, Object> propsComposites = this.obtenerPropiedades(value);
          Criterio criterioCompuesto = new Criterio();
          criterioCompuesto.contruccion(propsComposites);
          if (!criterioCompuesto.igualdad.isEmpty()) {
            Set<String> eqKeysPK = criterioCompuesto.igualdad.keySet();
            for (String keyPK : eqKeysPK) {
              if (idx > 1) {
                qry.append(AND);
              }
              qry.append(OBJ);
              qry.append(key);
              qry.append(".");
              qry.append(keyPK);
              qry.append(EQ);
              qry.append(idx);
              parametros.add(criterioCompuesto.igualdad.get(keyPK));
              idx++;
            }
          }
          if (!criterioCompuesto.like.isEmpty()) {
            Set<String> likeKeysPK = criterioCompuesto.like.keySet();
            for (String keyPK : likeKeysPK) {
              System.out.println(
                  "Compuesto LIKE: " + keyPK + ", " + criterioCompuesto.igualdad.get(keyPK));
              if (idx > 1) {
                qry.append(AND);
              }
              Object valor = criterioCompuesto.like.get(keyPK);
              if (valor instanceof String) {
                qry.append(LOWER);
                qry.append(OBJ);
                qry.append(key);
                qry.append(".");
                qry.append(keyPK);
                qry.append(")");
                qry.append(LIKE);
                qry.append(idx);
                parametros.add(((String) valor).toLowerCase());
              } else {
                qry.append(OBJ);
                qry.append(key);
                qry.append(".");
                qry.append(keyPK);
                qry.append(LIKE);
                qry.append(idx);
                parametros.add(valor);
              }
              idx++;
            }
          }
        }
      } catch (RuntimeException e) {
        continue;
      }
    }

    if (idx == 1) {
      qry.append(" 1=1");
    }
    if (!ids.isEmpty()) {
      qry.append(ORDER);
    } else {
      qry.append("  ");
    }
    if (orden.length > 0) {
      for (String ord : orden) {
        qry.append(OBJ);
        qry.append(ord.substring(2));
        if (ord.startsWith("A,")) {
          qry.append(ASC);
        } else if (ord.startsWith("D,")) {
          qry.append(DESC);
        }
      }
    } else {
      for (String id : ids) {
        if (!id.contains("_persistence")) {
          qry.append(OBJ);
          qry.append(id);
          qry.append(ASC);
        }
      }
    }

    System.out.println(qry.substring(0, qry.length() - 2));
    Query query = this.em.createQuery(qry.substring(0, qry.length() - 2));
    if (!parametros.isEmpty()) {
      int i = 1;
      for (Object obj : parametros) {
        query.setParameter(i, obj);
        i++;
      }
    }
    return query;
  }
  /**
   * Test if the regular expression given in the pattern can be simplified to a LIKE SQL statement;
   * these are considerably more efficient to evaluate in most databases, so in case we can
   * simplify, we return a LIKE.
   *
   * @param value
   * @param pattern
   * @return
   */
  private String optimizeRegexp(String value, String pattern, ValueExpr flags) {
    String _flags =
        flags != null && flags instanceof ValueConstant
            ? ((ValueConstant) flags).getValue().stringValue()
            : null;

    String simplified = pattern;

    // apply simplifications

    // remove SQL quotes at beginning and end
    simplified = simplified.replaceFirst("^'", "");
    simplified = simplified.replaceFirst("'$", "");

    // remove .* at beginning and end, they are the default anyways
    simplified = simplified.replaceFirst("^\\.\\*", "");
    simplified = simplified.replaceFirst("\\.\\*$", "");

    // replace all occurrences of % with \% and _ with \_, as they are special characters in SQL
    simplified = simplified.replaceAll("%", "\\%");
    simplified = simplified.replaceAll("_", "\\_");

    // if pattern now does not start with a ^, we put a "%" in front
    if (!simplified.startsWith("^")) {
      simplified = "%" + simplified;
    } else {
      simplified = simplified.substring(1);
    }

    // if pattern does not end with a "$", we put a "%" at the end
    if (!simplified.endsWith("$")) {
      simplified = simplified + "%";
    } else {
      simplified = simplified.substring(0, simplified.length() - 1);
    }

    // replace all non-escaped occurrences of .* with %
    simplified = simplified.replaceAll("(?<!\\\\)\\.\\*", "%");

    // replace all non-escaped occurrences of .+ with _%
    simplified = simplified.replaceAll("(?<!\\\\)\\.\\+", "_%");

    // the pattern is not simplifiable if the simplification still contains unescaped regular
    // expression constructs
    Pattern notSimplifiable = Pattern.compile("(?<!\\\\)[\\.\\*\\+\\{\\}\\[\\]\\|]");

    if (notSimplifiable.matcher(simplified).find()) {
      return parent.getDialect().getRegexp(value, pattern, _flags);
    } else {
      if (!simplified.startsWith("%") && !simplified.endsWith("%")) {
        if (StringUtils.containsIgnoreCase(_flags, "i")) {
          return String.format("lower(%s) = lower('%s')", value, simplified);
        } else {
          return String.format("%s = '%s'", value, simplified);
        }
      } else {
        if (StringUtils.containsIgnoreCase(_flags, "i")) {
          return parent.getDialect().getILike(value, "'" + simplified + "'");
        } else {
          return value + " LIKE '" + simplified + "'";
        }
      }
    }
  }
  /* (non-Javadoc)
   * @see forge.card.ability.SpellAbilityEffect#resolve(forge.card.spellability.SpellAbility)
   */
  @Override
  public void resolve(final SpellAbility sa) {
    final Card hostCard = sa.getHostCard();
    final Game game = hostCard.getGame();
    final List<String> keywords = new ArrayList<String>();
    final List<String> types = new ArrayList<String>();
    final List<String> svars = new ArrayList<String>();
    final List<String> triggers = new ArrayList<String>();
    if (sa.hasParam("Optional")) {
      if (!sa.getActivatingPlayer()
          .getController()
          .confirmAction(sa, null, "Copy this permanent?")) {
        return;
      }
    }
    if (sa.hasParam("Keywords")) {
      keywords.addAll(Arrays.asList(sa.getParam("Keywords").split(" & ")));
    }
    if (sa.hasParam("AddTypes")) {
      types.addAll(Arrays.asList(sa.getParam("AddTypes").split(" & ")));
    }
    if (sa.hasParam("AddSVars")) {
      svars.addAll(Arrays.asList(sa.getParam("AddSVars").split(" & ")));
    }
    if (sa.hasParam("Triggers")) {
      triggers.addAll(Arrays.asList(sa.getParam("Triggers").split(" & ")));
    }
    final int numCopies =
        sa.hasParam("NumCopies")
            ? AbilityUtils.calculateAmount(hostCard, sa.getParam("NumCopies"), sa)
            : 1;

    Player controller = null;
    if (sa.hasParam("Controller")) {
      final FCollectionView<Player> defined =
          AbilityUtils.getDefinedPlayers(hostCard, sa.getParam("Controller"), sa);
      if (!defined.isEmpty()) {
        controller = defined.getFirst();
      }
    }
    if (controller == null) {
      controller = sa.getActivatingPlayer();
    }

    List<Card> tgtCards = getTargetCards(sa);
    final TargetRestrictions tgt = sa.getTargetRestrictions();

    if (sa.hasParam("ValidSupportedCopy")) {
      List<PaperCard> cards =
          Lists.newArrayList(StaticData.instance().getCommonCards().getUniqueCards());
      String valid = sa.getParam("ValidSupportedCopy");
      if (valid.contains("X")) {
        valid =
            valid.replace("X", Integer.toString(AbilityUtils.calculateAmount(hostCard, "X", sa)));
      }
      if (StringUtils.containsIgnoreCase(valid, "creature")) {
        Predicate<PaperCard> cpp =
            Predicates.compose(CardRulesPredicates.Presets.IS_CREATURE, PaperCard.FN_GET_RULES);
        cards = Lists.newArrayList(Iterables.filter(cards, cpp));
      }
      if (StringUtils.containsIgnoreCase(valid, "equipment")) {
        Predicate<PaperCard> cpp =
            Predicates.compose(CardRulesPredicates.Presets.IS_EQUIPMENT, PaperCard.FN_GET_RULES);
        cards = Lists.newArrayList(Iterables.filter(cards, cpp));
      }
      if (sa.hasParam("RandomCopied")) {
        List<PaperCard> copysource = new ArrayList<PaperCard>(cards);
        List<Card> choice = new ArrayList<Card>();
        final String num = sa.hasParam("RandomNum") ? sa.getParam("RandomNum") : "1";
        int ncopied = AbilityUtils.calculateAmount(hostCard, num, sa);
        while (ncopied > 0) {
          final PaperCard cp = Aggregates.random(copysource);
          Card possibleCard =
              Card.fromPaperCard(
                  cp,
                  sa.getActivatingPlayer()); // Need to temporarily set the Owner so the Game is set

          if (possibleCard.isValid(valid, hostCard.getController(), hostCard)) {
            choice.add(possibleCard);
            copysource.remove(cp);
            ncopied -= 1;
          }
        }
        tgtCards = choice;
      } else if (sa.hasParam("DefinedName")) {
        String name = sa.getParam("DefinedName");
        if (name.equals("NamedCard")) {
          if (!hostCard.getNamedCard().isEmpty()) {
            name = hostCard.getNamedCard();
          }
        }

        Predicate<PaperCard> cpp =
            Predicates.compose(
                CardRulesPredicates.name(StringOp.EQUALS, name), PaperCard.FN_GET_RULES);
        cards = Lists.newArrayList(Iterables.filter(cards, cpp));

        tgtCards.clear();
        if (!cards.isEmpty()) {
          tgtCards.add(Card.fromPaperCard(cards.get(0), controller));
        }
      }
    }
    hostCard.clearClones();

    for (final Card c : tgtCards) {
      if ((tgt == null) || c.canBeTargetedBy(sa)) {

        int multiplier = numCopies * hostCard.getController().getTokenDoublersMagnitude();
        final List<Card> crds = new ArrayList<Card>(multiplier);

        for (int i = 0; i < multiplier; i++) {
          final Card copy = CardFactory.copyCopiableCharacteristics(c, sa.getActivatingPlayer());
          copy.setToken(true);
          copy.setCopiedPermanent(c);
          CardFactory.copyCopiableAbilities(c, copy);
          // add keywords from sa
          for (final String kw : keywords) {
            copy.addIntrinsicKeyword(kw);
          }
          for (final String type : types) {
            copy.addType(type);
          }
          for (final String svar : svars) {
            String actualsVar = hostCard.getSVar(svar);
            String name = svar;
            if (actualsVar.startsWith("SVar:")) {
              actualsVar = actualsVar.split("SVar:")[1];
              name = actualsVar.split(":")[0];
              actualsVar = actualsVar.split(":")[1];
            }
            copy.setSVar(name, actualsVar);
          }
          for (final String s : triggers) {
            final String actualTrigger = hostCard.getSVar(s);
            final Trigger parsedTrigger = TriggerHandler.parseTrigger(actualTrigger, copy, true);
            copy.addTrigger(parsedTrigger);
          }

          // Temporarily register triggers of an object created with CopyPermanent
          // game.getTriggerHandler().registerActiveTrigger(copy, false);
          final Card copyInPlay = game.getAction().moveToPlay(copy);

          // when copying something stolen:
          copyInPlay.setController(controller, 0);
          copyInPlay.setSetCode(c.getSetCode());

          copyInPlay.setCloneOrigin(hostCard);
          sa.getHostCard().addClone(copyInPlay);
          crds.add(copyInPlay);
          if (sa.hasParam("RememberCopied")) {
            hostCard.addRemembered(copyInPlay);
          }
          if (sa.hasParam("Tapped")) {
            copyInPlay.setTapped(true);
          }
          if (sa.hasParam("CopyAttacking") && game.getPhaseHandler().inCombat()) {
            final String attacked = sa.getParam("CopyAttacking");
            GameEntity defender;
            if ("True".equals(attacked)) {
              FCollectionView<GameEntity> defs = game.getCombat().getDefenders();
              defender =
                  c.getController()
                      .getController()
                      .chooseSingleEntityForEffect(
                          defs, sa, "Choose which defender to attack with " + c, false);
            } else {
              defender =
                  AbilityUtils.getDefinedPlayers(hostCard, sa.getParam("CopyAttacking"), sa).get(0);
            }
            game.getCombat().addAttacker(copyInPlay, defender);
            game.fireEvent(new GameEventCombatChanged());
          }

          if (sa.hasParam("AttachedTo")) {
            CardCollectionView list =
                AbilityUtils.getDefinedCards(hostCard, sa.getParam("AttachedTo"), sa);
            if (list.isEmpty()) {
              list = copyInPlay.getController().getGame().getCardsIn(ZoneType.Battlefield);
              list =
                  CardLists.getValidCards(
                      list, sa.getParam("AttachedTo"), copyInPlay.getController(), copyInPlay);
            }
            if (!list.isEmpty()) {
              Card attachedTo =
                  sa.getActivatingPlayer()
                      .getController()
                      .chooseSingleEntityForEffect(
                          list, sa, copyInPlay + " - Select a card to attach to.");
              if (copyInPlay.isAura()) {
                if (attachedTo.canBeEnchantedBy(copyInPlay)) {
                  copyInPlay.enchantEntity(attachedTo);
                } else { // can't enchant
                  continue;
                }
              } else if (copyInPlay.isEquipment()) { // Equipment
                if (attachedTo.canBeEquippedBy(copyInPlay)) {
                  copyInPlay.equipCard(attachedTo);
                } else {
                  continue;
                }
              } else { // Fortification
                copyInPlay.fortifyCard(attachedTo);
              }
            } else {
              continue;
            }
          }
        }

        if (sa.hasParam("AtEOT")) {
          final String location = sa.getParam("AtEOT");
          registerDelayedTrigger(sa, location, crds);
        }
      } // end canBeTargetedBy
    } // end foreach Card
  } // end resolve
Example #20
0
  public String buildUrl(
      String action,
      HttpServletRequest request,
      HttpServletResponse response,
      Map<String, Object> params,
      String urlScheme,
      boolean includeContext,
      boolean encodeResult,
      boolean forceAddSchemeHostAndPort,
      boolean escapeAmp) {

    StringBuilder link = new StringBuilder();
    boolean changedScheme = false;

    String scheme = null;
    if (isValidScheme(urlScheme)) {
      scheme = urlScheme;
    }

    // only append scheme if it is different to the current scheme *OR*
    // if we explicity want it to be appended by having forceAddSchemeHostAndPort = true
    if (forceAddSchemeHostAndPort) {
      String reqScheme = request.getScheme();
      changedScheme = true;
      link.append(scheme != null ? scheme : reqScheme);
      link.append("://");
      link.append(request.getServerName());

      if (scheme != null) {
        // If switching schemes, use the configured port for the particular scheme.
        if (!scheme.equals(reqScheme)) {
          if ((HTTP_PROTOCOL.equals(scheme) && (httpPort != DEFAULT_HTTP_PORT))
              || (HTTPS_PROTOCOL.equals(scheme) && httpsPort != DEFAULT_HTTPS_PORT)) {
            link.append(":");
            link.append(HTTP_PROTOCOL.equals(scheme) ? httpPort : httpsPort);
          }
          // Else use the port from the current request.
        } else {
          int reqPort = request.getServerPort();

          if ((scheme.equals(HTTP_PROTOCOL) && (reqPort != DEFAULT_HTTP_PORT))
              || (scheme.equals(HTTPS_PROTOCOL) && reqPort != DEFAULT_HTTPS_PORT)) {
            link.append(":");
            link.append(reqPort);
          }
        }
      }
    } else if ((scheme != null) && !scheme.equals(request.getScheme())) {
      changedScheme = true;
      link.append(scheme);
      link.append("://");
      link.append(request.getServerName());

      if ((scheme.equals(HTTP_PROTOCOL) && (httpPort != DEFAULT_HTTP_PORT))
          || (HTTPS_PROTOCOL.equals(scheme) && httpsPort != DEFAULT_HTTPS_PORT)) {
        link.append(":");
        link.append(HTTP_PROTOCOL.equals(scheme) ? httpPort : httpsPort);
      }
    }

    if (action != null) {
      // Check if context path needs to be added
      // Add path to absolute links
      if (action.startsWith("/") && includeContext) {
        String contextPath = request.getContextPath();
        if (!contextPath.equals("/")) {
          link.append(contextPath);
        }
      } else if (changedScheme) {

        // (Applicable to Servlet 2.4 containers)
        // If the request was forwarded, the attribute below will be set with the original URL
        String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");

        // If the attribute wasn't found, default to the value in the request object
        if (uri == null) {
          uri = request.getRequestURI();
        }

        link.append(uri.substring(0, uri.lastIndexOf('/') + 1));
      }

      // Add page
      link.append(action);
    } else {
      // Go to "same page"
      String requestURI = (String) request.getAttribute("struts.request_uri");

      // (Applicable to Servlet 2.4 containers)
      // If the request was forwarded, the attribute below will be set with the original URL
      if (requestURI == null) {
        requestURI = (String) request.getAttribute("javax.servlet.forward.request_uri");
      }

      // If neither request attributes were found, default to the value in the request object
      if (requestURI == null) {
        requestURI = request.getRequestURI();
      }

      link.append(requestURI);
    }

    // if the action was not explicitly set grab the params from the request
    if (escapeAmp) {
      buildParametersString(params, link, AMP);
    } else {
      buildParametersString(params, link, "&");
    }

    String result = link.toString();

    if (StringUtils.containsIgnoreCase(result, "<script")) {
      result = StringEscapeUtils.escapeEcmaScript(result);
    }
    try {
      result = encodeResult ? response.encodeURL(result) : result;
    } catch (Exception ex) {
      LOG.debug("Could not encode the URL for some reason, use it unchanged", ex);
      result = link.toString();
    }

    return result;
  }
Example #21
0
  @Override
  public Collection<SearchResult> search(final SearchContext context) {
    final String term = context.getSearchTerm();

    final Collection<SearchResult> results = new ArrayList<>();
    if (StringUtils.isBlank(context.getAnnotationData())) {
      return results;
    }

    try {
      // parse the annotation data
      final Criteria criteria = CriteriaSerDe.deserialize(context.getAnnotationData());

      // ensure there are some rules
      if (criteria.getRules() != null) {
        final FlowFilePolicy flowFilePolicy = criteria.getFlowFilePolicy();
        if (flowFilePolicy != null && StringUtils.containsIgnoreCase(flowFilePolicy.name(), term)) {
          results.add(
              new SearchResult.Builder()
                  .label("FlowFile policy")
                  .match(flowFilePolicy.name())
                  .build());
        }

        for (final Rule rule : criteria.getRules()) {
          if (StringUtils.containsIgnoreCase(rule.getName(), term)) {
            results.add(
                new SearchResult.Builder().label("Rule name").match(rule.getName()).build());
          }

          // ensure there are some conditions
          if (rule.getConditions() != null) {
            for (final Condition condition : rule.getConditions()) {
              if (StringUtils.containsIgnoreCase(condition.getExpression(), term)) {
                results.add(
                    new SearchResult.Builder()
                        .label(String.format("Condition in rule '%s'", rule.getName()))
                        .match(condition.getExpression())
                        .build());
              }
            }
          }

          // ensure there are some actions
          if (rule.getActions() != null) {
            for (final Action action : rule.getActions()) {
              if (StringUtils.containsIgnoreCase(action.getAttribute(), term)) {
                results.add(
                    new SearchResult.Builder()
                        .label(String.format("Action in rule '%s'", rule.getName()))
                        .match(action.getAttribute())
                        .build());
              }
              if (StringUtils.containsIgnoreCase(action.getValue(), term)) {
                results.add(
                    new SearchResult.Builder()
                        .label(String.format("Action in rule '%s'", rule.getName()))
                        .match(action.getValue())
                        .build());
              }
            }
          }
        }
      }

      return results;
    } catch (Exception e) {
      return results;
    }
  }
Example #22
0
 public static boolean hasFeaturedArtist(String artist) {
   return StringUtils.containsIgnoreCase(artist, "feat.");
 }
Example #23
0
  @Override
  public void execute() throws IOException, URISyntaxException {

    Collection<String> blackList = getWordsBlackList(getDownloadable());

    SearchResult selectedResult = null;

    Set<String> blackListedUrls = new HashSet<>();
    List<SearchResult> existingResults =
        searchResultDAO.getSearchResults(getDownloadable().getId());
    for (SearchResult searchResult : existingResults) {
      if (searchResult.isBlackListed()) {
        blackListedUrls.add(searchResult.getUrl());
      } else {
        if (searchResult.getType() != SearchResultType.HTTP) {
          // TODO : implement HTTP downloads
          selectedResult = searchResult; // auto download this one
        }
        break;
      }
    }

    if (selectedResult == null) {

      String baseLabel = getCurrentLabel();

      int currentScore = -1;

      List<DownloadFinder> providers = (List<DownloadFinder>) getProviders();
      if (providers != null) {

        totalItems = providers.size();

        for (DownloadFinder provider : providers) {
          if (!provider.isEnabled()) {
            continue;
          }

          if (cancelled) {
            break;
          }

          setCurrentLabel(String.format("%s - Searching from %s", baseLabel, provider.toString()));

          while (!provider.isReady()) {
            try {
              Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
          }

          List<SearchResult> resultsForProvider = getResults(provider, getDownloadable());
          if (resultsForProvider != null && resultsForProvider.size() > 0) {
            for (Iterator<SearchResult> iterator = resultsForProvider.iterator();
                iterator.hasNext(); ) {
              SearchResult searchResult = iterator.next();
              // remove blacklisted results

              if (blackListedUrls != null && blackListedUrls.contains(searchResult.getUrl())) {
                iterator.remove();
                continue;
              }

              if (blackList != null) {
                for (String word : blackList) {
                  if (StringUtils.isNoneBlank(word)
                      && StringUtils.containsIgnoreCase(searchResult.getTitle(), word)) {
                    iterator.remove();
                    break;
                  }
                }
              }
            }

            if (resultsForProvider.size() > 0) {
              filterResults(resultsForProvider);
              for (SearchResult searchResult : resultsForProvider) {
                int score = evaluateResult(searchResult);
                if (score > currentScore) {
                  selectedResult = searchResult;
                  currentScore = score;
                }
              }

              if (currentScore >= SCORE_THRESHOLD) {
                break;
              }
            }
          }
          itemsDone++;
        }
      }
    }

    if (!cancelled) {

      if (selectedResult != null) {
        selectResult(selectedResult);
      } else {
        mustReschedule = true;
      }
    }
  }