List of usage examples for org.apache.commons.lang3 StringUtils isNumeric
public static boolean isNumeric(final CharSequence cs)
Checks if the CharSequence contains only Unicode digits.
From source file:forge.game.card.CardFactoryUtil.java
/** * <p>/* w w w.j a va2s. c om*/ * Parse non-mana X variables. * </p> * * @param c * a {@link forge.game.card.Card} object. * @param expression * a {@link java.lang.String} object. * @return a int. */ public static int xCount(final Card c, final String expression) { if (StringUtils.isBlank(expression)) { return 0; } if (StringUtils.isNumeric(expression)) { return Integer.parseInt(expression); } final Player cc = c.getController(); final Game game = c.getGame(); final Player activePlayer = game.getPhaseHandler().getPlayerTurn(); final String[] l = expression.split("/"); final String m = extractOperators(expression); // accept straight numbers if (l[0].startsWith("Number$")) { final String number = l[0].substring(7); if (number.equals("ChosenNumber")) { return doXMath(c.getChosenNumber(), m, c); } return doXMath(Integer.parseInt(number), m, c); } if (l[0].startsWith("Count$")) { l[0] = l[0].substring(6); } if (l[0].startsWith("SVar$")) { return doXMath(xCount(c, c.getSVar(l[0].substring(5))), m, c); } if (l[0].startsWith("Controller$")) { return playerXProperty(cc, l[0].substring(11), c); } // Manapool if (l[0].startsWith("ManaPool")) { final String color = l[0].split(":")[1]; if (color.equals("All")) { return cc.getManaPool().totalMana(); } return cc.getManaPool().getAmountOfColor(MagicColor.fromName(color)); } // count valid cards in any specified zone/s if (l[0].startsWith("Valid")) { String[] lparts = l[0].split(" ", 2); final String[] rest = lparts[1].split(","); final CardCollectionView cardsInZones = lparts[0].length() > 5 ? game.getCardsIn(ZoneType.listValueOf(lparts[0].substring(5))) : game.getCardsIn(ZoneType.Battlefield); CardCollection cards = CardLists.getValidCards(cardsInZones, rest, cc, c); return doXMath(cards.size(), m, c); } if (l[0].startsWith("ImprintedCardManaCost") && !c.getImprintedCards().isEmpty()) { return c.getImprintedCards().get(0).getCMC(); } if (l[0].startsWith("GreatestPower_")) { final String restriction = l[0].substring(14); final String[] rest = restriction.split(","); CardCollection list = CardLists.getValidCards(cc.getGame().getCardsIn(ZoneType.Battlefield), rest, cc, c); int highest = 0; for (final Card crd : list) { if (crd.getNetPower() > highest) { highest = crd.getNetPower(); } } return highest; } if (l[0].startsWith("GreatestToughness_")) { final String restriction = l[0].substring(18); final String[] rest = restriction.split(","); CardCollection list = CardLists.getValidCards(cc.getGame().getCardsIn(ZoneType.Battlefield), rest, cc, c); int highest = 0; for (final Card crd : list) { if (crd.getNetToughness() > highest) { highest = crd.getNetToughness(); } } return highest; } if (l[0].startsWith("HighestCMC_")) { final String restriction = l[0].substring(11); final String[] rest = restriction.split(","); CardCollection list = CardLists.getValidCards(cc.getGame().getCardsInGame(), rest, cc, c); int highest = 0; for (final Card crd : list) { if (crd.isSplitCard()) { if (crd.getCMC(Card.SplitCMCMode.LeftSplitCMC) > highest) { highest = crd.getCMC(Card.SplitCMCMode.LeftSplitCMC); } if (crd.getCMC(Card.SplitCMCMode.RightSplitCMC) > highest) { highest = crd.getCMC(Card.SplitCMCMode.RightSplitCMC); } } else { if (crd.getCMC() > highest) { highest = crd.getCMC(); } } } return highest; } if (l[0].startsWith("DifferentCardNames_")) { final List<String> crdname = new ArrayList<String>(); final String restriction = l[0].substring(19); final String[] rest = restriction.split(","); CardCollection list = CardLists.getValidCards(cc.getGame().getCardsInGame(), rest, cc, c); for (final Card card : list) { if (!crdname.contains(card.getName())) { crdname.add(card.getName()); } } return doXMath(crdname.size(), m, c); } if (l[0].startsWith("RememberedSize")) { return doXMath(c.getRememberedCount(), m, c); } if (l[0].startsWith("RememberedNumber")) { int num = 0; for (final Object o : c.getRemembered()) { if (o instanceof Integer) { num += (Integer) o; } } return doXMath(num, m, c); } // Count$CountersAdded <CounterType> <ValidSource> if (l[0].startsWith("CountersAdded")) { final String[] components = l[0].split(" ", 3); final CounterType counterType = CounterType.valueOf(components[1]); String restrictions = components[2]; final String[] rest = restrictions.split(","); CardCollection candidates = CardLists.getValidCards(game.getCardsInGame(), rest, cc, c); int added = 0; for (final Card counterSource : candidates) { added += c.getCountersAddedBy(counterSource, counterType); } return doXMath(added, m, c); } if (l[0].startsWith("CommanderCastFromCommandZone")) { // Read SVar CommanderCostRaise from Commander Effect Card commeff = CardLists .filter(cc.getCardsIn(ZoneType.Command), CardPredicates.nameEquals("Commander Effect")).get(0); return doXMath(xCount(commeff, commeff.getSVar("CommanderCostRaise")), "DivideEvenlyDown.2", c); } if (l[0].startsWith("MostProminentCreatureType")) { String restriction = l[0].split(" ")[1]; CardCollection list = CardLists.getValidCards(game.getCardsIn(ZoneType.Battlefield), restriction, cc, c); return doXMath(getMostProminentCreatureTypeSize(list), m, c); } if (l[0].startsWith("SecondMostProminentColor")) { String restriction = l[0].split(" ")[1]; CardCollection list = CardLists.getValidCards(game.getCardsIn(ZoneType.Battlefield), restriction, cc, c); int[] colorSize = SortColorsFromList(list); return doXMath(colorSize[colorSize.length - 2], m, c); } if (l[0].startsWith("RolledThisTurn")) { return game.getPhaseHandler().getPlanarDiceRolledthisTurn(); } final String[] sq; sq = l[0].split("\\."); if (sq[0].contains("xPaid")) { return doXMath(c.getXManaCostPaid(), m, c); } if (sq[0].contains("xColorPaid")) { String[] attrs = sq[0].split(" "); String colors = ""; for (int i = 1; i < attrs.length; i++) { colors += attrs[i]; } return doXMath(c.getXManaCostPaidCount(colors), m, c); } if (sq[0].equals("YouDrewThisTurn")) { return doXMath(c.getController().getNumDrawnThisTurn(), m, c); } if (sq[0].equals("FirstSpellTotalManaSpent")) { return doXMath(c.getFirstSpellAbility().getTotalManaSpent(), m, c); } if (sq[0].equals("StormCount")) { return doXMath(game.getStack().getSpellsCastThisTurn().size() - 1, m, c); } if (sq[0].equals("DamageDoneThisTurn")) { return doXMath(c.getDamageDoneThisTurn(), m, c); } if (sq[0].equals("BloodthirstAmount")) { return doXMath(c.getController().getBloodthirstAmount(), m, c); } if (sq[0].equals("RegeneratedThisTurn")) { return doXMath(c.getRegeneratedThisTurn(), m, c); } // TriggeringObjects if (sq[0].startsWith("Triggered")) { return doXMath(xCount((Card) c.getTriggeringObject("Card"), sq[0].substring(9)), m, c); } if (sq[0].contains("YourStartingLife")) { return doXMath(cc.getStartingLife(), m, c); } if (sq[0].contains("YourLifeTotal")) { return doXMath(cc.getLife(), m, c); } if (sq[0].contains("OppGreatestLifeTotal")) { return doXMath(cc.getOpponentsGreatestLifeTotal(), m, c); } if (sq[0].contains("OppsAtLifeTotal")) { final int lifeTotal = xCount(c, sq[1]); int number = 0; for (final Player opp : cc.getOpponents()) { if (opp.getLife() == lifeTotal) { number++; } } return doXMath(number, m, c); } // Count$TargetedLifeTotal (targeted player's life total) if (sq[0].contains("TargetedLifeTotal")) { // This doesn't work in some circumstances, since the active SA isn't passed through for (final SpellAbility sa : c.getCurrentState().getNonManaAbilities()) { final SpellAbility saTargeting = sa.getSATargetingPlayer(); if (saTargeting != null) { for (final Player tgtP : saTargeting.getTargets().getTargetPlayers()) { return doXMath(tgtP.getLife(), m, c); } } } } if (sq[0].contains("LifeYouLostThisTurn")) { return doXMath(cc.getLifeLostThisTurn(), m, c); } if (sq[0].contains("LifeYouGainedThisTurn")) { return doXMath(cc.getLifeGainedThisTurn(), m, c); } if (sq[0].contains("LifeOppsLostThisTurn")) { int lost = 0; for (Player opp : cc.getOpponents()) { lost += opp.getLifeLostThisTurn(); } return doXMath(lost, m, c); } if (sq[0].equals("TotalDamageDoneByThisTurn")) { return doXMath(c.getTotalDamageDoneBy(), m, c); } if (sq[0].equals("TotalDamageReceivedThisTurn")) { return doXMath(c.getTotalDamageRecievedThisTurn(), m, c); } if (sq[0].contains("YourPoisonCounters")) { return doXMath(cc.getPoisonCounters(), m, c); } if (sq[0].contains("TotalOppPoisonCounters")) { return doXMath(cc.getOpponentsTotalPoisonCounters(), m, c); } if (sq[0].contains("YourDamageThisTurn")) { return doXMath(cc.getAssignedDamage(), m, c); } if (sq[0].contains("TotalOppDamageThisTurn")) { return doXMath(cc.getOpponentsAssignedDamage(), m, c); } if (sq[0].contains("MaxOppDamageThisTurn")) { return doXMath(cc.getMaxOpponentAssignedDamage(), m, c); } // Count$YourTypeDamageThisTurn Type if (sq[0].contains("YourTypeDamageThisTurn")) { return doXMath(cc.getAssignedDamage(sq[0].split(" ")[1]), m, c); } if (sq[0].contains("YourDamageSourcesThisTurn")) { Iterable<Card> allSrc = cc.getAssignedDamageSources(); String restriction = sq[0].split(" ")[1]; CardCollection filtered = CardLists.getValidCards(allSrc, restriction, cc, c); return doXMath(filtered.size(), m, c); } if (sq[0].contains("YourLandsPlayed")) { return doXMath(cc.getLandsPlayedThisTurn(), m, c); } // Count$TopOfLibraryCMC if (sq[0].contains("TopOfLibraryCMC")) { final Card topCard = cc.getCardsIn(ZoneType.Library).getFirst(); return doXMath(topCard == null ? 0 : topCard.getCMC(), m, c); } // Count$EnchantedControllerCreatures if (sq[0].contains("EnchantedControllerCreatures")) { if (c.getEnchantingCard() != null) { return CardLists.count(c.getEnchantingCard().getController().getCardsIn(ZoneType.Battlefield), CardPredicates.Presets.CREATURES); } return 0; } // Count$MonstrosityMagnitude if (sq[0].contains("MonstrosityMagnitude")) { return doXMath(c.getMonstrosityNum(), m, c); } // Count$Chroma.<color name> // Count$Devotion.<color name> if (sq[0].contains("Chroma") || sq[0].equals("Devotion")) { ZoneType sourceZone = sq[0].contains("ChromaInGrave") ? ZoneType.Graveyard : ZoneType.Battlefield; String colorName = sq[1]; if (colorName.contains("Chosen")) { colorName = MagicColor.toShortString(c.getChosenColor()); } final CardCollectionView cards; if (sq[0].contains("ChromaSource")) { // Runs Chroma for passed in Source card cards = new CardCollection(c); } else { cards = cc.getCardsIn(sourceZone); } int colorOcurrencices = 0; byte colorCode = MagicColor.fromName(colorName); for (Card c0 : cards) { for (ManaCostShard sh : c0.getManaCost()) { if ((sh.getColorMask() & colorCode) != 0) colorOcurrencices++; } } return doXMath(colorOcurrencices, m, c); } // Count$DevotionDual.<color name>.<color name> if (sq[0].contains("DevotionDual")) { int colorOcurrencices = 0; byte color1 = MagicColor.fromName(sq[1]); byte color2 = MagicColor.fromName(sq[2]); for (Card c0 : cc.getCardsIn(ZoneType.Battlefield)) { for (ManaCostShard sh : c0.getManaCost()) { if ((sh.getColorMask() & (color1 | color2)) != 0) { colorOcurrencices++; } } } return doXMath(colorOcurrencices, m, c); } if (sq[0].contains("Hellbent")) { return doXMath(Integer.parseInt(sq[cc.hasHellbent() ? 1 : 2]), m, c); } if (sq[0].contains("Metalcraft")) { return doXMath(Integer.parseInt(sq[cc.hasMetalcraft() ? 1 : 2]), m, c); } if (sq[0].contains("FatefulHour")) { return doXMath(Integer.parseInt(sq[cc.getLife() <= 5 ? 1 : 2]), m, c); } if (sq[0].contains("Landfall")) { return doXMath(Integer.parseInt(sq[cc.hasLandfall() ? 1 : 2]), m, c); } if (sq[0].contains("Threshold")) { return doXMath(Integer.parseInt(sq[cc.hasThreshold() ? 1 : 2]), m, c); } if (sq[0].startsWith("Kicked")) { return doXMath(Integer.parseInt(sq[c.getKickerMagnitude() > 0 ? 1 : 2]), m, c); } if (sq[0].startsWith("AltCost")) { return doXMath(Integer.parseInt(sq[c.isOptionalCostPaid(OptionalCost.AltCost) ? 1 : 2]), m, c); } // Count$wasCastFrom<Zone>.<true>.<false> if (sq[0].startsWith("wasCastFrom")) { boolean zonesMatch = c.getCastFrom() == ZoneType.smartValueOf(sq[0].substring(11)); return doXMath(Integer.parseInt(sq[zonesMatch ? 1 : 2]), m, c); } if (sq[0].startsWith("Devoured")) { final String validDevoured = l[0].split(" ")[1]; CardCollection cl = CardLists.getValidCards(c.getDevoured(), validDevoured.split(","), cc, c); return doXMath(cl.size(), m, c); } if (sq[0].contains("CardPower")) { return doXMath(c.getNetPower(), m, c); } if (sq[0].contains("CardToughness")) { return doXMath(c.getNetToughness(), m, c); } if (sq[0].contains("CardSumPT")) { return doXMath((c.getNetPower() + c.getNetToughness()), m, c); } // Count$SumPower_valid if (sq[0].contains("SumPower")) { final String[] restrictions = l[0].split("_"); final String[] rest = restrictions[1].split(","); CardCollection filteredCards = CardLists.getValidCards(cc.getGame().getCardsIn(ZoneType.Battlefield), rest, cc, c); return doXMath(Aggregates.sum(filteredCards, CardPredicates.Accessors.fnGetNetPower), m, c); } // Count$CardManaCost if (sq[0].contains("CardManaCost")) { Card ce; if (sq[0].contains("Equipped") && c.isEquipping()) { ce = c.getEquipping(); } else if (sq[0].contains("Remembered")) { ce = (Card) c.getFirstRemembered(); } else { ce = c; } return doXMath(ce == null ? 0 : ce.getCMC(), m, c); } // Count$SumCMC_valid if (sq[0].contains("SumCMC")) { final String[] restrictions = l[0].split("_"); final String[] rest = restrictions[1].split(","); CardCollectionView cardsonbattlefield = game.getCardsIn(ZoneType.Battlefield); CardCollection filteredCards = CardLists.getValidCards(cardsonbattlefield, rest, cc, c); return Aggregates.sum(filteredCards, CardPredicates.Accessors.fnGetCmc); } if (sq[0].contains("CardNumColors")) { return doXMath(CardUtil.getColors(c).countColors(), m, c); } if (sq[0].contains("ChosenNumber")) { return doXMath(c.getChosenNumber(), m, c); } if (sq[0].contains("CardCounters")) { // CardCounters.ALL to be used for Kinsbaile Borderguard and anything that cares about all counters int count = 0; if (sq[1].equals("ALL")) { for (Integer i : c.getCounters().values()) { if (i != null && i > 0) { count += i; } } } else { count = c.getCounters(CounterType.getType(sq[1])); } return doXMath(count, m, c); } // Count$TotalCounters.<counterType>_<valid> if (sq[0].contains("TotalCounters")) { final String[] restrictions = l[0].split("_"); final CounterType cType = CounterType.getType(restrictions[1]); final String[] validFilter = restrictions[2].split(","); CardCollectionView validCards = game.getCardsIn(ZoneType.Battlefield); validCards = CardLists.getValidCards(validCards, validFilter, cc, c); int cCount = 0; for (final Card card : validCards) { cCount += card.getCounters(cType); } return doXMath(cCount, m, c); } if (sq[0].contains("CardTypes")) { return doXMath(getCardTypesFromList(game.getCardsIn(ZoneType.smartValueOf(sq[1]))), m, c); } if (sq[0].contains("BushidoPoint")) { return doXMath(c.getKeywordMagnitude("Bushido"), m, c); } if (sq[0].contains("TimesKicked")) { return doXMath(c.getKickerMagnitude(), m, c); } if (sq[0].contains("TimesPseudokicked")) { return doXMath(c.getPseudoKickerMagnitude(), m, c); } // Count$IfMainPhase.<numMain>.<numNotMain> // 7/10 if (sq[0].contains("IfMainPhase")) { final PhaseHandler cPhase = cc.getGame().getPhaseHandler(); final boolean isMyMain = cPhase.getPhase().isMain() && cPhase.getPlayerTurn().equals(cc); return doXMath(Integer.parseInt(sq[isMyMain ? 1 : 2]), m, c); } // Count$ThisTurnEntered <ZoneDestination> [from <ZoneOrigin>] <Valid> if (sq[0].contains("ThisTurnEntered")) { final String[] workingCopy = l[0].split("_"); ZoneType destination = ZoneType.smartValueOf(workingCopy[1]); final boolean hasFrom = workingCopy[2].equals("from"); ZoneType origin = hasFrom ? ZoneType.smartValueOf(workingCopy[3]) : null; String validFilter = workingCopy[hasFrom ? 4 : 2]; final CardCollection res = CardUtil.getThisTurnEntered(destination, origin, validFilter, c); if (origin == null) { // Remove cards on the battlefield that changed controller CardCollectionView sameDest = CardUtil.getThisTurnEntered(destination, destination, validFilter, c); res.removeAll(sameDest); } return doXMath(res.size(), m, c); } // Count$LastTurnEntered <ZoneDestination> [from <ZoneOrigin>] <Valid> if (sq[0].contains("LastTurnEntered")) { final String[] workingCopy = l[0].split("_"); ZoneType destination = ZoneType.smartValueOf(workingCopy[1]); final boolean hasFrom = workingCopy[2].equals("from"); ZoneType origin = hasFrom ? ZoneType.smartValueOf(workingCopy[3]) : null; String validFilter = workingCopy[hasFrom ? 4 : 2]; final CardCollection res = CardUtil.getLastTurnEntered(destination, origin, validFilter, c); if (origin == null) { // Remove cards on the battlefield that changed controller CardCollectionView sameDest = CardUtil.getLastTurnEntered(destination, destination, validFilter, c); res.removeAll(sameDest); } return doXMath(res.size(), m, c); } // Count$AttackersDeclared if (sq[0].contains("AttackersDeclared")) { return doXMath(cc.getAttackersDeclaredThisTurn(), m, c); } // Count$ThisTurnCast <Valid> // Count$LastTurnCast <Valid> if (sq[0].contains("ThisTurnCast") || sq[0].contains("LastTurnCast")) { final String[] workingCopy = l[0].split("_"); final String validFilter = workingCopy[1]; CardCollection res; if (workingCopy[0].contains("This")) { res = CardUtil.getThisTurnCast(validFilter, c); } else { res = CardUtil.getLastTurnCast(validFilter, c); } final int ret = doXMath(res.size(), m, c); return ret; } // Count$Morbid.<True>.<False> if (sq[0].startsWith("Morbid")) { final CardCollection res = CardUtil.getThisTurnEntered(ZoneType.Graveyard, ZoneType.Battlefield, "Creature", c, true); if (res.size() > 0) { return doXMath(Integer.parseInt(sq[1]), m, c); } return doXMath(Integer.parseInt(sq[2]), m, c); } if (sq[0].equals("YourTurns")) { return doXMath(cc.getTurn(), m, c); } if (sq[0].equals("TotalTurns")) { // Sorry for the Singleton use, replace this once this function has game passed into it return doXMath(game.getPhaseHandler().getTurn(), m, c); } //Count$Random.<Min>.<Max> if (sq[0].equals("Random")) { int min = StringUtils.isNumeric(sq[1]) ? Integer.parseInt(sq[1]) : xCount(c, c.getSVar(sq[1])); int max = StringUtils.isNumeric(sq[2]) ? Integer.parseInt(sq[2]) : xCount(c, c.getSVar(sq[2])); return forge.util.MyRandom.getRandom().nextInt(1 + max - min) + min; } // Count$Domain if (sq[0].startsWith("Domain")) { int n = 0; Player neededPlayer = sq[0].equals("DomainActivePlayer") ? activePlayer : cc; CardCollection someCards = CardLists.filter(neededPlayer.getCardsIn(ZoneType.Battlefield), Presets.LANDS); for (String basic : MagicColor.Constant.BASIC_LANDS) { if (!CardLists.getType(someCards, basic).isEmpty()) { n++; } } return doXMath(n, m, c); } // Count$Converge if (sq[0].contains("Converge")) { return doXMath(c.getSunburstValue(), m, c); } // Count$ColoredCreatures *a DOMAIN for creatures* if (sq[0].contains("ColoredCreatures")) { int mask = 0; CardCollection someCards = CardLists.filter(cc.getCardsIn(ZoneType.Battlefield), Presets.CREATURES); for (final Card crd : someCards) { mask |= CardUtil.getColors(crd).getColor(); } return doXMath(ColorSet.fromMask(mask).countColors(), m, c); } // Count$CardMulticolor.<numMC>.<numNotMC> if (sq[0].contains("CardMulticolor")) { final boolean isMulti = CardUtil.getColors(c).isMulticolor(); return doXMath(Integer.parseInt(sq[isMulti ? 1 : 2]), m, c); } // Complex counting methods CardCollectionView someCards = getCardListForXCount(c, cc, sq); // 1/10 - Count$MaxCMCYouCtrl if (sq[0].contains("MaxCMC")) { int mmc = Aggregates.max(someCards, CardPredicates.Accessors.fnGetCmc); return doXMath(mmc, m, c); } return doXMath(someCards.size(), m, c); }
From source file:com.glaf.core.util.StringTools.java
@SuppressWarnings("unchecked") public static List<Integer> splitToInt(String text, String delimiter) { if (delimiter == null) { throw new RuntimeException("delimiter is null"); }// www.jav a2 s .c o m if (text == null) { return Collections.EMPTY_LIST; } List<Integer> pieces = new java.util.ArrayList<Integer>(); int start = 0; int end = text.indexOf(delimiter); while (end != -1) { String tmp = text.substring(start, end); if (StringUtils.isNotEmpty(tmp) && StringUtils.isNumeric(tmp)) { pieces.add(Integer.parseInt(tmp)); } start = end + delimiter.length(); end = text.indexOf(delimiter, start); } if (start < text.length()) { String tmp = text.substring(start); if (tmp != null && tmp.trim().length() > 0) { if (StringUtils.isNumeric(tmp)) { pieces.add(Integer.parseInt(tmp)); } } } return pieces; }
From source file:com.glaf.core.util.StringTools.java
@SuppressWarnings("unchecked") public static List<Long> splitToLong(String text, String delimiter) { if (delimiter == null) { throw new RuntimeException("delimiter is null"); }/*from w w w .jav a 2 s . c o m*/ if (text == null) { return Collections.EMPTY_LIST; } List<Long> pieces = new java.util.ArrayList<Long>(); int start = 0; int end = text.indexOf(delimiter); while (end != -1) { String tmp = text.substring(start, end); if (StringUtils.isNotEmpty(tmp) && StringUtils.isNumeric(tmp)) { pieces.add(Long.parseLong(tmp)); } start = end + delimiter.length(); end = text.indexOf(delimiter, start); } if (start < text.length()) { String tmp = text.substring(start); if (tmp != null && tmp.trim().length() > 0) { if (StringUtils.isNumeric(tmp)) { pieces.add(Long.parseLong(tmp)); } } } return pieces; }
From source file:com.moviejukebox.reader.MovieNFOReader.java
/** * Parse Sets from the XML NFO file//from ww w. j av a 2 s . c o m * * @param nlElements * @param movie */ private static void parseSets(NodeList nlElements, Movie movie) { Node nElements; for (int looper = 0; looper < nlElements.getLength(); looper++) { nElements = nlElements.item(looper); if (nElements.getNodeType() == Node.ELEMENT_NODE) { Element eId = (Element) nElements; String setOrder = eId.getAttribute("order"); if (StringUtils.isNumeric(setOrder)) { movie.addSet(eId.getTextContent(), Integer.parseInt(setOrder)); } else { movie.addSet(eId.getTextContent()); } } } }
From source file:com.glaf.core.service.impl.MxTableDataServiceImpl.java
@Transactional public void updateAllDbids(List<Dbid> rows) { if (rows != null && !rows.isEmpty()) { Map<String, Long> idMap = new java.util.HashMap<String, Long>(); List<Dbid> list = this.getAllDbids(); for (Dbid id : rows) { if (StringUtils.isNumeric(id.getValue())) { idMap.put(id.getName(), Long.parseLong(id.getValue())); }//w ww . j a va 2 s .c o m } if (list != null && !list.isEmpty()) { for (Dbid dbid : list) { if (idMap.containsKey(dbid.getName()) && StringUtils.isNumeric(dbid.getValue())) { if (idMap.get(dbid.getName()) > Long.parseLong(dbid.getValue())) { dbid.setValue(idMap.get(dbid.getName()).toString()); dbid.setVersion(dbid.getVersion() + 1); idMapper.updateNextDbId(dbid); } } } } } }
From source file:com.moviejukebox.reader.MovieNFOReader.java
/** * Parse the year from the XML NFO file// w w w .j a v a2 s .com * * @param tempYear * @param movie * @return */ private static boolean parseYear(String tempYear, Movie movie) { // START year if (StringUtils.isNumeric(tempYear) && tempYear.length() == 4) { if (OverrideTools.checkOverwriteYear(movie, NFO_PLUGIN_ID)) { movie.setYear(tempYear, NFO_PLUGIN_ID); } return Boolean.TRUE; } if (StringUtils.isBlank(tempYear)) { // The year is blank, so skip it. return Boolean.TRUE; } return Boolean.FALSE; }
From source file:com.moviejukebox.MovieJukebox.java
private void generateLibrary() throws Throwable { /**/*from w ww.ja v a 2 s .com*/ * ****************************************************************************** * @author Gabriel Corneanu * * The tools used for parallel processing are NOT thread safe (some operations are, but not all) therefore all are added to * a container which is instantiated one per thread * * - xmlWriter looks thread safe<br> * - htmlWriter was not thread safe<br> * - getTransformer is fixed (simple workaround)<br> * - MovieImagePlugin : not clear, made thread specific for safety<br> * - MediaInfoScanner : not sure, made thread specific * * Also important: <br> * The library itself is not thread safe for modifications (API says so) it could be adjusted with concurrent versions, but * it needs many changes it seems that it is safe for subsequent reads (iterators), so leave for now... * * - DatabasePluginController is also fixed to be thread safe (plugins map for each thread) * */ class ToolSet { private final MovieImagePlugin imagePlugin = MovieJukebox .getImagePlugin(getProperty("mjb.image.plugin", "com.moviejukebox.plugin.DefaultImagePlugin")); private final MovieImagePlugin backgroundPlugin = MovieJukebox.getBackgroundPlugin( getProperty("mjb.background.plugin", "com.moviejukebox.plugin.DefaultBackgroundPlugin")); private final MediaInfoScanner miScanner = new MediaInfoScanner(); private final OpenSubtitlesPlugin subtitlePlugin = new OpenSubtitlesPlugin(); private final TrailerScanner trailerScanner = new TrailerScanner(); // FANART.TV TV Artwork Scanners private final ArtworkScanner clearArtScanner = new FanartTvScanner(ArtworkType.CLEARART); private final ArtworkScanner clearLogoScanner = new FanartTvScanner(ArtworkType.CLEARLOGO); private final ArtworkScanner tvThumbScanner = new FanartTvScanner(ArtworkType.TVTHUMB); private final ArtworkScanner seasonThumbScanner = new FanartTvScanner(ArtworkType.SEASONTHUMB); // FANART.TV Movie Artwork Scanners private final ArtworkScanner movieArtScanner = new FanartTvScanner(ArtworkType.MOVIEART); private final ArtworkScanner movieLogoScanner = new FanartTvScanner(ArtworkType.MOVIELOGO); private final ArtworkScanner movieDiscScanner = new FanartTvScanner(ArtworkType.MOVIEDISC); } final ThreadLocal<ToolSet> threadTools = new ThreadLocal<ToolSet>() { @Override protected ToolSet initialValue() { return new ToolSet(); } }; final MovieJukeboxXMLReader xmlReader = new MovieJukeboxXMLReader(); final MovieJukeboxXMLWriter xmlWriter = new MovieJukeboxXMLWriter(); final MovieJukeboxHTMLWriter htmlWriter = new MovieJukeboxHTMLWriter(); File mediaLibraryRoot = new File(movieLibraryRoot); final File jukeboxDetailsRootFile = new FileTools.FileEx(jukebox.getJukeboxRootLocationDetails()); MovieListingPlugin listingPlugin = getListingPlugin( getProperty("mjb.listing.plugin", "com.moviejukebox.plugin.MovieListingPluginBase")); videoimageDownload = PropertiesUtil.getBooleanProperty("mjb.includeVideoImages", Boolean.FALSE); bannerDownload = PropertiesUtil.getBooleanProperty("mjb.includeWideBanners", Boolean.FALSE); photoDownload = PropertiesUtil.getBooleanProperty("mjb.includePhoto", Boolean.FALSE); backdropDownload = PropertiesUtil.getBooleanProperty("mjb.includeBackdrop", Boolean.FALSE); boolean processExtras = PropertiesUtil.getBooleanProperty("filename.extras.process", Boolean.TRUE); boolean moviejukeboxListing = PropertiesUtil.getBooleanProperty("mjb.listing.generate", Boolean.FALSE); // Multi-thread: Processing thread settings maxThreadsProcess = Integer.parseInt(getProperty("mjb.MaxThreadsProcess", "0")); if (maxThreadsProcess <= 0) { maxThreadsProcess = Runtime.getRuntime().availableProcessors(); } maxThreadsDownload = Integer.parseInt(getProperty("mjb.MaxThreadsDownload", "0")); if (maxThreadsDownload <= 0) { maxThreadsDownload = maxThreadsProcess; } LOG.info("Using {} processing threads and {} downloading threads...", maxThreadsProcess, maxThreadsDownload); if (maxThreadsDownload + maxThreadsProcess == 2) { // Display the note about the performance, otherwise assume that the user knows how to change // these parameters as they aren't set to the minimum LOG.info("See README.TXT for increasing performance using these settings."); } /* * ****************************************************************************** * * PART 1 : Preparing the temporary environment * */ SystemTools.showMemory(); LOG.info("Preparing environment..."); // create the ".mjbignore" and ".no_photo.nmj" file in the jukebox folder try { FileTools.makeDirs(jukebox.getJukeboxRootLocationDetailsFile()); new File(jukebox.getJukeboxRootLocationDetailsFile(), ".mjbignore").createNewFile(); FileTools.addJukeboxFile(".mjbignore"); if (getBooleanProperty("mjb.nmjCompliant", Boolean.FALSE)) { new File(jukebox.getJukeboxRootLocationDetailsFile(), ".no_photo.nmj").createNewFile(); FileTools.addJukeboxFile(".no_photo.nmj"); } } catch (IOException error) { LOG.error("Failed creating jukebox directory. Ensure this directory is read/write!"); LOG.error(SystemTools.getStackTrace(error)); return; } // Delete the existing filecache.txt try { (new File("filecache.txt")).delete(); } catch (Exception error) { LOG.error("Failed to delete the filecache.txt file."); LOG.error(SystemTools.getStackTrace(error)); return; } // Save the current state of the preferences to the skin directory for use by the skin // The forceHtmlOverwrite is set by the user or by the JukeboxProperties if there has been a skin change if (PropertiesUtil.getBooleanProperty("mjb.forceHTMLOverwrite", Boolean.FALSE) || !(new File(PropertiesUtil.getPropertiesFilename(Boolean.TRUE))).exists()) { PropertiesUtil.writeProperties(); } SystemTools.showMemory(); LOG.info("Initializing..."); try { FileTools.deleteDir(jukebox.getJukeboxTempLocation()); } catch (Exception error) { LOG.error( "Failed deleting the temporary jukebox directory ({}), please delete this manually and try again", jukebox.getJukeboxTempLocation()); return; } // Try and create the temp directory LOG.debug("Creating temporary jukebox location: {}", jukebox.getJukeboxTempLocation()); FileTools.makeDirs(jukebox.getJukeboxTempLocationDetailsFile()); /* * ****************************************************************************** * * PART 2 : Scan movie libraries for files... * */ SystemTools.showMemory(); LOG.info("Scanning library directory {}", mediaLibraryRoot); LOG.info("Jukebox output goes to {}", jukebox.getJukeboxRootLocation()); if (PropertiesUtil.getBooleanProperty("mjb.dirHash", Boolean.FALSE)) { // Add all folders 2 deep to the fileCache FileTools.fileCache.addDir(jukeboxDetailsRootFile, 2); /* * TODO: Need to watch for any issues when we have scanned the whole * jukebox, such as the watched folder, NFO folder, etc now existing * in the cache */ } else { // If the dirHash is not needed, just scan to the root level plus the watched and people folders FileTools.fileCache.addDir(jukeboxDetailsRootFile, 0); // Add the watched folder File watchedFileHandle = new FileTools.FileEx( jukebox.getJukeboxRootLocationDetails() + File.separator + "Watched"); FileTools.fileCache.addDir(watchedFileHandle, 0); // Add the people folder if needed if (isValidString(peopleFolder)) { File peopleFolderHandle = new FileTools.FileEx( jukebox.getJukeboxRootLocationDetails() + File.separator + peopleFolder); FileTools.fileCache.addDir(peopleFolderHandle, 0); } } ThreadExecutor<Void> tasks = new ThreadExecutor<>(maxThreadsProcess, maxThreadsDownload); final Library library = new Library(); for (final MediaLibraryPath mediaLibraryPath : mediaLibraryPaths) { // Multi-thread parallel processing tasks.submit(new Callable<Void>() { @Override public Void call() { LOG.debug("Scanning media library {}", mediaLibraryPath.getPath()); MovieDirectoryScanner mds = new MovieDirectoryScanner(); // scan uses synchronized method Library.addMovie mds.scan(mediaLibraryPath, library); System.out.print("\n"); return null; } }); } tasks.waitFor(); SystemTools.showMemory(); // If the user asked to preserve the existing movies, scan the output directory as well if (isJukeboxPreserve()) { LOG.info("Scanning output directory for additional videos"); OutputDirectoryScanner ods = new OutputDirectoryScanner(jukebox.getJukeboxRootLocationDetails()); ods.scan(library); } // Now that everything's been scanned, add all extras to library library.mergeExtras(); LOG.info("Found {} videos in your media library", library.size()); LOG.info("Stored {} files in the info cache", FileTools.fileCache.size()); if (enableWatchTraktTv) { // if Trakt.TV watched is enabled then refresh if necessary and preLoad watched data TraktTV.getInstance().initialize().refreshIfNecessary().preloadWatched(); } JukeboxStatistics.setJukeboxTime(JukeboxStatistics.JukeboxTimes.SCAN_END, System.currentTimeMillis()); JukeboxStatistics.setStatistic(JukeboxStatistic.VIDEOS, library.size()); tasks.restart(); if (!library.isEmpty()) { // Issue 1882: Separate index files for each category boolean separateCategories = PropertiesUtil.getBooleanProperty("mjb.separateCategories", Boolean.FALSE); LOG.info("Searching for information on the video files..."); int movieCounter = 0; for (final Movie movie : library.values()) { // Issue 997: Skip the processing of extras if not required if (movie.isExtra() && !processExtras) { continue; } final int count = ++movieCounter; final String movieTitleExt = movie.getOriginalTitle() + (movie.isTVShow() ? (" [Season " + movie.getSeason() + "]") : "") + (movie.isExtra() ? " [Extra]" : ""); if (movie.isTVShow()) { JukeboxStatistics.increment(JukeboxStatistic.TVSHOWS); } else { JukeboxStatistics.increment(JukeboxStatistic.MOVIES); } // Multi-thread parallel processing tasks.submit(new Callable<Void>() { @Override public Void call() throws FileNotFoundException, XMLStreamException { ToolSet tools = threadTools.get(); // Change the output message depending on the existance of the XML file boolean xmlExists = FileTools.fileCache .fileExists(StringTools.appendToPath(jukebox.getJukeboxRootLocationDetails(), movie.getBaseName()) + EXT_DOT_XML); if (xmlExists) { LOG.info("Checking existing video: {}", movieTitleExt); JukeboxStatistics.increment(JukeboxStatistic.EXISTING_VIDEOS); } else { LOG.info("Processing new video: {}", movieTitleExt); JukeboxStatistics.increment(JukeboxStatistic.NEW_VIDEOS); } if (ScanningLimit.getToken()) { // First get movie data (title, year, director, genre, etc...) library.toggleDirty( updateMovieData(xmlReader, tools.miScanner, jukebox, movie, library)); if (!movie.getMovieType().equals(Movie.REMOVE)) { // Check for watched and unwatched files if (enableWatchScanner || enableWatchTraktTv) { // Issue 1938 library.toggleDirty(WatchedScanner.checkWatched(jukebox, movie)); } // Get subtitle tools.subtitlePlugin.generate(movie); // Get Trailers if (trailersScannerEnable) { tools.trailerScanner.getTrailers(movie); } // Then get this movie's poster LOG.debug("Updating poster for: {}", movieTitleExt); updateMoviePoster(jukebox, movie); // Download episode images if required if (videoimageDownload) { VideoImageScanner.scan(tools.imagePlugin, jukebox, movie); } // Get FANART only if requested // Note that the FanartScanner will check if the file is newer / different if ((fanartMovieDownload && !movie.isTVShow()) || (fanartTvDownload && movie.isTVShow())) { FanartScanner.scan(tools.backgroundPlugin, jukebox, movie); } // Get BANNER if requested and is a TV show if (bannerDownload && movie.isTVShow()) { if (!BannerScanner.scan(tools.imagePlugin, jukebox, movie)) { updateTvBanner(jukebox, movie, tools.imagePlugin); } } // Get ClearART/LOGOS/etc if (movie.isTVShow()) { // Only scan using the TV Show artwork scanners tools.clearArtScanner.scan(jukebox, movie); tools.clearLogoScanner.scan(jukebox, movie); tools.tvThumbScanner.scan(jukebox, movie); tools.seasonThumbScanner.scan(jukebox, movie); } else { // Only scan using the Movie artwork scanners tools.movieArtScanner.scan(jukebox, movie); tools.movieDiscScanner.scan(jukebox, movie); tools.movieLogoScanner.scan(jukebox, movie); } for (int i = 0; i < footerCount; i++) { if (FOOTER_ENABLE.get(i)) { updateFooter(jukebox, movie, tools.imagePlugin, i, forceFooterOverwrite || movie.isDirty()); } } // If we are multipart, we need to make sure all archives have expanded names. if (PropertiesUtil.getBooleanProperty("mjb.scanner.mediainfo.rar.extended.url", Boolean.FALSE)) { Collection<MovieFile> partsFiles = movie.getFiles(); for (MovieFile mf : partsFiles) { String filename; filename = mf.getFile().getAbsolutePath(); // Check the filename is a mediaInfo extension (RAR, ISO) ? if (tools.miScanner.extendedExtension(filename) == Boolean.TRUE) { if (mf.getArchiveName() == null) { LOG.debug("MovieJukebox: Attempting to get archive name for {}", filename); String archive = tools.miScanner.archiveScan(filename); if (archive != null) { LOG.debug("MovieJukebox: Setting archive name to {}", archive); mf.setArchiveName(archive); } // got archivename } // not already set } // is extension } // for all files } // property is set if (!movie.isDirty()) { ScanningLimit.releaseToken(); } } else { ScanningLimit.releaseToken(); library.remove(movie); } LOG.info(LOG_FINISHED, movieTitleExt, count, library.size()); } else { movie.setSkipped(true); JukeboxProperties.setScanningLimitReached(Boolean.TRUE); LOG.info("Skipped: {} ({}/{})", movieTitleExt, count, library.size()); } // Show memory every (processing count) movies if (showMemory && (count % maxThreadsProcess) == 0) { SystemTools.showMemory(); } return null; } }); } tasks.waitFor(); // Add the new extra files (like trailers that were downloaded) to the library and to the corresponding movies library.mergeExtras(); OpenSubtitlesPlugin.logOut(); AniDbPlugin.anidbClose(); JukeboxStatistics.setJukeboxTime(JukeboxStatistics.JukeboxTimes.PROCESSING_END, System.currentTimeMillis()); if (peopleScan && peopleScrape && !ScanningLimit.isLimitReached()) { LOG.info("Searching for people information..."); int peopleCounter = 0; Map<String, Person> popularPeople = new TreeMap<>(); for (Movie movie : library.values()) { // Issue 997: Skip the processing of extras if not required if (movie.isExtra() && !processExtras) { continue; } if (popularity > 0) { for (Filmography person : movie.getPeople()) { boolean exists = Boolean.FALSE; String name = person.getName(); for (Map.Entry<String, Person> entry : popularPeople.entrySet()) { if (entry.getKey().substring(3).equalsIgnoreCase(name)) { entry.getValue().addDepartment(person.getDepartment()); entry.getValue().popularityUp(movie); exists = Boolean.TRUE; } } if (!exists) { Person p = new Person(person); p.addDepartment(p.getDepartment()); String key = String.format("%03d", person.getOrder()) + person.getName(); popularPeople.put(key, p); popularPeople.get(key).popularityUp(movie); } } } else { peopleCounter += movie.getPeople().size(); } } tasks.restart(); if (popularity > 0) { List<Person> as = new ArrayList<>(popularPeople.values()); Collections.sort(as, new PersonComparator()); List<Person> stars = new ArrayList<>(); Iterator<Person> itr = as.iterator(); while (itr.hasNext()) { if (peopleCounter >= peopleMax) { break; } Person person = itr.next(); if (popularity > person.getPopularity()) { break; } stars.add(person); peopleCounter++; } final int peopleCount = peopleCounter; peopleCounter = 0; for (final Person person : stars) { final int count = ++peopleCounter; final String personName = person.getName(); final Person p = new Person(person); // Multi-thread parallel processing tasks.submit(new Callable<Void>() { @Override public Void call() throws FileNotFoundException, XMLStreamException { ToolSet tools = threadTools.get(); // Get person data (name, birthday, etc...), download photo updatePersonData(xmlReader, jukebox, p, tools.imagePlugin); library.addPerson(p); LOG.info(LOG_FINISHED, personName, count, peopleCount); // Show memory every (processing count) movies if (showMemory && (count % maxThreadsProcess) == 0) { SystemTools.showMemory(); } return null; } }); } } else { final int peopleCount = peopleCounter; peopleCounter = 0; for (Movie movie : library.values()) { // Issue 997: Skip the processing of extras if not required if (movie.isExtra() && !processExtras) { continue; } Map<String, Integer> typeCounter = new TreeMap<>(); for (Filmography person : movie.getPeople()) { final int count = ++peopleCounter; String job = person.getJob(); if (!typeCounter.containsKey(job)) { typeCounter.put(job, 1); } else if (typeCounter.get(job) == peopleMax) { continue; } else { typeCounter.put(job, typeCounter.get(job) + 1); } final Person p = new Person(person); final String personName = p.getName(); // Multi-thread parallel processing tasks.submit(new Callable<Void>() { @Override public Void call() throws FileNotFoundException, XMLStreamException { ToolSet tools = threadTools.get(); // Get person data (name, birthday, etc...), download photo and put to library updatePersonData(xmlReader, jukebox, p, tools.imagePlugin); library.addPerson(p); LOG.info(LOG_FINISHED, personName, count, peopleCount); // Show memory every (processing count) movies if (showMemory && (count % maxThreadsProcess) == 0) { SystemTools.showMemory(); } return null; } }); } } } tasks.waitFor(); LOG.info("Add/update people information to the videos..."); boolean dirty; for (Movie movie : library.values()) { // Issue 997: Skip the processing of extras if not required if (movie.isExtra() && !processExtras) { continue; } for (Filmography person : movie.getPeople()) { dirty = Boolean.FALSE; for (Person p : library.getPeople()) { if (Filmography.comparePersonName(person, p) || comparePersonId(person, p)) { if (!person.getFilename().equals(p.getFilename()) && isValidString(p.getFilename())) { person.setFilename(p.getFilename()); dirty = Boolean.TRUE; } if (!person.getUrl().equals(p.getUrl()) && isValidString(p.getUrl())) { person.setUrl(p.getUrl()); dirty = Boolean.TRUE; } for (Map.Entry<String, String> e : p.getIdMap().entrySet()) { if (isNotValidString(e.getValue())) { continue; } if (person.getId(e.getKey()).equals(e.getValue())) { continue; } person.setId(e.getKey(), e.getValue()); dirty = Boolean.TRUE; } if (!person.getPhotoFilename().equals(p.getPhotoFilename()) && isValidString(p.getPhotoFilename())) { person.setPhotoFilename(p.getPhotoFilename()); dirty = Boolean.TRUE; } break; } } if (dirty) { movie.setDirty(DirtyFlag.INFO, Boolean.TRUE); } } for (Person p : library.getPeople()) { for (Filmography film : p.getFilmography()) { if (Filmography.compareMovieAndFilm(movie, film)) { film.setFilename(movie.getBaseName()); film.setTitle(movie.getTitle()); if (film.isDirty()) { p.setDirty(); } break; } } } } for (Person p : library.getPeople()) { for (Filmography film : p.getFilmography()) { if (film.isDirty() || StringTools.isNotValidString(film.getFilename())) { continue; } dirty = Boolean.FALSE; for (Movie movie : library.values()) { if (movie.isExtra() && !processExtras) { continue; } dirty = Filmography.compareMovieAndFilm(movie, film); if (dirty) { break; } } if (!dirty) { film.clearFilename(); p.setDirty(); } } } JukeboxStatistics.setJukeboxTime(JukeboxStatistics.JukeboxTimes.PEOPLE_END, System.currentTimeMillis()); } /* * ****************************************************************************** * * PART 3 : Indexing the library * */ SystemTools.showMemory(); // This is for programs like NMTServer where they don't need the indexes. if (skipIndexGeneration) { LOG.info("Indexing of libraries skipped."); } else { LOG.info("Indexing libraries..."); library.buildIndex(tasks); JukeboxStatistics.setJukeboxTime(JukeboxStatistics.JukeboxTimes.INDEXING_END, System.currentTimeMillis()); SystemTools.showMemory(); } /* * ****************************************************************************** * * PART 3B - Indexing masters */ LOG.info("Indexing masters..."); /* * This is kind of a hack -- library.values() are the movies that * were found in the library and library.getMoviesList() are the * ones that are there now. So the movies that are in getMoviesList * but not in values are the index masters. */ List<Movie> indexMasters = new ArrayList<>(library.getMoviesList()); indexMasters.removeAll(library.values()); JukeboxStatistics.setStatistic(JukeboxStatistic.SETS, indexMasters.size()); // Multi-thread: Parallel Executor tasks.restart(); final boolean autoCollection = PropertiesUtil.getBooleanProperty("themoviedb.collection", Boolean.FALSE); final TheMovieDbPlugin tmdb = new TheMovieDbPlugin(); for (final Movie movie : indexMasters) { // Multi-tread: Start Parallel Processing tasks.submit(new Callable<Void>() { @Override public Void call() throws FileNotFoundException, XMLStreamException { ToolSet tools = threadTools.get(); String safeSetMasterBaseName = FileTools.makeSafeFilename(movie.getBaseName()); /* * The master's movie XML is used for generating the * playlist it will be overwritten by the index XML */ LOG.debug("Updating set artwork for: {}...", movie.getOriginalTitle()); // If we can find a set artwork file, use it; otherwise, stick with the first movie's artwork String oldArtworkFilename = movie.getPosterFilename(); // Set a default poster name in case it's not found during the scan movie.setPosterFilename(safeSetMasterBaseName + "." + posterExtension); if (isNotValidString(PosterScanner.scan(jukebox, movie))) { LOG.debug("Local set poster ({}) not found.", safeSetMasterBaseName); String collectionId = movie.getId(TheMovieDbPlugin.CACHE_COLLECTION); if (autoCollection && StringUtils.isNumeric(collectionId)) { LOG.debug("MovieDb Collection detected with ID {}", collectionId); movie.setPosterURL(tmdb.getCollectionPoster(Integer.parseInt(collectionId))); movie.setFanartURL(tmdb.getCollectionFanart(Integer.parseInt(collectionId))); updateMoviePoster(jukebox, movie); } else { movie.setPosterFilename(oldArtworkFilename); } } // If this is a TV Show and we want to download banners, then also check for a banner Set file if (movie.isTVShow() && bannerDownload) { // Set a default banner filename in case it's not found during the scan movie.setBannerFilename(safeSetMasterBaseName + bannerToken + "." + bannerExtension); movie.setWideBannerFilename( safeSetMasterBaseName + wideBannerToken + "." + bannerExtension); if (!BannerScanner.scan(tools.imagePlugin, jukebox, movie)) { updateTvBanner(jukebox, movie, tools.imagePlugin); LOG.debug("Local set banner ({}{}.*) not found.", safeSetMasterBaseName, bannerToken); } else { LOG.debug("Local set banner found, using {}", movie.getBannerFilename()); } } // Check for Set FANART if (setIndexFanart) { // Set a default fanart filename in case it's not found during the scan movie.setFanartFilename(safeSetMasterBaseName + fanartToken + "." + fanartExtension); if (!FanartScanner.scan(tools.backgroundPlugin, jukebox, movie)) { LOG.debug("Local set fanart ({}{}.*) not found.", safeSetMasterBaseName, fanartToken); } else { LOG.debug("Local set fanart found, using {}", movie.getFanartFilename()); } } StringBuilder artworkFilename = new StringBuilder(safeSetMasterBaseName); artworkFilename.append(thumbnailToken).append(".").append(thumbnailExtension); movie.setThumbnailFilename(artworkFilename.toString()); artworkFilename = new StringBuilder(safeSetMasterBaseName); artworkFilename.append(posterToken).append(".").append(posterExtension); movie.setDetailPosterFilename(artworkFilename.toString()); // Generate footer filenames for (int inx = 0; inx < footerCount; inx++) { if (FOOTER_ENABLE.get(inx)) { artworkFilename = new StringBuilder(safeSetMasterBaseName); if (FOOTER_NAME.get(inx).contains("[")) { artworkFilename.append(footerToken).append("_").append(inx); } else { artworkFilename.append(".").append(FOOTER_NAME.get(inx)); } artworkFilename.append(".").append(FOOTER_EXTENSION.get(inx)); movie.setFooterFilename(artworkFilename.toString(), inx); } } // No playlist for index masters // htmlWriter.generatePlaylist(jukeboxDetailsRoot, tempJukeboxDetailsRoot, movie); // Add all the movie files to the exclusion list FileTools.addMovieToJukeboxFilenames(movie); return null; } }); } tasks.waitFor(); // Clear the cache if we've used it CacheMemory.clear(); JukeboxStatistics.setJukeboxTime(JukeboxStatistics.JukeboxTimes.MASTERS_END, System.currentTimeMillis()); SystemTools.showMemory(); // Issue 1886: Html indexes recreated every time StringBuilder indexFilename; for (Movie setMovie : library.getMoviesList()) { if (setMovie.isSetMaster()) { indexFilename = new StringBuilder(jukebox.getJukeboxRootLocationDetails()); indexFilename.append(File.separator).append(setMovie.getBaseName()).append(EXT_DOT_XML); File xmlFile = FileTools.fileCache.getFile(indexFilename.toString()); if (xmlFile.exists()) { xmlReader.parseSetXML(xmlFile, setMovie, library.getMoviesList()); } } } // Issue 1882: Separate index files for each category List<String> categoriesList = Arrays.asList( getProperty("mjb.categories.indexList", "Other,Genres,Title,Certification,Year,Library,Set") .split(",")); if (!skipIndexGeneration) { LOG.info("Writing Indexes XML..."); xmlWriter.writeIndexXML(jukebox, library, tasks); // Issue 2235: Update artworks after masterSet changed ToolSet tools = threadTools.get(); StringBuilder idxName; boolean createPosters = PropertiesUtil.getBooleanProperty("mjb.sets.createPosters", Boolean.FALSE); for (IndexInfo idx : library.getGeneratedIndexes()) { if (!idx.canSkip && idx.categoryName.equals(Library.INDEX_SET)) { idxName = new StringBuilder(idx.categoryName); idxName.append("_").append(FileTools.makeSafeFilename(idx.key)).append("_1"); for (Movie movie : indexMasters) { if (!movie.getBaseName().equals(idxName.toString())) { continue; } if (createPosters) { // Create/update a detail poster for setMaster LOG.debug("Create/update detail poster for set: {}", movie.getBaseName()); createPoster(tools.imagePlugin, jukebox, SkinProperties.getSkinHome(), movie, Boolean.TRUE); } // Create/update a thumbnail for setMaster LOG.debug("Create/update thumbnail for set: {}, isTV: {}, isHD: {}", movie.getBaseName(), movie.isTVShow(), movie.isHD()); createThumbnail(tools.imagePlugin, jukebox, SkinProperties.getSkinHome(), movie, Boolean.TRUE); for (int inx = 0; inx < footerCount; inx++) { if (FOOTER_ENABLE.get(inx)) { LOG.debug("Create/update footer for set: {}, footerName: {}", movie.getBaseName(), FOOTER_NAME.get(inx)); updateFooter(jukebox, movie, tools.imagePlugin, inx, Boolean.TRUE); } } } } } LOG.info("Writing Category XML..."); library.setDirty(library.isDirty() || forceIndexOverwrite); xmlWriter.writeCategoryXML(jukebox, library, "Categories", library.isDirty()); // Issue 1882: Separate index files for each category if (separateCategories) { for (String categoryName : categoriesList) { xmlWriter.writeCategoryXML(jukebox, library, categoryName, library.isDirty()); } } } SystemTools.showMemory(); LOG.info("Writing Library data..."); // Multi-thread: Parallel Executor tasks.restart(); int totalCount = library.values().size(); int currentCount = 1; for (final Movie movie : library.values()) { System.out.print("\r Processing library #" + currentCount++ + "/" + totalCount); // Issue 997: Skip the processing of extras if not required if (movie.isExtra() && !processExtras) { continue; } if (movie.isSkipped()) { continue; } // Multi-tread: Start Parallel Processing tasks.submit(new Callable<Void>() { @Override public Void call() throws FileNotFoundException, XMLStreamException { ToolSet tools = threadTools.get(); // Update movie XML files with computed index information LOG.debug("Writing index data to movie: {}", movie.getBaseName()); xmlWriter.writeMovieXML(jukebox, movie, library); // Create a detail poster for each movie LOG.debug("Creating detail poster for movie: {}", movie.getBaseName()); createPoster(tools.imagePlugin, jukebox, SkinProperties.getSkinHome(), movie, forcePosterOverwrite); // Create a thumbnail for each movie LOG.debug("Creating thumbnails for movie: {}", movie.getBaseName()); createThumbnail(tools.imagePlugin, jukebox, SkinProperties.getSkinHome(), movie, forceThumbnailOverwrite); if (!skipIndexGeneration && !skipHtmlGeneration) { // write the movie details HTML LOG.debug("Writing detail HTML to movie: {}", movie.getBaseName()); htmlWriter.generateMovieDetailsHTML(jukebox, movie); // write the playlist for the movie if needed if (!skipPlaylistGeneration) { FileTools.addJukeboxFiles(htmlWriter.generatePlaylist(jukebox, movie)); } } // Add all the movie files to the exclusion list FileTools.addMovieToJukeboxFilenames(movie); return null; } }); } tasks.waitFor(); System.out.print("\n"); SystemTools.showMemory(); JukeboxStatistics.setJukeboxTime(JukeboxStatistics.JukeboxTimes.WRITE_INDEX_END, System.currentTimeMillis()); if (peopleScan) { LOG.info("Writing people data..."); // Multi-thread: Parallel Executor tasks.restart(); totalCount = library.getPeople().size(); currentCount = 1; for (final Person person : library.getPeople()) { // Multi-tread: Start Parallel Processing System.out.print("\r Processing person #" + currentCount++ + "/" + totalCount); tasks.submit(new Callable<Void>() { @Override public Void call() throws FileNotFoundException, XMLStreamException { // ToolSet tools = threadTools.get(); // Update person XML files with computed index information LOG.debug("Writing index data to person: {}", person.getName()); xmlWriter.writePersonXML(jukebox, person); if (!skipIndexGeneration && !skipHtmlGeneration) { // write the person details HTML htmlWriter.generatePersonDetailsHTML(jukebox, person); } return null; } }); } tasks.waitFor(); System.out.print("\n"); SystemTools.showMemory(); JukeboxStatistics.setJukeboxTime(JukeboxStatistics.JukeboxTimes.WRITE_PEOPLE_END, System.currentTimeMillis()); } if (!skipIndexGeneration) { if (!skipHtmlGeneration) { LOG.info("Writing Indexes HTML..."); LOG.info(" Video indexes..."); htmlWriter.generateMoviesIndexHTML(jukebox, library, tasks); LOG.info(" Category indexes..."); htmlWriter.generateMoviesCategoryHTML(jukebox, "Categories", "categories.xsl", library.isDirty()); // Issue 1882: Separate index files for each category if (separateCategories) { LOG.info(" Separate category indexes..."); for (String categoryName : categoriesList) { htmlWriter.generateMoviesCategoryHTML(jukebox, categoryName, "category.xsl", library.isDirty()); } } } /* * Generate the index file. * * Do not skip this part as it's the index that starts the jukebox */ htmlWriter.generateMainIndexHTML(jukebox, library); JukeboxStatistics.setJukeboxTime(JukeboxStatistics.JukeboxTimes.WRITE_HTML_END, System.currentTimeMillis()); /* Generate extra pages if required */ String pageList = PropertiesUtil.getProperty("mjb.customPages", ""); if (StringUtils.isNotBlank(pageList)) { List<String> newPages = new ArrayList<>(Arrays.asList(pageList.split(","))); for (String page : newPages) { LOG.info("Transforming skin custom page '{}'", page); htmlWriter.transformXmlFile(jukebox, page); } } } if (enableCompleteMovies) { CompleteMoviesWriter.generate(library, jukebox); } /** * ****************************************************************************** * * PART 4 : Copy files to target directory * */ SystemTools.showMemory(); LOG.info("Copying new files to Jukebox directory..."); String index = getProperty("mjb.indexFile", "index.htm"); FileTools.copyDir(jukebox.getJukeboxTempLocationDetails(), jukebox.getJukeboxRootLocationDetails(), Boolean.TRUE); FileTools.copyFile(new File(jukebox.getJukeboxTempLocation() + File.separator + index), new File(jukebox.getJukeboxRootLocation() + File.separator + index)); String skinDate = jukebox.getJukeboxRootLocationDetails() + File.separator + "pictures" + File.separator + "skin.date"; File skinFile = new File(skinDate); File propFile = new File(userPropertiesName); // Only check the property file date if the jukebox properties are not being monitored. boolean copySkin = JukeboxProperties.isMonitor() ? Boolean.FALSE : FileTools.isNewer(propFile, skinFile); // If forceSkinOverwrite is set, the skin file doesn't exist, the user properties file doesn't exist or is newer than the skin.date file if (forceSkinOverwrite || !skinFile.exists() || !propFile.exists() || (SkinProperties.getFileDate() > skinFile.lastModified()) || copySkin) { if (forceSkinOverwrite) { LOG.info("Copying skin files to Jukebox directory (forceSkinOverwrite)..."); } else if (SkinProperties.getFileDate() > skinFile.lastModified()) { LOG.info("Copying skin files to Jukebox directory (Skin is newer)..."); } else if (!propFile.exists()) { LOG.info("Copying skin files to Jukebox directory (No property file)..."); } else if (FileTools.isNewer(propFile, skinFile)) { LOG.info("Copying skin files to Jukebox directory ({} is newer)...", propFile.getName()); } else { LOG.info("Copying skin files to Jukebox directory..."); } StringTokenizer st = new StringTokenizer(PropertiesUtil.getProperty("mjb.skin.copyDirs", "html"), " ,;|"); while (st.hasMoreTokens()) { String skinDirName = st.nextToken(); String skinDirFull = StringTools.appendToPath(SkinProperties.getSkinHome(), skinDirName); if ((new File(skinDirFull).exists())) { LOG.info("Copying the {} directory...", skinDirName); FileTools.copyDir(skinDirFull, jukebox.getJukeboxRootLocationDetails(), Boolean.TRUE); } } if (skinFile.exists()) { skinFile.setLastModified(JukeboxStatistics.getTime(JukeboxStatistics.JukeboxTimes.START)); } else { FileTools.makeDirsForFile(skinFile); skinFile.createNewFile(); } } else { LOG.info("Skin copying skipped."); LOG.debug("Use mjb.forceSkinOverwrite=true to force the overwitting of the skin files"); } FileTools.fileCache.saveFileList("filecache.txt"); JukeboxStatistics.setJukeboxTime(JukeboxStatistics.JukeboxTimes.COPYING_END, System.currentTimeMillis()); /** * ****************************************************************************** * * PART 5: Clean-up the jukebox directory * */ SystemTools.showMemory(); // Clean the jukebox folder of unneeded files cleanJukeboxFolder(); if (moviejukeboxListing) { LOG.info("Generating listing output..."); listingPlugin.generate(jukebox, library); } LOG.info("Clean up temporary files"); File rootIndex = new File(appendToPath(jukebox.getJukeboxTempLocation(), index)); rootIndex.delete(); FileTools.deleteDir(jukebox.getJukeboxTempLocation()); // clean up extracted attachments AttachmentScanner.cleanUp(); } // Set the end time JukeboxStatistics.setTimeEnd(System.currentTimeMillis()); // Write the jukebox details file at the END of the run (Issue 1830) JukeboxProperties.writeFile(jukebox, library, mediaLibraryPaths); // Output the statistics JukeboxStatistics.writeFile(jukebox, library, mediaLibraryPaths); LOG.info(""); LOG.info("MovieJukebox process completed at {}", new Date()); LOG.info("Processing took {}", JukeboxStatistics.getProcessingTime()); }
From source file:forge.game.player.Player.java
@Override public final boolean hasProperty(final String property, final Player sourceController, final Card source) { if (property.equals("You")) { if (!equals(sourceController)) { return false; }/* w ww .j a v a2s.c o m*/ } else if (property.equals("Opponent")) { if (equals(sourceController) || !isOpponentOf(sourceController)) { return false; } } else if (property.equals("Allies")) { if (equals(sourceController) || isOpponentOf(sourceController)) { return false; } } else if (property.equals("Active")) { if (!equals(game.getPhaseHandler().getPlayerTurn())) { return false; } } else if (property.equals("NonActive")) { if (equals(game.getPhaseHandler().getPlayerTurn())) { return false; } } else if (property.equals("OpponentToActive")) { final Player active = game.getPhaseHandler().getPlayerTurn(); if (equals(active) || !isOpponentOf(active)) { return false; } } else if (property.equals("Other")) { if (equals(sourceController)) { return false; } } else if (property.equals("OtherThanSourceOwner")) { if (equals(source.getOwner())) { return false; } } else if (property.equals("wasDealtDamageBySourceThisGame")) { if (!source.getDamageHistory().getThisGameDamaged().contains(this)) { return false; } } else if (property.equals("wasDealtDamageBySourceThisTurn")) { if (!source.getDamageHistory().getThisTurnDamaged().contains(this)) { return false; } } else if (property.equals("attackedBySourceThisCombat")) { if (game.getCombat() == null || !equals(game.getCombat().getDefenderPlayerByAttacker(source))) { return false; } } else if (property.startsWith("wasDealtDamageThisTurn")) { if (assignedDamage.isEmpty()) { return false; } } else if (property.startsWith("LostLifeThisTurn")) { if (lifeLostThisTurn <= 0) { return false; } } else if (property.startsWith("DeclaredAttackerThisTurn")) { if (attackersDeclaredThisTurn <= 0) { return false; } } else if (property.startsWith("NoCardsInHandAtBeginningOfTurn")) { if (numCardsInHandStartedThisTurnWith > 0) { return false; } } else if (property.startsWith("CardsInHandAtBeginningOfTurn")) { if (numCardsInHandStartedThisTurnWith <= 0) { return false; } } else if (property.startsWith("WithCardsInHand")) { if (property.contains("AtLeast")) { int amount = Integer.parseInt(property.split("AtLeast")[1]); if (getCardsIn(ZoneType.Hand).size() < amount) { return false; } } } else if (property.equals("IsRemembered")) { if (!source.isRemembered(this)) { return false; } } else if (property.equals("IsNotRemembered")) { if (source.isRemembered(this)) { return false; } } else if (property.startsWith("EnchantedBy")) { if (!isEnchantedBy(source)) { return false; } } else if (property.startsWith("Chosen")) { if (source.getChosenPlayer() == null || !source.getChosenPlayer().equals(this)) { return false; } } else if (property.startsWith("LifeEquals_")) { int life = AbilityUtils.calculateAmount(source, property.substring(11), null); if (getLife() != life) { return false; } } else if (property.equals("IsPoisoned")) { if (getPoisonCounters() <= 0) { return false; } } else if (property.startsWith("controls")) { final String[] type = property.substring(8).split("_"); final CardCollectionView list = CardLists.getValidCards(getCardsIn(ZoneType.Battlefield), type[0], sourceController, source); String comparator = type[1]; String compareTo = comparator.substring(2); int y = StringUtils.isNumeric(compareTo) ? Integer.parseInt(compareTo) : 0; if (!Expressions.compare(list.size(), comparator, y)) { return false; } } else if (property.startsWith("withMore")) { final String cardType = property.split("sThan")[0].substring(8); final Player controller = "Active".equals(property.split("sThan")[1]) ? game.getPhaseHandler().getPlayerTurn() : sourceController; final CardCollectionView oppList = CardLists.filter(getCardsIn(ZoneType.Battlefield), CardPredicates.isType(cardType)); final CardCollectionView yourList = CardLists.filter(controller.getCardsIn(ZoneType.Battlefield), CardPredicates.isType(cardType)); if (oppList.size() <= yourList.size()) { return false; } } else if (property.startsWith("withAtLeast")) { final String cardType = property.split("More")[1].split("sThan")[0]; final int amount = Integer.parseInt(property.substring(11, 12)); final Player controller = "Active".equals(property.split("sThan")[1]) ? game.getPhaseHandler().getPlayerTurn() : sourceController; final CardCollectionView oppList = CardLists.filter(getCardsIn(ZoneType.Battlefield), CardPredicates.isType(cardType)); final CardCollectionView yourList = CardLists.filter(controller.getCardsIn(ZoneType.Battlefield), CardPredicates.isType(cardType)); System.out.println(yourList.size()); if (oppList.size() < yourList.size() + amount) { return false; } } else if (property.startsWith("hasMore")) { final Player controller = property.contains("Than") && "Active".equals(property.split("Than")[1]) ? game.getPhaseHandler().getPlayerTurn() : sourceController; if (property.substring(7).startsWith("Life") && getLife() <= controller.getLife()) { return false; } else if (property.substring(7).startsWith("CardsInHand") && getCardsIn(ZoneType.Hand).size() <= controller.getCardsIn(ZoneType.Hand).size()) { return false; } } else if (property.startsWith("hasFewer")) { final Player controller = "Active".equals(property.split("Than")[1]) ? game.getPhaseHandler().getPlayerTurn() : sourceController; if (property.substring(8).startsWith("CreaturesInYard")) { final CardCollectionView oppList = CardLists.filter(getCardsIn(ZoneType.Graveyard), Presets.CREATURES); final CardCollectionView yourList = CardLists.filter(controller.getCardsIn(ZoneType.Graveyard), Presets.CREATURES); if (oppList.size() >= yourList.size()) { return false; } } } else if (property.startsWith("withMost")) { if (property.substring(8).equals("Life")) { int highestLife = getLife(); // Negative base just in case a few Lich's are running around for (final Player p : game.getPlayers()) { if (p.getLife() > highestLife) { highestLife = p.getLife(); } } if (getLife() != highestLife) { return false; } } else if (property.substring(8).equals("CardsInHand")) { int largestHand = 0; Player withLargestHand = null; for (final Player p : game.getPlayers()) { if (p.getCardsIn(ZoneType.Hand).size() > largestHand) { largestHand = p.getCardsIn(ZoneType.Hand).size(); withLargestHand = p; } } if (!equals(withLargestHand)) { return false; } } else if (property.substring(8).startsWith("Type")) { String type = property.split("Type")[1]; boolean checkOnly = false; if (type.endsWith("Only")) { checkOnly = true; type = type.replace("Only", ""); } int typeNum = 0; List<Player> controlmost = new ArrayList<Player>(); for (final Player p : game.getPlayers()) { final int num = CardLists.getType(p.getCardsIn(ZoneType.Battlefield), type).size(); if (num > typeNum) { typeNum = num; controlmost.clear(); } if (num == typeNum) { controlmost.add(p); } } if (checkOnly && controlmost.size() != 1) { return false; } if (!controlmost.contains(this)) { return false; } } } else if (property.startsWith("withLowest")) { if (property.substring(10).equals("Life")) { int lowestLife = getLife(); List<Player> lowestlifep = new ArrayList<Player>(); for (final Player p : game.getPlayers()) { if (p.getLife() == lowestLife) { lowestlifep.add(p); } else if (p.getLife() < lowestLife) { lowestLife = p.getLife(); lowestlifep.clear(); lowestlifep.add(p); } } if (!lowestlifep.contains(this)) { return false; } } } return true; }
From source file:com.moviejukebox.plugin.DefaultImagePlugin.java
private void fillOverlayParams(String xmlOverlayFilename) { if (!xmlOverlayFilename.toUpperCase().endsWith("XML")) { return;/*from w ww .j av a 2 s. c o m*/ } File xmlOverlayFile = new File(overlayRoot + xmlOverlayFilename); if (xmlOverlayFile.exists() && xmlOverlayFile.isFile()) { try { XMLConfiguration c = new XMLConfiguration(xmlOverlayFile); List<HierarchicalConfiguration> layers = c.configurationsAt("layer"); overlayLayers.clear(); int index = 0; for (HierarchicalConfiguration layer : layers) { String name = layer.getString("name"); if (StringTools.isNotValidString(name)) { continue; } LogoOverlay overlay = new LogoOverlay(); String after = layer.getString("[@after]"); if (StringTools.isValidString(after) && after.equalsIgnoreCase(TRUE)) { overlay.setBefore(Boolean.FALSE); } String left = layer.getString(LEFT); String top = layer.getString(TOP); String align = layer.getString("align"); String valign = layer.getString("valign"); String width = layer.getString("width"); String height = layer.getString("height"); overlay.setNames(Arrays.asList(name.split("/"))); if (StringUtils.isNumeric(left)) { overlay.setLeft(NumberUtils.toInt(left, 0)); } if (StringUtils.isNumeric(top)) { overlay.setTop(NumberUtils.toInt(top, 0)); } if (StringTools.isValidString(align) && (align.equalsIgnoreCase(LEFT) || align.equalsIgnoreCase(CENTER) || align.equalsIgnoreCase(RIGHT))) { overlay.setAlign(align); } if (StringTools.isValidString(valign) && (valign.equalsIgnoreCase(TOP) || valign.equalsIgnoreCase(CENTER) || valign.equalsIgnoreCase(BOTTOM))) { overlay.setValign(valign); } if (StringTools.isValidString(width) && (width.equalsIgnoreCase(EQUAL) || width.equalsIgnoreCase(AUTO) || width.matches(D_PLUS))) { overlay.setWidth(width); } if (StringTools.isValidString(height) && (height.equalsIgnoreCase(EQUAL) || height.equalsIgnoreCase(AUTO) || height.matches(D_PLUS))) { overlay.setHeight(height); } List<HierarchicalConfiguration> images = c .configurationsAt("layer(" + index + ").images.image"); for (HierarchicalConfiguration image : images) { name = image.getString("[@name]"); String value = image.getString("[@value]"); String filename = image.getString("[@filename]"); if (StringTools.isNotValidString(name)) { name = overlay.getNames().get(0); } if (!overlay.getNames().contains(name) || StringTools.isNotValidString(value) || StringTools.isNotValidString(filename)) { continue; } ImageOverlay img = new ImageOverlay(name, value, filename, Arrays.asList(value.split("/"))); if (img.getValues().size() > 1) { for (int i = 0; i < overlay.getNames().size(); i++) { if (img.getValues().size() <= i) { img.getValues().add(Movie.UNKNOWN); } else if (StringTools.isNotValidString(img.getValues().get(i))) { img.getValues().set(i, Movie.UNKNOWN); } } } overlay.getImages().add(img); } if (overlay.getNames().size() > 1) { List<HierarchicalConfiguration> positions = c .configurationsAt("layer(" + index + ").positions.position"); for (HierarchicalConfiguration position : positions) { String value = position.getString("[@value]"); left = position.getString("[@left]"); top = position.getString("[@top]"); align = position.getString("[@align]"); valign = position.getString("[@valign]"); width = position.getString("[@width]"); height = position.getString("[@height]"); if (StringTools.isNotValidString(value)) { continue; } ConditionOverlay condition = new ConditionOverlay(); condition.setValues(Arrays.asList(value.split("/"))); if (StringTools.isNotValidString(left)) { left = Integer.toString(overlay.getLeft()); } if (StringTools.isNotValidString(top)) { top = Integer.toString(overlay.getTop()); } if (StringTools.isNotValidString(align)) { align = overlay.getAlign(); } if (StringTools.isNotValidString(valign)) { valign = overlay.getValign(); } if (StringTools.isNotValidString(width)) { width = overlay.getWidth(); } if (StringTools.isNotValidString(height)) { height = overlay.getHeight(); } List<String> lefts = Arrays.asList(left.split("/")); List<String> tops = Arrays.asList(top.split("/")); List<String> aligns = Arrays.asList(align.split("/")); List<String> valigns = Arrays.asList(valign.split("/")); List<String> widths = Arrays.asList(width.split("/")); List<String> heights = Arrays.asList(height.split("/")); for (int i = 0; i < overlay.getNames().size(); i++) { if (StringTools.isNotValidString(condition.getValues().get(i))) { condition.getValues().set(i, Movie.UNKNOWN); } PositionOverlay p = new PositionOverlay( (lefts.size() <= i || StringTools.isNotValidString(lefts.get(i))) ? overlay.getLeft() : Integer.parseInt(lefts.get(i)), (tops.size() <= i || StringTools.isNotValidString(tops.get(i))) ? overlay.getTop() : Integer.parseInt(tops.get(i)), (aligns.size() <= i || StringTools.isNotValidString(aligns.get(i))) ? overlay.getAlign() : aligns.get(i), (valigns.size() <= i || StringTools.isNotValidString(valigns.get(i))) ? overlay.getValign() : valigns.get(i), (widths.size() <= i || StringTools.isNotValidString(widths.get(i))) ? overlay.getWidth() : widths.get(i), (heights.size() <= i || StringTools.isNotValidString(heights.get(i))) ? overlay.getHeight() : heights.get(i)); condition.getPositions().add(p); } overlay.getPositions().add(condition); } } overlayLayers.add(overlay); index++; } List<HierarchicalConfiguration> blocks = c.configurationsAt(BLOCK); overlayBlocks.clear(); for (HierarchicalConfiguration block : blocks) { String name = block.getString("name"); if (StringTools.isNotValidString(name)) { continue; } String dir = block.getString("dir"); dir = StringTools.isNotValidString(dir) ? "horizontal" : dir; String size = block.getString("size"); size = StringTools.isNotValidString(size) ? AUTO : size; String cols = block.getString("cols"); cols = StringTools.isNotValidString(cols) ? AUTO : cols; String rows = block.getString("rows"); rows = StringTools.isNotValidString(rows) ? AUTO : rows; String hmargin = block.getString("hmargin"); hmargin = StringTools.isNotValidString(hmargin) ? "0" : hmargin; String vmargin = block.getString("vmargin"); vmargin = StringTools.isNotValidString(vmargin) ? "0" : vmargin; String clones = block.getString("clones"); overlayBlocks.put(name, new LogosBlock("horizontal".equalsIgnoreCase(dir), "static".equalsIgnoreCase(size), cols, rows, hmargin, vmargin, StringTools.isNotValidString(clones) ? blockClones : (TRUE.equalsIgnoreCase(clones) ? true : (FALSE.equalsIgnoreCase(clones) ? false : blockClones)))); } } catch (ConfigurationException ex) { LOG.error("Failed parsing moviejukebox overlay configuration file: {}", xmlOverlayFile.getName()); LOG.error(SystemTools.getStackTrace(ex)); } } else { LOG.error("The moviejukebox overlay configuration file you specified is invalid: {}", xmlOverlayFile.getAbsolutePath()); } }
From source file:com.moviejukebox.model.Library.java
/** * Determine the year banding for the category. * * If the year is this year or last year, return those, otherwise return the decade the year resides in * * @param filmYear The year to check/*w w w . j a v a 2s. c om*/ * @return "This Year", "Last Year" or the decade range (1990-1999) */ public static String getYearCategory(final String filmYear) { StringBuilder yearCat; if (StringTools.isValidString(filmYear) && StringUtils.isNumeric(filmYear)) { if (filmYear.equals(String.valueOf(CURRENT_YEAR))) { yearCat = new StringBuilder("This Year"); } else if (filmYear.equals(String.valueOf(CURRENT_YEAR - 1))) { yearCat = new StringBuilder("Last Year"); } else { String beginYear = filmYear.substring(0, filmYear.length() - 1) + "0"; String endYear; int tmpYear = NumberUtils.toInt(filmYear, -1); if (tmpYear < 0) { LOG.debug("Year is not number: {}", filmYear); return Movie.UNKNOWN; } else if (tmpYear >= CURRENT_DECADE) { // The film year is in the current decade, so we need to adjust the end year endYear = String.valueOf(FINAL_YEAR); } else { // Otherwise it's 9 endYear = filmYear.substring(0, filmYear.length() - 1) + "9"; } LOG.trace("Library years for categories: Begin='{}' End='{}'", beginYear, endYear); yearCat = new StringBuilder(beginYear); yearCat.append("-").append(endYear.substring(endYear.length() >= 4 ? endYear.length() - 2 : 0)); } } else { LOG.trace("Library: Invalid year '{}'", filmYear); yearCat = new StringBuilder(Movie.UNKNOWN); } return yearCat.toString(); }