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 va 2s. c o m*/ * postFactoryKeywords. * </p> * * @param card * a {@link forge.game.card.Card} object. */ public static void setupKeywordedAbilities(final Card card) { // this function should handle any keywords that need to be added after // a spell goes through the factory // Cards with Cycling abilities // -1 means keyword "Cycling" not found for (String keyword : card.getKeywords()) { if (keyword.startsWith("Multikicker")) { final String[] k = keyword.split("kicker "); String mkCost = k[1].split(":")[0]; final SpellAbility sa = card.getFirstSpellAbility(); sa.setMultiKickerManaCost(new ManaCost(new ManaCostParser(mkCost))); if (k[1].endsWith("Generic")) { sa.addAnnounceVar("Pseudo-multikicker"); } else { sa.addAnnounceVar("Multikicker"); } } else if (keyword.startsWith("Replicate")) { card.getFirstSpellAbility().addAnnounceVar("Replicate"); } else if (keyword.startsWith("Fuse")) { card.getState(CardStateName.Original).addNonManaAbility(AbilityFactory.buildFusedAbility(card)); } else if (keyword.startsWith("Evoke")) { card.addSpellAbility(makeEvokeSpell(card, keyword)); } else if (keyword.startsWith("Dash")) { card.addSpellAbility(makeDashSpell(card, keyword)); } else if (keyword.startsWith("Awaken")) { card.addSpellAbility(makeAwakenSpell(card, keyword)); } else if (keyword.startsWith("Monstrosity")) { final String[] k = keyword.split(":"); final String magnitude = k[0].substring(12); final String manacost = k[1]; card.removeIntrinsicKeyword(keyword); String ref = "X".equals(magnitude) ? " | References$ X" : ""; String counters = StringUtils.isNumeric(magnitude) ? Lang.nounWithNumeral(Integer.parseInt(magnitude), "+1/+1 counter") : "X +1/+1 counters"; String effect = "AB$ PutCounter | Cost$ " + manacost + " | ConditionPresent$ " + "Card.Self+IsNotMonstrous | Monstrosity$ True | CounterNum$ " + magnitude + " | CounterType$ P1P1 | SpellDescription$ Monstrosity " + magnitude + " (If this creature isn't monstrous, put " + counters + " on it and it becomes monstrous.) | StackDescription$ SpellDescription" + ref; card.addSpellAbility(AbilityFactory.getAbility(effect, card)); // add ability to instrinic strings so copies/clones create the ability also card.getCurrentState().addUnparsedAbility(effect); } else if (keyword.startsWith("Unearth")) { card.removeIntrinsicKeyword(keyword); final String[] k = keyword.split(":"); final String manacost = k[1]; String effect = "AB$ ChangeZone | Cost$ " + manacost + " | Defined$ Self" + " | Origin$ Graveyard | Destination$ Battlefield | SorcerySpeed$" + " True | ActivationZone$ Graveyard | Unearth$ True | SubAbility$" + " UnearthPumpSVar | PrecostDesc$ Unearth | StackDescription$ " + "Unearth: Return CARDNAME to the battlefield. | SpellDescription$" + " (" + ManaCostParser.parse(manacost) + ": Return CARDNAME to the " + "battlefield. It gains haste. Exile it at the beginning of the next" + " end step or if it would leave the battlefield. Unearth only as a sorcery.)"; String dbpump = "DB$ Pump | Defined$ Self | KW$ Haste & HIDDEN If CARDNAME" + " would leave the battlefield, exile it instead of putting it " + "anywhere else. | Permanent$ True | SubAbility$ UnearthDelayTrigger"; String delTrig = "DB$ DelayedTrigger | Mode$ Phase | Phase$ End of Turn" + " | Execute$ UnearthTrueDeath | TriggerDescription$ Exile " + "CARDNAME at the beginning of the next end step."; String truedeath = "DB$ ChangeZone | Defined$ Self | Origin$ Battlefield" + " | Destination$ Exile"; card.setSVar("UnearthPumpSVar", dbpump); card.setSVar("UnearthDelayTrigger", delTrig); card.setSVar("UnearthTrueDeath", truedeath); card.addSpellAbility(AbilityFactory.getAbility(effect, card)); // add ability to instrinic strings so copies/clones create the ability also card.getCurrentState().addUnparsedAbility(effect); } else if (keyword.startsWith("Level up")) { final String strMaxLevel = card.getSVar("maxLevel"); card.removeIntrinsicKeyword(keyword); final String[] k = keyword.split(":"); final String manacost = k[1]; String effect = "AB$ PutCounter | Cost$ " + manacost + " | " + "SorcerySpeed$ True | LevelUp$ True | CounterNum$ 1" + " | CounterType$ LEVEL | PrecostDesc$ Level Up | MaxLevel$ " + strMaxLevel + " | SpellDescription$ (Put a level counter on" + " this permanent. Activate this ability only any time you" + " could cast a sorcery.)"; card.addSpellAbility(AbilityFactory.getAbility(effect, card)); // add ability to instrinic strings so copies/clones create the ability also card.getCurrentState().addUnparsedAbility(effect); } else if (keyword.startsWith("Cycling")) { card.removeIntrinsicKeyword(keyword); final String[] k = keyword.split(":"); final String manacost = k[1]; card.addSpellAbility(abilityCycle(card, manacost)); } else if (keyword.startsWith("TypeCycling")) { card.removeIntrinsicKeyword(keyword); final String[] k = keyword.split(":"); final String type = k[1]; final String manacost = k[2]; card.addSpellAbility(abilityTypecycle(card, manacost, type)); } else if (keyword.startsWith("Transmute")) { card.removeIntrinsicKeyword(keyword); final String manacost = keyword.split(":")[1]; final String sbTransmute = "AB$ ChangeZone | Cost$ " + manacost + " Discard<1/CARDNAME>" + " | CostDesc$ Transmute " + ManaCostParser.parse(manacost) + " | ActivationZone$ Hand" + " | Origin$ Library | Destination$ Hand | ChangeType$ Card.cmcEQ" + card.getManaCost().getCMC() + " | ChangeNum$ 1 | SorcerySpeed$ True | References$ TransmuteX | SpellDescription$ (" + ManaCostParser.parse(manacost) + ", Discard this card: Search your library for a card " + "with the same converted mana cost as the discarded card, reveal that card, " + "and put it into your hand. Then shuffle your library. Activate this ability " + "only any time you could cast a sorcery.)"; final SpellAbility abTransmute = AbilityFactory.getAbility(sbTransmute, card); card.addSpellAbility(abTransmute); card.getCurrentState().addUnparsedAbility(sbTransmute); } else if (keyword.startsWith("Soulshift")) { final String[] k = keyword.split(" "); final int manacost = Integer.parseInt(k[1]); final String actualTrigger = "Mode$ ChangesZone | Origin$ Battlefield | Destination$ Graveyard" + "| OptionalDecider$ You | ValidCard$ Card.Self | Execute$ SoulshiftAbility" + "| TriggerController$ TriggeredCardController | TriggerDescription$ " + keyword + " (When this creature dies, you may return target Spirit card with converted mana cost " + manacost + " or less from your graveyard to your hand.)"; final String abString = "DB$ ChangeZone | Origin$ Graveyard | Destination$ Hand" + "| ValidTgts$ Spirit.YouOwn+cmcLE" + manacost; final Trigger parsedTrigger = TriggerHandler.parseTrigger(actualTrigger, card, true); card.addTrigger(parsedTrigger); card.setSVar("SoulshiftAbility", abString); } else if (keyword.startsWith("Champion")) { card.removeIntrinsicKeyword(keyword); final String[] k = keyword.split(":"); final String[] valid = k[1].split(","); String desc = k.length > 2 ? k[2] : k[1]; String article = Lang.startsWithVowel(desc) ? "an" : "a"; if (desc.equals("Creature")) { desc = "creature"; //use lowercase for "Champion a creature" } StringBuilder changeType = new StringBuilder(); for (String v : valid) { if (changeType.length() != 0) { changeType.append(","); } changeType.append(v).append(".YouCtrl+Other"); } StringBuilder trig = new StringBuilder(); trig.append("Mode$ ChangesZone | Origin$ Any | Destination$ Battlefield | ValidCard$ Card.Self | "); trig.append("Execute$ ChampionAbility | TriggerDescription$ Champion ").append(article + " "); trig.append(desc) .append(" (When this enters the battlefield, sacrifice it unless you exile another "); trig.append(desc).append( " you control. When this leaves the battlefield, that card returns to the battlefield.)"); StringBuilder trigReturn = new StringBuilder(); trigReturn.append( "Mode$ ChangesZone | Origin$ Battlefield | Destination$ Any | ValidCard$ Card.Self | "); trigReturn.append( "Execute$ ChampionReturn | Secondary$ True | TriggerDescription$ When this leaves the battlefield, that card returns to the battlefield."); StringBuilder ab = new StringBuilder(); ab.append( "DB$ ChangeZone | Origin$ Battlefield | Destination$ Exile | RememberChanged$ True | Champion$ True | "); ab.append("Hidden$ True | Optional$ True | SubAbility$ ChampionSacrifice | ChangeType$ ") .append(changeType); StringBuilder subAb = new StringBuilder(); subAb.append( "DB$ Sacrifice | Defined$ Card.Self | ConditionDefined$ Remembered | ConditionPresent$ Card | ConditionCompare$ EQ0"); String returnChampion = "DB$ ChangeZone | Defined$ Remembered | Origin$ Exile | Destination$ Battlefield"; final Trigger parsedTrigger = TriggerHandler.parseTrigger(trig.toString(), card, true); final Trigger parsedTrigReturn = TriggerHandler.parseTrigger(trigReturn.toString(), card, true); card.addTrigger(parsedTrigger); card.addTrigger(parsedTrigReturn); card.setSVar("ChampionAbility", ab.toString()); card.setSVar("ChampionReturn", returnChampion); card.setSVar("ChampionSacrifice", subAb.toString()); } else if (keyword.startsWith("If CARDNAME would be put into a graveyard " + "from anywhere, reveal CARDNAME and shuffle it into its owner's library instead.")) { String replacement = "Event$ Moved | Destination$ Graveyard | ValidCard$ Card.Self | ReplaceWith$ GraveyardToLibrary"; String ab = "DB$ ChangeZone | Hidden$ True | Origin$ All | Destination$ Library | Defined$ ReplacedCard | Reveal$ True | Shuffle$ True"; card.addReplacementEffect(ReplacementHandler.parseReplacement(replacement, card, true)); card.setSVar("GraveyardToLibrary", ab); } else if (keyword.startsWith("Echo")) { final String[] k = keyword.split(":"); final String cost = k[1]; String upkeepTrig = "Mode$ Phase | Phase$ Upkeep | ValidPlayer$ You | TriggerZones$ Battlefield " + " | Execute$ TrigUpkeepEcho | IsPresent$ Card.Self+cameUnderControlSinceLastUpkeep | Secondary$ True | " + "TriggerDescription$ Echo: At the beginning of your upkeep, if CARDNAME came under your control since the " + "beginning of your last upkeep, sacrifice it unless you pay the Echo cost"; String ref = "X".equals(cost) ? " | References$ X" : ""; card.setSVar("TrigUpkeepEcho", "AB$ Sacrifice | Cost$ 0 | SacValid$ Self | " + "Echo$ " + cost + ref); final Trigger parsedUpkeepTrig = TriggerHandler.parseTrigger(upkeepTrig, card, true); card.addTrigger(parsedUpkeepTrig); } else if (keyword.startsWith("Suspend")) { card.removeIntrinsicKeyword(keyword); card.setSuspend(true); final String[] k = keyword.split(":"); final String timeCounters = k[1]; final String cost = k[2]; card.addSpellAbility(abilitySuspendStatic(card, cost, timeCounters)); addSuspendUpkeepTrigger(card); addSuspendPlayTrigger(card); } else if (keyword.startsWith("Fading")) { final String[] k = keyword.split(":"); card.addIntrinsicKeyword("etbCounter:FADE:" + k[1] + ":no Condition:no desc"); String upkeepTrig = "Mode$ Phase | Phase$ Upkeep | ValidPlayer$ You | TriggerZones$ Battlefield " + " | Execute$ TrigUpkeepFading | Secondary$ True | TriggerDescription$ At the beginning of " + "your upkeep, remove a fade counter from CARDNAME. If you can't, sacrifice CARDNAME."; card.setSVar("TrigUpkeepFading", "AB$ RemoveCounter | Cost$ 0 | Defined$ Self | CounterType$ FADE" + " | CounterNum$ 1 | RememberRemoved$ True | SubAbility$ DBUpkeepFadingSac"); card.setSVar("DBUpkeepFadingSac", "DB$ Sacrifice | SacValid$ Self | ConditionCheckSVar$ FadingCheckSVar" + " | ConditionSVarCompare$ EQ0 | References$ FadingCheckSVar | SubAbility$ FadingCleanup"); card.setSVar("FadingCleanup", "DB$ Cleanup | ClearRemembered$ True"); card.setSVar("FadingCheckSVar", "Count$RememberedSize"); final Trigger parsedUpkeepTrig = TriggerHandler.parseTrigger(upkeepTrig, card, true); card.addTrigger(parsedUpkeepTrig); } else if (keyword.startsWith("Renown")) { final String[] k = keyword.split(" "); final String suffix = !k[1].equals("1") ? "s" : ""; card.removeIntrinsicKeyword(keyword); String renownTrig = "Mode$ DamageDone | ValidSource$ Card.Self | ValidTarget$ Player" + " | IsPresent$ Card.Self+IsNotRenowned | CombatDamage$ True | Execute$" + " TrigBecomeRenown | TriggerDescription$ Renown " + k[1] + " (When this " + "creature deals combat damage to a player, if it isn't renowned, put " + k[1] + " +1/+1 counter" + suffix + " on it and it becomes renowned.) "; card.setSVar("TrigBecomeRenown", "AB$ PutCounter | Cost$ 0 | Defined$ Self | " + "CounterType$ P1P1 | CounterNum$ " + k[1] + " | Renown$ True"); final Trigger parseRenownTrig = TriggerHandler.parseTrigger(renownTrig, card, true); card.addTrigger(parseRenownTrig); } else if (keyword.startsWith("Vanishing")) { final String[] k = keyword.split(":"); // etbcounter card.addIntrinsicKeyword("etbCounter:TIME:" + k[1] + ":no Condition:no desc"); // Remove Time counter trigger String upkeepTrig = "Mode$ Phase | Phase$ Upkeep | ValidPlayer$ You | " + "TriggerZones$ Battlefield | IsPresent$ Card.Self+counters_GE1_TIME" + " | Execute$ TrigUpkeepVanishing | TriggerDescription$ At the " + "beginning of your upkeep, if CARDNAME has a time counter on it, " + "remove a time counter from it. | Secondary$ True"; card.setSVar("TrigUpkeepVanishing", "AB$ RemoveCounter | Cost$ 0 | Defined$ Self" + " | CounterType$ TIME | CounterNum$ 1"); final Trigger parsedUpkeepTrig = TriggerHandler.parseTrigger(upkeepTrig, card, true); card.addTrigger(parsedUpkeepTrig); // sacrifice trigger String sacTrig = "Mode$ CounterRemoved | TriggerZones$ Battlefield | ValidCard$" + " Card.Self | NewCounterAmount$ 0 | Secondary$ True | CounterType$ TIME |" + " Execute$ TrigVanishingSac | TriggerDescription$ When the last time " + "counter is removed from CARDNAME, sacrifice it."; card.setSVar("TrigVanishingSac", "AB$ Sacrifice | Cost$ 0 | SacValid$ Self"); final Trigger parsedSacTrigger = TriggerHandler.parseTrigger(sacTrig, card, true); card.addTrigger(parsedSacTrigger); } else if (keyword.equals("Delve")) { card.getSpellAbilities().getFirst().setDelve(true); } else if (keyword.startsWith("Haunt")) { setupHauntSpell(card); } else if (keyword.equals("Provoke")) { final String actualTrigger = "Mode$ Attacks | ValidCard$ Card.Self | " + "OptionalDecider$ You | Execute$ ProvokeAbility | Secondary$ True | TriggerDescription$ " + "When this attacks, you may have target creature defending player " + "controls untap and block it if able."; final String abString = "DB$ MustBlock | ValidTgts$ Creature.DefenderCtrl | " + "TgtPrompt$ Select target creature defending player controls | SubAbility$ ProvokeUntap"; final String dbString = "DB$ Untap | Defined$ Targeted"; final Trigger parsedTrigger = TriggerHandler.parseTrigger(actualTrigger, card, true); card.addTrigger(parsedTrigger); card.setSVar("ProvokeAbility", abString); card.setSVar("ProvokeUntap", dbString); } else if (keyword.equals("Living Weapon")) { card.removeIntrinsicKeyword(keyword); final StringBuilder sbTrig = new StringBuilder(); sbTrig.append("Mode$ ChangesZone | Origin$ Any | Destination$ Battlefield | "); sbTrig.append("ValidCard$ Card.Self | Execute$ TrigGerm | TriggerDescription$ "); sbTrig.append("Living Weapon (When this Equipment enters the battlefield, "); sbTrig.append("put a 0/0 black Germ creature token onto the battlefield, then attach this to it.)"); final StringBuilder sbGerm = new StringBuilder(); sbGerm.append( "DB$ Token | TokenAmount$ 1 | TokenName$ Germ | TokenTypes$ Creature,Germ | RememberTokens$ True | "); sbGerm.append( "TokenOwner$ You | TokenColors$ Black | TokenPower$ 0 | TokenToughness$ 0 | TokenImage$ B 0 0 Germ | SubAbility$ DBGermAttach"); final StringBuilder sbAttach = new StringBuilder(); sbAttach.append("DB$ Attach | Defined$ Remembered | SubAbility$ DBGermClear"); final StringBuilder sbClear = new StringBuilder(); sbClear.append("DB$ Cleanup | ClearRemembered$ True"); card.setSVar("TrigGerm", sbGerm.toString()); card.setSVar("DBGermAttach", sbAttach.toString()); card.setSVar("DBGermClear", sbClear.toString()); final Trigger etbTrigger = TriggerHandler.parseTrigger(sbTrig.toString(), card, true); card.addTrigger(etbTrigger); } else if (keyword.equals("Epic")) { makeEpic(card); } else if (keyword.equals("Soulbond")) { // Setup ETB trigger for card with Soulbond keyword final String actualTriggerSelf = "Mode$ ChangesZone | Origin$ Any | Destination$ Battlefield | " + "ValidCard$ Card.Self | Execute$ TrigBondOther | OptionalDecider$ You | " + "IsPresent$ Creature.Other+YouCtrl+NotPaired | Secondary$ True | " + "TriggerDescription$ When CARDNAME enters the battlefield, " + "you may pair CARDNAME with another unpaired creature you control"; final String abStringSelf = "AB$ Bond | Cost$ 0 | Defined$ Self | ValidCards$ Creature.Other+YouCtrl+NotPaired"; final Trigger parsedTriggerSelf = TriggerHandler.parseTrigger(actualTriggerSelf, card, true); card.addTrigger(parsedTriggerSelf); card.setSVar("TrigBondOther", abStringSelf); // Setup ETB trigger for other creatures you control final String actualTriggerOther = "Mode$ ChangesZone | Origin$ Any | Destination$ Battlefield | " + "ValidCard$ Creature.Other+YouCtrl | TriggerZones$ Battlefield | OptionalDecider$ You | " + "Execute$ TrigBondSelf | IsPresent$ Creature.Self+NotPaired | Secondary$ True | " + " TriggerDescription$ When another unpaired creature you control enters the battlefield, " + "you may pair it with CARDNAME"; final String abStringOther = "AB$ Bond | Cost$ 0 | Defined$ TriggeredCard | ValidCards$ Creature.Self+NotPaired"; final Trigger parsedTriggerOther = TriggerHandler.parseTrigger(actualTriggerOther, card, true); card.addTrigger(parsedTriggerOther); card.setSVar("TrigBondSelf", abStringOther); } else if (keyword.equals("Extort")) { final String extortTrigger = "Mode$ SpellCast | ValidCard$ Card | ValidActivatingPlayer$ You | " + "TriggerZones$ Battlefield | Execute$ ExtortOpps | Secondary$ True" + " | TriggerDescription$ Extort (Whenever you cast a spell, you may pay W/B. If you do, " + "each opponent loses 1 life and you gain that much life.)"; final String abString = "AB$ LoseLife | Cost$ WB | Defined$ Player.Opponent | " + "LifeAmount$ 1 | SubAbility$ ExtortGainLife"; final String dbString = "DB$ GainLife | Defined$ You | LifeAmount$ AFLifeLost | References$ AFLifeLost"; final Trigger parsedTrigger = TriggerHandler.parseTrigger(extortTrigger, card, true); card.addTrigger(parsedTrigger); card.setSVar("ExtortOpps", abString); card.setSVar("ExtortGainLife", dbString); card.setSVar("AFLifeLost", "Number$0"); } else if (keyword.equals("Evolve")) { final String evolveTrigger = "Mode$ ChangesZone | Origin$ Any | Destination$ Battlefield | " + " ValidCard$ Creature.YouCtrl+Other | EvolveCondition$ True | " + "TriggerZones$ Battlefield | Execute$ EvolveAddCounter | Secondary$ True | " + "TriggerDescription$ Evolve (Whenever a creature enters the battlefield under your " + "control, if that creature has greater power or toughness than this creature, put a " + "+1/+1 counter on this creature.)"; final String abString = "AB$ PutCounter | Cost$ 0 | Defined$ Self | CounterType$ P1P1 | " + "CounterNum$ 1 | Evolve$ True"; final Trigger parsedTrigger = TriggerHandler.parseTrigger(evolveTrigger, card, true); card.addTrigger(parsedTrigger); card.setSVar("EvolveAddCounter", abString); } else if (keyword.startsWith("Dredge")) { final int dredgeAmount = card.getKeywordMagnitude("Dredge"); final String actualRep = "Event$ Draw | ActiveZones$ Graveyard | ValidPlayer$ You | " + "ReplaceWith$ DredgeCards | Secondary$ True | Optional$ True | CheckSVar$ " + "DredgeCheckLib | SVarCompare$ GE" + dredgeAmount + " | References$ " + "DredgeCheckLib | AICheckDredge$ True | Description$ " + card.getName() + " - Dredge " + dredgeAmount; final String abString = "DB$ Mill | Defined$ You | NumCards$ " + dredgeAmount + " | " + "SubAbility$ DredgeMoveToPlay"; final String moveToPlay = "DB$ ChangeZone | Origin$ Graveyard | Destination$ Hand | " + "Defined$ Self"; final String checkSVar = "Count$ValidLibrary Card.YouOwn"; card.setSVar("DredgeCards", abString); card.setSVar("DredgeMoveToPlay", moveToPlay); card.setSVar("DredgeCheckLib", checkSVar); card.addReplacementEffect(ReplacementHandler.parseReplacement(actualRep, card, true)); } else if (keyword.startsWith("Tribute")) { final int tributeAmount = card.getKeywordMagnitude("Tribute"); final String actualRep = "Event$ Moved | Destination$ Battlefield | ValidCard$ Card.Self |" + " ReplaceWith$ TributeAddCounter | Secondary$ True | Description$ Tribute " + tributeAmount + " (As this creature enters the battlefield, an opponent of your" + " choice may place " + tributeAmount + " +1/+1 counter on it.)"; final String abString = "DB$ PutCounter | Defined$ ReplacedCard | Tribute$ True | " + "CounterType$ P1P1 | CounterNum$ " + tributeAmount + " | ETB$ True | SubAbility$ TributeMoveToPlay"; final String moveToPlay = "DB$ ChangeZone | Origin$ All | Destination$ Battlefield | " + "Defined$ ReplacedCard | Hidden$ True"; card.setSVar("TributeAddCounter", abString); card.setSVar("TributeMoveToPlay", moveToPlay); card.addReplacementEffect(ReplacementHandler.parseReplacement(actualRep, card, true)); } else if (keyword.startsWith("Amplify")) { // find position of Amplify keyword final int ampPos = card.getKeywordPosition("Amplify"); final String[] ampString = card.getKeywords().get(ampPos).split(":"); final String amplifyMagnitude = ampString[1]; final String suffix = !amplifyMagnitude.equals("1") ? "s" : ""; final String ampTypes = ampString[2]; String[] refinedTypes = ampTypes.split(","); final StringBuilder types = new StringBuilder(); for (int i = 0; i < refinedTypes.length; i++) { types.append("Card.").append(refinedTypes[i]).append("+YouCtrl"); if (i + 1 != refinedTypes.length) { types.append(","); } } // Setup ETB replacement effects final String actualRep = "Event$ Moved | Destination$ Battlefield | ValidCard$ Card.Self |" + " ReplaceWith$ AmplifyReveal | Secondary$ True | Description$ As this creature " + "enters the battlefield, put " + amplifyMagnitude + " +1/+1 counter" + suffix + " on it for each " + ampTypes.replace(",", " and/or ") + " card you reveal in your hand.)"; final String abString = "DB$ Reveal | AnyNumber$ True | RevealValid$ " + types.toString() + " | RememberRevealed$ True | SubAbility$ Amplify"; final String dbString = "DB$ PutCounter | Defined$ ReplacedCard | CounterType$ P1P1 | " + "CounterNum$ AmpMagnitude | References$ Revealed,AmpMagnitude | SubAbility$" + " AmplifyMoveToPlay | ETB$ True"; final String moveToPlay = "DB$ ChangeZone | Origin$ All | Destination$ Battlefield | " + "Defined$ ReplacedCard | Hidden$ True | SubAbility$ DBCleanup"; card.addReplacementEffect(ReplacementHandler.parseReplacement(actualRep, card, true)); card.setSVar("AmplifyReveal", abString); card.setSVar("AmplifyMoveToPlay", moveToPlay); card.setSVar("Amplify", dbString); card.setSVar("DBCleanup", "DB$ Cleanup | ClearRemembered$ True"); card.setSVar("AmpMagnitude", "SVar$Revealed/Times." + amplifyMagnitude); card.setSVar("Revealed", "Remembered$Amount"); } else if (keyword.startsWith("Equip")) { // Check for additional params such as preferred AI targets final String equipString = keyword.substring(5); final String[] equipExtras = equipString.contains("|") ? equipString.split("\\|", 2) : null; // Get cost string String equipCost = ""; if (equipExtras != null) { equipCost = equipExtras[0].trim(); } else { equipCost = equipString.trim(); } // Create attach ability string final StringBuilder abilityStr = new StringBuilder(); abilityStr.append("AB$ Attach | Cost$ "); abilityStr.append(equipCost); abilityStr .append(" | ValidTgts$ Creature.YouCtrl | TgtPrompt$ Select target creature you control "); abilityStr.append( "| SorcerySpeed$ True | Equip$ True | AILogic$ Pump | IsPresent$ Card.Self+nonCreature "); if (equipExtras != null) { abilityStr.append("| ").append(equipExtras[1]).append(" "); } abilityStr.append("| PrecostDesc$ Equip "); Cost cost = new Cost(equipCost, true); if (!cost.isOnlyManaCost()) { //Something other than a mana cost abilityStr.append("- "); } abilityStr.append("| CostDesc$ " + cost.toSimpleString() + " "); abilityStr.append("| SpellDescription$ (" + cost.toSimpleString() + ": Attach to target creature you control. Equip only as a sorcery.)"); // instantiate attach ability final SpellAbility sa = AbilityFactory.getAbility(abilityStr.toString(), card); card.addSpellAbility(sa); // add ability to instrinic strings so copies/clones create the ability also card.getCurrentState().addUnparsedAbility(abilityStr.toString()); } else if (keyword.startsWith("Outlast")) { final String outlastString = keyword.substring(7); final String[] outlastExtras = outlastString.contains("|") ? outlastString.split("\\|", 2) : null; // Get cost string String outlastCost = ""; if (outlastExtras != null) { outlastCost = outlastExtras[0].trim(); } else { outlastCost = outlastString.trim(); } // Create outlast ability string final StringBuilder abilityStr = new StringBuilder(); abilityStr.append("AB$ PutCounter | Cost$ "); abilityStr.append(outlastCost); abilityStr.append(" T | Defined$ Self | CounterType$ P1P1 | CounterNum$ 1 "); abilityStr.append("| SorcerySpeed$ True | Outlast$ True "); if (outlastExtras != null) { abilityStr.append("| ").append(outlastExtras[1]).append(" "); } abilityStr.append("| PrecostDesc$ Outlast "); Cost cost = new Cost(outlastCost, true); if (!cost.isOnlyManaCost()) { //Something other than a mana cost abilityStr.append("- "); } abilityStr.append("| CostDesc$ " + cost.toSimpleString() + " "); abilityStr.append("| SpellDescription$ (" + cost.toSimpleString() + ", {T}: Put a +1/+1 counter on this creature. Outlast only as a sorcery.)"); final SpellAbility sa = AbilityFactory.getAbility(abilityStr.toString(), card); card.addSpellAbility(sa); // add ability to instrinic strings so copies/clones create the ability also card.getCurrentState().addUnparsedAbility(abilityStr.toString()); } else if (keyword.startsWith("Fortify")) { final String equipString = keyword.substring(7); final String[] equipExtras = equipString.contains("|") ? equipString.split("\\|", 2) : null; // Get cost string String equipCost = ""; if (equipExtras != null) { equipCost = equipExtras[0].trim(); } else { equipCost = equipString.trim(); } // Create attach ability string final StringBuilder abilityStr = new StringBuilder(); abilityStr.append("AB$ Attach | Cost$ "); abilityStr.append(equipCost); abilityStr.append(" | ValidTgts$ Land.YouCtrl | TgtPrompt$ Select target land you control "); abilityStr.append("| SorcerySpeed$ True | AILogic$ Pump | IsPresent$ Card.Self+nonCreature "); if (equipExtras != null) { abilityStr.append("| ").append(equipExtras[1]).append(" "); } abilityStr.append("| PrecostDesc$ Fortify "); Cost cost = new Cost(equipCost, true); if (!cost.isOnlyManaCost()) { //Something other than a mana cost abilityStr.append("- "); } abilityStr.append("| CostDesc$ " + cost.toSimpleString() + " "); abilityStr.append("| SpellDescription$ (" + cost.toSimpleString() + ": Attach to target land you control. Fortify only as a sorcery.)"); // instantiate attach ability final SpellAbility sa = AbilityFactory.getAbility(abilityStr.toString(), card); card.addSpellAbility(sa); // add ability to intrinsic strings so copies/clones create the ability also card.getCurrentState().addUnparsedAbility(abilityStr.toString()); } else if (keyword.startsWith("Bestow")) { final String[] params = keyword.split(":"); final String cost = params[1]; card.removeIntrinsicKeyword(keyword); final StringBuilder sbAttach = new StringBuilder(); sbAttach.append("SP$ Attach | Cost$ "); sbAttach.append(cost); sbAttach.append(" | AILogic$ ").append(params.length > 2 ? params[2] : "Pump"); sbAttach.append(" | Bestow$ True | ValidTgts$ Creature"); final SpellAbility bestow = AbilityFactory.getAbility(sbAttach.toString(), card); bestow.setDescription("Bestow " + ManaCostParser.parse(cost) + " (If you cast this" + " card for its bestow cost, it's an Aura spell with enchant creature. It" + " becomes a creature again if it's not attached to a creature.)"); bestow.setStackDescription("Bestow - " + card.getName()); bestow.setBasicSpell(false); card.addSpellAbility(bestow); card.getCurrentState().addUnparsedAbility(sbAttach.toString()); } else if (keyword.equals("Hideaway")) { card.getCurrentState().addIntrinsicKeyword("CARDNAME enters the battlefield tapped."); final Trigger hideawayTrigger = TriggerHandler.parseTrigger( "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Execute$ TrigHideawayDig | TriggerDescription$ When CARDNAME enters the battlefield, look at the top four cards of your library, exile one face down, then put the rest on the bottom of your library.", card, true); card.addTrigger(hideawayTrigger); card.setSVar("TrigHideawayDig", "DB$ Dig | Defined$ You | DigNum$ 4 | DestinationZone$ Exile | ExileFaceDown$ True | RememberChanged$ True | SubAbility$ DBHideawayEffect"); final Trigger gainControlTrigger = TriggerHandler.parseTrigger( "Mode$ ChangesController | ValidCard$ Card.Self | Execute$ DBHideawayEffect | Static$ True", card, true); card.addTrigger(gainControlTrigger); card.setSVar("DBHideawayEffect", "DB$ Effect | StaticAbilities$ STHideawayEffectLookAtCard | Triggers$ THideawayEffectCleanup | SVars$ DBHideawayEffectExileSelf | ImprintOnHost$ True | Duration$ Permanent | SubAbility$ DBHideawayRemember"); card.setSVar("STHideawayEffectLookAtCard", "Mode$ Continuous | Affected$ Card.IsRemembered | MayLookAt$ True | EffectZone$ Command | AffectedZone$ Exile | Description$ You may look at the exiled card."); card.setSVar("THideawayEffectCleanup", "Mode$ ChangesZone | ValidCard$ Card.IsRemembered | Origin$ Exile | Destination$ Any | TriggerZone$ Command | Execute$ DBHideawayEffectExileSelf | Static$ True"); card.setSVar("DBHideawayEffectExileSelf", "DB$ ChangeZone | Defined$ Self | Origin$ Command | Destination$ Exile"); final Trigger changeZoneTrigger = TriggerHandler.parseTrigger( "Mode$ ChangesZone | ValidCard$ Card.IsRemembered | Origin$ Exile | Destination$ Any | TriggerZone$ Command | Execute$ DBHideawayCleanup | Static$ True", card, true); card.addTrigger(changeZoneTrigger); card.setSVar("DBHideawayRemember", "DB$ Animate | Defined$ Imprinted | RememberObjects$ Remembered | Permanent$ True"); card.setSVar("DBHideawayCleanup", "DB$ Cleanup | ClearRemembered$ True"); } } // AddCost if (card.hasSVar("FullCost")) { final SpellAbility sa1 = card.getFirstSpellAbility(); if (sa1 != null && sa1.isSpell()) { sa1.setPayCosts(new Cost(card.getSVar("FullCost"), sa1.isAbility())); } } // AltCost String altCost = card.getSVar("AltCost"); if (StringUtils.isNotBlank(altCost)) { final SpellAbility sa1 = card.getFirstSpellAbility(); if (sa1 != null && sa1.isSpell()) { card.addSpellAbility(makeAltCostAbility(card, altCost, sa1)); } } setupEtbKeywords(card); }
From source file:ch.cyberduck.ui.cocoa.controller.InfoController.java
/** * Permission value from input field.// w ww. j av a 2 s .co m * * @return Null if invalid string has been entered entered, */ private Permission getPermissionFromOctalField() { if (StringUtils.isNotBlank(octalField.stringValue())) { if (StringUtils.length(octalField.stringValue()) >= 3) { if (StringUtils.isNumeric(octalField.stringValue())) { return new Permission(Integer.valueOf(octalField.stringValue()).intValue()); } } } log.warn(String.format("Invalid octal field input %s", octalField.stringValue())); return null; }
From source file:com.sonicle.webtop.mail.Service.java
public void processSendMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { JsonResult json = null;/*from w w w . ja va 2s . co m*/ CoreManager coreMgr = WT.getCoreManager(); IContactsManager contactsManager = (IContactsManager) WT.getServiceManager("com.sonicle.webtop.contacts", true, environment.getProfileId()); // TODO: Cloud integration!!! /* VFSService vfs=(VFSService)wts.getServiceByName("vfs"); ArrayList<String> hashlinks=null; if (vfs!=null) { //look for links to cloud in the html String html=request.getParameter("content"); hashlinks=new ArrayList<String>(); int hlx=-1; String puburl=wtd.getSetting("vfs.pub.url"); char chars[]=new char[] { '\'', '"'}; for(char c: chars) { String pattern="<a href="+c+puburl+"/public/vfs/"; Service.logger.debug("Looking for pattern "+pattern); while((hlx=html.indexOf(pattern,hlx+1))>=0) { int xhash1=hlx+pattern.length(); int xhash2=html.indexOf(c,xhash1); if (xhash2>xhash1) { String hash=html.substring(xhash1,xhash2); Service.logger.debug("Found hash "+hash); hashlinks.add(hash); } } } }*/ try { MailAccount account = getAccount(request); //String emails[]=request.getParameterValues("recipients"); Payload<MapItem, JsMessage> pl = ServletUtils.getPayload(request, JsMessage.class); JsMessage jsmsg = pl.data; long msgId = ServletUtils.getLongParameter(request, "msgId", true); boolean isFax = ServletUtils.getBooleanParameter(request, "isFax", false); boolean save = ServletUtils.getBooleanParameter(request, "save", false); if (isFax) { int faxmaxtos = getEnv().getCoreServiceSettings().getFaxMaxRecipients(); //check for valid fax recipients String faxpattern = getEnv().getCoreServiceSettings().getFaxPattern(); String regex = "^" + faxpattern.replace("{number}", "(\\d+)").replace("{username}", "(\\w+)") + "$"; Pattern pattern = Pattern.compile(regex); int nemails = 0; for (JsRecipient jsr : jsmsg.recipients) { if (StringUtils.isEmpty(jsr.email)) continue; ++nemails; if (StringUtils.isNumeric(jsr.email)) continue; boolean matches = false; try { InternetAddress ia = new InternetAddress(jsr.email); String email = ia.getAddress(); matches = pattern.matcher(email).matches(); } catch (Exception exc) { } if (!matches) { throw new Exception(lookupResource(MailLocaleKey.FAX_ADDRESS_ERROR)); } } if (faxmaxtos > 0 && nemails > faxmaxtos) { throw new WTException(lookupResource(MailLocaleKey.FAX_MAXADDRESS_ERROR), faxmaxtos); } } account.checkStoreConnected(); //String attachments[] = request.getParameterValues("attachments"); //if (attachments == null) { // attachments = new String[0]; //} SimpleMessage msg = prepareMessage(jsmsg, msgId, save, isFax); Identity ifrom = msg.getFrom(); String from = environment.getProfile().getEmailAddress(); if (ifrom != null) { from = ifrom.getEmail(); } account.checkStoreConnected(); Exception exc = sendMessage(msg, jsmsg.attachments); if (exc == null) { //if is draft, check for deletion if (jsmsg.draftuid > 0 && jsmsg.draftfolder != null && ss.isDefaultFolderDraftsDeleteMsgOnSend()) { FolderCache fc = account.getFolderCache(jsmsg.draftfolder); fc.deleteMessages(new long[] { jsmsg.draftuid }, false); } //Save used recipients for (JsRecipient rcpt : pl.data.recipients) { String email = rcpt.email; if (email != null && email.trim().length() > 0) coreMgr.autoLearnInternetRecipient(email); } //Save subject for suggestions if (jsmsg.subject != null && jsmsg.subject.trim().length() > 0) WT.getCoreManager().addServiceStoreEntry(SERVICE_ID, "subject", jsmsg.subject.toUpperCase(), jsmsg.subject); coreMgr.deleteMyAutosaveData(getEnv().getClientTrackingID(), SERVICE_ID, "newmail", "" + msgId); deleteAutosavedDraft(account, msgId); // TODO: Cloud integration!!! Destination emails added to share /* if (vfs!=null && hashlinks!=null && hashlinks.size()>0) { for(String hash: hashlinks) { Service.logger.debug("Adding emails to hash "+hash); vfs.setAuthEmails(hash, from, emails); } }*/ FolderCache fc = account.getFolderCache(account.getFolderSent()); fc.setForceRefresh(); //check for in-reply-to and set the answered flags //String inreplyto = request.getParameter("inreplyto"); //String replyfolder = request.getParameter("replyfolder"); //String forwardedfrom = request.getParameter("forwardedfrom"); //String forwardedfolder = request.getParameter("forwardedfolder"); //String soriguid=request.getParameter("origuid"); //long origuid=0; //try { origuid=Long.parseLong(soriguid); } catch(RuntimeException rexc) {} String foundfolder = null; if (jsmsg.forwardedfrom != null && jsmsg.forwardedfrom.trim().length() > 0) { try { foundfolder = foundfolder = flagForwardedMessage(account, jsmsg.forwardedfolder, jsmsg.forwardedfrom, jsmsg.origuid); } catch (Exception xexc) { Service.logger.error("Exception", xexc); } } else if ((jsmsg.inreplyto != null && jsmsg.inreplyto.trim().length() > 0) || (jsmsg.replyfolder != null && jsmsg.replyfolder.trim().length() > 0 && jsmsg.origuid > 0)) { try { String[] toRecipients = SimpleMessage.breakAddr(msg.getTo()); for (String toRecipient : toRecipients) { InternetAddress internetAddress = getInternetAddress(toRecipient); String contactEmail = internetAddress.getAddress(); String contactPersonal = internetAddress.getPersonal(); Condition<ContactQuery> predicate = new ContactQuery().email().eq(contactEmail); List<Integer> myCategories = contactsManager.listCategoryIds(); List<Integer> sharedCategories = contactsManager.listIncomingCategoryIds(); myCategories.addAll(sharedCategories); boolean existsContact = contactsManager.existContact(myCategories, predicate); if (!existsContact) { sendAddContactMessage(contactEmail, contactPersonal); break; } } foundfolder = flagAnsweredMessage(account, jsmsg.replyfolder, jsmsg.inreplyto, jsmsg.origuid); } catch (Exception xexc) { Service.logger.error("Exception", xexc); } } json = new JsonResult().set("foundfolder", foundfolder).set("saved", Boolean.FALSE); } else { Throwable cause = exc.getCause(); String msgstr = cause != null ? cause.getMessage() : exc.getMessage(); json = new JsonResult(false, msgstr); } } catch (Exception exc) { Service.logger.error("Exception", exc); Throwable cause = exc.getCause(); String msg = cause != null ? cause.getMessage() : exc.getMessage(); json = new JsonResult(false, msg); } json.printTo(out); }
From source file:com.cch.aj.entryrecorder.frame.MainJFrame.java
private void btnQuantityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuantityActionPerformed int a1 = 0;/*from ww w .ja v a 2 s .c o m*/ int a2 = 0; int b1 = 0; int b2 = 0; if (StringUtils.isNumeric(this.txtPalletProducedA.getText())) { currentEntry.setPalletProducedA(Integer.parseInt(this.txtPalletProducedA.getText())); a1 = Integer.parseInt(this.txtPalletProducedA.getText()); } if (StringUtils.isNumeric(this.txtPalletProducedB.getText())) { currentEntry.setPalletProducedB(Integer.parseInt(this.txtPalletProducedB.getText())); b1 = Integer.parseInt(this.txtPalletProducedB.getText()); } if (StringUtils.isNumeric(this.txtPalletQuantity.getText())) { currentEntry.setPalletQuantity(Integer.parseInt(this.txtPalletQuantity.getText())); a2 = Integer.parseInt(this.txtPalletQuantity.getText()); } if (StringUtils.isNumeric(this.txtOtherQuantity.getText())) { currentEntry.setOtherQuantity(Integer.parseInt(this.txtOtherQuantity.getText())); b2 = Integer.parseInt(this.txtOtherQuantity.getText()); } this.entryService.UpdateEntity(currentEntry); this.labQuantityTotal.setText(Integer.toString((a1 * a2) + (b1 * b2))); }
From source file:com.sonicle.webtop.mail.Service.java
private SimpleMessage prepareMessage(JsMessage jsmsg, long msgId, boolean save, boolean isFax) throws Exception { PrivateEnvironment env = environment; UserProfile profile = env.getProfile(); //expand multiple addresses ArrayList<String> aemails = new ArrayList<>(); ArrayList<String> artypes = new ArrayList<>(); for (JsRecipient jsrcpt : jsmsg.recipients) { String emails[] = StringUtils.split(jsrcpt.email, ';'); for (String email : emails) { aemails.add(email);/* ww w . j a v a 2 s . c o m*/ artypes.add(jsrcpt.rtype); } } String emails[] = new String[aemails.size()]; emails = (String[]) aemails.toArray(emails); String rtypes[] = new String[artypes.size()]; rtypes = (String[]) artypes.toArray(rtypes); //String replyfolder = request.getParameter("replyfolder"); //String inreplyto = request.getParameter("inreplyto"); //String references = request.getParameter("references"); //String forwardedfolder = request.getParameter("forwardedfolder"); //String forwardedfrom = request.getParameter("forwardedfrom"); //String subject = request.getParameter("subject"); //String mime = request.getParameter("mime"); //String sident = request.getParameter("identity"); //String content = request.getParameter("content"); //String msgid = request.getParameter("newmsgid"); //String ssave = request.getParameter("save"); //boolean save = (ssave != null && ssave.equals("true")); //String sreceipt = request.getParameter("receipt"); //boolean receipt = (sreceipt != null && sreceipt.equals("true")); //String spriority = request.getParameter("priority"); //boolean priority = (spriority != null && spriority.equals("true")); //boolean isFax = request.getParameter("fax") != null; String to = null; String cc = null; String bcc = null; for (int i = 0; i < emails.length; ++i) { //String email=decoder.decode(ByteBuffer.wrap(emails[i].getBytes())).toString(); String email = emails[i]; if (email == null || email.trim().length() == 0) { continue; } //Check for list boolean checkemail = true; boolean listdone = false; if (email.indexOf('@') < 0) { if (isFax && StringUtils.isNumeric(email)) { String faxpattern = getEnv().getCoreServiceSettings().getFaxPattern(); String faxemail = faxpattern.replace("{number}", email).replace("{username}", profile.getUserId()); email = faxemail; } } else { //check for list if one email with domain equals one allowed service id InternetAddress ia = null; try { ia = new InternetAddress(email); } catch (AddressException exc) { } if (ia != null) { String iamail = ia.getAddress(); String dom = iamail.substring(iamail.indexOf("@") + 1); CoreManager core = WT.getCoreManager(); if (environment.getSession().isServiceAllowed(dom)) { List<Recipient> rcpts = core.expandVirtualProviderRecipient(iamail); for (Recipient rcpt : rcpts) { String xemail = rcpt.getAddress(); String xpersonal = rcpt.getPersonal(); String xrtype = EnumUtils.toSerializedName(rcpt.getType()); if (xpersonal != null) xemail = xpersonal + " <" + xemail + ">"; try { checkEmail(xemail); InternetAddress.parse(xemail.replace(',', ' '), true); } catch (AddressException exc) { throw new AddressException( lookupResource(MailLocaleKey.ADDRESS_ERROR) + " : " + xemail); } if (rtypes[i].equals("to")) { if (xrtype.equals("to")) { if (to == null) to = xemail; else to += "; " + xemail; } else if (xrtype.equals("cc")) { if (cc == null) cc = xemail; else cc += "; " + xemail; } else if (xrtype.equals("bcc")) { if (bcc == null) bcc = xemail; else bcc += "; " + xemail; } } else if (rtypes[i].equals("cc")) { if (cc == null) cc = xemail; else cc += "; " + xemail; } else if (rtypes[i].equals("bcc")) { if (bcc == null) bcc = xemail; else bcc += "; " + xemail; } listdone = true; checkemail = false; } } } } if (listdone) { continue; } if (checkemail) { try { checkEmail(email); //InternetAddress.parse(email.replace(',', ' '), false); getInternetAddress(email); } catch (AddressException exc) { Service.logger.error("Exception", exc); throw new AddressException(lookupResource(MailLocaleKey.ADDRESS_ERROR) + " : " + email); } } if (rtypes[i].equals("to")) { if (to == null) { to = email; } else { to += "; " + email; } } else if (rtypes[i].equals("cc")) { if (cc == null) { cc = email; } else { cc += "; " + email; } } else if (rtypes[i].equals("bcc")) { if (bcc == null) { bcc = email; } else { bcc += "; " + email; } } } //long id = Long.parseLong(msgid); SimpleMessage msg = new SimpleMessage(msgId); /*int idx = jsmsg.identity - 1; Identity from = null; if (idx >= 0) { from = mprofile.getIdentity(idx); }*/ Identity from = mprofile.getIdentity(jsmsg.identityId); msg.setFrom(from); msg.setTo(to); msg.setCc(cc); msg.setBcc(bcc); msg.setSubject(jsmsg.subject); //TODO: fax coverpage - dismissed /*if (isFax) { String coverpage = request.getParameter("faxcover"); if (coverpage != null) { if (coverpage.equals("none")) { msg.addHeaderLine("X-FAX-AutoCoverPage: No"); } else { msg.addHeaderLine("X-FAX-AutoCoverPage: Yes"); msg.addHeaderLine("X-FAX-Cover-Template: " + coverpage); } } }*/ //TODO: custom headers keys /*String[] headersKeys = request.getParameterValues("headersKeys"); String[] headersValues = request.getParameterValues("headersValues"); if (headersKeys != null && headersValues != null && headersKeys.length == headersValues.length) { for (int i = 0; i < headersKeys.length; i++) { if (!headersKeys[i].equals("")) { msg.addHeaderLine(headersKeys[i] + ": " + headersValues[i]); } } }*/ if (jsmsg.inreplyto != null) { msg.setInReplyTo(jsmsg.inreplyto); } if (jsmsg.references != null) { msg.setReferences(new String[] { jsmsg.references }); } if (jsmsg.replyfolder != null) { msg.setReplyFolder(jsmsg.replyfolder); } if (jsmsg.forwardedfolder != null) { msg.setForwardedFolder(jsmsg.forwardedfolder); } if (jsmsg.forwardedfrom != null) { msg.setForwardedFrom(jsmsg.forwardedfrom); } msg.setReceipt(jsmsg.receipt); msg.setPriority(jsmsg.priority ? 1 : 3); if (jsmsg.format == null || jsmsg.format.equals("plain")) { msg.setContent(jsmsg.content); } else { if (jsmsg.format.equalsIgnoreCase("html")) { //TODO: change this weird matching of cids2urls! //CIDs String content = jsmsg.content; String pattern1 = RegexUtils .escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId="); String pattern2 = RegexUtils.escapeRegexSpecialChars("&cid="); content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, "cid:"); pattern1 = RegexUtils.escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId="); pattern2 = RegexUtils.escapeRegexSpecialChars("&cid="); content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, "cid:"); //URLs pattern1 = RegexUtils .escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId="); pattern2 = RegexUtils.escapeRegexSpecialChars("&url="); content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, ""); pattern1 = RegexUtils.escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId="); pattern2 = RegexUtils.escapeRegexSpecialChars("&url="); content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, ""); //My resources as cids? if (ss.isPublicResourceLinksAsInlineAttachments()) { ArrayList<JsAttachment> rescids = new ArrayList<>(); String match = "\"" + URIUtils.concat(getEnv().getCoreServiceSettings().getPublicBaseUrl(), ResourceRequest.URL); while (StringUtils.contains(content, match)) { pattern1 = RegexUtils.escapeRegexSpecialChars(match); Pattern pattern = Pattern.compile(pattern1 + "\\S*"); Matcher matcher = pattern.matcher(content); matcher.find(); String matched = matcher.group(); String url = matched.substring(1, matched.length() - 1); URI uri = new URI(url); // Retrieve macthed URL // and save it locally logger.debug("Downloading resource file as uploaded file from URL [{}]", url); HttpClient httpCli = null; try { httpCli = HttpClientUtils.createBasicHttpClient(HttpClientUtils.configureSSLAcceptAll(), uri); InputStream is = HttpClientUtils.getContent(httpCli, uri); String tag = "" + msgId; String filename = PathUtils.getFileName(uri.getPath()); UploadedFile ufile = addAsUploadedFile(tag, filename, ServletHelper.guessMediaType(filename), is); rescids.add(new JsAttachment(ufile.getUploadId(), filename, ufile.getUploadId(), true, ufile.getSize())); content = matcher.replaceFirst("\"cid:" + ufile.getUploadId() + "\""); } catch (IOException ex) { throw new WTException(ex, "Unable to retrieve webcal [{0}]", uri); } finally { HttpClientUtils.closeQuietly(httpCli); } } //add new resource cids as attachments if (rescids.size() > 0) { if (jsmsg.attachments == null) jsmsg.attachments = new ArrayList<>(); jsmsg.attachments.addAll(rescids); } } String textcontent = MailUtils.HtmlToText_convert(MailUtils.htmlunescapesource(content)); String htmlcontent = MailUtils.htmlescapefixsource(content).trim(); if (htmlcontent.length() < 6 || !htmlcontent.substring(0, 6).toLowerCase().equals("<html>")) { htmlcontent = "<html><header></header><body>" + htmlcontent + "</body></html>"; } msg.setContent(htmlcontent, textcontent, "text/html"); } else { msg.setContent(jsmsg.content, null, "text/" + jsmsg.format); } } return msg; }
From source file:com.globalsight.webservices.Ambassador.java
private String appendJobCondition(String p_jobName) { String condition = "NAME=?"; try {/*from w w w. ja va 2 s. c om*/ int index = p_jobName.lastIndexOf("_"); if (index > -1) { String random = p_jobName.substring(index + 1); if (random != null && random.length() > 6 && StringUtils.isNumeric(random)) { condition = "(NAME=? OR NAME LIKE '%" + random + "')"; } } } catch (Exception ignore) { } return condition; }
From source file:com.dell.asm.asmcore.asmmanager.app.rest.ServiceTemplateService.java
private static String getFabricLocation(String s) { String numeric = s.split("^\\w+\\.\\w+\\.")[1]; String[] numericSplit = numeric.split("-"); String location = numericSplit[0]; if (s.contains("NIC.Embedded") || s.contains("NIC.Integrated")) { return "0"; }// ww w. j ava 2s.c om if (StringUtils.isNumeric(location)) { return location; } else { return location.charAt(location.length() - 1) + ""; } }
From source file:com.masergy.rest.client.BossProdTypeIdEnum.java
public static BossProdTypeIdEnum fromIntStr(String value) { if (StringUtils.isNumeric(value)) { return fromInt(Integer.parseInt(value)); }//from w w w. j a v a2 s .c om return null; }
From source file:net.sourceforge.pmd.lang.java.qname.JavaTypeQualifiedName.java
/** * Returns true if this qualified name identifies an * anonymous class.//from w w w. j a va 2s .c om */ public boolean isAnonymousClass() { return !isLocalClass() && StringUtils.isNumeric(getClassSimpleName()); }
From source file:net.technicpack.launcher.LauncherMain.java
public static void main(String[] args) { try {//from w w w . j a va 2 s . co m UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { Utils.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } StartupParameters params = new StartupParameters(args); try { new JCommander(params, args); } catch (Exception ex) { ex.printStackTrace(); } Relauncher launcher = new Relauncher( new HttpUpdateStream("http://beta.technicpack.net/api/launcher/version/")); TechnicSettings settings = null; try { settings = SettingsFactory.buildSettingsObject(launcher.getRunningPath(LauncherMain.class), params.isMover()); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } if (settings == null) { ResourceLoader installerResources = new ResourceLoader("net", "technicpack", "launcher", "resources"); installerResources.setLocale(ResourceLoader.DEFAULT_LOCALE); InstallerFrame dialog = new InstallerFrame(installerResources, params); dialog.setVisible(true); return; } LauncherDirectories directories = new TechnicLauncherDirectories(settings.getTechnicRoot()); ResourceLoader resources = new ResourceLoader("net", "technicpack", "launcher", "resources"); resources.setLocale(settings.getLanguageCode()); setupLogging(directories, resources); boolean needsReboot = false; if (System.getProperty("awt.useSystemAAFontSettings") == null || !System.getProperty("awt.useSystemAAFontSettings").equals("lcd")) needsReboot = true; else if (!Boolean.parseBoolean(System.getProperty("java.net.preferIPv4Stack"))) needsReboot = true; if (params.isLauncher()) startLauncher(settings, params, directories, resources); else if (params.isMover()) startMover(params, launcher); else if (needsReboot && StringUtils.isNumeric(resources.getLauncherBuild())) { // ^^^^^ //The debugger can't really relaunch so double check the build number to make sure we're operating in a valid environment launcher.launch(null, LauncherMain.class, params.getArgs()); return; } else { updateAndRelaunch(params, directories, resources, settings, launcher); } }