file_id
int64
1
46.7k
content
stringlengths
14
344k
repo
stringlengths
7
109
path
stringlengths
8
171
46,044
/* * Copyright (c) 2018. Aberic - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.dao.entity; import com.gitee.sunchenbin.mybatis.actable.annotation.Column; import com.gitee.sunchenbin.mybatis.actable.annotation.Table; import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * 作者:Aberic on 2018/7/12 21:02 * 邮箱:abericyang@gmail.com */ @Setter @Getter @ToString @Table(name = "fns_ca") public class CA { @Column(name = "id",type = MySqlTypeConstant.INT,length = 9,isKey = true,isAutoIncrement = true) private int id; @Column(name = "name",type = MySqlTypeConstant.VARCHAR,length = 32) private String name; @Column(name = "sk",type = MySqlTypeConstant.TEXT) private String sk; @Column(name = "certificate",type = MySqlTypeConstant.TEXT) private String certificate; @Column(name = "flag",type = MySqlTypeConstant.VARCHAR,length = 128) private String flag; // optional @Column(name = "peer_id",type = MySqlTypeConstant.INT,length = 9) private int peerId; @Column(name = "date",type = MySqlTypeConstant.VARCHAR,length = 14) private String date; // optional private String peerName; // optional private String orgName; // optional private String leagueName; // optional }
aberic/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/dao/entity/CA.java
46,045
package java.mediator; import java.awt.Checkbox; import java.awt.CheckboxGroup; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; public class ColleagueCheckbox extends Checkbox implements ItemListener, Colleague { private Mediator mediator; public ColleagueCheckbox(String caption, CheckboxGroup group, boolean state) { super(caption, group, state); } @Override public void setMediator(Mediator mediator) { this.mediator = mediator; } @Override public void setColleagueEnabled(boolean enabled) { setEnabled(enabled); } @Override public void itemStateChanged(ItemEvent e) { mediator.colleagueChanged(); } }
hyunnnn98/IT-Note
chapter06-디자인패턴/java/mediator/ColleagueCheckbox.java
46,046
/* * AtBScenario.java * * Copyright (C) 2014-2021 - The MegaMek Team. All Rights Reserved. * Copyright (c) 2014 Carl Spain. All rights reserved. * * This file is part of MekHQ. * * MekHQ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MekHQ is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MekHQ. If not, see <http://www.gnu.org/licenses/>. */ package mekhq.campaign.mission; import megamek.Version; import megamek.codeUtilities.ObjectUtility; import megamek.common.*; import megamek.common.annotations.Nullable; import megamek.common.EntityWeightClass; import megamek.common.enums.SkillLevel; import megamek.common.icons.Camouflage; import megamek.common.options.OptionsConstants; import mekhq.MHQConstants; import mekhq.MekHQ; import mekhq.campaign.Campaign; import mekhq.campaign.againstTheBot.AtBConfiguration; import mekhq.campaign.againstTheBot.AtBStaticWeightGenerator; import mekhq.campaign.force.Force; import mekhq.campaign.force.Lance; import mekhq.campaign.mission.ObjectiveEffect.ObjectiveEffectType; import mekhq.campaign.mission.ScenarioObjective.ObjectiveCriterion; import mekhq.campaign.mission.atb.IAtBScenario; import mekhq.campaign.mission.enums.AtBLanceRole; import mekhq.campaign.personnel.SkillType; import mekhq.campaign.rating.IUnitRating; import mekhq.campaign.unit.Unit; import mekhq.campaign.universe.*; import mekhq.utilities.MHQXMLUtility; import org.apache.logging.log4j.LogManager; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.PrintWriter; import java.text.ParseException; import java.time.LocalDate; import java.util.*; /** * @author Neoancient */ public abstract class AtBScenario extends Scenario implements IAtBScenario { //region Variable Declarations public static final int DYNAMIC = -1; public static final int BASEATTACK = 0; public static final int EXTRACTION = 1; public static final int CHASE = 2; public static final int HOLDTHELINE = 3; public static final int BREAKTHROUGH = 4; public static final int HIDEANDSEEK = 5; public static final int STANDUP = 6; public static final int RECONRAID = 7; public static final int PROBE = 8; public static final int OFFICERDUEL = 9; // Special Scenario public static final int ACEDUEL = 10; // Special Scenario public static final int AMBUSH = 11; // Special Scenario public static final int CIVILIANHELP = 12; // Special Scenario public static final int ALLIEDTRAITORS = 13; // Special Scenario public static final int PRISONBREAK = 14; // Special Scenario public static final int STARLEAGUECACHE1 = 15; // Special Scenario public static final int STARLEAGUECACHE2 = 16; // Special Scenario public static final int ALLYRESCUE = 17; // Big Battle public static final int CIVILIANRIOT = 18; // Big Battle public static final int CONVOYRESCUE = 19; // Big Battle public static final int CONVOYATTACK = 20; // Big Battle public static final int PIRATEFREEFORALL = 21; // Big Battle public static final int FORCE_MEK = 0; public static final int FORCE_VEHICLE = 1; public static final int FORCE_MIXED = 2; public static final int FORCE_NOVA = 3; public static final int FORCE_VEENOVA = 4; public static final int FORCE_INFANTRY = 5; public static final int FORCE_BA = 6; public static final int FORCE_AERO = 7; public static final int FORCE_PROTOMEK = 8; public static final String[] forceTypeNames = { "Mek", "Vehicle", "Mixed", "Nova", "Nova", "Infantry", "Battle Armor", "Aerospace", "ProtoMek" }; public static final String[] antiRiotWeapons = { "ISERSmallLaser", "Small Laser", "Small Laser Prototype", "ISSmallPulseLaser", "ISSmallXPulseLaser", "Small Re-engineered Laser", "ISSmallVSPLaser", "CLERMicroLaser", "CLERSmallLaser", "ER Small Laser (CP)", "CLHeavySmallLaser", "CLImprovedSmallHeavyLaser", "ClSmall Laser", "CLERSmallPulseLaser", "CLMicroPulseLaser", "CLSmallPulseLaser", "CLSmallChemLaser", "Heavy Machine Gun", "Light Machine Gun", "Machine Gun", "Heavy Rifle", "Light Rifle", "Medium Rifle", "CLHeavyMG", "CLLightMG", "CLMG", "Flamer", "ER Flamer", "CLFlamer", "CLERFlamer", "Vehicle Flamer", "Heavy Flamer", "CLVehicleFlamer", "CLHeavyFlamer" }; /* The starting position chart in the AtB rules includes the four * corner positions as well, but this creates some conflict with * setting the home edge for the bot, which only includes the four * sides. */ protected static final int [] startPos = { Board.START_N, Board.START_E, Board.START_S, Board.START_W }; private static final int[] randomAeroWeights = { EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_HEAVY }; public static final int NO_LANCE = -1; private boolean attacker; private int lanceForceId; // -1 if scenario is not generated for a specific lance (special scenario, big battle) private AtBLanceRole lanceRole; /* set when scenario is created in case it is changed for the next week before the scenario is resolved; specifically affects scenarios generated for scout lances, in which the deployment may be delayed for slower units */ private int deploymentDelay; private int lanceCount; private int rerollsRemaining; private int enemyHome; private List<Entity> alliesPlayer; private List<String> alliesPlayerStub; /** * Special Scenarios cannot generate the enemy until the unit is added, but needs the Campaign * object which is not passed by addForce or addUnit. Instead we generate all possibilities * (one for each weight class) when the scenario is created and choose the correct one when a * unit is deployed. */ private List<List<Entity>> specialScenarioEnemies; /* Big battles have a similar problem for attached allies. Though * we could generate the maximum number (4) and remove them as * the player deploys additional units, they would be lost if * any units are undeployed. */ private List<Entity> bigBattleAllies; /* Units that need to be tracked for possible contract breaches * (for destruction), or bonus rolls (for survival). */ private List<UUID> attachedUnitIds; private List<UUID> survivalBonus; private Map<UUID, Entity> entityIds; // key-value pairs linking transports and the units loaded onto them. private Map<String, List<String>> transportLinkages; private Map<Integer, Integer> numPlayerMinefields; protected final transient ResourceBundle defaultResourceBundle = ResourceBundle.getBundle("mekhq.resources.AtBScenarioBuiltIn", MekHQ.getMHQOptions().getLocale()); //endregion Variable Declarations public AtBScenario () { super(); lanceForceId = -1; lanceRole = AtBLanceRole.UNASSIGNED; alliesPlayer = new ArrayList<>(); alliesPlayerStub = new ArrayList<>(); attachedUnitIds = new ArrayList<>(); survivalBonus = new ArrayList<>(); entityIds = new HashMap<>(); transportLinkages = new HashMap<>(); numPlayerMinefields = new HashMap<>(); deploymentDelay = 0; lanceCount = 0; rerollsRemaining = 0; } public void initialize(Campaign c, Lance lance, boolean attacker, LocalDate date) { setAttacker(attacker); alliesPlayer = new ArrayList<>(); botForces = new ArrayList<>(); alliesPlayerStub = new ArrayList<>(); botForcesStubs = new ArrayList<>(); attachedUnitIds = new ArrayList<>(); survivalBonus = new ArrayList<>(); entityIds = new HashMap<>(); if (null == lance) { lanceForceId = -1; lanceRole = AtBLanceRole.UNASSIGNED; } else { this.lanceForceId = lance.getForceId(); lanceRole = lance.getRole(); setMissionId(lance.getMissionId()); for (UUID id : c.getForce(lance.getForceId()).getAllUnits(true)) { entityIds.put(id, c.getUnit(id).getEntity()); } } light = PlanetaryConditions.L_DAY; weather = PlanetaryConditions.WE_NONE; wind = PlanetaryConditions.WI_NONE; fog = PlanetaryConditions.FOG_NONE; atmosphere = PlanetaryConditions.ATMO_STANDARD; gravity = (float) 1.0; deploymentDelay = 0; setDate(date); lanceCount = 0; rerollsRemaining = 0; if (isStandardScenario()) { setName(getScenarioTypeDescription() + (isAttacker() ? " (Attacker)" : " (Defender)")); } else { setName(getScenarioTypeDescription()); } initBattle(c); } public String getDesc() { return getScenarioTypeDescription() + (isStandardScenario() ? (isAttacker() ? " (Attacker)" : " (Defender)") : ""); } @Override public boolean isStandardScenario() { return !isSpecialScenario() && !isBigBattle(); } @Override public boolean isSpecialScenario() { return false; } @Override public boolean isBigBattle() { return false; } @Override public ResourceBundle getResourceBundle() { return defaultResourceBundle; } /** * Determines battle conditions: terrain, weather, map. * * @param campaign */ private void initBattle(Campaign campaign) { setTerrain(); if (campaign.getCampaignOptions().isUseLightConditions()) { setLightConditions(); } if (campaign.getCampaignOptions().isUseWeatherConditions()) { setWeather(); } if (campaign.getCampaignOptions().isUsePlanetaryConditions() && null != campaign.getMission(getMissionId())) { setPlanetaryConditions(campaign.getMission(getMissionId()), campaign); } setMapSize(); setMapFile(); if (isStandardScenario()) { lanceCount = 1; } else if (isBigBattle()) { lanceCount = 2; } if (null != getLance(campaign)) { getLance(campaign).refreshCommander(campaign); if (null != getLance(campaign).getCommander(campaign).getSkill(SkillType.S_TACTICS)) { rerollsRemaining = getLance(campaign).getCommander(campaign).getSkill(SkillType.S_TACTICS).getLevel(); } } } public void setTerrain() { setTerrainType(terrainChart[Compute.d6(2) - 2]); } public void setLightConditions() { setLight(PlanetaryConditions.L_DAY); int roll = Compute.randomInt(10) + 1; if (roll < 6) { setLight(PlanetaryConditions.L_DAY); } else if (roll < 8) { setLight(PlanetaryConditions.L_DUSK); } else if (roll == 8) { setLight(PlanetaryConditions.L_FULL_MOON); } else if (roll == 9) { setLight(PlanetaryConditions.L_MOONLESS); } else { setLight(PlanetaryConditions.L_PITCH_BLACK); } } public void setWeather() { setWeather(PlanetaryConditions.WE_NONE); setWind(PlanetaryConditions.WI_NONE); setFog(PlanetaryConditions.FOG_NONE); int roll = Compute.randomInt(10) + 1; int r2 = Compute.d6(); if (roll == 6) { if (r2 < 4) { setWeather(PlanetaryConditions.WE_LIGHT_RAIN); } else if (r2 < 6) { setWeather(PlanetaryConditions.WE_MOD_RAIN); } else { setWeather(PlanetaryConditions.WE_HEAVY_RAIN); } } else if (roll == 7) { if (r2 < 4) { setWeather(PlanetaryConditions.WE_LIGHT_SNOW); } else if (r2 < 6) { setWeather(PlanetaryConditions.WE_MOD_SNOW); } else { setWeather(PlanetaryConditions.WE_HEAVY_SNOW); } } else if (roll == 8) { if (r2 < 4) { setWind(PlanetaryConditions.WI_LIGHT_GALE); } else if (r2 < 6) { setWind(PlanetaryConditions.WI_MOD_GALE); } else { setWind(PlanetaryConditions.WI_STRONG_GALE); } } else if (roll == 9) { if (r2 == 1) { setWind(PlanetaryConditions.WI_STORM); } else if (r2 == 2) { setWeather(PlanetaryConditions.WE_DOWNPOUR); } else if (r2 == 3) { setWeather(PlanetaryConditions.WE_SLEET); } else if (r2 == 4) { setWeather(PlanetaryConditions.WE_ICE_STORM); } else if (r2 == 5) { // tornadoes are classified as wind rather than weather. setWind(PlanetaryConditions.WI_TORNADO_F13); } else if (r2 == 6) { setWind(PlanetaryConditions.WI_TORNADO_F4); } } else if (roll > 9) { if (r2 < 5) { setFog(PlanetaryConditions.FOG_LIGHT); } else { setFog(PlanetaryConditions.FOG_HEAVY); } } // roll < 6 can be ignored, as it would just return nothing } public void setPlanetaryConditions(Mission mission, Campaign campaign) { if (null != mission) { PlanetarySystem psystem = Systems.getInstance().getSystemById(mission.getSystemId()); //assume primary planet for now Planet p = psystem.getPrimaryPlanet(); if (null != p) { setAtmosphere(ObjectUtility.nonNull(p.getPressure(campaign.getLocalDate()), getAtmosphere())); setGravity(ObjectUtility.nonNull(p.getGravity(), getGravity()).floatValue()); } } } public void setMapSize() { int roll = Compute.randomInt(20) + 1; if (roll < 6) { setMapSizeX(20); setMapSizeY(10); } else if (roll < 11) { setMapSizeX(10); setMapSizeY(20); } else if (roll < 13) { setMapSizeX(30); setMapSizeY(10); } else if (roll < 15) { setMapSizeX(10); setMapSizeY(30); } else if (roll < 19) { setMapSizeX(20); setMapSizeY(20); } else if (roll == 19) { setMapSizeX(40); setMapSizeY(10); } else { setMapSizeX(10); setMapSizeY(40); } } public int getMapX() { int base = getMapSizeX() + 5 * lanceCount; return Math.max(base, 20); } public int getMapY() { int base = getMapSizeY() + 5 * lanceCount; return Math.max(base, 20); } public int getBaseMapX() { return (5 * getLanceCount()) + getMapSizeX(); } public int getBaseMapY() { return (5 * getLanceCount()) + getMapSizeY(); } public void setMapFile() { final String[][] maps = { {"Sandy-hills", "Hills-craters", "Hills", "Wooded-hills", "Cliffs", "Town-hills"}, //hills {"Sandy-valley", "Rocky-valley", "Light-craters", "Heavy-craters", "Rubble-mountain", "Cliffs"}, //badlands {"Muddy-swamp", "Lake-marsh", "Lake-high", "Wooded-lake", "Swamp", "Wooded-swamp"}, //wetlands {"Town-mining", "Town-wooded", "Town-generic", "Town-farming", "Town-ruin", "Town-mountain"}, //light urban {"Savannah", "Dust-bowl", "Sandy-hills", "Town-ruin", "Town-generic", "Some-trees"}, //flatlands {"Some-trees", "Wooded-lake", "Woods-medium", "Wooded-hills", "Woods-deep", "Wooded-valley"}, //wooded {"Fortress-city", "Fortress-city", "Town-concrete", "Town-concrete", "City-high", "City-dense"}, //heavy urban {"River-huge", "Woods-river", "Sandy-river", "Rubble-river", "Seaport", "River-wetlands"}, //coastal {"Mountain-lake", "Cliffs-lake", "Rubble-mountain", "Cliffs", "Mountain-medium", "Mountain-high"} //mountains }; int actualTerrainType = getTerrainType(); // we want to make sure the terrain type we pick is in bounds, if ((getTerrainType() < 0) || (getTerrainType() >= maps.length)) { actualTerrainType = Compute.randomInt(maps.length); } setMap(maps[actualTerrainType][Compute.d6() - 1]); } public boolean canRerollTerrain() { return canRerollMap(); } public boolean canRerollMapSize() { return true; } public boolean canRerollMap() { return true; } public boolean canRerollLight() { return true; } public boolean canRerollWeather() { return true; } /** * Determines whether a unit is eligible to deploy to the scenario. The * default is true, but some special scenarios and big battles restrict * the participants. * * @param unit * @param campaign * @return true if the unit is eligible, otherwise false */ @Override public boolean canDeploy(Unit unit, Campaign campaign) { if (isBigBattle() && (getForces(campaign).getAllUnits(true).size() > 7)) { return false; } else { return !isSpecialScenario() || (getForces(campaign).getAllUnits(true).size() <= 0); } } /** * Determines whether a force is eligible to deploy to a scenario by * checking all units contained in the force * * @param force * @param campaign * @return true if the force is eligible to deploy, otherwise false */ public boolean canDeploy(Force force, Campaign campaign) { Vector<UUID> units = force.getAllUnits(true); if (isBigBattle() && getForces(campaign).getAllUnits(true).size() + units.size() > 8) { return false; } else if (isSpecialScenario() && getForces(campaign).getAllUnits(true).size() + units.size() > 0) { return false; } for (UUID id : units) { if (!canDeploy(campaign.getUnit(id), campaign)) { return false; } } return true; } /** * Determines whether a list of units is eligible to deploy to the scenario. * * @param units - a Vector made up of Units to be deployed * @param campaign - a pointer to the Campaign * @return true if all units in the list are eligible, otherwise false */ @Override public boolean canDeployUnits(Vector<Unit> units, Campaign campaign) { if (isBigBattle()) { return getForces(campaign).getAllUnits(true).size() + units.size() <= 8; } else if (isSpecialScenario()) { return getForces(campaign).getAllUnits(true).size() + units.size() <= 1; } else { return units.stream().allMatch(unit -> canDeploy(unit, campaign)); } } /** * Determines whether a list of forces is eligible to deploy to the scenario. * * @param forces list of forces * @param c the campaign that the forces are part of * @return true if all units in all forces in the list are eligible, otherwise false */ @Override public boolean canDeployForces(Vector<Force> forces, Campaign c) { int total = 0; for (Force force : forces) { Vector<UUID> units = force.getAllUnits(true); total += units.size(); if (isBigBattle()) { return getForces(c).getAllUnits(true).size() + units.size() <= 8; } else if (isSpecialScenario()) { return getForces(c).getAllUnits(true).size() + units.size() <= 0; } for (UUID id : units) { if (!canDeploy(c.getUnit(id), c)) { return false; } } } if (isBigBattle()) { return getForces(c).getAllUnits(true).size() + total <= 8; } else if (isSpecialScenario()) { return getForces(c).getAllUnits(true).size() + total <= 0; } return true; } /** * Corrects the enemy (special scenarios) and allies (big battles) * as necessary based on player deployments. This ought to be called * when the scenario details are displayed or the scenario is started. * * @param campaign */ public void refresh(Campaign campaign) { if (isStandardScenario()) { setObjectives(campaign, getContract(campaign)); return; } Vector<UUID> deployed = getForces(campaign).getAllUnits(true); if (isBigBattle()) { int numAllies = Math.min(4, 8 - deployed.size()); alliesPlayer.clear(); for (int i = 0; i < numAllies; i++) { alliesPlayer.add(bigBattleAllies.get(i)); getExternalIDLookup().put(bigBattleAllies.get(i).getExternalIdAsString(), bigBattleAllies.get(i)); } setObjectives(campaign, getContract(campaign)); } else { if (deployed.isEmpty()) { return; } int weight = campaign.getUnit(deployed.get(0)).getEntity().getWeightClass(); /* In the event that Star League Cache 1 generates a primitive 'Mech, * the player can keep the 'Mech without a battle so no enemy * units are generated. */ if (specialScenarioEnemies == null ) { setForces(campaign); } if ((specialScenarioEnemies != null) && (getBotForces().get(0) != null) && (specialScenarioEnemies.get(weight) != null)) { getBotForces().get(0).setFixedEntityList(specialScenarioEnemies.get(weight)); } setObjectives(campaign, getContract(campaign)); } } /** * Determines enemy and allied forces for the scenario. The forces for a standard * battle are based on the player's deployed lance. The enemy forces for * special scenarios depend on the weight class of the player's deployed * unit and the number of allies in big battles varies according to the * number the player deploys. Since the various possibilities are rather * limited, all possibilities are generated and the most appropriate is * chosen rather than rerolling every time the player changes. This is * both for efficiency and to prevent shopping. * * @param campaign */ public void setForces(Campaign campaign) { if (isStandardScenario()) { setStandardScenarioForces(campaign); } else if (isSpecialScenario()) { setSpecialScenarioForces(campaign); } else { setBigBattleForces(campaign); } setObjectives(campaign, getContract(campaign)); } /** * Generates attached allied units (bot or player controlled), the main * enemy force, any enemy reinforcements, and any additional forces * (such as civilian). * * @param campaign */ private void setStandardScenarioForces(Campaign campaign) { /* Find the number of attached units required by the command rights clause */ int attachedUnitWeight = EntityWeightClass.WEIGHT_MEDIUM; if (lanceRole.isScouting() || lanceRole.isTraining()) { attachedUnitWeight = EntityWeightClass.WEIGHT_LIGHT; } int numAttachedPlayer = 0; int numAttachedBot = 0; if (getContract(campaign).getContractType().isCadreDuty()) { numAttachedPlayer = 3; } else if (campaign.getFactionCode().equals("MERC")) { switch (getContract(campaign).getCommandRights()) { case INTEGRATED: if (campaign.getCampaignOptions().isPlayerControlsAttachedUnits()) { numAttachedPlayer = 2; } else { numAttachedBot = 2; } break; case HOUSE: if (campaign.getCampaignOptions().isPlayerControlsAttachedUnits()) { numAttachedPlayer = 1; } else { numAttachedBot = 1; } break; case LIAISON: numAttachedPlayer = 1; break; default: break; } } /* The entities in the attachedAllies list will be added to the player's forces * in MM and don't require a separate BotForce */ final Camouflage camouflage = getContract(campaign).getAllyCamouflage(); for (int i = 0; i < numAttachedPlayer; i++) { Entity en = getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.MEK, attachedUnitWeight, campaign); if (null != en) { alliesPlayer.add(en); attachedUnitIds.add(UUID.fromString(en.getExternalIdAsString())); getExternalIDLookup().put(en.getExternalIdAsString(), en); if (!campaign.getCampaignOptions().isAttachedPlayerCamouflage()) { en.setCamouflage(camouflage.clone()); } } else { LogManager.getLogger().error("Entity for player-controlled allies is null"); } } /* The allyBot list will be passed to the BotForce constructor */ ArrayList<Entity> allyEntities = new ArrayList<>(); for (int i = 0; i < numAttachedBot; i++) { Entity en = getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.MEK, attachedUnitWeight, campaign); if (null != en) { allyEntities.add(en); attachedUnitIds.add(UUID.fromString(en.getExternalIdAsString())); } else { LogManager.getLogger().error("Entity for ally bot is null"); } } ArrayList<Entity> enemyEntities = new ArrayList<>(); setExtraScenarioForces(campaign, allyEntities, enemyEntities); addAeroReinforcements(campaign); addScrubReinforcements(campaign); /* Possible enemy reinforcements */ int roll = Compute.d6(); if (roll > 3) { ArrayList<Entity> reinforcements = new ArrayList<>(); if (roll == 6) { addLance(reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_ASSAULT, campaign, 8); } else { addLance(reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_ASSAULT, campaign, 6); } /* Must set per-entity start pos for units after start of scenarios. Reinforcements * arrive from the enemy home edge, which is not necessarily the start pos. */ final int enemyDir = enemyHome; reinforcements.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(enemyDir); }); if (campaign.getCampaignOptions().isAllowOpForLocalUnits()) { reinforcements.addAll(AtBDynamicScenarioFactory.fillTransports(this, reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), campaign)); } BotForce bf = getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, reinforcements); bf.setName(bf.getName() + " (Reinforcements)"); addBotForce(bf, campaign); } if (campaign.getCampaignOptions().isUseDropShips()) { if (canAddDropShips()) { boolean dropshipFound = false; for (UUID id : campaign.getForces().getAllUnits(true)) { if ((campaign.getUnit(id).getEntity().getEntityType() & Entity.ETYPE_DROPSHIP) != 0 && campaign.getUnit(id).isAvailable()) { addUnit(id); campaign.getUnit(id).setScenarioId(getId()); dropshipFound = true; break; } } if (!dropshipFound) { addDropship(campaign); } for (int i = 0; i < Compute.d6() - 3; i++) { addLance(enemyEntities, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), AtBStaticWeightGenerator.getRandomWeight(campaign, UnitType.MEK, getContract(campaign).getEnemy()), EntityWeightClass.WEIGHT_ASSAULT, campaign); } } else if (getLanceRole().isScouting()) { /* Set allied forces to deploy in (6 - speed) turns just as player's units, * but only if not deploying by DropShip. */ alliesPlayer.stream().filter(Objects::nonNull).forEach(entity -> { int speed = entity.getWalkMP(); if (entity.getJumpMP() > 0) { if (entity instanceof megamek.common.Infantry) { speed = entity.getJumpMP(); } else { speed++; } } entity.setDeployRound(Math.max(0, 6 - speed)); }); allyEntities.stream().filter(Objects::nonNull).forEach(entity -> { int speed = entity.getWalkMP(); if (entity.getJumpMP() > 0) { if (entity instanceof megamek.common.Infantry) { speed = entity.getJumpMP(); } else { speed++; } } entity.setDeployRound(Math.max(0, 6 - speed)); }); } } // aaand for fun, run everyone through the crew upgrader if (campaign.getCampaignOptions().isUseAbilities()) { AtBDynamicScenarioFactory.upgradeBotCrews(this, campaign); } } @Override public void setExtraScenarioForces(Campaign campaign, ArrayList<Entity> allyEntities, ArrayList<Entity> enemyEntities) { int enemyStart; int playerHome; playerHome = startPos[Compute.randomInt(4)]; setStart(playerHome); enemyStart = getStart() + 4; if (enemyStart > 8) { enemyStart -= 8; } enemyHome = enemyStart; if (!allyEntities.isEmpty()) { addBotForce(getAllyBotForce(getContract(campaign), getStart(), playerHome, allyEntities), campaign); } addEnemyForce(enemyEntities, getLance(campaign).getWeightClass(campaign), campaign); addBotForce(getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, enemyEntities), campaign); } @Override public boolean canAddDropShips() { return false; } /** * Generate four sets of forces: one for each weight class the player * can choose to deploy. * * @param campaign */ private void setSpecialScenarioForces(Campaign campaign) { // enemy must always be the first on the botforce list so we can find it on refresh() specialScenarioEnemies = new ArrayList<>(); ArrayList<Entity> enemyEntities = new ArrayList<>(); ArrayList<Entity> allyEntities = new ArrayList<>(); setExtraScenarioForces(campaign, allyEntities, enemyEntities); } public List<List<Entity>> getSpecialScenarioEnemies() { return specialScenarioEnemies; } /** * Generates enemy forces and four allied units that may be used if the player * deploys fewer than eight of his or her own units. * * @param campaign */ private void setBigBattleForces(Campaign campaign) { ArrayList<Entity> enemyEntities = new ArrayList<>(); ArrayList<Entity> allyEntities = new ArrayList<>(); setExtraScenarioForces(campaign, allyEntities, enemyEntities); bigBattleAllies = new ArrayList<>(); bigBattleAllies.addAll(alliesPlayer); } protected void addEnemyForce(List<Entity> list, int weightClass, Campaign c) { addEnemyForce(list, weightClass, EntityWeightClass.WEIGHT_ASSAULT, 0, 0, c); } /** * Generates the enemy force based on the weight class of the lance deployed * by the player. Certain scenario types may set a maximum weight class for * enemy units or modify the roll. * * @param list All generated enemy entities are added to this list. * @param weightClass The weight class of the player's lance. * @param maxWeight The maximum weight class of each generated enemy entity * @param rollMod Modifier to the enemy lances roll. * @param weightMod Modifier to the weight class of enemy lances. * @param campaign */ protected void addEnemyForce(List<Entity> list, int weightClass, int maxWeight, int rollMod, int weightMod, Campaign campaign) { String org = AtBConfiguration.getParentFactionType(getContract(campaign).getEnemy()); String lances = campaign.getAtBConfig().selectBotLances(org, weightClass, rollMod / 20f); if (lances == null) { LogManager.getLogger().error(String.format( "Cannot add enemy force: failed to generate lances for faction %s at weight class %s", org, weightClass)); return; } int maxLances = Math.min(lances.length(), campaign.getCampaignOptions().getSkillLevel().getAdjustedValue() + 1); for (int i = 0; i < maxLances; i++) { addEnemyLance(list, AtBConfiguration.decodeWeightStr(lances, i) + weightMod, maxWeight, campaign); } if (campaign.getCampaignOptions().isAllowOpForLocalUnits()) { list.addAll(AtBDynamicScenarioFactory.fillTransports(this, list, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), campaign)); } } /** * Generates an enemy lance of a given weight class. * * @param list Generated enemy entities are added to this list. * @param weight Weight class of the enemy lance. * @param maxWeight Maximum weight of enemy entities. * @param campaign The current campaign */ private void addEnemyLance(List<Entity> list, int weight, int maxWeight, Campaign campaign) { if (weight < EntityWeightClass.WEIGHT_LIGHT) { weight = EntityWeightClass.WEIGHT_LIGHT; } if (weight > EntityWeightClass.WEIGHT_ASSAULT) { weight = EntityWeightClass.WEIGHT_ASSAULT; } addLance(list, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), weight, maxWeight, campaign); lanceCount++; } /** * Determines the most appropriate RAT and uses it to generate a random Entity * * @param faction The faction code to use for locating the correct RAT and assigning a crew name * @param skill The {@link SkillLevel} that represents the skill level of the overall force. * @param quality The equipment rating of the force. * @param unitType The UnitTableData constant for the type of unit to generate. * @param weightClass The weight class of the unit to generate * @param campaign The current campaign * @return A new Entity with crew. */ protected @Nullable Entity getEntity(String faction, SkillLevel skill, int quality, int unitType, int weightClass, Campaign campaign) { return AtBDynamicScenarioFactory.getEntity(faction, skill, quality, unitType, weightClass, false, campaign); } /** * Units that exceed the maximum weight for individual entities in the scenario * are replaced in the lance by two lighter units. * * @param weights A string of single-character letter codes for the weights of the units in the lance (e.g. "LMMH") * @param maxWeight The maximum weight allowed for the force by the parameters of the scenario type * @return A new String of the same format as weights */ private String adjustForMaxWeight(String weights, int maxWeight) { String retVal = weights; if (maxWeight == EntityWeightClass.WEIGHT_HEAVY) { //Hide and Seek (defender) retVal = weights.replaceAll("A", "LM"); } else if (maxWeight == EntityWeightClass.WEIGHT_MEDIUM) { //Probe, Recon Raid (attacker) retVal = weights.replaceAll("A", "MM"); retVal = retVal.replaceAll("H", "LM"); } return retVal; } /** * Adjust weights of units in a lance for factions that do not fit the typical * weight distribution. * * @param weights A string of single-character letter codes for the weights of the units in the lance (e.g. "LMMH") * @param faction The code of the faction to which the force belongs. * @return A new String of the same format as weights */ private String adjustWeightsForFaction(String weights, String faction) { /* Official AtB rules only specify DC, LA, and FWL; I have added * variations for some Clans. */ String retVal = weights; if (faction.equals("DC")) { retVal = weights.replaceFirst("MM", "LH"); } if ((faction.equals("LA") || faction.equals("CCO") || faction.equals("CGB")) && weights.matches("[LM]{3,}")) { retVal = weights.replaceFirst("M", "H"); } if (faction.equals("FWL") || faction.equals("CIH")) { retVal = weights.replaceFirst("HA", "HH"); } return retVal; } /* * Convenience functions overloaded to provide default values. */ protected void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, Campaign campaign) { addLance(list, faction, skill, quality, weightClass, EntityWeightClass.WEIGHT_ASSAULT, campaign, 0); } protected void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign c) { addLance(list, faction, skill, quality, weightClass, maxWeight, c, 0); } /** * * Generates a lance of the indicated weight class. If the faction is Clan, * calls addStar instead. If the faction is CS/WoB, calls addLevelII. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { if (Factions.getInstance().getFaction(faction).isClan()) { addStar(list, faction, skill, quality, weightClass, maxWeight, campaign, arrivalTurn); return; } else if (faction.equals("CS") || faction.equals("WOB")) { addLevelII(list, faction, skill, quality, weightClass, maxWeight, campaign, arrivalTurn); return; } String weights = campaign.getAtBConfig().selectBotUnitWeights(AtBConfiguration.ORG_IS, weightClass); if (weights == null) { // we can't generate a weight, so cancel adding the lance LogManager.getLogger().error("Cannot add lance: failed to generate weights for faction IS with weight class " + weightClass); return; } weights = adjustForMaxWeight(weights, maxWeight); int forceType = FORCE_MEK; if (campaign.getCampaignOptions().isUseVehicles()) { int totalWeight = campaign.getCampaignOptions().getOpForLanceTypeMechs() + campaign.getCampaignOptions().getOpForLanceTypeMixed() + campaign.getCampaignOptions().getOpForLanceTypeVehicles(); if (totalWeight > 0) { int roll = Compute.randomInt(totalWeight); if (roll < campaign.getCampaignOptions().getOpForLanceTypeVehicles()) { forceType = FORCE_VEHICLE; } else if (roll < campaign.getCampaignOptions().getOpForLanceTypeVehicles() + campaign.getCampaignOptions().getOpForLanceTypeMixed()) { forceType = FORCE_MIXED; } } } if (forceType == FORCE_MEK && campaign.getCampaignOptions().isRegionalMechVariations()) { weights = adjustWeightsForFaction(weights, faction); } int[] unitTypes = new int[weights.length()]; Arrays.fill(unitTypes, (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK); /* Distribute vehicles randomly(-ish) through mixed units */ if (forceType == FORCE_MIXED) { for (int i = 0; i < weights.length() / 2; i++) { int j = Compute.randomInt(weights.length()); while (unitTypes[j] == UnitType.TANK) { j++; if (j >= weights.length()) { j = 0; } } unitTypes[j] = UnitType.TANK; } } for (int i = 0; i < weights.length(); i++) { Entity en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } if ((unitTypes[i] == UnitType.TANK) && campaign.getCampaignOptions().isDoubleVehicles()) { en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates a Star of the indicated weight class. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addStar(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { int forceType = FORCE_MEK; /* 1 chance in 12 of a Nova, per AtB rules; CHH/CSL * close to 1/2, no chance for CBS. Added a chance to encounter * a vehicle Star in Clan second-line (rating C or lower) units, * or all unit ratings for CHH/CSL and CBS. */ int roll = Compute.d6(2); int novaTarget = 11; if (faction.equals("CHH") || faction.equals("CSL")) { novaTarget = 8; } else if (faction.equals("CBS")) { novaTarget = TargetRoll.AUTOMATIC_FAIL; } int vehicleTarget = 4; if (!faction.equals("CHH") && !faction.equals("CSL") && !faction.equals("CBS")) { vehicleTarget -= quality; } if (roll >= novaTarget) { forceType = FORCE_NOVA; } else if (campaign.getCampaignOptions().isClanVehicles() && roll <= vehicleTarget) { forceType = FORCE_VEHICLE; } String weights = campaign.getAtBConfig().selectBotUnitWeights(AtBConfiguration.ORG_CLAN, weightClass); if (weights == null) { // we can't generate a weight, so cancel adding the star LogManager.getLogger().error("Cannot add star: failed to generate weights for faction CLAN with weight class " + weightClass); return; } weights = adjustForMaxWeight(weights, maxWeight); int unitType = (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK; if (campaign.getCampaignOptions().isRegionalMechVariations()) { if (unitType == UnitType.MEK) { weights = adjustWeightsForFaction(weights, faction); } /* medium vees are rare among the Clans, FM:CC, p. 8 */ if (unitType == UnitType.TANK) { weights = adjustWeightsForFaction(weights, "DC"); } } int unitsPerPoint; switch (unitType) { case UnitType.TANK: case UnitType.AERO: unitsPerPoint = 2; break; case UnitType.PROTOMEK: unitsPerPoint = 5; break; case UnitType.MEK: case UnitType.INFANTRY: case UnitType.BATTLE_ARMOR: default: unitsPerPoint = 1; break; } /* Ensure Novas use Frontline tables to get best chance at Omnis */ int tmpQuality = quality; if (forceType == FORCE_NOVA && quality < IUnitRating.DRAGOON_B) { tmpQuality = IUnitRating.DRAGOON_B; } for (int point = 0; point < weights.length(); point++) { for (int unit = 0; unit < unitsPerPoint; unit++) { Entity en = getEntity(faction, skill, tmpQuality, unitType, AtBConfiguration.decodeWeightStr(weights, point), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } if (forceType == FORCE_NOVA) { unitType = UnitType.BATTLE_ARMOR; for (int i = 0; i < 5; i++) { Entity en = getEntity(faction, skill, quality, unitType, -1, campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates a ComStar/WoB Level II of the indicated weight class. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addLevelII(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { String weights = campaign.getAtBConfig().selectBotUnitWeights(AtBConfiguration.ORG_CS, weightClass); if (weights == null) { // we can't generate a weight, so cancel adding the Level II LogManager.getLogger().error("Cannot add Level II: failed to generate weights for faction CS with weight class " + weightClass); return; } weights = adjustForMaxWeight(weights, maxWeight); int forceType = FORCE_MEK; int roll = Compute.d6(); if (roll < 4) { forceType = FORCE_VEHICLE; } else if (roll < 6) { forceType = FORCE_MIXED; } int[] unitTypes = new int[weights.length()]; Arrays.fill(unitTypes, (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK); /* Distribute vehicles randomly(-ish) through mixed units */ if (forceType == FORCE_MIXED) { for (int i = 0; i < weights.length() / 2; i++) { int j = Compute.randomInt(weights.length()); while (unitTypes[j] == UnitType.TANK) { j++; if (j >= weights.length()) { j = 0; } } unitTypes[j] = UnitType.TANK; } } for (int i = 0; i < weights.length(); i++) { Entity en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } if (unitTypes[i] == UnitType.TANK && campaign.getCampaignOptions().isDoubleVehicles()) { en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates the indicated number of civilian entities. * * @param list Generated entities are added to this list * @param num The number of civilian entities to generate * @param campaign */ protected void addCivilianUnits(List<Entity> list, int num, Campaign campaign) { list.addAll(AtBDynamicScenarioFactory.generateCivilianUnits(num, campaign)); } /** * Generates the indicated number of turret entities. * * @param list Generated entities are added to this list * @param num The number of turrets to generate * @param skill The skill level of the turret operators * @param quality The quality level of the turrets * @param campaign The campaign for which the turrets are being generated. * @param faction The faction the turrets are being generated for */ protected void addTurrets(List<Entity> list, int num, SkillLevel skill, int quality, Campaign campaign, Faction faction) { list.addAll(AtBDynamicScenarioFactory.generateTurrets(num, skill, quality, campaign, faction)); } /** * Potentially generates and adds a force of enemy aircraft to the mix of opposing force. * @param campaign The campaign for which the aircraft are being generated. */ protected void addAeroReinforcements(Campaign campaign) { // if the campaign is configured to it and we're in a 'standard' scenario or 'big battle' (don't add extra units to special scenarios) // if the opfor owns the planet, we have a user-defined chance of seeing 1-5 hostile conventional aircraft, // one per "pip" of difficulty. // if the opfor does not own the planet, we have a (slightly lower) user-defined chance of seeing 1-5 hostile aerotechs, // one per "pip" of difficulty. // if generating aeros (crude approximation), we have a 1/2 chance of a light, 1/3 chance of medium and 1/6 chance of heavy if (!(campaign.getCampaignOptions().isAllowOpForAeros() && (isStandardScenario() || isBigBattle()))) { return; } AtBContract contract = getContract(campaign); boolean opForOwnsPlanet = contract.getSystem().getFactions(campaign.getLocalDate()) .contains(contract.getEnemyCode()); boolean spawnConventional = opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpForAeroChance(); // aerotechs are rarer, so spawn them less often boolean spawnAerotech = !opForOwnsPlanet && Compute.d6() > MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpForAeroChance() / 2; ArrayList<Entity> aircraft = new ArrayList<>(); Entity aero; if (spawnConventional) { // skill level is an enum going from ultra-green to legendary for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel().getAdjustedValue(); unitCount++) { aero = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.CONV_FIGHTER, EntityWeightClass.WEIGHT_LIGHT, campaign); if (aero != null) { aircraft.add(aero); } } } else if (spawnAerotech) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel().getAdjustedValue(); unitCount++) { // compute weight class int weightClass = randomAeroWeights[Compute.d6() - 1]; aero = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.AERO, weightClass, campaign); if (aero != null) { aircraft.add(aero); } } } if (!aircraft.isEmpty()) { /* Must set per-entity start pos for units after start of scenarios. Reinforcements * arrive from the enemy home edge, which is not necessarily the start pos. */ final int deployRound = Compute.d6() + 2; // deploy the new aircraft some time after the start of the game aircraft.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(enemyHome); en.setDeployRound(deployRound); }); boolean isAeroMap = getTerrainType() == TER_LOW_ATMO || getTerrainType() == TER_SPACE; AtBDynamicScenarioFactory.populateAeroBombs(aircraft, campaign, !isAeroMap); BotForce bf = getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, aircraft); bf.setName(bf.getName() + " (Air Support)"); addBotForce(bf, campaign); } } /** * Potentially generates some scrubs (turrets and/or infantry) to be randomly added to the opposing force. * @param campaign The campaign for which the scrubs are being generated. */ protected void addScrubReinforcements(Campaign campaign) { // if the campaign is configured to it and we are in a standard scenario or big battle // if the opfor owns the planet, and the opfor is defender we have a 1/3 chance of seeing 1-5 hostile turrets, one per "pip" of difficulty. // if the opfor owns the planet, and the opfor is defender we have a 1/3 chance of seeing 1-5 hostile conventional infantry, one per "pip". // if the opfor does not own the planet, we have a 1/6 chance of seeing 1-5 hostile battle armor, one per "pip" of difficulty. if (!(campaign.getCampaignOptions().isAllowOpForLocalUnits() && isAttacker() && (isStandardScenario() || isBigBattle()))) { return; } AtBContract contract = getContract(campaign); boolean opForOwnsPlanet = contract.getSystem().getFactions(campaign.getLocalDate()) .contains(contract.getEnemyCode()); boolean spawnTurrets = opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpForLocalUnitChance(); boolean spawnConventionalInfantry = opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpForLocalUnitChance(); // battle armor is more rare boolean spawnBattleArmor = !opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpForLocalUnitChance() / 2; boolean isTurretAppropriateTerrain = (getTerrainType() == TER_HEAVYURBAN) || (getTerrainType() == TER_LIGHTURBAN); boolean isInfantryAppropriateTerrain = isTurretAppropriateTerrain || (getTerrainType() == TER_WOODED); ArrayList<Entity> scrubs = new ArrayList<>(); // don't bother spawning turrets if there won't be anything to put them on if (spawnTurrets && isTurretAppropriateTerrain) { // skill level is an enum from ultra-green to legendary, and drives the number of extra units addTurrets(scrubs, campaign.getCampaignOptions().getSkillLevel().getAdjustedValue() + 1, contract.getEnemySkill(), contract.getEnemyQuality(), campaign, contract.getEnemy()); } if (spawnConventionalInfantry && isInfantryAppropriateTerrain) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel().getAdjustedValue(); unitCount++) { Entity infantry = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.INFANTRY, EntityWeightClass.WEIGHT_LIGHT, campaign); if (infantry != null) { scrubs.add(infantry); } } } if (spawnBattleArmor && isInfantryAppropriateTerrain) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel().getAdjustedValue(); unitCount++) { // some factions don't have access to battle armor, so they get conventional infantry instead Entity generatedUnit = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.BATTLE_ARMOR, EntityWeightClass.WEIGHT_LIGHT, campaign); if (generatedUnit != null) { scrubs.add(generatedUnit); } else { Entity infantry = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.INFANTRY, EntityWeightClass.WEIGHT_LIGHT, campaign); if (infantry != null) { scrubs.add(infantry); } } } } if (!scrubs.isEmpty()) { /* Must set per-entity start pos for units after start of scenarios. Scrubs start in the center of the map. */ scrubs.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(Board.START_CENTER); // if it's a short range enemy unit, it has a chance to be hidden based on // the option being enabled and the difficulty if (campaign.getGameOptions().booleanOption(OptionsConstants.ADVANCED_HIDDEN_UNITS) && (en.getMaxWeaponRange() <= 4) && (Compute.randomInt(5) <= campaign.getCampaignOptions().getSkillLevel().getAdjustedValue())) { en.setHidden(true); } }); BotForce bf = getEnemyBotForce(getContract(campaign), Board.START_CENTER, enemyHome, scrubs); bf.setName(bf.getName() + " (Local Forces)"); addBotForce(bf, campaign); } } /** * Worker method that adds a DropShip and related objective to the scenario. * @param campaign */ protected void addDropship(Campaign campaign) { Entity dropship = AtBDynamicScenarioFactory.getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.DROPSHIP, AtBDynamicScenarioFactory.UNIT_WEIGHT_UNSPECIFIED, campaign); if (dropship != null) { alliesPlayer.add(dropship); attachedUnitIds.add(UUID.fromString(dropship.getExternalIdAsString())); getExternalIDLookup().put(dropship.getExternalIdAsString(), dropship); ScenarioObjective dropshipObjective = new ScenarioObjective(); dropshipObjective.setDescription("The employer has provided a DropShip for your use in this battle. Ensure it survives. Losing it will result in a 5 point penalty to your contract score."); dropshipObjective.setObjectiveCriterion(ObjectiveCriterion.Preserve); dropshipObjective.setPercentage(100); dropshipObjective.addUnit(dropship.getExternalIdAsString()); // update the contract score by -5 if the objective is failed. ObjectiveEffect failureEffect = new ObjectiveEffect(); failureEffect.effectType = ObjectiveEffectType.ContractScoreUpdate; failureEffect.howMuch = -5; dropshipObjective.addFailureEffect(failureEffect); getScenarioObjectives().add(dropshipObjective); } } /* Convenience methods for frequently-used arguments */ protected BotForce getAllyBotForce(AtBContract c, int start, int home, List<Entity> entities) { return new BotForce(c.getAllyBotName(), 1, start, home, entities, c.getAllyCamouflage().clone(), c.getAllyColour()); } protected BotForce getEnemyBotForce(AtBContract c, int start, List<Entity> entities) { return getEnemyBotForce(c, start, start, entities); } protected BotForce getEnemyBotForce(AtBContract c, int start, int home, List<Entity> entities) { return new BotForce(c.getEnemyBotName(), 2, start, home, entities, c.getEnemyCamouflage().clone(), c.getEnemyColour()); } @Override public void generateStub(Campaign c) { super.generateStub(c); alliesPlayerStub = generateEntityStub(alliesPlayer); alliesPlayer.clear(); if (null != bigBattleAllies) { bigBattleAllies.clear(); } if (null != specialScenarioEnemies) { specialScenarioEnemies.clear(); } } protected void setObjectives(Campaign c, AtBContract contract) { getScenarioObjectives().clear(); } @Override protected void writeToXMLEnd(final PrintWriter pw, int indent) { MHQXMLUtility.writeSimpleXMLTag(pw, indent, "attacker", isAttacker()); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "lanceForceId", lanceForceId); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "lanceRole", lanceRole.name()); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "deploymentDelay", deploymentDelay); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "lanceCount", lanceCount); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "rerollsRemaining", rerollsRemaining); if (null != bigBattleAllies && !bigBattleAllies.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "bigBattleAllies"); for (Entity entity : bigBattleAllies) { if (entity != null) { MHQXMLUtility.writeEntityWithCrewToXML(pw, indent, entity, bigBattleAllies); } } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "bigBattleAllies"); } else if (!alliesPlayer.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "alliesPlayer"); for (Entity entity : alliesPlayer) { if (entity != null) { MHQXMLUtility.writeEntityWithCrewToXML(pw, indent, entity, alliesPlayer); } } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "alliesPlayer"); } if (!alliesPlayerStub.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "alliesPlayerStub"); for (String stub : alliesPlayerStub) { MHQXMLUtility.writeSimpleXMLTag(pw, indent, "entityStub", stub); } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "alliesPlayerStub"); } if (!attachedUnitIds.isEmpty()) { MHQXMLUtility.writeSimpleXMLTag(pw, indent, "attachedUnits", getCsvFromList(attachedUnitIds)); } if (!survivalBonus.isEmpty()) { MHQXMLUtility.writeSimpleXMLTag(pw, indent, "survivalBonus", getCsvFromList(survivalBonus)); } if (null != specialScenarioEnemies && !specialScenarioEnemies.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "specialScenarioEnemies"); for (int i = 0; i < specialScenarioEnemies.size(); i++) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "playerWeight", "class", i); for (Entity entity : specialScenarioEnemies.get(i)) { if (entity != null) { MHQXMLUtility.writeEntityWithCrewToXML(pw, indent, entity, specialScenarioEnemies.get(i)); } } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "playerWeight"); } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "specialScenarioEnemies"); } if (!transportLinkages.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "transportLinkages"); for (String key : transportLinkages.keySet()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "transportLinkage"); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "transportID", key); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "transportedUnits", transportLinkages.get(key)); MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "transportLinkage"); } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "transportLinkages"); } if (!numPlayerMinefields.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "numPlayerMinefields"); for (int key : numPlayerMinefields.keySet()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "numPlayerMinefield"); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "minefieldType", key); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "minefieldCount", numPlayerMinefields.get(key).toString()); MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "numPlayerMinefield"); } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "numPlayerMinefields"); } super.writeToXMLEnd(pw, indent); } @Override protected void loadFieldsFromXmlNode(final Node wn, final Version version, final Campaign campaign) throws ParseException { super.loadFieldsFromXmlNode(wn, version, campaign); NodeList nl = wn.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); try { if (wn2.getNodeName().equalsIgnoreCase("attacker")) { setAttacker(Boolean.parseBoolean(wn2.getTextContent().trim())); } else if (wn2.getNodeName().equalsIgnoreCase("lanceForceId")) { lanceForceId = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("lanceRole")) { lanceRole = AtBLanceRole.parseFromString(wn2.getTextContent().trim()); } else if (wn2.getNodeName().equalsIgnoreCase("deploymentDelay")) { deploymentDelay = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("usingFixedMap")) { setUsingFixedMap(Boolean.parseBoolean(wn2.getTextContent().trim())); } else if (wn2.getNodeName().equalsIgnoreCase("lanceCount")) { lanceCount = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("rerollsRemaining")) { rerollsRemaining = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("alliesPlayer")) { NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MHQXMLUtility.parseSingleEntityMul((Element) wn3, campaign); } catch (Exception ex) { LogManager.getLogger().error("Error loading allied unit in scenario", ex); } if (en != null) { alliesPlayer.add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } else if (wn2.getNodeName().equalsIgnoreCase("bigBattleAllies")) { bigBattleAllies = new ArrayList<>(); NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MHQXMLUtility.parseSingleEntityMul((Element) wn3, campaign); } catch (Exception ex) { LogManager.getLogger().error("Error loading allied unit in scenario", ex); } if (en != null) { bigBattleAllies.add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } else if (wn2.getNodeName().equalsIgnoreCase("specMissionEnemies") // Legacy - 0.49.11 removal || wn2.getNodeName().equalsIgnoreCase("specialScenarioEnemies")) { specialScenarioEnemies = new ArrayList<>(); for (int i = EntityWeightClass.WEIGHT_ULTRA_LIGHT; i <= EntityWeightClass.WEIGHT_COLOSSAL; i++) { specialScenarioEnemies.add(new ArrayList<>()); } NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("playerWeight")) { int weightClass = Integer.parseInt(wn3.getAttributes().getNamedItem("class").getTextContent()); NodeList nl3 = wn3.getChildNodes(); for (int j = 0; j < nl3.getLength(); j++) { Node wn4 = nl3.item(j); if (wn4.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MHQXMLUtility.parseSingleEntityMul((Element) wn4, campaign); } catch (Exception ex) { LogManager.getLogger().error("Error loading enemy unit in scenario", ex); } if (null != en) { specialScenarioEnemies.get(weightClass).add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } } } else if (wn2.getNodeName().equalsIgnoreCase("alliesPlayerStub")) { alliesPlayerStub = getEntityStub(wn2); } else if (wn2.getNodeName().equalsIgnoreCase("attachedUnits")) { String[] ids = wn2.getTextContent().split(","); for (String s : ids) { attachedUnitIds.add(UUID.fromString(s)); } } else if (wn2.getNodeName().equalsIgnoreCase("survivalBonus")) { String[] ids = wn2.getTextContent().split(","); for (String s : ids) { survivalBonus.add(UUID.fromString(s)); } } else if (wn2.getNodeName().equalsIgnoreCase("transportLinkages")) { try { transportLinkages = loadTransportLinkages(wn2); } catch (Exception e) { LogManager.getLogger().error("Error loading transport linkages in scenario", e); } } else if (wn2.getNodeName().equalsIgnoreCase("numPlayerMinefields")) { try { loadMinefieldCounts(wn2); } catch (Exception e) { LogManager.getLogger().error("Error loading minefield counts in scenario", e); } } } catch (Exception e) { LogManager.getLogger().error("", e); } } /* In the event a discrepancy occurs between a RAT entry and the unit lookup name, * remove the entry from the list of entities that give survival bonuses * to avoid an critical error that prevents battle resolution. */ ArrayList<UUID> toRemove = new ArrayList<>(); for (UUID uid : survivalBonus) { if (!entityIds.containsKey(uid)) { toRemove.add(uid); } } survivalBonus.removeAll(toRemove); } private static Map<String, List<String>> loadTransportLinkages(Node wn) { NodeList nl = wn.getChildNodes(); Map<String, List<String>> transportLinkages = new HashMap<>(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("transportLinkage")) { loadTransportLinkage(wn2, transportLinkages); } } return transportLinkages; } private static void loadTransportLinkage(Node wn, Map<String, List<String>> transportLinkages) { NodeList nl = wn.getChildNodes(); String transportID = null; List<String> transportedUnitIDs = null; for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("transportID")) { transportID = wn2.getTextContent().trim(); } else if (wn2.getNodeName().equalsIgnoreCase("transportedUnits")) { transportedUnitIDs = Arrays.asList(wn2.getTextContent().split(",")); } } if ((transportID != null) && (transportedUnitIDs != null)) { transportLinkages.put(transportID, transportedUnitIDs); } } /** * Worker function that loads the minefield counts for the player */ private void loadMinefieldCounts(Node wn) throws NumberFormatException { NodeList nl = wn.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("numPlayerMinefield")) { NodeList minefieldNodes = wn2.getChildNodes(); int minefieldType = 0; int minefieldCount = 0; for (int minefieldIndex = 0; minefieldIndex < minefieldNodes.getLength(); minefieldIndex++) { Node wn3 = minefieldNodes.item(minefieldIndex); if (wn3.getNodeName().equalsIgnoreCase("minefieldType")) { minefieldType = Integer.parseInt(wn3.getTextContent()); } else if (wn3.getNodeName().equalsIgnoreCase("minefieldCount")) { minefieldCount = Integer.parseInt(wn3.getTextContent()); } } numPlayerMinefields.put(minefieldType, minefieldCount); } } } protected String getCsvFromList(List<?> list) { StringJoiner retVal = new StringJoiner(","); for (Object item : list) { retVal.add(item.toString()); } return retVal.toString(); } public AtBContract getContract(Campaign c) { return (AtBContract) c.getMission(getMissionId()); } /** * Gets all the entities that are part of the given entity list and are * not in this scenario's transport linkages as a transported unit. */ public List<Entity> filterUntransportedUnits(List<Entity> entities) { List<Entity> retVal = new ArrayList<>(); // assemble a set of transported units for easier lookup Set<String> transportedUnits = new HashSet<>(); for (List<String> transported : getTransportLinkages().values()) { transportedUnits.addAll(transported); } for (Entity entity : entities) { if (!transportedUnits.contains(entity.getExternalIdAsString())) { retVal.add(entity); } } return retVal; } public int getLanceForceId() { return lanceForceId; } public AtBLanceRole getLanceRole() { return lanceRole; } public Lance getLance(Campaign c) { return c.getLances().get(lanceForceId); } public void setLance(Lance l) { lanceForceId = l.getForceId(); } public boolean isAttacker() { return attacker; } public void setAttacker(boolean attacker) { this.attacker = attacker; } public List<Entity> getAlliesPlayer() { return alliesPlayer; } public List<UUID> getAttachedUnitIds() { return attachedUnitIds; } public List<UUID> getSurvivalBonusIds() { return survivalBonus; } public Entity getEntity(UUID id) { return entityIds.get(id); } public List<String> getAlliesPlayerStub() { return alliesPlayerStub; } public int getDeploymentDelay() { return deploymentDelay; } public void setDeploymentDelay(int delay) { this.deploymentDelay = delay; } public int getLanceCount() { return lanceCount; } public void setLanceCount(int lanceCount) { this.lanceCount = lanceCount; } public int getRerollsRemaining() { return rerollsRemaining; } public void useReroll() { rerollsRemaining--; } public void setRerolls(int rerolls) { rerollsRemaining = rerolls; } public int getEnemyHome() { return enemyHome; } public void setEnemyHome(int enemyHome) { this.enemyHome = enemyHome; } public int getNumPlayerMinefields(int minefieldType) { return numPlayerMinefields.containsKey(minefieldType) ? numPlayerMinefields.get(minefieldType) : 0; } public void setNumPlayerMinefields(int minefieldType, int numPlayerMinefields) { this.numPlayerMinefields.put(minefieldType, numPlayerMinefields); } public Map<String, List<String>> getTransportLinkages() { return transportLinkages; } public void setTransportLinkages(HashMap<String, List<String>> transportLinkages) { this.transportLinkages = transportLinkages; } /** * Adds a transport-cargo pair to the internal transport relationship store. * @param transport * @param cargo */ public void addTransportRelationship(String transport, String cargo) { if (!transportLinkages.containsKey(transport)) { transportLinkages.put(transport, new ArrayList<>()); } transportLinkages.get(transport).add(cargo); } @Override public boolean isFriendlyUnit(Entity entity, Campaign campaign) { return getAlliesPlayer().stream().anyMatch(unit -> unit.getExternalIdAsString().equals(entity.getExternalIdAsString())) || super.isFriendlyUnit(entity, campaign); } public String getBattlefieldControlDescription() { return getResourceBundle().getString("battleDetails.common.winnerControlsBattlefield"); } public String getDeploymentInstructions() { if (this.isBigBattle()) { return getResourceBundle().getString("battleDetails.deployEightMeks"); } else if (isSpecialScenario()) { return getResourceBundle().getString("battleDetails.deploySingleMek"); } else { return ""; } } @Override public boolean canStartScenario(Campaign c) { return c.getLocalDate().equals(getDate()) && super.canStartScenario(c); } }
sixlettervariables/mekhq
MekHQ/src/mekhq/campaign/mission/AtBScenario.java
46,047
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package com.aionemu.gameserver.restrictions; import com.aionemu.gameserver.configs.main.GroupConfig; import com.aionemu.gameserver.model.DescriptionId; import com.aionemu.gameserver.model.actions.PlayerMode; import com.aionemu.gameserver.model.gameobjects.Creature; import com.aionemu.gameserver.model.gameobjects.Item; import com.aionemu.gameserver.model.gameobjects.VisibleObject; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.model.gameobjects.state.CreatureState; import com.aionemu.gameserver.model.team2.group.PlayerGroup; import com.aionemu.gameserver.model.templates.zone.ZoneClassName; import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE; import com.aionemu.gameserver.skillengine.effect.AbnormalState; import com.aionemu.gameserver.skillengine.effect.EffectType; import com.aionemu.gameserver.skillengine.model.Skill; import com.aionemu.gameserver.skillengine.model.SkillTemplate; import com.aionemu.gameserver.skillengine.model.SkillType; import com.aionemu.gameserver.skillengine.model.TransformType; import com.aionemu.gameserver.utils.PacketSendUtility; import com.aionemu.gameserver.world.zone.ZoneInstance; import com.aionemu.gameserver.world.zone.ZoneName; /** * @author lord_rex modified by Sippolo */ public class PlayerRestrictions extends AbstractRestrictions { @Override public boolean canAffectBySkill(Player player, VisibleObject target, Skill skill) { if (skill == null) { return false; } if (player.isInPlayerMode(PlayerMode.RIDE)) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_CANNOT_RIDE_ABNORMAL_STATE); return false; } // dont allow to use skills in Fly Teleport state if (target instanceof Player && ((Player) target).isProtectionActive()) { return false; } if (player.isUsingFlyTeleport() || (target instanceof Player && ((Player) target).isUsingFlyTeleport())) { return false; } if (((Creature) target).getLifeStats().isAlreadyDead() && !skill.getSkillTemplate().hasResurrectEffect() && !skill.checkNonTargetAOE()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_SKILL_TARGET_IS_NOT_VALID); return false; } // cant ressurect non players and non dead if (skill.getSkillTemplate().hasResurrectEffect() && (!(target instanceof Player) || !((Creature) target).getLifeStats().isAlreadyDead() || (!((Creature) target).isInState(CreatureState.DEAD) && !((Creature) target).isInState(CreatureState.FLOATING_CORPSE)))) { return false; } if (skill.getSkillTemplate().hasItemHealFpEffect() && !player.isInFlyingState()) { // player must be PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_SKILL_RESTRICTION_FLY_ONLY); return false; } if (!skill.getSkillTemplate().hasEvadeEffect()) { if (player.getEffectController().isAbnormalState(AbnormalState.CANT_ATTACK_STATE)) { return false; } } // Fix for Summon Group Member, cannot be used while either caster or summoned is actively in combat // example skillId: 1606 if (skill.getSkillTemplate().hasRecallInstant()) { // skill properties should already filter only players if (player.getController().isInCombat() || ((Player) target).getController().isInCombat()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_Recall_CANNOT_ACCEPT_EFFECT(target.getName())); return false; } } if (player.isInState(CreatureState.PRIVATE_SHOP)) { // You cannot use an item while running a Private Store. PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_CANNOT_USE_ITEM_DURING_PATH_FLYING(new DescriptionId(2800123))); return false; } if (((target instanceof Player)) && (((Player) target).isTransformed()) && (((Player) target).getTransformModel().getType() == TransformType.AVATAR) && (skill.getSkillTemplate().getEffects().isEffectTypePresent(EffectType.HIDE))) { return false; } return true; } private boolean checkFly(Player player, VisibleObject target) { if (player.isUsingFlyTeleport() || player.isInPlayerMode(PlayerMode.WINDSTREAM)) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_SKILL_RESTRICTION_NO_FLY); return false; } if (target != null && target instanceof Player) { Player playerTarget = (Player) target; if (playerTarget.isUsingFlyTeleport() || playerTarget.isInPlayerMode(PlayerMode.WINDSTREAM)) { return false; } } return true; } @Override public boolean canUseSkill(Player player, Skill skill) { VisibleObject target = player.getTarget(); SkillTemplate template = skill.getSkillTemplate(); if (!checkFly(player, target)) { return false; } // TODO cancel skill if other is used if (player.isCasting()) { return false; } if (player.isInPlayerMode(PlayerMode.RIDE)) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_SKILL_RESTRICTION_RIDE); return false; } if (player.getInventory().isFull()) { //You are too overburdened to fight. PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_TOO_HEAVY_TO_ATTACK); return false; } if (!player.canAttack() && !template.hasEvadeEffect()) { return false; } // in 3.0 players can use remove shock even when silenced if (template.getType() == SkillType.MAGICAL && player.getEffectController().isAbnormalSet(AbnormalState.SILENCE) && !template.hasEvadeEffect()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_SKILL_CANT_CAST_MAGIC_SKILL_WHILE_SILENCED); return false; } if (template.getType() == SkillType.PHYSICAL && player.getEffectController().isAbnormalSet(AbnormalState.BIND)) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_SKILL_CANT_CAST_PHYSICAL_SKILL_IN_FEAR); return false; } // //cannot use abyss skill in tiamat down // if (skill.getSkillTemplate().getStack().contains("ABYSS_RANKERSKILL") && player.getWorldId() == 600040000) { // PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_SKILL_CANT_CAST_IN_CURRENT_POSTION); // return false; // } if (player.isSkillDisabled(template)) { return false; } // cannot use skills while transformed if (player.getTransformModel().isActive()) { if (player.getTransformModel().getType() == TransformType.NONE) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_SKILL_CAN_NOT_CAST_IN_SHAPECHANGE); return false; } } if (template.hasResurrectEffect()) { if (!(target instanceof Player)) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_SKILL_TARGET_IS_NOT_VALID); return false; } Player targetPlayer = (Player) target; if (!targetPlayer.isInState(CreatureState.DEAD)) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_SKILL_TARGET_IS_NOT_VALID); return false; } } if ((player.isTransformed()) && (player.getTransformModel().getType() == TransformType.AVATAR) && (skill.getSkillTemplate().getEffects().isEffectTypePresent(EffectType.HIDE))) { return false; } return true; } @Override public boolean canInviteToGroup(Player player, Player target) { final com.aionemu.gameserver.model.team2.group.PlayerGroup group = player.getPlayerGroup2(); if (group != null && group.isFull()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_CANT_ADD_NEW_MEMBER); return false; } else if (group != null && !player.getObjectId().equals(group.getLeader().getObjectId())) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_ONLY_LEADER_CAN_INVITE); return false; } else if (target == null) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_NO_USER_TO_INVITE); return false; } else if (target.getRace() != player.getRace() && !GroupConfig.GROUP_INVITEOTHERFACTION) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_CANT_INVITE_OTHER_RACE); return false; } else if (target.sameObjectId(player.getObjectId())) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_CAN_NOT_INVITE_SELF); return false; } else if (target.getLifeStats().isAlreadyDead()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_UI_PARTY_DEAD); return false; } else if (player.getLifeStats().isAlreadyDead()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_CANT_INVITE_WHEN_DEAD); return false; } else if (player.isInGroup2() && target.isInGroup2() && player.getPlayerGroup2().getTeamId() == target.getPlayerGroup2().getTeamId()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_HE_IS_ALREADY_MEMBER_OF_OUR_PARTY(target.getName())); } else if (target.isInGroup2()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_HE_IS_ALREADY_MEMBER_OF_OTHER_PARTY(target.getName())); return false; } else if (target.isInAlliance2()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_FORCE_ALREADY_OTHER_FORCE(target.getName())); return false; } return true; } @Override public boolean canInviteToAlliance(Player player, Player target) { int level = player.getLevel(); if (target == null) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_FORCE_NO_USER_TO_INVITE); return false; } if (target.getRace() != player.getRace() && !GroupConfig.ALLIANCE_INVITEOTHERFACTION) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_CANT_INVITE_OTHER_RACE); return false; } final com.aionemu.gameserver.model.team2.alliance.PlayerAlliance alliance = player.getPlayerAlliance2(); if (level < 10) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_ALLIANCE_TOO_LOW_LEVEL_TO_INVITE("10")); return false; } if (target.isInAlliance2()) { if (target.getPlayerAlliance2() == alliance) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_ALLIANCE_HE_IS_ALREADY_MEMBER_OF_OUR_ALLIANCE(target.getName())); return false; } else { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_FORCE_ALREADY_OTHER_FORCE(target.getName())); return false; } } if (alliance != null && alliance.isFull()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_ALLIANCE_CANT_ADD_NEW_MEMBER); return false; } if (alliance != null && !alliance.isSomeCaptain(player)) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_PARTY_ALLIANCE_ONLY_PARTY_LEADER_CAN_LEAVE_ALLIANCE); return false; } if (target.sameObjectId(player.getObjectId())) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_FORCE_CAN_NOT_INVITE_SELF); return false; } if (target.getLifeStats().isAlreadyDead()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_UI_PARTY_DEAD); return false; } if (player.getLifeStats().isAlreadyDead()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_FORCE_CANT_INVITE_WHEN_DEAD); return false; } if (target.isInGroup2()) { PlayerGroup targetGroup = target.getPlayerGroup2(); if (targetGroup.isLeader(target)) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_FORCE_INVITE_PARTY_HIM(target.getName(), targetGroup.getLeader().getName())); return false; } if (alliance != null && (targetGroup.size() + alliance.size() >= 24)) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_FORCE_INVITE_FAILED_NOT_ENOUGH_SLOT); return false; } } return true; } public boolean canInviteToLeague(Player player, Player target) { if (target == null) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_UNION_ONLY_INVITE_FORCE_MEMBER); return false; } final com.aionemu.gameserver.model.team2.alliance.PlayerAlliance alliance = player.getPlayerAlliance2(); if (target.isInLeague()) { if (target.getPlayerAlliance2() == alliance) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_UNION_ALREADY_MY_UNION(target.getName())); return false; } else { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_UNION_ALREADY_OTHER_UNION(target.getName())); return false; } } if (alliance != null && alliance.isFull()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_UNION_CANT_ADD_NEW_MEMBER); return false; } if (alliance != null) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_UNION_ONLY_LEADER_CAN_LEAVE); return false; } if (player.getLifeStats().isAlreadyDead()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_UNION_CANT_INVITE_WHEN_DEAD); return false; } if (target.isInGroup2()) { PlayerGroup targetGroup = target.getPlayerGroup2(); if (targetGroup.isLeader(target)) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_UNION_INVITE_HIM(target.getName(), targetGroup.getLeader().getName())); return false; } } return true; } @Override public boolean canAttack(Player player, VisibleObject target) { if (target == null) { return false; } if (!checkFly(player, target)) { return false; } if (!(target instanceof Creature)) { return false; } Creature creature = (Creature) target; if (creature.getLifeStats().isAlreadyDead()) { return false; } if (player.isInPlayerMode(PlayerMode.RIDE)) { //You cannot attack while mounted. PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_ATTACK_RESTRICTION_RIDE); return false; } if (player.getInventory().isFull()) { //You are too overburdened to fight. PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_TOO_HEAVY_TO_ATTACK); return false; } return player.isEnemy(creature); } @Override public boolean canUseWarehouse(Player player) { int level = player.getLevel(); if (player == null || !player.isOnline()) { return false; } if (player.isTrading()) { return false; } if (level < 10) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_FREE_EXPERIENCE_CHARACTER_CANT_USE_ACCOUNT_WAREHOUSE("10")); return false; } return true; } @Override public boolean canTrade(Player player) { int level = player.getLevel(); if (player == null || !player.isOnline()) { return false; } if (player.isTrading()) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_EXCHANGE_PARTNER_IS_EXCHANGING_WITH_OTHER); return false; } if (player.getEffectController().isAbnormalSet(AbnormalState.HIDE)) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_EXCHANGE_CANT_EXCHANGE_WHILE_INVISIBLE); return false; } if (level < 10) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_FREE_EXPERIENCE_CHARACTER_CANT_TRADE("10")); return false; } return true; } @Override public boolean canChangeEquip(Player player){ if (player.getEffectController().isAbnormalSet(AbnormalState.CANT_ATTACK_STATE)) { return false; } return true; } @Override public boolean canChat(Player player) { if (player == null || !player.isOnline()) { return false; } return !player.isGagged(); } @Override public boolean canUseItem(Player player, Item item) { if (player == null || !player.isOnline()) { return false; } if (player.getEffectController().isAbnormalState(AbnormalState.CANT_ATTACK_STATE)) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_SKILL_CAN_NOT_USE_ITEM_WHILE_IN_ABNORMAL_STATE); return false; } if (item.getItemTemplate().hasAreaRestriction()) { ZoneName restriction = item.getItemTemplate().getUseArea(); if (restriction == ZoneName.get("_ABYSS_CASTLE_AREA_")) { boolean isInFortZone = false; for (ZoneInstance zone : player.getPosition().getMapRegion().getZones(player)) { if (zone.getZoneTemplate().getZoneType().equals(ZoneClassName.FORT)) { isInFortZone = true; break; } } if (!isInFortZone) { PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1300143)); return false; } } else if (restriction != null && !player.isInsideItemUseZone(restriction)) { // You cannot use that item here. PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1300143)); return false; } } return true; } }
PhantomKNA/aion-germany
AL-Game/src/com/aionemu/gameserver/restrictions/PlayerRestrictions.java
46,048
package org.synyx.urlaubsverwaltung.mail; import org.synyx.urlaubsverwaltung.person.MailNotification; import org.synyx.urlaubsverwaltung.person.Person; import java.util.List; public interface MailRecipientService { /** * Returns all responsible managers of the given person. * Managers are: * <ul> * <li>bosses</li> * <li>department heads</li> * <li>second stage authorities.</li> * </ul> * * @param personOfInterest person to get managers from * @return list of all responsible managers */ List<Person> getResponsibleManagersOf(Person personOfInterest); /** * Returns a list of recipients of interest for a given person based on * <ul> * <li>is Office and the given mail notification is active</li> * <li>is Boss and the given mail notification is active</li> * <li>is responsible Department Head and the given mail notification is active</li> * <li>is responsible Second Stage Authority and the given mail notification is active</li> * <li>is Boss in the same Department and the given mail notification is active</li> * </ul> * * @param personOfInterest person to get recipients from * @param mailNotification given notification that one of must be active * @return list of recipients of interest */ List<Person> getRecipientsOfInterest(Person personOfInterest, MailNotification mailNotification); /** * Returns a list of colleagues for a given person based on * <ul> * <li>is in the same department</li> * <li>is active</li> * <li>is not department head of the department</li> * <li>is not second stage authority of the department</li> * <li>and the given mail notification is active</li> * </ul> * * @param personOfInterest person to get recipients from * @param mailNotification given notification that one of must be active * @return list of colleagues */ List<Person> getColleagues(Person personOfInterest, MailNotification mailNotification); }
urlaubsverwaltung/urlaubsverwaltung
src/main/java/org/synyx/urlaubsverwaltung/mail/MailRecipientService.java
46,049
/* * Copyright (c) 2018. Aberic - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.dao.entity; import com.gitee.sunchenbin.mybatis.actable.annotation.Column; import com.gitee.sunchenbin.mybatis.actable.annotation.Table; import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * 作者:Aberic on 2018/6/27 21:15 * 邮箱:abericyang@gmail.com */ @Setter @Getter @ToString @Table(name = "fns_peer") public class Peer { @Column(name = "id",type = MySqlTypeConstant.INT,length = 9,isKey = true,isAutoIncrement = true) private int id; // required @Column(name = "name",type = MySqlTypeConstant.VARCHAR,length = 128) private String name; // required @Column(name = "location",type = MySqlTypeConstant.VARCHAR,length = 256) private String location; // required @Column(name = "event_hub_location",type = MySqlTypeConstant.VARCHAR,length = 256) private String eventHubLocation; // required @Column(name = "org_id",type = MySqlTypeConstant.INT,length = 9) private int orgId; // required @Column(name = "server_crt_path",type = MySqlTypeConstant.VARCHAR,length = 512) private String serverCrtPath; @Column(name = "client_cert_path",type = MySqlTypeConstant.VARCHAR,length = 512) private String clientCertPath; @Column(name = "client_key_path",type = MySqlTypeConstant.VARCHAR,length = 512) private String clientKeyPath; @Column(name = "date",type = MySqlTypeConstant.VARCHAR,length = 14) private String date; // required private String orgName; // required private String leagueName; // optional private int channelCount; // required }
aberic/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/dao/entity/Peer.java
46,050
package com.mercury.platform.shared; import com.mercury.platform.shared.entity.message.CurrencyTradeNotificationDescriptor; import com.mercury.platform.shared.entity.message.ItemTradeNotificationDescriptor; import com.mercury.platform.shared.entity.message.NotificationDescriptor; import com.mercury.platform.shared.entity.message.NotificationType; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class MessageParser { private final static String poeTradeStashTabPattern = "^(.*\\s)?(.+): (.+ to buy your\\s+?(.+?)(\\s+?listed for\\s+?([\\d\\.]+?)\\s+?(.+))?\\s+?in\\s+?(.+?)\\s+?\\(stash tab \"(.*)\"; position: left (\\d+), top (\\d+)\\)\\s*?(.*))$"; private final static String poeTradePattern = "^(.*\\s)?(.+): (.+ to buy your\\s+?(.+?)(\\s+?listed for\\s+?([\\d\\.]+?)\\s+?(.+))?\\s+?in\\s+?(.*?))$"; private final static String poeAppPattern = "^(.*\\s)?(.+): (\\s*?wtb\\s+?(.+?)(\\s+?listed for\\s+?([\\d\\.]+?)\\s+?(.+))?\\s+?in\\s+?(.+?)\\s+?\\(stash\\s+?\"(.*?)\";\\s+?left\\s+?(\\d+?),\\s+?top\\s+(\\d+?)\\)\\s*?(.*))$"; private final static String poeAppBulkCurrenciesPattern = "^(.*\\s)?(.+): (\\s*?wtb\\s+?(.+?)(\\s+?listed for\\s+?([\\d\\.]+?)\\s+?(.+))?\\s+?in\\s+?(.+?)\\s+?\\(stash\\s+?\"(.*?)\";\\s+?left\\s+?(\\d+?),\\s+?top\\s+(\\d+?)\\)\\s*?(.*))$"; private final static String poeCurrencyPattern = "^(.*\\s)?(.+): (.+ to buy your (\\d+(\\.\\d+)?)? (.+) for my (\\d+(\\.\\d+)?)? (.+) in (.*?)\\.\\s*(.*))$"; private final static String poeMapLiveRegex = "^(.*\\s)?(.+): (I'd like to exchange my (T\\d+:\\s\\([\\s\\S,]+) for your (T\\d+:\\s\\([\\S,\\s]+) in\\s+?(.+?)\\.)"; private Pattern poeAppItemPattern; private Pattern poeTradeStashItemPattern; private Pattern poeTradeItemPattern; private Pattern poeTradeCurrencyPattern; private Pattern poeMapLivePattern; public MessageParser() { this.poeAppItemPattern = Pattern.compile(poeAppPattern); this.poeTradeStashItemPattern = Pattern.compile(poeTradeStashTabPattern); this.poeTradeItemPattern = Pattern.compile(poeTradePattern); this.poeTradeCurrencyPattern = Pattern.compile(poeCurrencyPattern); this.poeMapLivePattern = Pattern.compile(poeMapLiveRegex); } public NotificationDescriptor parse(String fullMessage) { Matcher poeAppItemMatcher = poeAppItemPattern.matcher(fullMessage); if (poeAppItemMatcher.find()) { ItemTradeNotificationDescriptor tradeNotification = new ItemTradeNotificationDescriptor(); tradeNotification.setWhisperNickname(poeAppItemMatcher.group(2)); tradeNotification.setSourceString(poeAppItemMatcher.group(3)); tradeNotification.setItemName(poeAppItemMatcher.group(4)); if (poeAppItemMatcher.group(5) != null) { tradeNotification.setCurCount(Double.parseDouble(poeAppItemMatcher.group(6))); tradeNotification.setCurrency(poeAppItemMatcher.group(7)); } else { tradeNotification.setCurCount(0d); tradeNotification.setCurrency("???"); } tradeNotification.setLeague(poeAppItemMatcher.group(8)); if (poeAppItemMatcher.group(9) != null) { tradeNotification.setTabName(poeAppItemMatcher.group(9)); tradeNotification.setLeft(Integer.parseInt(poeAppItemMatcher.group(10))); tradeNotification.setTop(Integer.parseInt(poeAppItemMatcher.group(11))); } tradeNotification.setOffer(poeAppItemMatcher.group(12)); tradeNotification.setType(NotificationType.INC_ITEM_MESSAGE); return tradeNotification; } Matcher poeTradeStashItemMatcher = poeTradeStashItemPattern.matcher(fullMessage); if (poeTradeStashItemMatcher.find()) { ItemTradeNotificationDescriptor tradeNotification = new ItemTradeNotificationDescriptor(); tradeNotification.setWhisperNickname(poeTradeStashItemMatcher.group(2)); tradeNotification.setSourceString(poeTradeStashItemMatcher.group(3)); tradeNotification.setItemName(poeTradeStashItemMatcher.group(4)); if (poeTradeStashItemMatcher.group(6) != null) { tradeNotification.setCurCount(Double.parseDouble(poeTradeStashItemMatcher.group(6))); tradeNotification.setCurrency(poeTradeStashItemMatcher.group(7)); } else { tradeNotification.setCurCount(0d); tradeNotification.setCurrency("???"); } tradeNotification.setLeague(poeTradeStashItemMatcher.group(8)); tradeNotification.setTabName(poeTradeStashItemMatcher.group(9)); tradeNotification.setLeft(Integer.parseInt(poeTradeStashItemMatcher.group(10))); tradeNotification.setTop(Integer.parseInt(poeTradeStashItemMatcher.group(11))); tradeNotification.setOffer(poeTradeStashItemMatcher.group(12)); tradeNotification.setType(NotificationType.INC_ITEM_MESSAGE); return tradeNotification; } Matcher poeTradeCurrencyMatcher = poeTradeCurrencyPattern.matcher(fullMessage); if (poeTradeCurrencyMatcher.find()) { CurrencyTradeNotificationDescriptor tradeNotification = new CurrencyTradeNotificationDescriptor(); if (poeTradeCurrencyMatcher.group(6).contains("&") || poeTradeCurrencyMatcher.group(6).contains(",")) { //todo this shit for bulk map String bulkItems = poeTradeCurrencyMatcher.group(4) + " " + poeTradeCurrencyMatcher.group(6); tradeNotification.setItems(Arrays.stream(StringUtils.split(bulkItems, ",&")).map(String::trim).collect(Collectors.toList())); } else { tradeNotification.setCurrForSaleCount(Double.parseDouble(poeTradeCurrencyMatcher.group(4))); tradeNotification.setCurrForSaleTitle(poeTradeCurrencyMatcher.group(6)); } tradeNotification.setWhisperNickname(poeTradeCurrencyMatcher.group(2)); tradeNotification.setSourceString(poeTradeCurrencyMatcher.group(3)); tradeNotification.setCurCount(Double.parseDouble(poeTradeCurrencyMatcher.group(7))); tradeNotification.setCurrency(poeTradeCurrencyMatcher.group(9)); tradeNotification.setLeague(poeTradeCurrencyMatcher.group(10)); tradeNotification.setOffer(poeTradeCurrencyMatcher.group(11)); tradeNotification.setType(NotificationType.INC_CURRENCY_MESSAGE); return tradeNotification; } Matcher poeTradeItemMatcher = poeTradeItemPattern.matcher(fullMessage); if (poeTradeItemMatcher.find()) { ItemTradeNotificationDescriptor tradeNotification = new ItemTradeNotificationDescriptor(); tradeNotification.setWhisperNickname(poeTradeItemMatcher.group(2)); tradeNotification.setSourceString(poeTradeItemMatcher.group(3)); tradeNotification.setItemName(poeTradeItemMatcher.group(4)); if (poeTradeItemMatcher.group(5) != null) { tradeNotification.setCurCount(Double.parseDouble(poeTradeItemMatcher.group(6))); tradeNotification.setCurrency(poeTradeItemMatcher.group(7)); } else { tradeNotification.setCurCount(0d); tradeNotification.setCurrency("???"); } tradeNotification.setLeague(poeTradeItemMatcher.group(8)); tradeNotification.setType(NotificationType.INC_ITEM_MESSAGE); return tradeNotification; } Matcher poeTradeMapLiveMatcher = poeMapLivePattern.matcher(fullMessage); if (poeTradeMapLiveMatcher.find()) { ItemTradeNotificationDescriptor tradeNotification = new ItemTradeNotificationDescriptor(); tradeNotification.setWhisperNickname(poeTradeMapLiveMatcher.group(2)); tradeNotification.setSourceString(poeTradeMapLiveMatcher.group(3)); tradeNotification.setItemName(poeTradeMapLiveMatcher.group(5)); tradeNotification.setOffer(poeTradeMapLiveMatcher.group(4)); tradeNotification.setLeague(poeTradeMapLiveMatcher.group(6)); tradeNotification.setType(NotificationType.INC_ITEM_MESSAGE); tradeNotification.setCurCount(0d); tradeNotification.setCurrency(""); tradeNotification.setType(NotificationType.INC_ITEM_MESSAGE); return tradeNotification; } return null; } }
Exslims/MercuryTrade
app-core/src/main/java/com/mercury/platform/shared/MessageParser.java
46,051
package data.hl; import data.Rules; import data.values.Penalties; import java.awt.Color; /** * This class sets attributes given by the humanoid-league rules. * * @author Michel-Zen */ public class HL extends Rules { public HL() { /** The league´s name this rules are for. */ leagueName = "HL Kid"; /** The league´s directory name with it´s teams and icons. */ leagueDirectory = "hl_kid"; /** How many robots are in a team. */ teamSize = 6; /** How many robots of each team may play at one time. */ robotsPlaying = 4; /** The Java Colors the left and the right team starts with. */ teamColor = new Color[] {Color.BLUE, Color.RED}; /** The name of the colors. */ teamColorName = new String[] {"Blue","Red"}; /** If the colors change automatically. */ colorChangeAuto = false; /** If the clock may stop in certain states (Ready, Set) in a play-off game. */ playOffTimeStop = false; /** Time in seconds one half is long. */ halfTime = 10*60; /** Time in seconds the ready state is long. */ readyTime = 45; /** Time in seconds between first and second half. */ pauseTime = 5*60; /** If left and right side may both have the first kickoff. */ kickoffChoice = true; /** Time in seconds the ball is blocked after kickoff. */ kickoffTime = 10; /** Time in seconds before a global game stuck can be called. */ minDurationBeforeStuck = 30; /** The number of seconds switching to Playing is delayed. */ delayedSwitchToPlaying = 0; /** If there is an overtime before penalty-shoot in a play-off game. */ overtime = true; /** Time in seconds one overtime half is long. */ overtimeTime = 5*60; /** If the game starts with penalty-shoots. */ startWithPenalty = false; /** Time in seconds between second half and penalty shoot. */ pausePenaltyShootOutTime = 0; /** If there can be a penalty-shoot retry. */ penaltyShotRetries = true; /** Time in seconds one penalty shoot is long. */ penaltyShotTime = 1*60; /** If there is a sudden-death. */ suddenDeath = false; /** Time in seconds one penalty shoot is long in sudden-death. */ penaltyShotTimeSuddenDeath = 2*60; // does not matter /** Number of penalty-shoots for each team when a half has 10minutes. */ numberOfPenaltyShotsShort = 5; /** Number of penalty-shoots for each team after full 10minutes playing. */ numberOfPenaltyShotsLong = 5; /** Time in seconds to increment penalties. */ penaltyIncreaseTime = 0; /** Whether the penalty count is reset on halftime */ resetPenaltyCountOnHalftime = true; /** Whether the ejected robots are reset on halftime */ resetEjectedRobotsOnHalftime = true; /** Whether penalties can be removed before the penalty time has passed. */ allowEarlyPenaltyRemoval = true; /** Penalty that players get when they substitute another player. */ substitutePenalty = Penalties.NONE; /** if robots should return from penalties when the game state changes. */ returnRobotsInGameStoppages = false; /** Time in seconds one team has as timeOut. */ timeOutTime = 2*60; /** One time-out per half? */ timeOutPerHalf = true; /** On how many pushings is a robot ejected. */ pushesToEjection = new int[] {}; /** Defines if the option for a referee timeout is available */ isRefereeTimeoutAvailable = true; /** How long the referee timeout is **/ refereeTimeout = 10*60; /** Defines if coach is available */ isCoachAvailable = false; /** Allowed to compensate for lost time? */ lostTime = false; /** If true, the drop-in player competition is active */ dropInPlayerMode = false; /** If true, the game controller should drop broadcast-messages */ dropBroadcastMessages = false; /** Background Side **/ backgroundSide = new String[][]{ { "robot_left_blue.png", "robot_left_red.png", }, { "robot_right_blue.png", "robot_right_red.png", } }; /** The time a team has to prepare for the free kick **/ game_interruption_preparation_time = 30; /** The time a team has to prepare for the penalty kick **/ penalty_kick_preparation_time = 30; /** The time an opponent is guaranteed to move away from the ball in preparation phase **/ game_interruption_minimal_ready_time = 15; } }
01rfcberlin/GameController
src/data/hl/HL.java
46,052
package net.dean.jraw.models; import com.google.auto.value.AutoValue; import com.squareup.moshi.Json; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import java.io.Serializable; @AutoValue public abstract class SubredditSearchResult implements Serializable { /** The approximate number of active users right now */ @Json(name = "active_user_count") public abstract int getActiveUserCount(); /** A full URL that points to the subreddit's icon */ @Json(name = "icon_img") public abstract String getIconUrl(); /** A hex color with the "#" included, or an empty string */ @Json(name = "key_color") public abstract String getKeyColor(); /** The subreddit's display name, e.g. "RocketLeague" */ public abstract String getName(); @Json(name = "subscriber_count") public abstract int getSubscriberCount(); @Json(name = "allow_images") public abstract boolean isAllowImages(); public static JsonAdapter<SubredditSearchResult> jsonAdapter(Moshi moshi) { return new AutoValue_SubredditSearchResult.MoshiJsonAdapter(moshi); } }
mattbdean/JRAW
lib/src/main/java/net/dean/jraw/models/SubredditSearchResult.java
46,053
/* * Copyright (c) 2018. Aberic - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.utils; import cn.aberic.fabric.dao.entity.Chaincode; import cn.aberic.fabric.dao.entity.Channel; import cn.aberic.fabric.dao.entity.Org; import cn.aberic.fabric.dao.entity.Peer; import cn.aberic.fabric.dao.mapper.*; import java.util.List; /** * 作者:Aberic on 2018/7/7 18:18 * 邮箱:abericyang@gmail.com */ public class DeleteUtil { private static DeleteUtil instance; public static DeleteUtil obtain() { if (null == instance) { synchronized (DeleteUtil.class) { if (null == instance) { instance = new DeleteUtil(); } } } return instance; } public int deleteLeague(int leagueId, LeagueMapper leagueMapper, OrgMapper orgMapper, OrdererMapper ordererMapper, PeerMapper peerMapper, CAMapper caMapper, ChannelMapper channelMapper, ChaincodeMapper chaincodeMapper, AppMapper appMapper, BlockMapper blockMapper) { List<Org> orgs = orgMapper.list(leagueId); if (orgs.size() == 0) { CacheUtil.removeHome(); } else { for (Org org : orgs) { deleteOrg(org.getId(), orgMapper, ordererMapper, peerMapper, caMapper, channelMapper, chaincodeMapper, appMapper, blockMapper); } } return leagueMapper.delete(leagueId); } public int deleteOrg(int orgId, OrgMapper orgMapper, OrdererMapper ordererMapper, PeerMapper peerMapper, CAMapper caMapper, ChannelMapper channelMapper, ChaincodeMapper chaincodeMapper, AppMapper appMapper, BlockMapper blockMapper) { List<Peer> peers = peerMapper.list(orgId); if (peers.size() == 0) { CacheUtil.removeHome(); } else { for (Peer peer : peers) { deletePeer(peer.getId(), peerMapper, caMapper, channelMapper, chaincodeMapper, appMapper, blockMapper); } } ordererMapper.deleteAll(orgId); return orgMapper.delete(orgId); } public int deletePeer(int peerId, PeerMapper peerMapper, CAMapper caMapper, ChannelMapper channelMapper, ChaincodeMapper chaincodeMapper, AppMapper appMapper, BlockMapper blockMapper) { List<Channel> channels = channelMapper.list(peerId); if (channels.size() == 0) { CacheUtil.removeHome(); } else { for (Channel channel : channels) { deleteChannel(channel.getId(), channelMapper, chaincodeMapper, appMapper, blockMapper); } } caMapper.deleteAll(peerId); return peerMapper.delete(peerId); } public int deleteChannel(int channelId, ChannelMapper channelMapper, ChaincodeMapper chaincodeMapper, AppMapper appMapper, BlockMapper blockMapper) { blockMapper.deleteByChannelId(channelId); BlockUtil.obtain().removeChannel(channelId); List<Chaincode> chaincodes = chaincodeMapper.list(channelId); if (chaincodes.size() == 0) { FabricHelper.obtain().removeChannelManager(channelId); CacheUtil.removeHome(); } else { for (Chaincode chaincode : chaincodes) { deleteChaincode(chaincode.getId(), chaincodeMapper, appMapper); } } return channelMapper.delete(channelId); } public int deleteChaincode(int chaincodeId, ChaincodeMapper chaincodeMapper, AppMapper appMapper) { appMapper.deleteAll(chaincodeId); FabricHelper.obtain().removeChaincodeManager(chaincodeMapper.get(chaincodeId).getCc()); CacheUtil.removeHome(); return chaincodeMapper.delete(chaincodeId); } }
aberic/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/utils/DeleteUtil.java
46,054
package module.matches; import core.datatype.CBItem; import core.db.DBManager; import core.gui.CursorToolkit; import core.gui.HOMainFrame; import core.gui.RefreshManager; import core.gui.comp.entry.ColorLabelEntry; import core.gui.comp.panel.ImagePanel; import core.gui.comp.panel.LazyImagePanel; import core.gui.model.MatchesColumnModel; import core.gui.theme.HOColorName; import core.gui.theme.HOIconName; import core.gui.theme.ThemeManager; import core.model.HOVerwaltung; import core.model.UserParameter; import core.model.match.IMatchDetails; import core.model.match.MatchKurzInfo; import core.model.match.MatchLineupPosition; import core.model.match.Matchdetails; import core.model.player.IMatchRoleID; import core.module.IModule; import core.net.OnlineWorker; import core.prediction.MatchEnginePanel; import core.prediction.MatchPredictionDialog; import core.prediction.engine.MatchPredictionManager; import core.prediction.engine.TeamData; import core.prediction.engine.TeamRatings; import core.rating.RatingPredictionModel; import core.util.HODateTime; import core.util.Helper; import module.lineup.Lineup; import module.matches.statistics.MatchesHighlightsTable; import module.matches.statistics.MatchesOverviewTable; import module.teamAnalyzer.ui.RatingUtil; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.awt.event.ItemEvent; import java.time.temporal.ChronoUnit; import java.util.List; import javax.swing.*; import javax.swing.event.ChangeEvent; import static core.util.Helper.getTranslation; public final class MatchesPanel extends LazyImagePanel { public static final int ALL_GAMES = 0; public static final int OWN_GAMES = 1; public static final int OWN_OFFICIAL_GAMES = 2; //own cup + league + qualif public static final int OWN_CUP_GAMES = 3; public static final int OWN_NATIONAL_CUP_GAMES = 4; public static final int OWN_SECONDARY_CUP_GAMES = 5; public static final int OWN_LEAGUE_GAMES = 6; public static final int OWN_QUALIF_GAMES = 7; public static final int OWN_FRIENDLY_GAMES = 8; public static final int OWN_TOURNAMENT_GAMES = 9; public static final int OTHER_TEAM_GAMES = 10; // Combobox matchesFilter ============================= public static final CBItem[] matchesTypeCBItems = { new CBItem(Helper.getTranslation("AlleSpiele"), MatchesPanel.ALL_GAMES), new CBItem(Helper.getTranslation("NurEigeneSpiele"), MatchesPanel.OWN_GAMES), new CBItem(Helper.getTranslation("NurEigenePflichtspiele"), MatchesPanel.OWN_OFFICIAL_GAMES), new CBItem(Helper.getTranslation("AllCupMatches"), MatchesPanel.OWN_CUP_GAMES), new CBItem(Helper.getTranslation("NurEigenePokalspiele"), MatchesPanel.OWN_NATIONAL_CUP_GAMES), new CBItem(Helper.getTranslation("OnlySecondaryCup"), MatchesPanel.OWN_SECONDARY_CUP_GAMES), new CBItem(Helper.getTranslation("NurEigeneLigaspiele"), MatchesPanel.OWN_LEAGUE_GAMES), new CBItem(Helper.getTranslation("OnlyQualificationMatches"), MatchesPanel.OWN_QUALIF_GAMES), new CBItem(Helper.getTranslation("NurEigeneFreundschaftsspiele"), MatchesPanel.OWN_FRIENDLY_GAMES), new CBItem(Helper.getTranslation("NurEigeneTournamentsspiele"), MatchesPanel.OWN_TOURNAMENT_GAMES), new CBItem(Helper.getTranslation("NurFremdeSpiele"), MatchesPanel.OTHER_TEAM_GAMES) }; private AufstellungsSternePanel aufstellungGastPanel; private AufstellungsSternePanel aufstellungHeimPanel; private JButton adoptLineupButton; private JButton deleteButton; private JButton reloadMatchButton; private JButton simulateMatchButton; private JComboBox<CBItem> gameSelectionFilter; private JSplitPane horizontalLeftSplitPane; private JSplitPane verticalSplitPane; private MatchesTable matchesTable; private MatchesOverviewTable matchesOverviewTable; private MatchesHighlightsTable matchesHighlightsTable; private MatchesModel matchesModel; @Override protected void initialize() { initComponents(); addListeners(); registerRefreshable(true); setNeedsRefresh(true); } @Override protected void update() { doReInit(); } private void addListeners() { this.reloadMatchButton.addActionListener(e -> reloadSelectedMatches()); this.deleteButton.addActionListener(e -> deleteSelectedMatches()); this.adoptLineupButton.addActionListener(e -> adoptLineup()); this.simulateMatchButton.addActionListener(e -> simulateMatch()); this.matchesTable.getSelectionModel().addListSelectionListener(e -> { if (!e.getValueIsAdjusting()) { newSelectionInform(); } }); HOMainFrame.instance().addApplicationClosingListener(this::saveSettings); gameSelectionFilter.addItemListener(e -> { if (e.getStateChange() == ItemEvent.SELECTED) { doReInit(); } }); } private void saveSettings() { matchesTable.saveColumnOrder(); matchesOverviewTable.saveColumnOrder(); UserParameter parameter = UserParameter.instance(); parameter.spielePanel_horizontalLeftSplitPane = horizontalLeftSplitPane .getDividerLocation(); parameter.spielePanel_verticalSplitPane = verticalSplitPane.getDividerLocation(); } private void adoptLineup() { if ((matchesModel.getMatch() != null) && (matchesModel.getMatch().getMatchStatus() == MatchKurzInfo.FINISHED)) { int teamid = HOVerwaltung.instance().getModel().getBasics().getTeamId(); List<MatchLineupPosition> positions = DBManager.instance().getMatchLineupPlayers( matchesModel.getMatch().getMatchID(), matchesModel.getMatch().getMatchType(), teamid); Lineup lineup = HOVerwaltung.instance().getModel().getCurrentLineup(); lineup.clearLineup(); // To make sure the old one is // gone. if (positions != null) { for (MatchLineupPosition player : positions) { if (player.getRoleId() == IMatchRoleID.setPieces) { lineup.setKicker(player.getPlayerId()); } else if (player.getRoleId() == IMatchRoleID.captain) { lineup.setCaptain(player.getPlayerId()); } else { lineup.setSpielerAtPosition(player.getRoleId(), player.getPlayerId(), player.getBehaviour()); } } } HOMainFrame.instance().getLineupPanel().update(); HOMainFrame.instance().showTab(IModule.LINEUP); } } private void reloadSelectedMatches() { HOMainFrame.instance().resetInformation(); int matchid = matchesModel.getMatch().getMatchID(); int i=0; int n = matchesTable.getSelectedRows().length; for ( var selectedRowNumber : matchesTable.getSelectedRows()){ var matchKurzInfo = getMatchKurzInfoOfRow(selectedRowNumber); OnlineWorker.downloadMatchData( matchKurzInfo.getMatchID(), matchKurzInfo.getMatchType(), true); HOMainFrame.instance().updateProgress((int)(++i * 100.0 / n)); } RefreshManager.instance().doReInit(); showMatch(matchid); HOMainFrame.instance().setInformationCompleted(); } private MatchKurzInfo getMatchKurzInfoOfRow(int selectedRowNumber) { return ((MatchesColumnModel) matchesTable.getSorter().getModel()) .getMatch((int) ((ColorLabelEntry) matchesTable.getSorter().getValueAt(selectedRowNumber, 7)).getNumber()); } private void deleteSelectedMatches() { int[] rows = matchesTable.getSelectedRows(); MatchKurzInfo[] infos = new MatchKurzInfo[rows.length]; for (int i = 0; i < rows.length; i++) { infos[i] = getMatchKurzInfoOfRow(rows[i]); } StringBuilder text = new StringBuilder(100); text.append(HOVerwaltung.instance().getLanguageString("ls.button.delete")); if (infos.length > 1) { text.append(" (").append(infos.length).append(" "); text.append(HOVerwaltung.instance().getLanguageString("Spiele")); text.append(")"); } text.append(":"); for (int i = 0; (i < infos.length) && (i < 11); i++) { text.append("\n").append(infos[i].getHomeTeamName()).append(" – ").append(infos[i].getGuestTeamName()); if (i == 10) { text.append("\n ... "); } } int value = JOptionPane.showConfirmDialog(MatchesPanel.this, text, HOVerwaltung.instance().getLanguageString("confirmation.title"), JOptionPane.YES_NO_OPTION); if (value == JOptionPane.YES_OPTION) { for (MatchKurzInfo info : infos) { DBManager.instance().deleteMatch(info); } RefreshManager.instance().doReInit(); } } private void simulateMatch() { if (matchesModel.getMatch() != null) { Matchdetails details = matchesModel.getDetails(); MatchPredictionManager manager = MatchPredictionManager.instance(); int teamId = HOVerwaltung.instance().getModel().getBasics().getTeamId(); boolean homeMatch = teamId == matchesModel.getMatch().getHomeTeamID(); TeamRatings homeTeamRatings = manager.generateTeamRatings( details != null ? getRatingValue(details.getHomeMidfield()) : 1, details != null ? getRatingValue(details.getHomeLeftDef()) : 1, details != null ? getRatingValue(details.getHomeMidDef()) : 1, details != null ? getRatingValue(details.getHomeRightDef()) : 1, details != null ? getRatingValue(details.getHomeLeftAtt()) : 1, details != null ? getRatingValue(details.getHomeMidAtt()) : 1, details != null ? getRatingValue(details.getHomeRightAtt()) : 1); TeamData homeTeamValues; if (homeMatch && !ratingsAreKnown(homeTeamRatings)) { homeTeamValues = getOwnLineupRatings(manager); } else { homeTeamValues = manager.generateTeamData(matchesModel.getMatch().getHomeTeamName(), homeTeamRatings, details != null ? details.getHomeTacticType() : IMatchDetails.TAKTIK_NORMAL, details != null ? getRatingValue(details.getHomeTacticSkill() - 1) : 1); } TeamRatings awayTeamRatings = manager.generateTeamRatings( details != null ? getRatingValue(details.getGuestMidfield()) : 1, details != null ? getRatingValue(details.getGuestLeftDef()) : 1, details != null ? getRatingValue(details.getGuestMidDef()) : 1, details != null ? getRatingValue(details.getGuestRightDef()) : 1, details != null ? getRatingValue(details.getGuestLeftAtt()) : 1, details != null ? getRatingValue(details.getGuestMidAtt()) : 1, details != null ? getRatingValue(details.getGuestRightAtt()) : 1); TeamData awayTeamValues; if (!homeMatch && !ratingsAreKnown(awayTeamRatings)) { awayTeamValues = getOwnLineupRatings(manager); } else { awayTeamValues = manager.generateTeamData(matchesModel.getMatch().getGuestTeamName(), awayTeamRatings, details != null ? details.getGuestTacticType() : IMatchDetails.TAKTIK_NORMAL, details != null ? getRatingValue(details.getGuestTacticSkill() - 1) : 1); } String matchName = matchesModel.getMatch().getHomeTeamName() + " – " + matchesModel.getMatch().getGuestTeamName(); MatchEnginePanel matchPredictionPanel = new MatchEnginePanel(homeTeamValues, awayTeamValues); MatchPredictionDialog d = new MatchPredictionDialog(matchPredictionPanel, matchName); } } /** * Helper to get at least the minimum rating value. */ private int getRatingValue(int in) { if (in > 0) { return in; } return 1; } /** * Check, if the ratings are ok/known or if all are at the default. */ private boolean ratingsAreKnown(TeamRatings ratings) { return (ratings != null && ratings.getMidfield() > 1d && ratings.getLeftDef() > 1d && ratings.getMiddleDef() > 1d && ratings.getRightDef() > 1d && ratings.getLeftAttack() > 1d && ratings.getMiddleAttack() > 1d && ratings .getRightAttack() > 1d); } /** * Get the team data for the own team (current lineup). */ private TeamData getOwnLineupRatings(MatchPredictionManager manager) { var hoModel = HOVerwaltung.instance().getModel(); var lineup = hoModel.getCurrentLineup(); var ratingPredictionModel = hoModel.getRatingPredictionModel(); TeamRatings teamRatings = manager.generateTeamRatings( getRatingValue(RatingUtil.getIntValue4Rating(ratingPredictionModel.getAverageRating(lineup, RatingPredictionModel.RatingSector.MIDFIELD, 90))), getRatingValue(RatingUtil.getIntValue4Rating(ratingPredictionModel.getAverageRating(lineup, RatingPredictionModel.RatingSector.DEFENCE_LEFT, 90))), getRatingValue(RatingUtil.getIntValue4Rating(ratingPredictionModel.getAverageRating(lineup, RatingPredictionModel.RatingSector.DEFENCE_CENTRAL, 90))), getRatingValue(RatingUtil.getIntValue4Rating(ratingPredictionModel.getAverageRating(lineup, RatingPredictionModel.RatingSector.DEFENCE_RIGHT, 90))), getRatingValue(RatingUtil.getIntValue4Rating(ratingPredictionModel.getAverageRating(lineup, RatingPredictionModel.RatingSector.ATTACK_LEFT, 90))), getRatingValue(RatingUtil.getIntValue4Rating(ratingPredictionModel.getAverageRating(lineup, RatingPredictionModel.RatingSector.ATTACK_CENTRAL, 90))), getRatingValue(RatingUtil.getIntValue4Rating(ratingPredictionModel.getAverageRating(lineup, RatingPredictionModel.RatingSector.ATTACK_RIGHT, 90)))); int tactic = lineup.getTacticType(); return manager.generateTeamData(HOVerwaltung.instance().getModel().getBasics().getTeamName(), teamRatings, tactic, getTacticStrength(lineup)); } /** * Get the tactic strength of the given lineup. */ private int getTacticStrength(Lineup lineup) { var ratingPredictionModel = HOVerwaltung.instance().getModel().getRatingPredictionModel(); return (int)ratingPredictionModel.getTacticRating(lineup, 0); } private void doReInit() { if (gameSelectionFilter.getSelectedIndex() > -1) { CursorToolkit.startWaitCursor(this); try { // Update tables int id = ((CBItem) gameSelectionFilter.getSelectedItem()).getId(); matchesTable.refresh(id, UserParameter.instance().matchLocation); matchesOverviewTable.refresh(id, UserParameter.instance().matchLocation); matchesHighlightsTable.refresh(id, UserParameter.instance().matchLocation); UserParameter.instance().spieleFilter = id; // then refresh all other panels newSelectionInform(); } finally { CursorToolkit.stopWaitCursor(this); } } } public void showMatch(int matchid) { matchesTable.markiereMatch(matchid); // If no match found in table if (matchesTable.getSelectedRow() < 0) { // Select all games for the marker to work gameSelectionFilter.setSelectedIndex(0); UserParameter.instance().spieleFilter = 0; matchesTable.markiereMatch(matchid); } newSelectionInform(); } private void initComponents() { this.matchesModel = new MatchesModel(); setLayout(new BorderLayout()); horizontalLeftSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, initMatchesTable(), initSpieldetails()); JPanel linupPanel = new JPanel(new GridLayout(2, 1)); aufstellungHeimPanel = new AufstellungsSternePanel(true); linupPanel.add(aufstellungHeimPanel); aufstellungGastPanel = new AufstellungsSternePanel(false); linupPanel.add(aufstellungGastPanel); verticalSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false, horizontalLeftSplitPane, new JScrollPane(linupPanel)); horizontalLeftSplitPane .setDividerLocation(UserParameter.instance().spielePanel_horizontalLeftSplitPane); verticalSplitPane .setDividerLocation(UserParameter.instance().spielePanel_verticalSplitPane); add(verticalSplitPane, BorderLayout.CENTER); } /** * Initialise player details GUI components. */ private Component initSpieldetails() { JPanel mainpanel = new ImagePanel(new BorderLayout()); JTabbedPane matchDetailsTabbedPane = new JTabbedPane(); // Allgemein StaerkenvergleichPanel teamsComparePanel = new StaerkenvergleichPanel(this.matchesModel); matchDetailsTabbedPane.addTab(HOVerwaltung.instance().getLanguageString("Allgemein"), new JScrollPane(teamsComparePanel)); // Rating Panel TeamsRatingPanel m_jpTeamsRatingPanel = new TeamsRatingPanel(this.matchesModel); matchDetailsTabbedPane.addTab(HOVerwaltung.instance().getLanguageString("matches.tabtitle.ratings"), new JScrollPane(m_jpTeamsRatingPanel)); // Highlights SpielHighlightPanel matchHighlightPanel = new SpielHighlightPanel(this.matchesModel); matchDetailsTabbedPane.addTab(HOVerwaltung.instance().getLanguageString("Highlights"), new JScrollPane(matchHighlightPanel)); // Match report MatchReportPanel matchReportPanel = new MatchReportPanel(this.matchesModel); matchDetailsTabbedPane.addTab(HOVerwaltung.instance().getLanguageString("Matchbericht"), matchReportPanel); mainpanel.add(matchDetailsTabbedPane, BorderLayout.CENTER); final JPanel buttonPanel = new ImagePanel(new FlowLayout(FlowLayout.LEFT)); // Reloadbutton reloadMatchButton = new JButton(ThemeManager.getIcon(HOIconName.RELOAD)); reloadMatchButton.setToolTipText(HOVerwaltung.instance().getLanguageString( "tt_Spiel_reload")); reloadMatchButton.setPreferredSize(new Dimension(24, 24)); reloadMatchButton.setEnabled(false); buttonPanel.add(reloadMatchButton); deleteButton = new JButton(ThemeManager.getIcon(HOIconName.REMOVE)); deleteButton.setBackground(ThemeManager.getColor(HOColorName.BUTTON_BG)); deleteButton.setToolTipText(HOVerwaltung.instance().getLanguageString("tt_Spiel_loeschen")); deleteButton.setPreferredSize(new Dimension(24, 24)); deleteButton.setEnabled(false); buttonPanel.add(deleteButton); adoptLineupButton = new JButton(ThemeManager.getIcon(HOIconName.GETLINEUP)); adoptLineupButton.setToolTipText(HOVerwaltung.instance().getLanguageString( "tt_Spiel_aufstellunguebernehmen")); adoptLineupButton.setPreferredSize(new Dimension(24, 24)); adoptLineupButton.setEnabled(false); buttonPanel.add(adoptLineupButton); simulateMatchButton = new JButton(ThemeManager.getIcon(HOIconName.SIMULATEMATCH)); simulateMatchButton.setToolTipText(HOVerwaltung.instance().getLanguageString("Simulate")); simulateMatchButton.setPreferredSize(new Dimension(24, 24)); simulateMatchButton.setEnabled(false); buttonPanel.add(simulateMatchButton); mainpanel.add(buttonPanel, BorderLayout.SOUTH); return mainpanel; } /** * Initialise matches panel. */ private Component initMatchesTable() { ImagePanel panel = new ImagePanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); gameSelectionFilter = new JComboBox<>(matchesTypeCBItems); Helper.setComboBoxFromID(gameSelectionFilter, UserParameter.instance().spieleFilter); gameSelectionFilter.setFont(gameSelectionFilter.getFont().deriveFont(Font.BOLD)); panel.add(gameSelectionFilter); // Add Match Location filtering ======= var jpMatchLocation = new JPanel(new BorderLayout()); jpMatchLocation.add(getMatchesLocationButtonsPanel()); panel.add(jpMatchLocation); // Matches tab =================================== matchesTable = new MatchesTable(UserParameter.instance().spieleFilter); matchesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scrollpane = new JScrollPane(matchesTable); // Statistics tab =================================== matchesOverviewTable = new MatchesOverviewTable(UserParameter.instance().spieleFilter); JScrollPane scrollpane1 = new JScrollPane(matchesOverviewTable); JPanel matchesOverviewPanel = new JPanel(new BorderLayout()); matchesOverviewPanel.add(scrollpane1, BorderLayout.SOUTH); // Statistics Goals tab =================================== matchesHighlightsTable = new MatchesHighlightsTable(UserParameter.instance().spieleFilter); JScrollPane scrollpane3 = new JScrollPane(matchesHighlightsTable); JTabbedPane pane = new JTabbedPane(); HOVerwaltung hov = HOVerwaltung.instance(); pane.addTab(hov.getLanguageString("Spiele"), scrollpane); pane.addTab( hov.getLanguageString("Statistik") + " (" + hov.getLanguageString("SerieAuswaertsSieg") + "-" + hov.getLanguageString("SerieAuswaertsUnendschieden") + "-" + hov.getLanguageString("SerieAuswaertsNiederlage") + ")", matchesOverviewPanel); pane.addTab(hov.getLanguageString("Statistik") + " (" + hov.getLanguageString("Tore") + ")", scrollpane3); panel.add(pane); return panel; } @NotNull private JPanel getMatchesLocationButtonsPanel() { JRadioButton all = new JRadioButton(MatchLocation.getText(MatchLocation.ALL) + " ", MatchLocation.ALL == UserParameter.instance().matchLocation); all.addChangeListener(e -> refreshOnButtonSelected(e, MatchLocation.ALL)); JRadioButton home = new JRadioButton(MatchLocation.getText(MatchLocation.HOME) + " ", MatchLocation.HOME == UserParameter.instance().matchLocation); home.addChangeListener(e -> refreshOnButtonSelected(e, MatchLocation.HOME)); JRadioButton away = new JRadioButton(MatchLocation.getText(MatchLocation.AWAY) + " ", MatchLocation.AWAY == UserParameter.instance().matchLocation); away.addChangeListener(e -> refreshOnButtonSelected(e, MatchLocation.AWAY)); JRadioButton neutral = new JRadioButton(MatchLocation.getText(MatchLocation.NEUTRAL) + " ", MatchLocation.NEUTRAL == UserParameter.instance().matchLocation); neutral.addChangeListener(e -> refreshOnButtonSelected(e, MatchLocation.NEUTRAL)); ButtonGroup matchesLocationButtons = new ButtonGroup(); matchesLocationButtons.add(all); matchesLocationButtons.add(home); matchesLocationButtons.add(away); matchesLocationButtons.add(neutral); JPanel matchesLocationButtonsPanel = new JPanel(); matchesLocationButtonsPanel.setLayout(new BoxLayout(matchesLocationButtonsPanel, BoxLayout.X_AXIS)); matchesLocationButtonsPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); JLabel label = new JLabel(getTranslation("ls.module.lineup.matchlocation.label") + ": "); label.setFont(new Font(this.getFont().getFontName(), Font.BOLD, this.getFont().getSize())); matchesLocationButtonsPanel.add(label); matchesLocationButtonsPanel.add(all); matchesLocationButtonsPanel.add(home); matchesLocationButtonsPanel.add(away); matchesLocationButtonsPanel.add(neutral); return matchesLocationButtonsPanel; } private void refreshOnButtonSelected(ChangeEvent e, MatchLocation selectedLocation) { if (((JRadioButton) e.getSource()).isSelected()) { UserParameter.instance().matchLocation = selectedLocation; doReInit(); } } private void newSelectionInform() { final int row = matchesTable.getSelectedRow(); if (row > -1) { // Selektiertes Spiel des Models holen und alle 3 Panel informieren MatchKurzInfo info = ((MatchesColumnModel) matchesTable.getSorter().getModel()) .getMatch((int) ((ColorLabelEntry) matchesTable.getSorter().getValueAt(row, 7)) .getNumber()); this.matchesModel.setMatch(info); updateButtons(); Matchdetails details = this.matchesModel.getDetails(); if (details == null || details.getMatchID() < 0 || info.getMatchStatus() != MatchKurzInfo.FINISHED) { aufstellungHeimPanel.clearAll(); aufstellungGastPanel.clearAll(); } else { aufstellungHeimPanel.refresh(info, info.getHomeTeamID()); aufstellungGastPanel.refresh(info, info.getGuestTeamID()); } } else { this.matchesModel.setMatch(null); // Alle Panels zurücksetzen reloadMatchButton.setEnabled(false); deleteButton.setEnabled(false); adoptLineupButton.setEnabled(false); simulateMatchButton.setEnabled(false); aufstellungHeimPanel.clearAll(); aufstellungGastPanel.clearAll(); } } /** * Refresh button states. */ private void updateButtons() { deleteButton.setEnabled(true); simulateMatchButton.setEnabled(true); var gameFinishTime = matchesModel.getMatch().getMatchSchedule().plus(3, ChronoUnit.HOURS); //assuming 3 hours to make sure the game is finished boolean gameFinished = matchesModel.getMatch().getMatchStatus() == MatchKurzInfo.FINISHED || gameFinishTime.isBefore(HODateTime.now()) ; reloadMatchButton.setEnabled(gameFinished); if (matchesModel.getMatch().getMatchStatus() == MatchKurzInfo.FINISHED) { final int teamid = HOVerwaltung.instance().getModel().getBasics().getTeamId(); adoptLineupButton.setEnabled((matchesModel.getMatch().getHomeTeamID() == teamid) || (matchesModel.getMatch().getGuestTeamID() == teamid)); } else { adoptLineupButton.setEnabled(false); } } }
ho-dev/HattrickOrganizer
src/main/java/module/matches/MatchesPanel.java
46,055
/* * This file is part of LeagueLib. * LeagueLib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LeagueLib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LeagueLib. If not, see <http://www.gnu.org/licenses/>. */ package com.achimala.leaguelib.models; public enum LeagueMatchmakingQueue { NONE, BOT, BOT_3x3, NORMAL, NORMAL_3x3, ODIN_UNRANKED, RANKED_SOLO_5x5, RANKED_TEAM_3x3, RANKED_TEAM_5x5, ARAM_UNRANKED_5x5, ONEFORALL_5x5 }
achimala/leaguelib
src/com/achimala/leaguelib/models/LeagueMatchmakingQueue.java
46,056
/* * Copyright (c) 2018. Aberic - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.dao.entity; import com.gitee.sunchenbin.mybatis.actable.annotation.Column; import com.gitee.sunchenbin.mybatis.actable.annotation.Table; import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * 作者:Aberic on 2018/6/27 21:15 * 邮箱:abericyang@gmail.com */ @Setter @Getter @ToString @Table(name = "fns_orderer") public class Orderer { @Column(name = "id",type = MySqlTypeConstant.INT,length = 9,isKey = true,isAutoIncrement = true) private int id; // required @Column(name = "name",type = MySqlTypeConstant.VARCHAR,length = 128) private String name; // required @Column(name = "location",type = MySqlTypeConstant.VARCHAR,length = 256) private String location; // required @Column(name = "server_crt_path",type = MySqlTypeConstant.VARCHAR,length = 512) private String serverCrtPath; @Column(name = "client_cert_path",type = MySqlTypeConstant.VARCHAR,length = 512) private String clientCertPath; @Column(name = "client_key_path",type = MySqlTypeConstant.VARCHAR,length = 512) private String clientKeyPath; @Column(name = "org_id",type = MySqlTypeConstant.INT,length = 9) private int orgId; // required @Column(name = "date",type = MySqlTypeConstant.VARCHAR,length = 14) private String date; // required private String leagueName; private String orgName; // required }
aberic/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/dao/entity/Orderer.java
46,057
/* * Copyright (c) 2018. Aberic - aberic@qq.com - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.service; import cn.aberic.fabric.dao.entity.League; import cn.aberic.fabric.dao.entity.Org; import java.util.List; /** * 作者:Aberic on 2018/6/27 22:07 * 邮箱:abericyang@gmail.com */ public interface OrgService { int add(Org org); int update(Org org); List<Org> listAll(); List<Org> listById(int id); Org get(int id); int countById(int id); int count(); int delete(int id); List<League> listAllLeague(); }
aberic/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/service/OrgService.java
46,058
/* * Copyright (c) 2018. Aberic - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.dao.entity; import com.gitee.sunchenbin.mybatis.actable.annotation.Column; import com.gitee.sunchenbin.mybatis.actable.annotation.Table; import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * 作者:Aberic on 2018/6/27 21:15 * 邮箱:abericyang@gmail.com */ @Setter @Getter @ToString @Table(name = "fns_channel") public class Channel { @Column(name = "id",type = MySqlTypeConstant.INT,length = 9,isKey = true,isAutoIncrement = true) private int id; // required @Column(name = "name",type = MySqlTypeConstant.VARCHAR,length = 128) private String name; // required @Column(name = "block_listener",type = MySqlTypeConstant.INT,length = 1) private boolean blockListener; // required @Column(name = "callback_location",type = MySqlTypeConstant.VARCHAR,length = 128) private String callbackLocation; // required @Column(name = "peer_id",type = MySqlTypeConstant.INT,length = 9) private int peerId; // required @Column(name = "height",type = MySqlTypeConstant.INT,length = 9) private int height; @Column(name = "date",type = MySqlTypeConstant.VARCHAR,length = 14) private String date; // optional private String peerName; // optional private String orgName; // optional private String leagueName; // optional private int chaincodeCount; // optional }
aberic/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/dao/entity/Channel.java
46,059
package data.hl; import data.Rules; import data.values.Penalties; import java.awt.*; /** * This class sets attributes given by the humanoid-league rules. * * @author Michel-Zen */ public class HLSim extends Rules { public HLSim() { /** The league´s name this rules are for. */ leagueName = "HL Simulation KidSize"; /** The league´s directory name with it´s teams and icons. */ leagueDirectory = "hl_sim_kid"; /** How many robots are in a team. */ teamSize = 4; /** How many robots of each team may play at one time. */ robotsPlaying = 4; /** The Java Colors the left and the right team starts with. */ teamColor = new Color[] {Color.BLUE, Color.RED}; /** The name of the colors. */ teamColorName = new String[] {"Blue","Red"}; /** If the colors change automatically. */ colorChangeAuto = false; /** If the clock may stop in certain states (Ready, Set) in a play-off game. */ playOffTimeStop = false; /** Time in seconds one half is long. */ halfTime = 10*60; /** Time in seconds the ready state is long. */ readyTime = 45; /** Time in seconds between first and second half. */ pauseTime = 0; /** If left and right side may both have the first kickoff. */ kickoffChoice = true; /** Time in seconds the ball is blocked after kickoff. */ kickoffTime = 10; /** Time in seconds the ball is blocked after a game interruption was executed. */ blockedAfterGameInterruption = 10; /** Time in seconds before a global game stuck can be called. */ minDurationBeforeStuck = 2*60; /** The number of seconds switching to Playing is delayed. */ delayedSwitchToPlaying = 0; /** If there is an overtime before penalty-shoot in a play-off game. */ overtime = true; /** Time in seconds one overtime half is long. */ overtimeTime = 5*60; /** If the game starts with penalty-shoots. */ startWithPenalty = false; /** Time in seconds between second half and penalty shoot. */ pausePenaltyShootOutTime = 0; /** If there can be a penalty-shoot retry. */ penaltyShotRetries = true; /** Time in seconds one penalty shoot is long. */ penaltyShotTime = 1*60; /** If there is a sudden-death. */ suddenDeath = false; /** Time in seconds one penalty shoot is long in sudden-death. */ penaltyShotTimeSuddenDeath = 1*60; // does not matter /** Number of penalty-shoots for each team when a half has 10minutes. */ numberOfPenaltyShotsShort = 5; /** Number of penalty-shoots for each team after full 10minutes playing. */ numberOfPenaltyShotsLong = 5; /** Time in seconds to increment penalties. */ penaltyIncreaseTime = 0; /** Whether the penalty count is reset on halftime */ resetPenaltyCountOnHalftime = true; /** Whether the ejected robots are reset on halftime */ resetEjectedRobotsOnHalftime = true; /** Whether penalties can be removed before the penalty time has passed. */ allowEarlyPenaltyRemoval = true; /** Penalty that players get when they substitute another player. */ substitutePenalty = Penalties.NONE; /** if robots should return from penalties when the game state changes. */ returnRobotsInGameStoppages = false; /** Time in seconds one team has as timeOut. */ timeOutTime = 0; /** One time-out per half? */ timeOutPerHalf = true; /** On how many pushings is a robot ejected. */ pushesToEjection = new int[] {}; /** Defines if the option for a referee timeout is available */ isRefereeTimeoutAvailable = true; /** How long the referee timeout is **/ refereeTimeout = 10*60; /** Defines if coach is available */ isCoachAvailable = false; /** Allowed to compensate for lost time? */ lostTime = false; /** If true, the drop-in player competition is active */ dropInPlayerMode = false; /** If true, the game controller should drop broadcast-messages */ dropBroadcastMessages = false; /** Background Side **/ backgroundSide = new String[][]{ { "robot_left_blue.png", "robot_left_red.png", }, { "robot_right_blue.png", "robot_right_red.png", } }; /** The time a team has to prepare for the free kick **/ game_interruption_preparation_time = 30; /** The time a team has to prepare for the penalty kick **/ penalty_kick_preparation_time = 30; /** The time an opponent is guaranteed to move away from the ball in preparation phase **/ game_interruption_minimal_ready_time = 15; } }
01rfcberlin/GameController
src/data/hl/HLSim.java
46,060
package com.wss.amd.note; import com.wss.amd.note.designpattern.adapter.classs.Dc5V; import com.wss.amd.note.designpattern.adapter.classs.Dc5VAdapter; import com.wss.amd.note.designpattern.adapter.obj.SixiDumplings; import com.wss.amd.note.designpattern.adapter.obj.SteamedBunsAdapter; import com.wss.amd.note.designpattern.bridge.Circle; import com.wss.amd.note.designpattern.bridge.Rectangle; import com.wss.amd.note.designpattern.bridge.Shape; import com.wss.amd.note.designpattern.bridge.pen.GreenPen; import com.wss.amd.note.designpattern.bridge.pen.RedPen; import com.wss.amd.note.designpattern.builder.TestDialog; import com.wss.amd.note.designpattern.combination.Employee; import com.wss.amd.note.designpattern.command.WaiterInvoker; import com.wss.amd.note.designpattern.command.command.NoodleCommand; import com.wss.amd.note.designpattern.command.command.RiceCommand; import com.wss.amd.note.designpattern.command.command.StirFryCommand; import com.wss.amd.note.designpattern.decorator.Egg; import com.wss.amd.note.designpattern.decorator.GreenPepperShreddedMeat; import com.wss.amd.note.designpattern.decorator.PotatoesBurnFireSirloin; import com.wss.amd.note.designpattern.decorator.Vegetables; import com.wss.amd.note.designpattern.decorator.base.Food; import com.wss.amd.note.designpattern.decorator.base.Noodle; import com.wss.amd.note.designpattern.decorator.base.Rice; import com.wss.amd.note.designpattern.facade.FoodMaker; import com.wss.amd.note.designpattern.fracory.abstractfactory.AssembleComputer; import com.wss.amd.note.designpattern.fracory.abstractfactory.interfaces.IComputerFactory; import com.wss.amd.note.designpattern.fracory.abstractfactory.interfaces.impl.computer.HaweiComputerFactoryFactory; import com.wss.amd.note.designpattern.fracory.abstractfactory.interfaces.impl.computer.IntelComputerFactoryFactory; import com.wss.amd.note.designpattern.fracory.abstractfactory.interfaces.impl.computer.MacComputerFactoryFactory; import com.wss.amd.note.designpattern.fracory.normalfactory.ConfigFactory; import com.wss.amd.note.designpattern.fracory.simplefactory.SimpleFactory; import com.wss.amd.note.designpattern.fracory.simplefactory.config.IConfig; import com.wss.amd.note.designpattern.interpreter.GameEnvironment; import com.wss.amd.note.designpattern.interpreter.GameUser; import com.wss.amd.note.designpattern.iterator.Iterator; import com.wss.amd.note.designpattern.iterator.UserAggregate; import com.wss.amd.note.designpattern.mediator.Colleague; import com.wss.amd.note.designpattern.mediator.ConcreteColleague1; import com.wss.amd.note.designpattern.mediator.ConcreteColleague2; import com.wss.amd.note.designpattern.mediator.ConcreteMediator; import com.wss.amd.note.designpattern.mediator.Mediator; import com.wss.amd.note.designpattern.memorandum.Caretaker; import com.wss.amd.note.designpattern.memorandum.Originator; import com.wss.amd.note.designpattern.observer.BinaryObserver; import com.wss.amd.note.designpattern.observer.HexaObserver; import com.wss.amd.note.designpattern.observer.Subject; import com.wss.amd.note.designpattern.proxy.User; import com.wss.amd.note.designpattern.proxy.UserService; import com.wss.amd.note.designpattern.proxy.UserServiceProxy; import com.wss.amd.note.designpattern.responsibility.LocationRuleHandler; import com.wss.amd.note.designpattern.responsibility.NewUserRuleHandler; import com.wss.amd.note.designpattern.responsibility.ParticipantsRuleHandler; import com.wss.amd.note.designpattern.responsibility.People; import com.wss.amd.note.designpattern.state.InvisibleState; import com.wss.amd.note.designpattern.state.OnLineState; import com.wss.amd.note.designpattern.state.QQUser; import com.wss.amd.note.designpattern.strategy.NoodleStrategy; import com.wss.amd.note.designpattern.strategy.NoonEatWhat; import com.wss.amd.note.designpattern.strategy.RiceStrategy; import com.wss.amd.note.designpattern.template.AbsTemplateMethod; import com.wss.amd.note.designpattern.template.TemplateMethod; import com.wss.amd.note.designpattern.visitor.SetMaterial; import com.wss.amd.note.designpattern.visitor.company.ArtCompany; import com.wss.amd.note.designpattern.visitor.company.MintCompany; import com.wss.amd.note.designpattern.visitor.material.Copper; import com.wss.amd.note.designpattern.visitor.material.Paper; import com.wss.common.base.BaseApplication; import org.junit.Test; /** * Describe:测试类 * Created by 吴天强 on 2022/1/17. */ public class NoteTest { @Test public void testSimpleFactory() { //创建开发环境 IConfig devConfig = SimpleFactory.createConfig(1); //创建生产环境 IConfig proConfig = SimpleFactory.createConfig(0); } @Test public void testConfigFactory() { //普通工厂 ConfigFactory configFactory = new ConfigFactory(); IConfig config = configFactory.createConfig(); String serviceUrl = config.getServiceUrl(); } @Test public void testAbstractFactory() { //抽象工厂 IComputerFactory factory; //创建华为工厂、组装华为电脑 factory = new HaweiComputerFactoryFactory(); AssembleComputer huaweiComputer = new AssembleComputer(factory.createCPU(), factory.createHardDisk() , factory.createMainBoard()); //创建Intel工厂、组装Intel电脑 factory = new IntelComputerFactoryFactory(); AssembleComputer intelComputer = new AssembleComputer(factory.createCPU(), factory.createHardDisk() , factory.createMainBoard()); //创建苹果工厂、组装苹果电脑 factory = new MacComputerFactoryFactory(); AssembleComputer macComputer = new AssembleComputer(factory.createCPU(), factory.createHardDisk() , factory.createMainBoard()); } @Test public void testBuilderDialog() { //建造者 new TestDialog.Builder(BaseApplication.i()) .setContent("对话框内容") .setCanCancel(false) .build() .show(); } @Test public void testUserProxy() { //代理模式 UserService service = new UserServiceProxy(); User admin = service.creteAdmin(); User user = service.createUser(); } @Test public void testObjAdapter() { //测试 对象适配器 SixiDumplings sixiDumplings = new SixiDumplings(); SteamedBunsAdapter bunsAdapter = new SteamedBunsAdapter(sixiDumplings); bunsAdapter.bunsFilling(); bunsAdapter.steam(); } @Test public void testClassAdapter() { //测试类适配器 Dc5V dc5V = new Dc5VAdapter(); int i = dc5V.dc5v(); } @Test public void testBridge() { //桥梁模式 //红色的圆圈 Shape circle = new Circle(10, new RedPen()); circle.draw(); //绿色的矩形 Shape rectangle = new Rectangle(10, 10, new GreenPen()); rectangle.draw(); } @Test public void testFoodMaker() { //门面模式 FoodMaker foodMaker = new FoodMaker(); foodMaker.makeBreakfast(); foodMaker.makeLunch(); foodMaker.makeDinner(); } @Test public void testDecorator() { //餐馆来了一位小哥, 他对老板说 //老板,来米饭 Food rice = new Rice(); System.out.println(rice.getName() + ",价格:" + rice.getPrice() + "元"); //加一分土豆烧牛腩 rice = new PotatoesBurnFireSirloin(rice); System.out.println(rice.getName() + ",价格:" + rice.getPrice() + "元"); //再加个鸡蛋 rice = new Egg(rice); System.out.println(rice.getName() + ",价格:" + rice.getPrice() + "元"); System.out.println(); //餐馆又来了一位大哥,他饭量比较好,需要双份的土豆牛腩和双份的青椒肉丝以及青菜、一个鸡蛋 //老板,来双份面条 Food noodle = new Noodle(); System.out.println(noodle.getName() + ",价格:" + noodle.getPrice() + "元"); //加双份土豆牛腩 noodle = new PotatoesBurnFireSirloin(new PotatoesBurnFireSirloin(noodle)); System.out.println(noodle.getName() + ",价格:" + noodle.getPrice() + "元"); //再加双份的青椒肉丝 noodle = new GreenPepperShreddedMeat(new GreenPepperShreddedMeat(noodle)); System.out.println(noodle.getName() + ",价格:" + noodle.getPrice() + "元"); //再来青菜 noodle = new Vegetables(noodle); System.out.println(noodle.getName() + ",价格:" + noodle.getPrice() + "元"); //再来一个鸡蛋 noodle = new Egg(noodle); System.out.println(noodle.getName() + ",价格:" + noodle.getPrice() + "元"); } @Test public void testCombination() { Employee employee = new Employee("张三", "信息部"); employee.add(new Employee("李四", "信息部")); employee.add(new Employee("王五", "信息部")); System.out.println(employee.toString()); } @Test public void testStrategy() { //10个人去吃米饭 NoonEatWhat noonEatWhat = new NoonEatWhat(new RiceStrategy()); noonEatWhat.executeEat(10); //5个人去吃面条 NoonEatWhat noonEatWhat1 = new NoonEatWhat(new NoodleStrategy()); noonEatWhat1.executeEat(5); } @Test public void testObserver() { //定义主题(被观察者) Subject subject = new Subject(); //定义两个观察者 new BinaryObserver(subject); new HexaObserver(subject); //模拟数据变更,被观察者有了变化 subject.setState(22); } @Test public void testResponsibility() { People people = new People(); people.setNewUser(true); people.setLocation("上海"); people.setParticipants(222); NewUserRuleHandler newUserRuleHandler = new NewUserRuleHandler(); LocationRuleHandler locationRuleHandler = new LocationRuleHandler(); ParticipantsRuleHandler participantsRuleHandler = new ParticipantsRuleHandler(); locationRuleHandler.setSuccessor(newUserRuleHandler); participantsRuleHandler.setSuccessor(locationRuleHandler); newUserRuleHandler.apply(people); } @Test public void testAbsTemplateMethod() { AbsTemplateMethod templateMethod = new TemplateMethod(); templateMethod.templateMethod(); } @Test public void testState() { QQUser qqUser = new QQUser("人生如梦"); //隐身 InvisibleState invisibleState = new InvisibleState(); invisibleState.doAction(qqUser); System.out.println(qqUser.getName() + "当前状态:" + qqUser.getState().toString()); //上线 OnLineState onLineState = new OnLineState(); onLineState.doAction(qqUser); System.out.println(qqUser.getName() + "当前状态:" + qqUser.getState().toString()); } @Test public void testIterator() { UserAggregate<User> aggregate = new UserAggregate<>(); aggregate.add(new User("张三")); aggregate.add(new User("李四")); aggregate.add(new User("王五")); Iterator iterator = aggregate.iterator(); System.out.println("First:" + iterator.first()); System.out.println("Has next:" + iterator.hasNext()); System.out.println("Next:" + iterator.next()); System.out.println("Next:" + iterator.next()); System.out.println("Has next:" + iterator.hasNext()); } @Test public void testCommand() { //饭店对外生成了一个服务员,同时也生成了米饭、面条、炒菜三个菜单 WaiterInvoker waiterInvoker = new WaiterInvoker(new RiceCommand(), new NoodleCommand(), new StirFryCommand()); //饭店开张,来了一位顾客,选择了米饭 waiterInvoker.chooseRice(); //又继续点了一份面条 waiterInvoker.chooseNoodle(); //最后又加了一份炒菜 waiterInvoker.chooseStirFry(); } @Test public void testMemorandum() { Originator originator = new Originator(); Caretaker caretaker = new Caretaker(); originator.setState("create"); System.out.println("当前状态:" + originator.getState()); //保存当前状态到备忘录 caretaker.setMemento(originator.createMemento()); originator.setState("working"); System.out.println("当前状态:" + originator.getState()); originator.restoreMemento(caretaker.getMemento()); System.out.println("当前状态:" + originator.getState()); } @Test public void testVisitor() { //定义材料集 SetMaterial setMaterial = new SetMaterial(); //添加纸 setMaterial.add(new Paper()); //添加铜 setMaterial.add(new Copper()); //艺术公司制作工艺品 String artSet = setMaterial.accept(new ArtCompany()); System.out.println("艺术公司成果:" + artSet); //造币公司制作钞票 String mintSet = setMaterial.accept(new MintCompany()); System.out.println("造币公司成果:" + mintSet); } @Test public void testMediator() { Mediator mediator = new ConcreteMediator(); Colleague concreteColleague1 = new ConcreteColleague1(); Colleague concreteColleague2 = new ConcreteColleague2(); mediator.register(concreteColleague1); mediator.register(concreteColleague2); concreteColleague1.send(); concreteColleague2.send(); } @Test public void testInterpreter() { //假设:阵营是齐国、吴国且等级大于50的玩家只能参加普通副本《捉泥鳅》, //其他的则可以参加高级副本《鹊桥仙》 //定义用户环境 GameEnvironment gameEnvironment = new GameEnvironment(); //第一位 来自齐国的66级的李逍遥 gameEnvironment.operation(new GameUser("李逍遥", 66, "齐国")); //第二位 来自楚国的51级的张小凡 gameEnvironment.operation(new GameUser("张小凡", 51, "楚国")); //第三位 来自燕国的11级的高渐离 gameEnvironment.operation(new GameUser("高渐离", 11, "燕国")); } }
wutq/AndroidModuleDemo
app/src/main/java/com/wss/amd/note/NoteTest.java
46,061
/* * Copyright (c) 2018. Aberic - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.dao.entity; import com.gitee.sunchenbin.mybatis.actable.annotation.Column; import com.gitee.sunchenbin.mybatis.actable.annotation.Table; import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * 作者:Aberic on 2018/6/27 21:16 * 邮箱:abericyang@gmail.com */ @Setter @Getter @ToString @Table(name = "fns_chaincode") public class Chaincode { @Column(name = "id",type = MySqlTypeConstant.INT,length = 9,isKey = true,isAutoIncrement = true) private int id; // required @Column(name = "name",type = MySqlTypeConstant.VARCHAR,length = 32) private String name; // required @Column(name = "source",type = MySqlTypeConstant.VARCHAR,length = 128) private String source; // optional @Column(name = "path",type = MySqlTypeConstant.VARCHAR,length = 128) private String path; // optional @Column(name = "policy",type = MySqlTypeConstant.VARCHAR,length = 128) private String policy; // optional @Column(name = "version",type = MySqlTypeConstant.VARCHAR,length = 45) private String version; // required @Column(name = "proposal_wait_time",type = MySqlTypeConstant.INT,length = 9) private int proposalWaitTime = 90000; // required @Column(name = "channel_id",type = MySqlTypeConstant.INT,length = 9) private int channelId; // required @Column(name = "cc",type = MySqlTypeConstant.VARCHAR,length = 128) private String cc; // optional @Column(name = "chaincode_event_listener",type = MySqlTypeConstant.INT,length = 1) private boolean chaincodeEventListener; // required @Column(name = "callback_location",type = MySqlTypeConstant.VARCHAR,length = 128) private String callbackLocation; // required @Column(name = "events",type = MySqlTypeConstant.VARCHAR,length = 512) private String events; @Column(name = "date",type = MySqlTypeConstant.VARCHAR,length = 14) private String date; // optional private String flag; private String channelName; // optional private String peerName; // optional private String orgName; // optional private String leagueName; // optional }
aberic/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/dao/entity/Chaincode.java
46,062
package com.company.mediator.section2; import java.util.Random; /** * @author cbf4Life cbf4life@126.com * I'm glad to share my knowledge with you all. * 销售 */ public class Sale extends AbstractColleague { public Sale(AbstractMediator _mediator){ super(_mediator); } //销售IBM型号的电脑 public void sellIBMComputer(int number){ super.mediator.execute("sale.sell", number); System.out.println("销售IBM电脑"+number+"台"); } //反馈销售情况,0——100之间变化,0代表根本就没人卖,100代表非常畅销,出1一个卖一个 public int getSaleStatus(){ Random rand = new Random(System.currentTimeMillis()); int saleStatus = rand.nextInt(100); System.out.println("IBM电脑的销售情况为:"+saleStatus); return saleStatus; } //折价处理 public void offSale(){ super.mediator.execute("sale.offsell"); } }
nivance/DPModel
src/dp/com/company/mediator/section2/Sale.java
46,063
/* Copyright (c) 2008~2009, Justin R. Bengtson (poopshotgun@yahoo.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Justin R. Bengtson nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ssw.gui; import Force.Unit; import IO.MTFWriter; import IO.Utils; import java.awt.Cursor; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import javax.swing.SwingWorker; import components.Mech; import filehandlers.*; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import list.*; import list.view.*; import ssw.filehandlers.MTFReader; import ssw.print.Printer; public class dlgOpen extends javax.swing.JFrame implements PropertyChangeListener { private ifMechForm parent; private UnitList list = new UnitList(); private Media media = new Media(); private String dirPath = ""; private String NL = ""; private String msg = ""; private abView twView = new tbTotalWarfareView(); private abView bfView = new tbBattleForceView(); private abView compView = new tbTotalWarfareCompact(); private abView chatView = new tbChatInformation(); private abView currentView = twView; private boolean cancelledListDirSelection = false; public int Requestor = SSW; public static final int SSW = 0, FORCE = 1; /** Creates new form dlgOpen */ public dlgOpen(java.awt.Frame parent, boolean modal) { initComponents(); ImageIcon icon = new ImageIcon(super.getClass().getResource("/ssw/Images/appicon.png")); super.setIconImage(icon.getImage()); this.parent = (ifMechForm) parent; prgResaving.setVisible(false); cmbTech.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Any Tech", "Clan", "Inner Sphere", "Mixed" })); cmbEra.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Any Era", "Age of War/Star League", "Succession Wars", "Clan Invasion", "Dark Ages", "All Eras (non-canon)" })); cmbRulesLevel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Any Level", "Introductory", "Tournament Legal", "Advanced Rules", "Experimental Tech", "Era Specific" })); cmbType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Any Type", "BattleMech", "IndustrialMech", "Primitive BattleMech", "Primitive IndustrialMech" })); cmbMotive.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Any Motive", "Biped", "Quad" })); NL = System.getProperty( "line.separator" ); } private void LoadMech() { switch ( Requestor ) { case SSW: LoadMechIntoSSW(); break; case FORCE: btnAdd2ForceActionPerformed(null); this.setVisible(false); parent.GetForceDialogue().setVisible(true); break; default: LoadMechIntoSSW(); } } private void LoadMechIntoSSW() { UnitListData Data = (UnitListData)((abView) tblMechData.getModel()).Get( tblMechData.convertRowIndexToModel( tblMechData.getSelectedRow() ) ); try { MechReader read = new MechReader(); Mech m = read.ReadMech( list.getDirectory() + Data.getFilename(), parent.GetData() ); if (Data.isOmni()) { m.SetCurLoadout( Data.getConfig() ); } parent.setMech( m ); parent.GetPrefs().put( "LastOpenDirectory", list.getDirectory() + Data.getFilename().substring( 0, Data.getFilename().lastIndexOf( File.separator ) + 1 ) ); parent.GetPrefs().put( "LastOpenFile", Data.getFilename().substring( Data.getFilename().lastIndexOf( File.separator ) + 1 ) ); parent.GetMech().SetChanged( false ); tblMechData.clearSelection(); //setupList(list, false); this.setVisible(false); } catch ( Exception e ) { Media.Messager( (javax.swing.JFrame) parent, e.getMessage() ); } } private void Calculate() { txtSelected.setText("0 Units Selected for 0 BV and 0 C-Bills"); int BV = 0; double Cost = 0; int[] rows = tblMechData.getSelectedRows(); for ( int i=0; i < rows.length; i++ ) { UnitListData data = (UnitListData)((abView) tblMechData.getModel()).Get( tblMechData.convertRowIndexToModel( rows[i] ) ); BV += data.getBV(); Cost += data.getCost(); } txtSelected.setText(rows.length + " Units Selected for " + String.format("%,d", BV) + " BV and " + String.format("%,.2f", Cost) + " C-Bills"); } public void LoadList() { LoadList(true); } public void LoadList(boolean useIndex) { this.lblStatus.setText("Loading Mechs..."); this.txtSelected.setText("0 Units Selected for 0 BV and 0 C-Bills"); this.tblMechData.setModel(new UnitList()); if (dirPath.isEmpty()) { dirPath = parent.GetPrefs().get("ListPath", parent.GetPrefs().get( "LastOpenDirectory", "" ) ); if ( dirPath.isEmpty() && this.isVisible() && !cancelledListDirSelection ) { dlgSSWFiles dFiles = new dlgSSWFiles(this, true); dFiles.setLocationRelativeTo(this); dFiles.setVisible(true); if ( dFiles.result ) { dirPath = media.GetDirectorySelection(this, "", "Select SSW File Directory"); parent.GetPrefs().put("ListPath", dirPath); if ( dirPath.isEmpty() ) { cancelledListDirSelection = true; this.setVisible( false ); } } else { cancelledListDirSelection = true; this.setVisible( false ); } dFiles.dispose(); } } this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); list = new UnitList(dirPath, useIndex); if (list.Size() > 0) { setupList(list, true); } String displayPath = dirPath; this.lblStatus.setText(list.Size() + " Mechs loaded from " + displayPath); this.lblStatus.setToolTipText(dirPath); spnMechTable.getVerticalScrollBar().setValue(0); this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } private void setupList(UnitList mechList, boolean forceSort) { ListFilter fileFilter = new ListFilter(); fileFilter.setExtension(".ssw"); currentView.list = mechList.Filter(fileFilter); tblMechData.setModel(currentView); currentView.setupTable(tblMechData); //tblMechData.setModel(mechList); lblShowing.setText("Showing " + mechList.Size() + " of " + list.Size()); } private void checkSelection() { if ( tblMechData.getSelectedRowCount() > 0 ) { Calculate(); btnOpen.setEnabled(true); btnPrint.setEnabled(true); btnAdd2Force.setEnabled(true); } else { btnOpen.setEnabled(false); btnPrint.setEnabled(false); btnAdd2Force.setEnabled(false); txtSelected.setText("0 Units Selected for 0 BV and 0 C-Bills"); } } private void batchUpdateMechs() { //String msg = ""; prgResaving.setValue(0); prgResaving.setVisible(true); int Response = javax.swing.JOptionPane.showConfirmDialog(this, "This will open and re-save each file in the current directory so that all files are updated with current BV and Cost calculations.\nThis process could take a few minutes, are you ready?", "Batch Mech Processing", javax.swing.JOptionPane.YES_NO_OPTION); if (Response == javax.swing.JOptionPane.YES_OPTION) { msg = ""; setCursor( Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR ) ); try { Resaver Saving = new Resaver( this ); Saving.addPropertyChangeListener( this ); Saving.execute(); } catch( Exception e ) { // fatal error. let the user know Media.Messager( this, "A fatal error occured while processing the 'Mechs:\n" + e.getMessage() ); e.printStackTrace(); } } else { prgResaving.setVisible(false); } } private void batchUpdateMTFs() { prgResaving.setValue(0); prgResaving.setVisible(true); int Response = javax.swing.JOptionPane.showConfirmDialog(this, "This will open every file in the current directory and all subdirectories and create an MTF file.\nThis process could take a few minutes, are you ready?", "Batch Mech Processing", javax.swing.JOptionPane.YES_NO_OPTION); if (Response == javax.swing.JOptionPane.YES_OPTION) { msg = ""; setCursor( Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR ) ); try { MTFSaver Saving = new MTFSaver( this ); Saving.addPropertyChangeListener( this ); Saving.execute(); } catch( Exception e ) { // fatal error. let the user know Media.Messager( this, "A fatal error occured while processing the 'Mechs:\n" + e.getMessage() ); e.printStackTrace(); } } else { prgResaving.setVisible(false); } } private void setTooltip( UnitListData data ) { //spnMechTable.setToolTipText( data.getInfo() ); try { String[] dirs = data.getFilename().split("\\\\"); String shortPath = ""; if ( dirs.length > 3) { for (int i = dirs.length-1; i >= dirs.length-3; i--) { shortPath = "\\" + dirs[i] + shortPath; } } txtSelected.setText(data.getInfo() + " (" + shortPath + ")"); } catch ( Exception e ) { //do nothing } } public void propertyChange( PropertyChangeEvent e ) { prgResaving.setValue( ((SwingWorker<Void,Void>) e.getSource()).getProgress() ); } private class Resaver extends SwingWorker<Void,Void> { dlgOpen Owner; int filesUpdated = 0, totalFileCount = 0; public Resaver( dlgOpen owner ) { Owner = owner; } @Override public void done() { setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR ) ); if( msg.length() > 0 ) { dlgTextExport Message = new dlgTextExport( Owner, true, msg ); Message.setLocationRelativeTo( Owner ); Message.setVisible( true ); } else { Media.Messager( Owner, filesUpdated + " Files Updated. Reloading list next." ); } prgResaving.setVisible(false); prgResaving.setValue( 0 ); LoadList(false); } @Override protected Void doInBackground() throws Exception { MechReader read = new MechReader(); MechWriter writer = new MechWriter(); File FileList = new File(dirPath); totalFileCount = Utils.countFilesInDirectory(FileList, ".ssw"); try { processDir( FileList, read, writer ); } catch ( IOException ie ) { System.out.println(ie.getMessage()); throw new Exception(msg); } catch ( Exception e ) { throw e; } return null; } private void processDir( File directory, MechReader read, MechWriter writer ) throws IOException { File[] files = directory.listFiles(); for ( int i=0; i < files.length; i++ ) { if ( files[i].isFile() && files[i].getCanonicalPath().endsWith(".ssw") ) { processFile( files[i], read, writer ); int progress = ((int) (( ((double) filesUpdated + 1) / (double) totalFileCount ) * 100.0 ) ); setProgress( progress ); } else if ( files[i].isDirectory() ) { processDir( files[i], read, writer ); } } } private void processFile( File file, MechReader read, MechWriter writer ) throws IOException { try { Mech m = read.ReadMech( file.getCanonicalPath(), parent.GetData() ); // save the mech to XML in the current location writer.setMech(m); try { writer.WriteXML( file.getCanonicalPath() ); filesUpdated += 1; } catch( IOException e ) { msg += "Could not load the following file(s):" + NL; msg += file.getCanonicalPath() + NL + NL; } } catch ( Exception e ) { // log the error msg += file.getCanonicalPath() + NL; if( e.getMessage() == null ) { StackTraceElement[] trace = e.getStackTrace(); for( int j = 0; j < trace.length; j++ ) { msg += trace[j].toString() + NL; } msg += NL; } else { msg += e.getMessage() + NL + NL; } } } } private class MTFSaver extends SwingWorker<Void,Void> { dlgOpen Owner; int filesUpdated = 0, totalFileCount = 0; public MTFSaver( dlgOpen owner ) { Owner = owner; } @Override public void done() { setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR ) ); if( msg.length() > 0 ) { dlgTextExport Message = new dlgTextExport( Owner, true, msg ); Message.setLocationRelativeTo( Owner ); Message.setVisible( true ); } else { Media.Messager( Owner, filesUpdated + " Files Updated. Reloading list next." ); } prgResaving.setVisible(false); prgResaving.setValue( 0 ); LoadList(false); } @Override protected Void doInBackground() throws Exception { MechReader read = new MechReader(); MTFWriter writer = new MTFWriter(); File FileList = new File(dirPath); totalFileCount = Utils.countFilesInDirectory(FileList, ".ssw"); try { processDir( FileList, read, writer ); } catch ( IOException ie ) { System.out.println(ie.getMessage()); throw new Exception(msg); } catch ( Exception e ) { throw e; } return null; } private void processDir( File directory, MechReader read, MTFWriter writer ) throws IOException { File[] files = directory.listFiles(); for ( int i=0; i < files.length; i++ ) { if ( files[i].isFile() && files[i].getCanonicalPath().endsWith(".ssw") ) { processFile( files[i], read, writer ); int progress = ((int) (( ((double) filesUpdated + 1) / (double) totalFileCount ) * 100.0 ) ); setProgress( progress ); } else if ( files[i].isDirectory() ) { processDir( files[i], read, writer ); } } } private void processFile( File file, MechReader read, MTFWriter writer ) throws IOException { try { Mech m = read.ReadMech( file.getCanonicalPath(), parent.GetData() ); // save the mech to XML in the current location writer.setMech(m); try { writer.WriteMTF( file.getCanonicalPath().replace(".ssw", ".mtf") ); filesUpdated += 1; } catch( IOException e ) { msg += "Could not load the following file(s):" + NL; msg += file.getCanonicalPath() + NL + NL; } } catch ( Exception e ) { // log the error msg += file.getCanonicalPath() + NL; if( e.getMessage() == null ) { StackTraceElement[] trace = e.getStackTrace(); for( int j = 0; j < trace.length; j++ ) { msg += trace[j].toString() + NL; } msg += NL; } else { msg += e.getMessage() + NL + NL; } } } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { txtSelected = new javax.swing.JLabel(); tlbActions = new javax.swing.JToolBar(); btnOpen = new javax.swing.JButton(); jSeparator4 = new javax.swing.JToolBar.Separator(); btnChangeDir = new javax.swing.JButton(); btnPrint = new javax.swing.JButton(); btnAdd2Force = new javax.swing.JButton(); btnViewForce = new javax.swing.JButton(); btnExport = new javax.swing.JButton(); jSeparator1 = new javax.swing.JToolBar.Separator(); btnOptions = new javax.swing.JButton(); btnRefresh = new javax.swing.JButton(); jSeparator2 = new javax.swing.JToolBar.Separator(); btnMagic = new javax.swing.JButton(); jSeparator3 = new javax.swing.JToolBar.Separator(); btnMTF = new javax.swing.JButton(); jSeparator6 = new javax.swing.JToolBar.Separator(); lblForce = new javax.swing.JLabel(); jSeparator5 = new javax.swing.JToolBar.Separator(); cmbView = new javax.swing.JComboBox(); spnMechTable = new javax.swing.JScrollPane(); tblMechData = new javax.swing.JTable(); pnlFilters = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); btnFilter = new javax.swing.JButton(); btnClearFilter = new javax.swing.JButton(); jPanel14 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); lblMinMP = new javax.swing.JLabel(); cmbMinMP = new javax.swing.JComboBox(); jPanel3 = new javax.swing.JPanel(); cmbEra = new javax.swing.JComboBox(); lblEra = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); lblMotive = new javax.swing.JLabel(); cmbMotive = new javax.swing.JComboBox(); jPanel2 = new javax.swing.JPanel(); cmbTech = new javax.swing.JComboBox(); lblTech = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); lblLevel = new javax.swing.JLabel(); cmbRulesLevel = new javax.swing.JComboBox(); jPanel5 = new javax.swing.JPanel(); lblType = new javax.swing.JLabel(); cmbType = new javax.swing.JComboBox(); jPanel15 = new javax.swing.JPanel(); jPanel13 = new javax.swing.JPanel(); lblName = new javax.swing.JLabel(); txtName = new javax.swing.JTextField(); jPanel12 = new javax.swing.JPanel(); txtSource = new javax.swing.JTextField(); lblSource = new javax.swing.JLabel(); jPanel9 = new javax.swing.JPanel(); txtMaxBV = new javax.swing.JTextField(); lblBV = new javax.swing.JLabel(); txtMinBV = new javax.swing.JTextField(); jPanel10 = new javax.swing.JPanel(); lblTonnage1 = new javax.swing.JLabel(); txtMinYear = new javax.swing.JTextField(); txtMaxYear = new javax.swing.JTextField(); jPanel8 = new javax.swing.JPanel(); lblTonnage = new javax.swing.JLabel(); txtMaxTon = new javax.swing.JTextField(); txtMinTon = new javax.swing.JTextField(); jPanel11 = new javax.swing.JPanel(); txtMinCost = new javax.swing.JTextField(); lblCost = new javax.swing.JLabel(); txtMaxCost = new javax.swing.JTextField(); chkOmni = new javax.swing.JCheckBox(); lblStatus = new javax.swing.JLabel(); prgResaving = new javax.swing.JProgressBar(); lblShowing = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Select Mech(s)"); setMinimumSize(new java.awt.Dimension(600, 500)); addWindowFocusListener(new java.awt.event.WindowFocusListener() { public void windowGainedFocus(java.awt.event.WindowEvent evt) { formWindowGainedFocus(evt); } public void windowLostFocus(java.awt.event.WindowEvent evt) { } }); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); txtSelected.setText("0 Units Selected"); tlbActions.setFloatable(false); tlbActions.setRollover(true); btnOpen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ssw/Images/folder-open-mech.png"))); // NOI18N btnOpen.setToolTipText("Open Mech"); btnOpen.setEnabled(false); btnOpen.setFocusable(false); btnOpen.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnOpen.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnOpen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOpenActionPerformed(evt); } }); tlbActions.add(btnOpen); tlbActions.add(jSeparator4); btnChangeDir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ssw/Images/folders.png"))); // NOI18N btnChangeDir.setToolTipText("Change Directory"); btnChangeDir.setFocusable(false); btnChangeDir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnChangeDir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnChangeDir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnChangeDirActionPerformed(evt); } }); tlbActions.add(btnChangeDir); btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ssw/Images/printer.png"))); // NOI18N btnPrint.setToolTipText("Print Selected Mechs"); btnPrint.setEnabled(false); btnPrint.setFocusable(false); btnPrint.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnPrint.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnPrint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPrintActionPerformed(evt); } }); tlbActions.add(btnPrint); btnAdd2Force.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ssw/Images/clipboard--plus.png"))); // NOI18N btnAdd2Force.setToolTipText("Add to Force List"); btnAdd2Force.setEnabled(false); btnAdd2Force.setFocusable(false); btnAdd2Force.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnAdd2Force.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnAdd2Force.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAdd2ForceActionPerformed(evt); } }); tlbActions.add(btnAdd2Force); btnViewForce.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ssw/Images/clipboard.png"))); // NOI18N btnViewForce.setToolTipText("View Force"); btnViewForce.setFocusable(false); btnViewForce.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnViewForce.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnViewForce.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnViewForceActionPerformed(evt); } }); tlbActions.add(btnViewForce); btnExport.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ssw/Images/document--arrow.png"))); // NOI18N btnExport.setToolTipText("Export List to CSV"); btnExport.setFocusable(false); btnExport.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnExport.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnExport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExportActionPerformed(evt); } }); tlbActions.add(btnExport); tlbActions.add(jSeparator1); btnOptions.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ssw/Images/gear.png"))); // NOI18N btnOptions.setToolTipText("Change Options"); btnOptions.setFocusable(false); btnOptions.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnOptions.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnOptions.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOptionsActionPerformed(evt); } }); tlbActions.add(btnOptions); btnRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ssw/Images/arrow-circle-double.png"))); // NOI18N btnRefresh.setToolTipText("Refresh Mech List"); btnRefresh.setFocusable(false); btnRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnRefresh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRefreshActionPerformed(evt); } }); tlbActions.add(btnRefresh); tlbActions.add(jSeparator2); btnMagic.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ssw/Images/wand.png"))); // NOI18N btnMagic.setToolTipText("Update Mech Files (Long Process!)"); btnMagic.setFocusable(false); btnMagic.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnMagic.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnMagic.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnMagicActionPerformed(evt); } }); tlbActions.add(btnMagic); tlbActions.add(jSeparator3); btnMTF.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ssw/Images/crown.png"))); // NOI18N btnMTF.setToolTipText("Export ALL to MTF (Long Process!)"); btnMTF.setFocusable(false); btnMTF.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnMTF.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnMTF.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnMTFActionPerformed(evt); } }); tlbActions.add(btnMTF); tlbActions.add(jSeparator6); tlbActions.add(lblForce); tlbActions.add(jSeparator5); cmbView.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Total Warfare Standard", "Total Warfare Compact", "BattleForce Information", "Chat Information" })); cmbView.setFocusable(false); cmbView.setMaximumSize(new java.awt.Dimension(139, 20)); cmbView.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbViewActionPerformed(evt); } }); tlbActions.add(cmbView); tblMechData.setAutoCreateRowSorter(true); tblMechData.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {}, {}, {}, {} }, new String [] { } )); tblMechData.setIntercellSpacing(new java.awt.Dimension(4, 4)); tblMechData.setShowVerticalLines(false); tblMechData.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tblMechDataMouseClicked(evt); } }); tblMechData.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { tblMechDataMouseMoved(evt); } }); tblMechData.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { tblMechDataKeyReleased(evt); } }); spnMechTable.setViewportView(tblMechData); pnlFilters.setBorder(javax.swing.BorderFactory.createTitledBorder("Filters")); btnFilter.setText("Filter"); btnFilter.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Filter(evt); } }); btnClearFilter.setText("Clear"); btnClearFilter.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnClearFilterFilter(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnFilter) .addComponent(btnClearFilter) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnFilter) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnClearFilter)) ); lblMinMP.setText("Min MP"); cmbMinMP.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" })); cmbMinMP.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbMinMPFilter(evt); } }); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblMinMP) .addComponent(cmbMinMP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addComponent(lblMinMP) .addGap(1, 1, 1) .addComponent(cmbMinMP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); cmbEra.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Any Era", "Age of War/Star League", "Succession Wars", "Clan Invasion", "Dark Ages", "All Eras (non-canon)" })); cmbEra.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Filter(evt); } }); lblEra.setText("Era"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cmbEra, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblEra) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(lblEra) .addGap(1, 1, 1) .addComponent(cmbEra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); lblMotive.setText("Motive Type"); cmbMotive.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Any Motive", "Biped", "Quad" })); cmbMotive.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbMotiveFilter(evt); } }); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblMotive) .addComponent(cmbMotive, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(lblMotive) .addGap(1, 1, 1) .addComponent(cmbMotive, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); cmbTech.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Any Tech", "Clan", "Inner Sphere", "Mixed" })); cmbTech.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Filter(evt); } }); lblTech.setText("Technology"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cmbTech, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblTech) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(lblTech) .addGap(0, 0, 0) .addComponent(cmbTech, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); lblLevel.setText("Rules Level"); cmbRulesLevel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Any Level", "Introductory", "Tournament Legal", "Advanced Rules", "Experimental Tech", "Era Specific" })); cmbRulesLevel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbRulesLevelFilter(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cmbRulesLevel, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblLevel) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(lblLevel) .addGap(1, 1, 1) .addComponent(cmbRulesLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); lblType.setText("Mech Type"); cmbType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Any Type", "BattleMech", "IndustrialMech", "Primitive BattleMech", "Primitive IndustrialMech" })); cmbType.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbTypeFilter(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cmbType, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblType) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(lblType) .addGap(1, 1, 1) .addComponent(cmbType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14); jPanel14.setLayout(jPanel14Layout); jPanel14Layout.setHorizontalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel14Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel14Layout.setVerticalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel14Layout.createSequentialGroup() .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel4, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(21, 21, 21)) .addGroup(jPanel14Layout.createSequentialGroup() .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); lblName.setText("Name"); txtName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtNameActionPerformed(evt); } }); txtName.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { txtNameKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtNameKeyTyped(evt); } }); javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13); jPanel13.setLayout(jPanel13Layout); jPanel13Layout.setHorizontalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblName) ); jPanel13Layout.setVerticalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addComponent(lblName) .addGap(4, 4, 4) .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); txtSource.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtSourceActionPerformed(evt); } }); txtSource.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { txtSourceKeyReleased(evt); } }); lblSource.setText("Source"); javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12); jPanel12.setLayout(jPanel12Layout); jPanel12Layout.setHorizontalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtSource, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblSource) ); jPanel12Layout.setVerticalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addComponent(lblSource) .addGap(4, 4, 4) .addComponent(txtSource, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); txtMaxBV.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Filter(evt); } }); txtMaxBV.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { txtMaxBVFocusLost(evt); } }); lblBV.setText("Battle Value"); txtMinBV.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { txtMinBVFocusLost(evt); } }); javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(txtMinBV, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtMaxBV, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(lblBV) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtMaxBV, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtMinBV, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup() .addComponent(lblBV) .addGap(24, 24, 24)) ); lblTonnage1.setText("Year"); txtMinYear.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { txtMinYearFocusLost(evt); } }); txtMaxYear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtMaxYearFilter(evt); } }); txtMaxYear.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { txtMaxYearFocusLost(evt); } }); javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10); jPanel10.setLayout(jPanel10Layout); jPanel10Layout.setHorizontalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTonnage1) .addGroup(jPanel10Layout.createSequentialGroup() .addComponent(txtMinYear, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtMaxYear, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel10Layout.setVerticalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel10Layout.createSequentialGroup() .addComponent(lblTonnage1) .addGap(4, 4, 4) .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtMaxYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtMinYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) ); lblTonnage.setText("Tonnage"); txtMaxTon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtMaxTonFilter(evt); } }); txtMaxTon.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { txtMaxTonFocusLost(evt); } }); txtMinTon.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { txtMinTonFocusLost(evt); } }); javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addComponent(txtMinTon, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtMaxTon, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(lblTonnage) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtMaxTon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtMinTon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup() .addComponent(lblTonnage) .addGap(24, 24, 24)) ); txtMinCost.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtMinCostFilter(evt); } }); txtMinCost.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { txtMinCostFocusLost(evt); } }); lblCost.setText("C-Bill Cost"); txtMaxCost.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtMaxCostFilter(evt); } }); txtMaxCost.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { txtMaxCostFocusLost(evt); } }); javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11); jPanel11.setLayout(jPanel11Layout); jPanel11Layout.setHorizontalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel11Layout.createSequentialGroup() .addComponent(txtMinCost, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtMaxCost, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(lblCost) ); jPanel11Layout.setVerticalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel11Layout.createSequentialGroup() .addComponent(lblCost) .addGap(4, 4, 4) .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtMinCost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtMaxCost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) ); chkOmni.setText("Omni Only"); chkOmni.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { chkOmniActionPerformed(evt); } }); javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15); jPanel15.setLayout(jPanel15Layout); jPanel15Layout.setHorizontalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(chkOmni) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel15Layout.setVerticalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel15Layout.createSequentialGroup() .addContainerGap() .addComponent(chkOmni))) .addContainerGap()) ); javax.swing.GroupLayout pnlFiltersLayout = new javax.swing.GroupLayout(pnlFilters); pnlFilters.setLayout(pnlFiltersLayout); pnlFiltersLayout.setHorizontalGroup( pnlFiltersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlFiltersLayout.createSequentialGroup() .addGroup(pnlFiltersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pnlFiltersLayout.setVerticalGroup( pnlFiltersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlFiltersLayout.createSequentialGroup() .addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlFiltersLayout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(19, 19, 19)) ); lblStatus.setText("Loading Mechs...."); prgResaving.setStringPainted(true); lblShowing.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); lblShowing.setText("Showing 0 of 0"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tlbActions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(spnMechTable, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(pnlFilters, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(lblStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblShowing, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(txtSelected, javax.swing.GroupLayout.PREFERRED_SIZE, 798, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(prgResaving, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(tlbActions, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(9, 9, 9) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(prgResaving, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtSelected, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(spnMechTable, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pnlFilters, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblShowing))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void tblMechDataMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblMechDataMouseClicked if ( evt.getClickCount() == 2 ) { LoadMech(); } else { checkSelection(); } }//GEN-LAST:event_tblMechDataMouseClicked private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenActionPerformed LoadMech(); }//GEN-LAST:event_btnOpenActionPerformed private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened //if (list.Size() == 0) { LoadList(); } }//GEN-LAST:event_formWindowOpened private void btnOptionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOptionsActionPerformed dlgPrefs preferences = new dlgPrefs( (javax.swing.JFrame) parent, true ); preferences.setLocationRelativeTo( this ); preferences.setVisible( true ); this.setVisible(true); parent.GetLoadoutRenderer().Reset(); LoadList(); }//GEN-LAST:event_btnOptionsActionPerformed private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed LoadList(false); //Filter(evt); this.setVisible(true); }//GEN-LAST:event_btnRefreshActionPerformed private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed if ( tblMechData.getSelectedRowCount() > 0 ) { Printer print = new Printer(); try { MechReader read = new MechReader(); int[] rows = tblMechData.getSelectedRows(); for ( int i=0; i < rows.length; i++ ) { UnitListData data = list.Get(tblMechData.convertRowIndexToModel(rows[i])); Mech m = read.ReadMech( list.getDirectory() + data.getFilename(), parent.GetData() ); if (data.isOmni()) { m.SetCurLoadout(data.getConfig()); } print.AddMech(m); } print.Print(); tblMechData.clearSelection(); checkSelection(); } catch ( Exception e ) { } } }//GEN-LAST:event_btnPrintActionPerformed private void btnMagicActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMagicActionPerformed //setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) ); batchUpdateMechs(); //setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR ) ); }//GEN-LAST:event_btnMagicActionPerformed private void btnMTFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMagicActionPerformed //setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) ); batchUpdateMTFs(); //setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR ) ); }//GEN-LAST:event_btnMagicActionPerformed private void Filter(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Filter ListFilter filters = new ListFilter(); filters.setExtension(".ssw"); if (cmbTech.getSelectedIndex() > 0) {filters.setTech(cmbTech.getSelectedItem().toString());} if (cmbEra.getSelectedIndex() > 0) {filters.setEra(cmbEra.getSelectedItem().toString());} if (cmbType.getSelectedIndex() > 0) {filters.setType(cmbType.getSelectedItem().toString());} if (cmbMotive.getSelectedIndex() > 0) {filters.setMotive(cmbMotive.getSelectedItem().toString());} if (cmbRulesLevel.getSelectedIndex() > 0) {filters.setLevel(cmbRulesLevel.getSelectedItem().toString());} if (cmbMinMP.getSelectedIndex() > 0) {filters.setMinMP(Integer.parseInt(cmbMinMP.getSelectedItem().toString()));} if (! txtMinBV.getText().isEmpty() ) { if ( txtMaxBV.getText().isEmpty() ) { filters.setBV(0, Integer.parseInt(txtMinBV.getText())); } else { filters.setBV(Integer.parseInt(txtMinBV.getText()), Integer.parseInt(txtMaxBV.getText())); } } if (! txtMinCost.getText().isEmpty() ) { if ( txtMaxCost.getText().isEmpty() ) { filters.setCost(0, Double.parseDouble(txtMinCost.getText())); } else { filters.setCost(Double.parseDouble(txtMinCost.getText()), Double.parseDouble(txtMaxCost.getText())); } } if (! txtMinTon.getText().isEmpty() ) { if ( txtMaxTon.getText().isEmpty() ) { filters.setTonnage(20, Integer.parseInt(txtMinTon.getText() )); } else { filters.setTonnage(Integer.parseInt( txtMinTon.getText() ), Integer.parseInt( txtMaxTon.getText() )); } } if (! txtMinYear.getText().isEmpty() ) { if ( txtMaxYear.getText().isEmpty() ) { filters.setYear(Integer.parseInt(txtMinYear.getText()), Integer.parseInt(txtMinYear.getText())); } else { filters.setYear(Integer.parseInt(txtMinYear.getText()), Integer.parseInt(txtMaxYear.getText())); } } if (! txtName.getText().isEmpty() ) { filters.setName(txtName.getText().trim()); } if (! txtSource.getText().isEmpty() ) { filters.setSource(txtSource.getText().trim()); } filters.setIsOmni(chkOmni.isSelected()); UnitList filtered = list.Filter(filters); setupList(filtered, false); }//GEN-LAST:event_Filter private void txtMinCostFilter(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMinCostFilter // TODO add your handling code here: }//GEN-LAST:event_txtMinCostFilter private void txtMaxCostFilter(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMaxCostFilter // TODO add your handling code here: }//GEN-LAST:event_txtMaxCostFilter private void btnClearFilterFilter(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearFilterFilter setupList(list, false); //clear the dropdowns cmbEra.setSelectedIndex(0); cmbMotive.setSelectedIndex(0); cmbRulesLevel.setSelectedIndex(0); cmbTech.setSelectedIndex(0); cmbType.setSelectedIndex(0); cmbMinMP.setSelectedIndex(0); //clear text fields txtMinBV.setText(""); txtMaxBV.setText(""); txtMinCost.setText(""); txtMaxCost.setText(""); txtMinTon.setText(""); txtMaxTon.setText(""); txtMinYear.setText(""); txtMaxYear.setText(""); txtName.setText(""); chkOmni.setSelected(false); }//GEN-LAST:event_btnClearFilterFilter private void btnAdd2ForceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdd2ForceActionPerformed //lblForce.setText(""); if ( tblMechData.getSelectedRowCount() > 0 ) { int[] rows = tblMechData.getSelectedRows(); for ( int i=0; i < rows.length; i++ ) { UnitListData data = (UnitListData)((abView) tblMechData.getModel()).Get(tblMechData.convertRowIndexToModel(rows[i])); parent.GetForceDialogue().getForce().AddUnit(new Unit(data)); parent.GetForceDialogue().getForce().RefreshBV(); lblForce.setText(lblForce.getText() + " " + data.getFullName() + " added;"); } btnViewForce.setEnabled( true ); String forceList = parent.GetForceDialogue().getForce().getUnits().size() + " Units Selected: "; for ( Unit u : parent.GetForceDialogue().getForce().getUnits() ) { forceList += " " + u.TypeModel; } lblForce.setText(parent.GetForceDialogue().getForce().getUnits().size() + " Units"); lblForce.setToolTipText(forceList); //btnViewForce.setToolTipText(forceList); } //tblMechData.clearSelection(); }//GEN-LAST:event_btnAdd2ForceActionPerformed private void txtMaxTonFilter(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMaxTonFilter Filter(null); }//GEN-LAST:event_txtMaxTonFilter private void cmbRulesLevelFilter(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbRulesLevelFilter Filter(null); }//GEN-LAST:event_cmbRulesLevelFilter private void txtNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNameActionPerformed Filter(null); }//GEN-LAST:event_txtNameActionPerformed private void txtNameKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNameKeyTyped //Filter(null); }//GEN-LAST:event_txtNameKeyTyped private void cmbTypeFilter(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTypeFilter Filter(null); }//GEN-LAST:event_cmbTypeFilter private void cmbMotiveFilter(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbMotiveFilter Filter(null); }//GEN-LAST:event_cmbMotiveFilter private void btnChangeDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChangeDirActionPerformed dirPath = media.GetDirectorySelection( (javax.swing.JFrame) parent, dirPath ); this.setVisible(true); parent.GetPrefs().put("ListPath", dirPath); LoadList(false); }//GEN-LAST:event_btnChangeDirActionPerformed private void chkOmniActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkOmniActionPerformed Filter(null); }//GEN-LAST:event_chkOmniActionPerformed private void txtSourceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSourceActionPerformed Filter(null); }//GEN-LAST:event_txtSourceActionPerformed private void txtSourceKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSourceKeyReleased Filter(null); }//GEN-LAST:event_txtSourceKeyReleased private void cmbMinMPFilter(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbMinMPFilter Filter(null); }//GEN-LAST:event_cmbMinMPFilter private void tblMechDataMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblMechDataMouseMoved setTooltip( (UnitListData) ((abView) tblMechData.getModel()).Get(tblMechData.convertRowIndexToModel(tblMechData.rowAtPoint(evt.getPoint()))) ); }//GEN-LAST:event_tblMechDataMouseMoved private void tblMechDataKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblMechDataKeyReleased String entered = txtName.getText(); switch (evt.getKeyCode()) { case KeyEvent.VK_BACK_SPACE: if ( !entered.isEmpty() ) { entered = entered.substring(0, entered.length()-1); } break; case KeyEvent.VK_DELETE: entered = ""; break; case KeyEvent.VK_ENTER: if ( ((abView) tblMechData.getModel()).list.Size() == 1 ) { tblMechData.selectAll(); LoadMech(); } break; case KeyEvent.VK_SHIFT: case KeyEvent.VK_CONTROL: case KeyEvent.VK_UP: case KeyEvent.VK_DOWN: case KeyEvent.VK_RIGHT: case KeyEvent.VK_LEFT: return; default: if ( (evt.getKeyCode() == 32) || (evt.getKeyCode() >= 45 && evt.getKeyCode() <= 90) ) { entered += evt.getKeyChar(); } } txtName.setText(entered); txtNameKeyReleased(evt); }//GEN-LAST:event_tblMechDataKeyReleased private void btnViewForceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewForceActionPerformed lblForce.setText(""); //if ( tblMechData.getSelectedRowCount() > 0 ) { // btnAdd2ForceActionPerformed(evt); //} parent.GetForceDialogue().setLocationRelativeTo(this); parent.GetForceDialogue().setVisible(true); }//GEN-LAST:event_btnViewForceActionPerformed private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed lblForce.setText(""); }//GEN-LAST:event_formWindowClosed private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus //Filter(null); }//GEN-LAST:event_formWindowGainedFocus private void cmbViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbViewActionPerformed switch ( cmbView.getSelectedIndex() ) { case 0: currentView = twView.setList(list); break; case 1: currentView = compView.setList(list); break; case 2: currentView = bfView.setList(list); break; case 3: currentView = chatView.setList(list); break; default: currentView = twView.setList(list); } tblMechData.setModel(currentView); currentView.setupTable(tblMechData); //Could call setupList here but calling filter allows for filter to presist between selections. Filter(null); }//GEN-LAST:event_cmbViewActionPerformed private void txtNameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNameKeyReleased Filter(null); }//GEN-LAST:event_txtNameKeyReleased private void txtMaxYearFilter(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMaxYearFilter // TODO add your handling code here: }//GEN-LAST:event_txtMaxYearFilter private void txtMinTonFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMinTonFocusLost if ( txtMaxTon.getText().isEmpty() ) { txtMaxTon.setText(txtMinTon.getText()); txtMaxTon.selectAll();} Filter(null); }//GEN-LAST:event_txtMinTonFocusLost private void txtMinBVFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMinBVFocusLost if ( txtMaxBV.getText().isEmpty() ) { txtMaxBV.setText(txtMinBV.getText()); txtMaxBV.selectAll(); } Filter(null); }//GEN-LAST:event_txtMinBVFocusLost private void txtMaxTonFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaxTonFocusLost Filter(null); }//GEN-LAST:event_txtMaxTonFocusLost private void txtMaxBVFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaxBVFocusLost Filter(null); }//GEN-LAST:event_txtMaxBVFocusLost private void txtMinYearFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMinYearFocusLost if ( txtMaxYear.getText().isEmpty() ) { txtMaxYear.setText(txtMinYear.getText()); txtMaxYear.selectAll();} Filter(null); }//GEN-LAST:event_txtMinYearFocusLost private void txtMaxYearFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaxYearFocusLost Filter(null); }//GEN-LAST:event_txtMaxYearFocusLost private void txtMinCostFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMinCostFocusLost if ( txtMaxCost.getText().isEmpty() ) { txtMaxCost.setText(txtMinCost.getText()); txtMaxCost.selectAll();} Filter(null); }//GEN-LAST:event_txtMinCostFocusLost private void txtMaxCostFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaxCostFocusLost Filter(null); }//GEN-LAST:event_txtMaxCostFocusLost private void btnExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportActionPerformed TXTWriter out = new TXTWriter(); String dir = ""; dir = media.GetDirectorySelection(this, parent.GetPrefs().get("ListDirectory", "")); if ( dir.isEmpty() ) { return; } parent.GetPrefs().put("ListDirectory", dir); try { out.WriteList(dir + File.separator + "MechListing.csv", ((abView) tblMechData.getModel()).list); Media.Messager(((abView) tblMechData.getModel()).list.Size() + " Mechs output to " + dir + File.separator + "MechListing.csv"); } catch (IOException ex) { //do nothing System.out.println(ex.getMessage()); Media.Messager("Unable to output list\n" + ex.getMessage() ); } }//GEN-LAST:event_btnExportActionPerformed @Override public void setVisible( boolean b ) { super.setVisible(b); cancelledListDirSelection = false; if ( list.Size() == 0 ) { LoadList(); } Filter(null); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAdd2Force; private javax.swing.JButton btnChangeDir; private javax.swing.JButton btnClearFilter; private javax.swing.JButton btnExport; private javax.swing.JButton btnFilter; private javax.swing.JButton btnMagic; private javax.swing.JButton btnMTF; private javax.swing.JButton btnOpen; private javax.swing.JButton btnOptions; private javax.swing.JButton btnPrint; private javax.swing.JButton btnRefresh; private javax.swing.JButton btnViewForce; private javax.swing.JCheckBox chkOmni; private javax.swing.JComboBox cmbEra; private javax.swing.JComboBox cmbMinMP; private javax.swing.JComboBox cmbMotive; private javax.swing.JComboBox cmbRulesLevel; private javax.swing.JComboBox cmbTech; private javax.swing.JComboBox cmbType; private javax.swing.JComboBox cmbView; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel11; private javax.swing.JPanel jPanel12; private javax.swing.JPanel jPanel13; private javax.swing.JPanel jPanel14; private javax.swing.JPanel jPanel15; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; private javax.swing.JToolBar.Separator jSeparator1; private javax.swing.JToolBar.Separator jSeparator2; private javax.swing.JToolBar.Separator jSeparator3; private javax.swing.JToolBar.Separator jSeparator4; private javax.swing.JToolBar.Separator jSeparator5; private javax.swing.JToolBar.Separator jSeparator6; private javax.swing.JLabel lblBV; private javax.swing.JLabel lblCost; private javax.swing.JLabel lblEra; private javax.swing.JLabel lblForce; private javax.swing.JLabel lblLevel; private javax.swing.JLabel lblMinMP; private javax.swing.JLabel lblMotive; private javax.swing.JLabel lblName; private javax.swing.JLabel lblShowing; private javax.swing.JLabel lblSource; private javax.swing.JLabel lblStatus; private javax.swing.JLabel lblTech; private javax.swing.JLabel lblTonnage; private javax.swing.JLabel lblTonnage1; private javax.swing.JLabel lblType; private javax.swing.JPanel pnlFilters; private javax.swing.JProgressBar prgResaving; private javax.swing.JScrollPane spnMechTable; private javax.swing.JTable tblMechData; private javax.swing.JToolBar tlbActions; private javax.swing.JTextField txtMaxBV; private javax.swing.JTextField txtMaxCost; private javax.swing.JTextField txtMaxTon; private javax.swing.JTextField txtMaxYear; private javax.swing.JTextField txtMinBV; private javax.swing.JTextField txtMinCost; private javax.swing.JTextField txtMinTon; private javax.swing.JTextField txtMinYear; private javax.swing.JTextField txtName; private javax.swing.JLabel txtSelected; private javax.swing.JTextField txtSource; // End of variables declaration//GEN-END:variables }
Solaris-Skunk-Werks/solarisskunkwerks
ssw/src/main/java/ssw/gui/dlgOpen.java
46,064
/* * Copyright (C) 2015 thirdy * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package qic; import static java.util.Arrays.asList; import static java.util.stream.Collectors.joining; import static org.apache.commons.lang3.StringUtils.substringAfter; import static qic.Command.Status.ERROR; import java.awt.Window; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URLEncoder; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import qic.BlackmarketLanguage.ParseResult; import qic.Command.Status; import qic.SearchPageScraper.SearchResultItem; import qic.ui.QicFrame; import qic.util.CommandLine; import qic.util.Config; import qic.util.SessProp; import qic.util.Util; /** * TODO, REFACTOR!!! * * @author thirdy * */ public class Main { private final static Logger logger = LoggerFactory.getLogger(Main.class.getName()); public static BlackmarketLanguage language; BackendClient backendClient = new BackendClient(); SessProp sessProp = new SessProp(); Long searchDuration = null; List<String> invalidSearchTerms = null; public static void main(String[] args) throws Exception { try { reloadConfig(); new Main(args); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error occured: " + e.getMessage()); throw e; } } public static void reloadConfig() throws Exception, FileNotFoundException { language = new BlackmarketLanguage(); Config.loadConfig(); } public static void reloadLookAndFeel() { if (Config.getBooleanProperty(Config.LOOK_AND_FEEL_DECORATED, false)) { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); System.setProperty("sun.awt.noerasebackground", "true"); } try { String lookAndFeel = Config.getPropety(Config.LOOK_AND_FEEL, "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); if (lookAndFeel.startsWith("Substance")) { lookAndFeel = "org.pushingpixels.substance.api.skin." + lookAndFeel; } UIManager.setLookAndFeel(lookAndFeel); } catch (Exception e) { try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception ex) { throw new RuntimeException(ex); } } for (Window window : Window.getWindows()) { SwingUtilities.updateComponentTreeUI(window); } } public Main(String[] args) throws Exception { CommandLine cmd = new CommandLine(args); boolean guiEnabled = cmd.hasFlag("-gui"); guiEnabled = guiEnabled || cmd.getNumberOfArguments() == 0; logger.info("guiEnabled: " + guiEnabled); if (guiEnabled) { showGui(cmd.getArgument(0)); } else { if (cmd.getNumberOfArguments() == 0) { throw new IllegalArgumentException("First arguement needed, and should be the query. e.g. 'search chest 100life 6s5L'. " + "Enclosed in double quoutes if needed."); } String query = cmd.getArgument(0); logger.info("Query: " + query); Command command = processLine(query); String json = command.toJson(); writeToFile(json); } } private void showGui(String query) { reloadLookAndFeel(); SwingUtilities.invokeLater(() -> new QicFrame(Main.this, query)); } public void writeToFile(String contents) throws IOException { Util.overwriteFile("results.json", contents); } public Command processLine(String line) throws Exception { Command command = new Command(line); searchDuration = null; invalidSearchTerms = new LinkedList<>(); try { if (line.startsWith("sort")&& !sessProp.getLocation().isEmpty()) { command.itemResults = runSearch(line, true); command.searchDuration = searchDuration; } else if (line.startsWith("s ")) { String terms = substringAfter(line, "s ").trim(); if (!terms.isEmpty()) { command.itemResults = runSearch(terms, false); command.searchDuration = searchDuration; } } command.league = sessProp.getLeague(); command.invalidSearchTerms = invalidSearchTerms; command.status = Status.SUCCESS; } catch (Exception e) { e.printStackTrace(); command.status = ERROR; command.errorMessage = e.getMessage(); command.errorStackTrace = ExceptionUtils.getStackTrace(e); throw e; } return command; } private List<SearchResultItem> runSearch(String terms, boolean sortOnly) throws Exception { String html = downloadHtml(terms, sortOnly); if (html == null) { return Collections.emptyList(); } SearchPageScraper scraper = new SearchPageScraper(html); List<SearchResultItem> items = scraper.parse(); logger.info("items found: " + items.size()); return items; } public String downloadHtml(String terms, boolean sortOnly) throws Exception { long start = System.currentTimeMillis(); String regex = "([^\\s]*=\".*?\")"; List<String> customHttpKeyVals = Util.regexMatches(regex, terms, 1); String customHttpKeyVal = customHttpKeyVals.stream() .map(s -> StringUtils.remove(s, '"')) .collect(Collectors.joining("&")); String query = terms.replaceAll(regex, " "); ParseResult sortParseResult = language.parseSortToken(query); String sort = sortParseResult.result; sort = sort == null ? "price_in_chaos" : sort; invalidSearchTerms.addAll(sortParseResult.invalidSearchTerms); if (!sortOnly) { logger.info("Query: " + query); ParseResult queryParseResult = language.parse(query); String payload = queryParseResult.result; invalidSearchTerms.addAll(queryParseResult.invalidSearchTerms); if (invalidSearchTerms.isEmpty()) { payload = asList(payload, customHttpKeyVal, "capquality=x").stream().filter(StringUtils::isNotBlank).collect(joining("&")); logger.info("Unencoded payload: " + payload); payload = asList(payload.split("&")).stream().map(Util::encodeQueryParm).collect(joining("&")); String location = submitSearchForm(payload); String league = language.parseLeagueToken(query); sessProp.setLocation(location); sessProp.setLeague(league); sessProp.saveToFile(); } } String searchPage = null; if (invalidSearchTerms.isEmpty()) { logger.info("sort: " + sort); searchPage = ajaxSort(sort); } else { logger.info("invalidSearchTerms: " + invalidSearchTerms.toString()); } long end = System.currentTimeMillis(); long duration = end - start; logger.info("Took " + duration + " ms"); searchDuration = Long.valueOf(duration); return searchPage; } private String ajaxSort(String sort) throws Exception { String searchPage = ""; sort = URLEncoder.encode(sort, "UTF-8"); sort = "sort=" + sort + "&bare=true"; searchPage = backendClient.postXMLHttpRequest(sessProp.getLocation(), sort); return searchPage; } private String submitSearchForm(String payload) throws Exception { String url = "http://poe.trade/search"; String location = backendClient.post(url, payload); return location; } }
gitter-badger/durian
durian/src/main/java/qic/Main.java
46,065
package com.company.mediator.section2; /** * @author cbf4Life cbf4life@126.com * I'm glad to share my knowledge with you all. * 存货 */ public class Stock extends AbstractColleague { public Stock(AbstractMediator _mediator){ super(_mediator); } //刚开始有100台电脑 private static int COMPUTER_NUMBER =100; //库存增加 public void increase(int number){ COMPUTER_NUMBER = COMPUTER_NUMBER + number; System.out.println("库存数量为:"+COMPUTER_NUMBER); } //库存降低 public void decrease(int number){ COMPUTER_NUMBER = COMPUTER_NUMBER - number; System.out.println("库存数量为:"+COMPUTER_NUMBER); } //获得库存数量 public int getStockNumber(){ return COMPUTER_NUMBER; } //存货压力大了,就要通知采购人员不要采购,销售人员要尽快销售 public void clearStock(){ System.out.println("清理存货数量为:"+COMPUTER_NUMBER); super.mediator.execute("stock.clear"); } }
nivance/DPModel
src/dp/com/company/mediator/section2/Stock.java
46,066
/* * Copyright 2017 github.com/kaaz * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package emily.command.poe; import emily.command.meta.AbstractCommand; import emily.db.controllers.CPoEToken; import emily.db.model.OPoEToken; import emily.main.DiscordBot; import emily.templates.Templates; import emily.util.Misc; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.MessageChannel; import net.dv8tion.jda.core.entities.User; import org.libpoe.model.StashTab; import org.libpoe.model.item.Item; import org.libpoe.model.property.MinMaxProperty; import org.libpoe.model.property.Property; import org.libpoe.net.AuthInfo; import org.libpoe.net.DataReader; import org.libpoe.util.League; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; /** * !poeitem * Analyzes an item from path of exile */ public class PoeCurrency extends AbstractCommand { public PoeCurrency() { super(); } @Override public String getDescription() { return "Returns a list of currency on your account"; } @Override public String getCommand() { return "poec"; } @Override public String[] getUsage() { return new String[]{ "poec //returns list of currency for default league", "poec token <token> //sets the session token", "poec league <league> //currency for league", }; } @Override public String[] getAliases() { return new String[]{}; } @Override public String execute(DiscordBot bot, String[] args, MessageChannel channel, User author, Message inputMessage) { if (args.length > 1) { if (args[0].equalsIgnoreCase("token")) { OPoEToken token = CPoEToken.findBy(author.getIdLong()); token.session_id = args[1]; CPoEToken.insertOrUpdate(token); return "Updated your token!"; } else if (args[0].equalsIgnoreCase("league")) { return "not implemented yet sorry boys!"; } return Templates.invalid_use.formatGuild(channel); } OPoEToken token = CPoEToken.findBy(author.getIdLong()); AuthInfo account = new AuthInfo(token.session_id); DataReader reader = new DataReader(account); if (!reader.authenticate()) { return "Your token is not valid :("; } bot.out.sendAsyncMessage(channel, "Fetching data this might take a minute!", null); HashMap<String, Integer> currency = new HashMap<>(); int max = 1; for (int i = 0; i < max; i++) { StashTab stashTab = null; try { stashTab = reader.getStashTab(League.ESSENCE.getId(), i); } catch (Exception e) { e.printStackTrace(); } if (stashTab != null) { if (max == 1) { max = stashTab.getNumTabs(); } System.out.println((i + 1) + " out of " + stashTab.getNumTabs()); for (Item item : stashTab.getItems()) { if (item.getTypeLine().toLowerCase().contains("orb")) { Property property = item.getProperty("Stack Size"); if (property instanceof MinMaxProperty) { MinMaxProperty p = (MinMaxProperty) property; if (!currency.containsKey(item.getTypeLine())) { currency.put(item.getTypeLine(), 0); } currency.put(item.getTypeLine(), currency.get(item.getTypeLine()) + p.getMinValue()); } } } } } String text = "Checking your currency in PoE!\n"; List<List<String>> tbl = new ArrayList<>(); Misc.sortByValue(currency).forEach((k, v) -> { ArrayList<String> row = new ArrayList<>(); row.add(k); row.add(String.valueOf(v)); tbl.add(row); }); text += Misc.makeAsciiTable(Arrays.asList("Currency", "#"), tbl, null); return text; } }
Kaaz/DiscordBot
src/main/java/emily/command/poe/PoeCurrency.java
46,067
package cc.hicore.qtool.ChatHook.ChatCracker; import android.annotation.SuppressLint; import android.graphics.Color; import android.text.TextUtils; import android.view.Gravity; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.List; import cc.hicore.HookItemLoader.Annotations.MethodScanner; import cc.hicore.HookItemLoader.Annotations.UIItem; import cc.hicore.HookItemLoader.Annotations.VerController; import cc.hicore.HookItemLoader.Annotations.XPExecutor; import cc.hicore.HookItemLoader.Annotations.XPItem; import cc.hicore.HookItemLoader.bridge.BaseXPExecutor; import cc.hicore.HookItemLoader.bridge.MethodContainer; import cc.hicore.HookItemLoader.bridge.QQVersion; import cc.hicore.HookItemLoader.bridge.UIInfo; import cc.hicore.LogUtils.LogUtils; import cc.hicore.ReflectUtils.Finders; import cc.hicore.ReflectUtils.MClass; import cc.hicore.ReflectUtils.MField; import cc.hicore.ReflectUtils.MMethod; import cc.hicore.Utils.Utils; @SuppressLint("ResourceType") @XPItem(itemType = XPItem.ITEM_Hook, name = "长按复制卡片代码") public class CopyCardCode { @UIItem @VerController public UIInfo getUIInfo() { UIInfo info = new UIInfo(); info.name = "长按复制卡片代码"; info.type = 1; info.targetID = 1; info.groupName = "聊天界面增强"; return info; } @VerController @XPExecutor(methodID = "onAIOGetView", period = XPExecutor.After) public BaseXPExecutor xpWorker() { return param -> { Object mGetView = param.getResult(); RelativeLayout mLayout; if (mGetView instanceof RelativeLayout) { mLayout = (RelativeLayout) mGetView; } else { return; } List MessageRecoreList = MField.GetFirstField(param.thisObject, List.class); if (MessageRecoreList == null) return; Object ChatMsg = MessageRecoreList.get((int) param.args[0]); if (ChatMsg.getClass().getSimpleName().equals("MessageForArkApp") || MClass.loadClass("com.tencent.mobileqq.data.MessageForStructing").isAssignableFrom(ChatMsg.getClass()) || ChatMsg.getClass().getSimpleName().equals("MessageForStarLeague")) { //复制卡片消息的标题 TextView tv = mLayout.findViewById(445588); if (tv == null) { //长按标签,位于Parent顶部中央,最大化 RelativeLayout.LayoutParams RLP = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); RLP.width = ViewGroup.LayoutParams.MATCH_PARENT; tv = new TextView(mLayout.getContext()); mLayout.addView(tv, RLP); tv.setText("长按复制卡片代码"); tv.setGravity(Gravity.CENTER);//居中显示 tv.setTextColor(Color.RED); tv.setId(445588); } tv.setTag(ChatMsg);//保存消息对象 tv.setOnLongClickListener(view -> { Object ChatMessage = view.getTag(); try { if (ChatMessage.getClass().getSimpleName().equals("MessageForArkApp")) { Object ArkAppMsg = MField.GetField(ChatMessage, ChatMessage.getClass(), "ark_app_message", MClass.loadClass("com.tencent.mobileqq.data.ArkAppMessage")); String json = MMethod.CallMethod(ArkAppMsg, MClass.loadClass("com.tencent.mobileqq.data.ArkAppMessage"), "toAppXml", String.class, new Class[0], new Object[0]); Utils.SetTextClipboard(json); Utils.ShowToast("已复制"); } else if (ChatMessage.getClass().getSimpleName().equals("MessageForStarLeague")) { String xml = MMethod.CallMethodSingle(ChatMessage, "getExtInfoFromExtStr", String.class, "SavedXml"); if (TextUtils.isEmpty(xml)) { Utils.ShowToast("未找到卡片描述信息,此类型消息必须开着模块接收才能复制代码"); } else { Utils.SetTextClipboard(xml); Utils.ShowToast("已复制"); } } else if (MClass.loadClass("com.tencent.mobileqq.data.MessageForStructing").isAssignableFrom(ChatMessage.getClass())) { Object Structing = MField.GetField(ChatMessage, ChatMessage.getClass(), "structingMsg", MClass.loadClass("com.tencent.mobileqq.structmsg.AbsStructMsg")); String xml = MMethod.CallMethod(Structing, MClass.loadClass("com.tencent.mobileqq.structmsg.AbsStructMsg"), "getXml", String.class, new Class[0], new Object[0]); Utils.SetTextClipboard(xml); Utils.ShowToast("已复制"); } } catch (Throwable e) { LogUtils.error("CopyXml", e); } return false; }); } }; } @MethodScanner @VerController(max_targetVer = QQVersion.QQ_8_9_0) public void getHookMethod(MethodContainer container) { Finders.AIOMessageListAdapter_getView(container); } @MethodScanner @VerController(targetVer = QQVersion.QQ_8_9_0) public void getHookMethod_890(MethodContainer container) { Finders.AIOMessageListAdapter_getView_890(container); } }
Hicores/QTool
QTool/src/main/java/cc/hicore/qtool/ChatHook/ChatCracker/CopyCardCode.java
46,068
package com.company.mediator.section2; /** * @author cbf4Life cbf4life@126.com * I'm glad to share my knowledge with you all. * 采购类 */ public class Purchase extends AbstractColleague{ public Purchase(AbstractMediator _mediator){ super(_mediator); } //采购IBM型号的电脑 public void buyIBMcomputer(int number){ super.mediator.execute("purchase.buy", number); } //不在采购IBM电脑 public void refuseBuyIBM(){ System.out.println("不再采购IBM电脑"); } }
nivance/DPModel
src/dp/com/company/mediator/section2/Purchase.java
46,069
/* * AtBScenario.java * * Copyright (C) 2014-2021 - The MegaMek Team. All Rights Reserved. * Copyright (c) 2014 Carl Spain. All rights reserved. * * This file is part of MekHQ. * * MekHQ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MekHQ is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MekHQ. If not, see <http://www.gnu.org/licenses/>. */ package mekhq.campaign.mission; import megamek.Version; import megamek.codeUtilities.ObjectUtility; import megamek.common.*; import megamek.common.annotations.Nullable; import megamek.common.enums.SkillLevel; import megamek.common.icons.Camouflage; import megamek.common.options.OptionsConstants; import megamek.common.util.EncodeControl; import mekhq.MHQConstants; import mekhq.MekHQ; import mekhq.MekHqXmlUtil; import mekhq.campaign.Campaign; import mekhq.campaign.againstTheBot.AtBConfiguration; import mekhq.campaign.force.Force; import mekhq.campaign.force.Lance; import mekhq.campaign.market.unitMarket.AtBMonthlyUnitMarket; import mekhq.campaign.mission.ObjectiveEffect.ObjectiveEffectType; import mekhq.campaign.mission.ScenarioObjective.ObjectiveCriterion; import mekhq.campaign.mission.atb.IAtBScenario; import mekhq.campaign.mission.enums.AtBLanceRole; import mekhq.campaign.personnel.SkillType; import mekhq.campaign.rating.IUnitRating; import mekhq.campaign.unit.Unit; import mekhq.campaign.universe.*; import org.apache.logging.log4j.LogManager; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.PrintWriter; import java.text.ParseException; import java.time.LocalDate; import java.util.*; /** * @author Neoancient */ public abstract class AtBScenario extends Scenario implements IAtBScenario { //region Variable Declarations public static final int DYNAMIC = -1; public static final int BASEATTACK = 0; public static final int EXTRACTION = 1; public static final int CHASE = 2; public static final int HOLDTHELINE = 3; public static final int BREAKTHROUGH = 4; public static final int HIDEANDSEEK = 5; public static final int STANDUP = 6; public static final int RECONRAID = 7; public static final int PROBE = 8; public static final int OFFICERDUEL = 9; //Special Mission public static final int ACEDUEL = 10; //Special Mission public static final int AMBUSH = 11; //Special Mission public static final int CIVILIANHELP = 12; //Special Mission public static final int ALLIEDTRAITORS = 13; //Special Mission public static final int PRISONBREAK = 14; //Special Mission public static final int STARLEAGUECACHE1 = 15; //Special Mission public static final int STARLEAGUECACHE2 = 16; //Special Mission public static final int ALLYRESCUE = 17; //Big Battle public static final int CIVILIANRIOT = 18; //Big Battle public static final int CONVOYRESCUE = 19; //Big Battle public static final int CONVOYATTACK = 20; //Big Battle public static final int PIRATEFREEFORALL = 21; //Big Battle public static final int FORCE_MEK = 0; public static final int FORCE_VEHICLE = 1; public static final int FORCE_MIXED = 2; public static final int FORCE_NOVA = 3; public static final int FORCE_VEENOVA = 4; public static final int FORCE_INFANTRY = 5; public static final int FORCE_BA = 6; public static final int FORCE_AERO = 7; public static final int FORCE_PROTOMEK = 8; public static final String[] forceTypeNames = { "Mek", "Vehicle", "Mixed", "Nova", "Nova", "Infantry", "Battle Armor", "Aerospace", "ProtoMek" }; public static final String[] antiRiotWeapons = { "ISERSmallLaser", "Small Laser", "Small Laser Prototype", "ISSmallPulseLaser", "ISSmallXPulseLaser", "Small Re-engineered Laser", "ISSmallVSPLaser", "CLERMicroLaser", "CLERSmallLaser", "ER Small Laser (CP)", "CLHeavySmallLaser", "CLImprovedSmallHeavyLaser", "ClSmall Laser", "CLERSmallPulseLaser", "CLMicroPulseLaser", "CLSmallPulseLaser", "CLSmallChemLaser", "Heavy Machine Gun", "Light Machine Gun", "Machine Gun", "Heavy Rifle", "Light Rifle", "Medium Rifle", "CLHeavyMG", "CLLightMG", "CLMG", "Flamer", "ER Flamer", "CLFlamer", "CLERFlamer", "Vehicle Flamer", "Heavy Flamer", "CLVehicleFlamer", "CLHeavyFlamer" }; /* The starting position chart in the AtB rules includes the four * corner positions as well, but this creates some conflict with * setting the home edge for the bot, which only includes the four * sides. */ protected static final int [] startPos = { Board.START_N, Board.START_E, Board.START_S, Board.START_W }; private static final int[] randomAeroWeights = { EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_HEAVY }; public static final int NO_LANCE = -1; private boolean attacker; private int lanceForceId; // -1 if scenario is not generated for a specific lance (special mission, big battle) private AtBLanceRole lanceRole; /* set when scenario is created in case it is changed for the next week before the scenario is resolved; specifically affects scenarios generated for scout lances, in which the deployment may be delayed for slower units */ private int deploymentDelay; private int lanceCount; private int rerollsRemaining; private int enemyHome; private List<Entity> alliesPlayer; private List<String> alliesPlayerStub; /* Special missions cannot generate the enemy until the unit is * added, but needs the Campaign object which is not passed * by addForce or addUnit. Instead we generate all possibilities * (one for each weight class) when the scenario is created and * choose the correct one when a unit is deployed. */ private List<List<Entity>> specMissionEnemies; /* Big battles have a similar problem for attached allies. Though * we could generate the maximum number (4) and remove them as * the player deploys additional units, they would be lost if * any units are undeployed. */ private List<Entity> bigBattleAllies; /* Units that need to be tracked for possible contract breaches * (for destruction), or bonus rolls (for survival). */ private List<UUID> attachedUnitIds; private List<UUID> survivalBonus; private Map<UUID, Entity> entityIds; // key-value pairs linking transports and the units loaded onto them. private Map<String, List<String>> transportLinkages; private Map<Integer, Integer> numPlayerMinefields; protected final transient ResourceBundle defaultResourceBundle = ResourceBundle.getBundle("mekhq.resources.AtBScenarioBuiltIn", MekHQ.getMHQOptions().getLocale(), new EncodeControl()); //endregion Variable Declarations public AtBScenario () { super(); lanceForceId = -1; lanceRole = AtBLanceRole.UNASSIGNED; alliesPlayer = new ArrayList<>(); alliesPlayerStub = new ArrayList<>(); attachedUnitIds = new ArrayList<>(); survivalBonus = new ArrayList<>(); entityIds = new HashMap<>(); transportLinkages = new HashMap<>(); numPlayerMinefields = new HashMap<>(); deploymentDelay = 0; lanceCount = 0; rerollsRemaining = 0; } public void initialize(Campaign c, Lance lance, boolean attacker, LocalDate date) { setAttacker(attacker); alliesPlayer = new ArrayList<>(); botForces = new ArrayList<>(); alliesPlayerStub = new ArrayList<>(); botForcesStubs = new ArrayList<>(); attachedUnitIds = new ArrayList<>(); survivalBonus = new ArrayList<>(); entityIds = new HashMap<>(); if (null == lance) { lanceForceId = -1; lanceRole = AtBLanceRole.UNASSIGNED; } else { this.lanceForceId = lance.getForceId(); lanceRole = lance.getRole(); setMissionId(lance.getMissionId()); for (UUID id : c.getForce(lance.getForceId()).getAllUnits(true)) { entityIds.put(id, c.getUnit(id).getEntity()); } } light = PlanetaryConditions.L_DAY; weather = PlanetaryConditions.WE_NONE; wind = PlanetaryConditions.WI_NONE; fog = PlanetaryConditions.FOG_NONE; atmosphere = PlanetaryConditions.ATMO_STANDARD; gravity = (float) 1.0; deploymentDelay = 0; setDate(date); lanceCount = 0; rerollsRemaining = 0; if (isStandardMission()) { setName(getScenarioTypeDescription() + (isAttacker() ? " (Attacker)" : " (Defender)")); } else { setName(getScenarioTypeDescription()); } initBattle(c); } public String getDesc() { return getScenarioTypeDescription() + (isStandardMission() ? (isAttacker() ? " (Attacker)" : " (Defender)") : ""); } @Override public boolean isStandardMission() { return !isSpecialMission() && !isBigBattle(); } @Override public boolean isSpecialMission() { return false; } @Override public boolean isBigBattle() { return false; } @Override public ResourceBundle getResourceBundle() { return defaultResourceBundle; } /** * Determines battle conditions: terrain, weather, map. * * @param campaign */ private void initBattle(Campaign campaign) { setTerrain(); if (campaign.getCampaignOptions().getUseLightConditions()) { setLightConditions(); } if (campaign.getCampaignOptions().getUseWeatherConditions()) { setWeather(); } if (campaign.getCampaignOptions().getUsePlanetaryConditions() && null != campaign.getMission(getMissionId())) { setPlanetaryConditions(campaign.getMission(getMissionId()), campaign); } setMapSize(); setMapFile(); if (isStandardMission()) { lanceCount = 1; } else if (isBigBattle()) { lanceCount = 2; } if (null != getLance(campaign)) { getLance(campaign).refreshCommander(campaign); if (null != getLance(campaign).getCommander(campaign).getSkill(SkillType.S_TACTICS)) { rerollsRemaining = getLance(campaign).getCommander(campaign).getSkill(SkillType.S_TACTICS).getLevel(); } } } public void setTerrain() { setTerrainType(terrainChart[Compute.d6(2) - 2]); } public void setLightConditions() { setLight(PlanetaryConditions.L_DAY); int roll = Compute.randomInt(10) + 1; if (roll < 6) setLight(PlanetaryConditions.L_DAY); else if (roll < 8) setLight(PlanetaryConditions.L_DUSK); else if (roll == 8) setLight(PlanetaryConditions.L_FULL_MOON); else if (roll == 9) setLight(PlanetaryConditions.L_MOONLESS); else setLight(PlanetaryConditions.L_PITCH_BLACK); } public void setWeather() { setWeather(PlanetaryConditions.WE_NONE); setWind(PlanetaryConditions.WI_NONE); setFog(PlanetaryConditions.FOG_NONE); int roll = Compute.randomInt(10) + 1; int r2 = Compute.d6(); if (roll == 6) { if (r2 < 4) setWeather(PlanetaryConditions.WE_LIGHT_RAIN); else if (r2 < 6) setWeather(PlanetaryConditions.WE_MOD_RAIN); else setWeather(PlanetaryConditions.WE_HEAVY_RAIN); } else if (roll == 7) { if (r2 < 4) setWeather(PlanetaryConditions.WE_LIGHT_SNOW); else if (r2 < 6) setWeather(PlanetaryConditions.WE_MOD_SNOW); else setWeather(PlanetaryConditions.WE_HEAVY_SNOW); } else if (roll == 8) { if (r2 < 4) setWind(PlanetaryConditions.WI_LIGHT_GALE); else if (r2 < 6) setWind(PlanetaryConditions.WI_MOD_GALE); else setWind(PlanetaryConditions.WI_STRONG_GALE); } else if (roll == 9) { if (r2 == 1) setWind(PlanetaryConditions.WI_STORM); else if (r2 == 2) setWeather(PlanetaryConditions.WE_DOWNPOUR); else if (r2 == 3) setWeather(PlanetaryConditions.WE_SLEET); else if (r2 == 4) setWeather(PlanetaryConditions.WE_ICE_STORM); else if (r2 == 5) setWind(PlanetaryConditions.WI_TORNADO_F13); // tornadoes are classified as wind rather than weather. else if (r2 == 6) setWind(PlanetaryConditions.WI_TORNADO_F4); } else if (roll > 9) { if (r2 < 5) setFog(PlanetaryConditions.FOG_LIGHT); else setFog(PlanetaryConditions.FOG_HEAVY); } // roll < 6 can be ignored, as it would just return nothing } public void setPlanetaryConditions(Mission mission, Campaign campaign) { if (null != mission) { PlanetarySystem psystem = Systems.getInstance().getSystemById(mission.getSystemId()); //assume primary planet for now Planet p = psystem.getPrimaryPlanet(); if (null != p) { setAtmosphere(ObjectUtility.nonNull(p.getPressure(campaign.getLocalDate()), getAtmosphere())); setGravity(ObjectUtility.nonNull(p.getGravity(), getGravity()).floatValue()); } } } public void setMapSize() { int roll = Compute.randomInt(20) + 1; if (roll < 6) { setMapSizeX(20); setMapSizeY(10); } else if (roll < 11) { setMapSizeX(10); setMapSizeY(20); } else if (roll < 13) { setMapSizeX(30); setMapSizeY(10); } else if (roll < 15) { setMapSizeX(10); setMapSizeY(30); } else if (roll < 19) { setMapSizeX(20); setMapSizeY(20); } else if (roll == 19) { setMapSizeX(40); setMapSizeY(10); } else { setMapSizeX(10); setMapSizeY(40); } } public int getMapX() { int base = getMapSizeX() + 5 * lanceCount; return Math.max(base, 20); } public int getMapY() { int base = getMapSizeY() + 5 * lanceCount; return Math.max(base, 20); } public int getBaseMapX() { return (5 * getLanceCount()) + getMapSizeX(); } public int getBaseMapY() { return (5 * getLanceCount()) + getMapSizeY(); } public void setMapFile() { final String[][] maps = { {"Sandy-hills", "Hills-craters", "Hills", "Wooded-hills", "Cliffs", "Town-hills"}, //hills {"Sandy-valley", "Rocky-valley", "Light-craters", "Heavy-craters", "Rubble-mountain", "Cliffs"}, //badlands {"Muddy-swamp", "Lake-marsh", "Lake-high", "Wooded-lake", "Swamp", "Wooded-swamp"}, //wetlands {"Town-mining", "Town-wooded", "Town-generic", "Town-farming", "Town-ruin", "Town-mountain"}, //light urban {"Savannah", "Dust-bowl", "Sandy-hills", "Town-ruin", "Town-generic", "Some-trees"}, //flatlands {"Some-trees", "Wooded-lake", "Woods-medium", "Wooded-hills", "Woods-deep", "Wooded-valley"}, //wooded {"Fortress-city", "Fortress-city", "Town-concrete", "Town-concrete", "City-high", "City-dense"}, //heavy urban {"River-huge", "Woods-river", "Sandy-river", "Rubble-river", "Seaport", "River-wetlands"}, //coastal {"Mountain-lake", "Cliffs-lake", "Rubble-mountain", "Cliffs", "Mountain-medium", "Mountain-high"} //mountains }; int actualTerrainType = getTerrainType(); // we want to make sure the terrain type we pick is in bounds, if ((getTerrainType() < 0) || (getTerrainType() >= maps.length)) { actualTerrainType = Compute.randomInt(maps.length); } setMap(maps[actualTerrainType][Compute.d6() - 1]); } public boolean canRerollTerrain() { return canRerollMap(); } public boolean canRerollMapSize() { return true; } public boolean canRerollMap() { return true; } public boolean canRerollLight() { return true; } public boolean canRerollWeather() { return true; } /** * Determines whether a unit is eligible to deploy to the scenario. The * default is true, but some special missions and big battles restrict * the participants. * * @param unit * @param campaign * @return true if the unit is eligible, otherwise false */ @Override public boolean canDeploy(Unit unit, Campaign campaign) { if (isBigBattle() && (getForces(campaign).getAllUnits(true).size() > 7)) { return false; } else { return !isSpecialMission() || (getForces(campaign).getAllUnits(true).size() <= 0); } } /** * Determines whether a force is eligible to deploy to a scenario by * checking all units contained in the force * * @param force * @param campaign * @return true if the force is eligible to deploy, otherwise false */ public boolean canDeploy(Force force, Campaign campaign) { Vector<UUID> units = force.getAllUnits(true); if (isBigBattle() && getForces(campaign).getAllUnits(true).size() + units.size() > 8) { return false; } else if (isSpecialMission() && getForces(campaign).getAllUnits(true).size() + units.size() > 0) { return false; } for (UUID id : units) { if (!canDeploy(campaign.getUnit(id), campaign)) { return false; } } return true; } /** * Determines whether a list of units is eligible to deploy to the scenario. * * @param units * @param campaign * @return true if all units in the list are eligible, otherwise false */ @Override public boolean canDeployUnits(Vector<Unit> units, Campaign campaign) { if (isBigBattle()) { return getForces(campaign).getAllUnits(true).size() + units.size() <= 8; } else if (isSpecialMission()) { return getForces(campaign).getAllUnits(true).size() + units.size() <= 1; } for (Unit unit : units) { if (!canDeploy(unit, campaign)) { return false; } } return true; } /** * Determines whether a list of forces is eligible to deploy to the scenario. * * @param forces list of forces * @param c the campaign that the forces are part of * @return true if all units in all forces in the list are eligible, otherwise false */ @Override public boolean canDeployForces(Vector<Force> forces, Campaign c) { int total = 0; for (Force force : forces) { Vector<UUID> units = force.getAllUnits(true); total += units.size(); if (isBigBattle()) { return getForces(c).getAllUnits(true).size() + units.size() <= 8; } else if (isSpecialMission()) { return getForces(c).getAllUnits(true).size() + units.size() <= 0; } for (UUID id : units) { if (!canDeploy(c.getUnit(id), c)) { return false; } } } if (isBigBattle()) { return getForces(c).getAllUnits(true).size() + total <= 8; } else if (isSpecialMission()) { return getForces(c).getAllUnits(true).size() + total <= 0; } return true; } /** * Corrects the enemy (special missions) and allies (big battles) * as necessary based on player deployments. This ought to be called * when the scenario details are displayed or the scenario is started. * * @param campaign */ public void refresh(Campaign campaign) { if (isStandardMission()) { setObjectives(campaign, getContract(campaign)); return; } Vector<UUID> deployed = getForces(campaign).getAllUnits(true); if (isBigBattle()) { int numAllies = Math.min(4, 8 - deployed.size()); alliesPlayer.clear(); for (int i = 0; i < numAllies; i++) { alliesPlayer.add(bigBattleAllies.get(i)); getExternalIDLookup().put(bigBattleAllies.get(i).getExternalIdAsString(), bigBattleAllies.get(i)); } setObjectives(campaign, getContract(campaign)); } else { if (deployed.size() == 0) { return; } int weight = campaign.getUnit(deployed.get(0)).getEntity().getWeightClass() - 1; /* In the event that Star League Cache 1 generates a primitive 'Mech, * the player can keep the 'Mech without a battle so no enemy * units are generated. */ if (specMissionEnemies == null ) { setForces(campaign); } if ((specMissionEnemies != null) && (getBotForces().get(0) != null) && (specMissionEnemies.get(weight) != null)) { getBotForces().get(0).setFixedEntityList(specMissionEnemies.get(weight)); } setObjectives(campaign, getContract(campaign)); } } /** * Determines enemy and allied forces for the scenario. The forces for a standard * battle are based on the player's deployed lance. The enemy forces for * special missions depend on the weight class of the player's deployed * unit and the number of allies in big battles varies according to the * number the player deploys. Since the various possibilities are rather * limited, all possibilities are generated and the most appropriate is * chosen rather than rerolling every time the player changes. This is * both for efficiency and to prevent shopping. * * @param campaign */ public void setForces(Campaign campaign) { if (isStandardMission()) { setStandardMissionForces(campaign); } else if (isSpecialMission()) { setSpecialMissionForces(campaign); } else { setBigBattleForces(campaign); } setObjectives(campaign, getContract(campaign)); } /** * Generates attached allied units (bot or player controlled), the main * enemy force, any enemy reinforcements, and any additional forces * (such as civilian). * * @param campaign */ private void setStandardMissionForces(Campaign campaign) { /* Find the number of attached units required by the command rights clause */ int attachedUnitWeight = EntityWeightClass.WEIGHT_MEDIUM; if (lanceRole.isScouting() || lanceRole.isTraining()) { attachedUnitWeight = EntityWeightClass.WEIGHT_LIGHT; } int numAttachedPlayer = 0; int numAttachedBot = 0; if (getContract(campaign).getContractType().isCadreDuty()) { numAttachedPlayer = 3; } else if (campaign.getFactionCode().equals("MERC")) { switch (getContract(campaign).getCommandRights()) { case INTEGRATED: if (campaign.getCampaignOptions().getPlayerControlsAttachedUnits()) { numAttachedPlayer = 2; } else { numAttachedBot = 2; } break; case HOUSE: if (campaign.getCampaignOptions().getPlayerControlsAttachedUnits()) { numAttachedPlayer = 1; } else { numAttachedBot = 1; } break; case LIAISON: numAttachedPlayer = 1; break; default: break; } } /* The entities in the attachedAllies list will be added to the player's forces * in MM and don't require a separate BotForce */ final Camouflage camouflage = getContract(campaign).getAllyCamouflage(); for (int i = 0; i < numAttachedPlayer; i++) { Entity en = getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.MEK, attachedUnitWeight, campaign); if (null != en) { alliesPlayer.add(en); attachedUnitIds.add(UUID.fromString(en.getExternalIdAsString())); getExternalIDLookup().put(en.getExternalIdAsString(), en); if (!campaign.getCampaignOptions().getAttachedPlayerCamouflage()) { en.setCamouflage(camouflage.clone()); } } else { LogManager.getLogger().error("Entity for player-controlled allies is null"); } } /* The allyBot list will be passed to the BotForce constructor */ ArrayList<Entity> allyEntities = new ArrayList<>(); for (int i = 0; i < numAttachedBot; i++) { Entity en = getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.MEK, attachedUnitWeight, campaign); if (null != en) { allyEntities.add(en); attachedUnitIds.add(UUID.fromString(en.getExternalIdAsString())); } else { LogManager.getLogger().error("Entity for ally bot is null"); } } ArrayList<Entity> enemyEntities = new ArrayList<>(); setExtraMissionForces(campaign, allyEntities, enemyEntities); addAeroReinforcements(campaign); addScrubReinforcements(campaign); /* Possible enemy reinforcements */ int roll = Compute.d6(); if (roll > 3) { ArrayList<Entity> reinforcements = new ArrayList<>(); if (roll == 6) { addLance(reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_ASSAULT, campaign, 8); } else { addLance(reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_ASSAULT, campaign, 6); } /* Must set per-entity start pos for units after start of scenarios. Reinforcements * arrive from the enemy home edge, which is not necessarily the start pos. */ final int enemyDir = enemyHome; reinforcements.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(enemyDir); }); if (campaign.getCampaignOptions().getAllowOpforLocalUnits()) { reinforcements.addAll(AtBDynamicScenarioFactory.fillTransports(this, reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), campaign)); } BotForce bf = getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, reinforcements); bf.setName(bf.getName() + " (Reinforcements)"); addBotForce(bf, campaign); } if (campaign.getCampaignOptions().getUseDropShips()) { if (canAddDropShips()) { boolean dropshipFound = false; for (UUID id : campaign.getForces().getAllUnits(true)) { if ((campaign.getUnit(id).getEntity().getEntityType() & Entity.ETYPE_DROPSHIP) != 0 && campaign.getUnit(id).isAvailable()) { addUnit(id); campaign.getUnit(id).setScenarioId(getId()); dropshipFound = true; break; } } if (!dropshipFound) { addDropship(campaign); } for (int i = 0; i < Compute.d6() - 3; i++) { addLance(enemyEntities, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), AtBMonthlyUnitMarket.getRandomWeight(campaign, UnitType.MEK, getContract(campaign).getEnemy()), EntityWeightClass.WEIGHT_ASSAULT, campaign); } } else if (getLanceRole().isScouting()) { /* Set allied forces to deploy in (6 - speed) turns just as player's units, * but only if not deploying by DropShip. */ alliesPlayer.stream().filter(Objects::nonNull).forEach(entity -> { int speed = entity.getWalkMP(); if (entity.getJumpMP() > 0) { if (entity instanceof megamek.common.Infantry) { speed = entity.getJumpMP(); } else { speed++; } } entity.setDeployRound(Math.max(0, 6 - speed)); }); allyEntities.stream().filter(Objects::nonNull).forEach(entity -> { int speed = entity.getWalkMP(); if (entity.getJumpMP() > 0) { if (entity instanceof megamek.common.Infantry) { speed = entity.getJumpMP(); } else { speed++; } } entity.setDeployRound(Math.max(0, 6 - speed)); }); } } // aaand for fun, run everyone through the crew upgrader if (campaign.getCampaignOptions().useAbilities()) { AtBDynamicScenarioFactory.upgradeBotCrews(this, campaign); } } @Override public void setExtraMissionForces(Campaign campaign, ArrayList<Entity> allyEntities, ArrayList<Entity> enemyEntities) { int enemyStart; int playerHome; playerHome = startPos[Compute.randomInt(4)]; setStart(playerHome); enemyStart = getStart() + 4; if (enemyStart > 8) { enemyStart -= 8; } enemyHome = enemyStart; if (allyEntities.size() > 0) { addBotForce(getAllyBotForce(getContract(campaign), getStart(), playerHome, allyEntities), campaign); } addEnemyForce(enemyEntities, getLance(campaign).getWeightClass(campaign), campaign); addBotForce(getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, enemyEntities), campaign); } @Override public boolean canAddDropShips() { return false; } /** * Generate four sets of forces: one for each weight class the player * can choose to deploy. * * @param campaign */ private void setSpecialMissionForces(Campaign campaign) { //enemy must always be the first on the botforce list so we can find it on refresh() specMissionEnemies = new ArrayList<>(); ArrayList<Entity> enemyEntities = new ArrayList<>(); ArrayList<Entity> allyEntities = new ArrayList<>(); setExtraMissionForces(campaign, allyEntities, enemyEntities); } public List<List<Entity>> getSpecMissionEnemies() { return specMissionEnemies; } /** * Generates enemy forces and four allied units that may be used if the player * deploys fewer than eight of his or her own units. * * @param campaign */ private void setBigBattleForces(Campaign campaign) { ArrayList<Entity> enemyEntities = new ArrayList<>(); ArrayList<Entity> allyEntities = new ArrayList<>(); setExtraMissionForces(campaign, allyEntities, enemyEntities); bigBattleAllies = new ArrayList<>(); bigBattleAllies.addAll(alliesPlayer); } protected void addEnemyForce(List<Entity> list, int weightClass, Campaign c) { addEnemyForce(list, weightClass, EntityWeightClass.WEIGHT_ASSAULT, 0, 0, c); } /** * Generates the enemy force based on the weight class of the lance deployed * by the player. Certain scenario types may set a maximum weight class for * enemy units or modify the roll. * * @param list All generated enemy entities are added to this list. * @param weightClass The weight class of the player's lance. * @param maxWeight The maximum weight class of each generated enemy entity * @param rollMod Modifier to the enemy lances roll. * @param weightMod Modifier to the weight class of enemy lances. * @param campaign */ protected void addEnemyForce(List<Entity> list, int weightClass, int maxWeight, int rollMod, int weightMod, Campaign campaign) { String org = AtBConfiguration.getParentFactionType(getContract(campaign).getEnemyCode()); String lances = campaign.getAtBConfig().selectBotLances(org, weightClass, rollMod / 20f); int maxLances = Math.min(lances.length(), campaign.getCampaignOptions().getSkillLevel() + 1); for (int i = 0; i < maxLances; i++) { addEnemyLance(list, AtBConfiguration.decodeWeightStr(lances, i) + weightMod, maxWeight, campaign); } if (campaign.getCampaignOptions().getAllowOpforLocalUnits()) { list.addAll(AtBDynamicScenarioFactory.fillTransports(this, list, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), campaign)); } } /** * Generates an enemy lance of a given weight class. * * @param list Generated enemy entities are added to this list. * @param weight Weight class of the enemy lance. * @param maxWeight Maximum weight of enemy entities. * @param campaign The current campaign */ private void addEnemyLance(List<Entity> list, int weight, int maxWeight, Campaign campaign) { if (weight < EntityWeightClass.WEIGHT_LIGHT) { weight = EntityWeightClass.WEIGHT_LIGHT; } if (weight > EntityWeightClass.WEIGHT_ASSAULT) { weight = EntityWeightClass.WEIGHT_ASSAULT; } addLance(list, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), weight, maxWeight, campaign); lanceCount++; } /** * Determines the most appropriate RAT and uses it to generate a random Entity * * @param faction The faction code to use for locating the correct RAT and assigning a crew name * @param skill The {@link SkillLevel} that represents the skill level of the overall force. * @param quality The equipment rating of the force. * @param unitType The UnitTableData constant for the type of unit to generate. * @param weightClass The weight class of the unit to generate * @param campaign The current campaign * @return A new Entity with crew. */ protected @Nullable Entity getEntity(String faction, SkillLevel skill, int quality, int unitType, int weightClass, Campaign campaign) { return AtBDynamicScenarioFactory.getEntity(faction, skill, quality, unitType, weightClass, false, campaign); } /** * Units that exceed the maximum weight for individual entities in the scenario * are replaced in the lance by two lighter units. * * @param weights A string of single-character letter codes for the weights of the units in the lance (e.g. "LMMH") * @param maxWeight The maximum weight allowed for the force by the parameters of the scenario type * @return A new String of the same format as weights */ private String adjustForMaxWeight(String weights, int maxWeight) { String retVal = weights; if (maxWeight == EntityWeightClass.WEIGHT_HEAVY) { //Hide and Seek (defender) retVal = weights.replaceAll("A", "LM"); } else if (maxWeight == EntityWeightClass.WEIGHT_MEDIUM) { //Probe, Recon Raid (attacker) retVal = weights.replaceAll("A", "MM"); retVal = retVal.replaceAll("H", "LM"); } return retVal; } /** * Adjust weights of units in a lance for factions that do not fit the typical * weight distribution. * * @param weights A string of single-character letter codes for the weights of the units in the lance (e.g. "LMMH") * @param faction The code of the faction to which the force belongs. * @return A new String of the same format as weights */ private String adjustWeightsForFaction(String weights, String faction) { /* Official AtB rules only specify DC, LA, and FWL; I have added * variations for some Clans. */ String retVal = weights; if (faction.equals("DC")) { retVal = weights.replaceFirst("MM", "LH"); } if ((faction.equals("LA") || faction.equals("CCO") || faction.equals("CGB")) && weights.matches("[LM]{3,}")) { retVal = weights.replaceFirst("M", "H"); } if (faction.equals("FWL") || faction.equals("CIH")) { retVal = weights.replaceFirst("HA", "HH"); } return retVal; } /* * Convenience functions overloaded to provide default values. */ protected void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, Campaign campaign) { addLance(list, faction, skill, quality, weightClass, EntityWeightClass.WEIGHT_ASSAULT, campaign, 0); } protected void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign c) { addLance(list, faction, skill, quality, weightClass, maxWeight, c, 0); } /** * * Generates a lance of the indicated weight class. If the faction is Clan, * calls addStar instead. If the faction is CS/WoB, calls addLevelII. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { if (Factions.getInstance().getFaction(faction).isClan()) { addStar(list, faction, skill, quality, weightClass, maxWeight, campaign, arrivalTurn); return; } if (faction.equals("CS") || faction.equals("WOB")) { addLevelII(list, faction, skill, quality, weightClass, maxWeight, campaign, arrivalTurn); return; } String weights = adjustForMaxWeight(campaign.getAtBConfig() .selectBotUnitWeights(AtBConfiguration.ORG_IS, weightClass), maxWeight); int forceType = FORCE_MEK; if (campaign.getCampaignOptions().getUseVehicles()) { int totalWeight = campaign.getCampaignOptions().getOpforLanceTypeMechs() + campaign.getCampaignOptions().getOpforLanceTypeMixed() + campaign.getCampaignOptions().getOpforLanceTypeVehicles(); if (totalWeight > 0) { int roll = Compute.randomInt(totalWeight); if (roll < campaign.getCampaignOptions().getOpforLanceTypeVehicles()) { forceType = FORCE_VEHICLE; } else if (roll < campaign.getCampaignOptions().getOpforLanceTypeVehicles() + campaign.getCampaignOptions().getOpforLanceTypeMixed()) { forceType = FORCE_MIXED; } } } if (forceType == FORCE_MEK && campaign.getCampaignOptions().getRegionalMechVariations()) { weights = adjustWeightsForFaction(weights, faction); } int[] unitTypes = new int[weights.length()]; Arrays.fill(unitTypes, (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK); /* Distribute vehicles randomly(-ish) through mixed units */ if (forceType == FORCE_MIXED) { for (int i = 0; i < weights.length() / 2; i++) { int j = Compute.randomInt(weights.length()); while (unitTypes[j] == UnitType.TANK) { j++; if (j >= weights.length()) { j = 0; } } unitTypes[j] = UnitType.TANK; } } for (int i = 0; i < weights.length(); i++) { Entity en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } if ((unitTypes[i] == UnitType.TANK) && campaign.getCampaignOptions().getDoubleVehicles()) { en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates a Star of the indicated weight class. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addStar(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { int forceType = FORCE_MEK; /* 1 chance in 12 of a Nova, per AtB rules; CHH/CSL * close to 1/2, no chance for CBS. Added a chance to encounter * a vehicle Star in Clan second-line (rating C or lower) units, * or all unit ratings for CHH/CSL and CBS. */ int roll = Compute.d6(2); int novaTarget = 11; if (faction.equals("CHH") || faction.equals("CSL")) { novaTarget = 8; } else if (faction.equals("CBS")) { novaTarget = TargetRoll.AUTOMATIC_FAIL; } int vehicleTarget = 4; if (!faction.equals("CHH") && !faction.equals("CSL") && !faction.equals("CBS")) { vehicleTarget -= quality; } if (roll >= novaTarget) { forceType = FORCE_NOVA; } else if (campaign.getCampaignOptions().getClanVehicles() && roll <= vehicleTarget) { forceType = FORCE_VEHICLE; } String weights = adjustForMaxWeight(campaign.getAtBConfig() .selectBotUnitWeights(AtBConfiguration.ORG_CLAN, weightClass), maxWeight); int unitType = (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK; if (campaign.getCampaignOptions().getRegionalMechVariations()) { if (unitType == UnitType.MEK) { weights = adjustWeightsForFaction(weights, faction); } /* medium vees are rare among the Clans, FM:CC, p. 8 */ if (unitType == UnitType.TANK) { weights = adjustWeightsForFaction(weights, "DC"); } } int unitsPerPoint; switch (unitType) { case UnitType.TANK: case UnitType.AERO: unitsPerPoint = 2; break; case UnitType.PROTOMEK: unitsPerPoint = 5; break; case UnitType.MEK: case UnitType.INFANTRY: case UnitType.BATTLE_ARMOR: default: unitsPerPoint = 1; break; } /* Ensure Novas use Frontline tables to get best chance at Omnis */ int tmpQuality = quality; if (forceType == FORCE_NOVA && quality < IUnitRating.DRAGOON_B) { tmpQuality = IUnitRating.DRAGOON_B; } for (int point = 0; point < weights.length(); point++) { for (int unit = 0; unit < unitsPerPoint; unit++) { Entity en = getEntity(faction, skill, tmpQuality, unitType, AtBConfiguration.decodeWeightStr(weights, point), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } if (forceType == FORCE_NOVA) { unitType = UnitType.BATTLE_ARMOR; for (int i = 0; i < 5; i++) { Entity en = getEntity(faction, skill, quality, unitType, -1, campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates a ComStar/WoB Level II of the indicated weight class. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addLevelII(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { String weights = adjustForMaxWeight(campaign.getAtBConfig() .selectBotUnitWeights(AtBConfiguration.ORG_CS, weightClass), maxWeight); int forceType = FORCE_MEK; int roll = Compute.d6(); if (roll < 4) { forceType = FORCE_VEHICLE; } else if (roll < 6) { forceType = FORCE_MIXED; } int[] unitTypes = new int[weights.length()]; Arrays.fill(unitTypes, (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK); /* Distribute vehicles randomly(-ish) through mixed units */ if (forceType == FORCE_MIXED) { for (int i = 0; i < weights.length() / 2; i++) { int j = Compute.randomInt(weights.length()); while (unitTypes[j] == UnitType.TANK) { j++; if (j >= weights.length()) { j = 0; } } unitTypes[j] = UnitType.TANK; } } for (int i = 0; i < weights.length(); i++) { Entity en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } if (unitTypes[i] == UnitType.TANK && campaign.getCampaignOptions().getDoubleVehicles()) { en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates the indicated number of civilian entities. * * @param list Generated entities are added to this list * @param num The number of civilian entities to generate * @param campaign */ protected void addCivilianUnits(List<Entity> list, int num, Campaign campaign) { list.addAll(AtBDynamicScenarioFactory.generateCivilianUnits(num, campaign)); } /** * Generates the indicated number of turret entities. * * @param list Generated entities are added to this list * @param num The number of turrets to generate * @param skill The skill level of the turret operators * @param quality The quality level of the turrets * @param campaign The campaign for which the turrets are being generated. * @param faction The faction the turrets are being generated for */ protected void addTurrets(List<Entity> list, int num, SkillLevel skill, int quality, Campaign campaign, Faction faction) { list.addAll(AtBDynamicScenarioFactory.generateTurrets(num, skill, quality, campaign, faction)); } /** * Potentially generates and adds a force of enemy aircraft to the mix of opposing force. * @param campaign The campaign for which the aircraft are being generated. */ protected void addAeroReinforcements(Campaign campaign) { // if the campaign is configured to it and we're in a 'standard' scenario or 'big battle' (don't add extra units to special scenarios) // if the opfor owns the planet, we have a user-defined chance of seeing 1-5 hostile conventional aircraft, // one per "pip" of difficulty. // if the opfor does not own the planet, we have a (slightly lower) user-defined chance of seeing 1-5 hostile aerotechs, // one per "pip" of difficulty. // if generating aeros (crude approximation), we have a 1/2 chance of a light, 1/3 chance of medium and 1/6 chance of heavy if (!(campaign.getCampaignOptions().getAllowOpforAeros() && (isStandardMission() || isBigBattle()))) { return; } AtBContract contract = getContract(campaign); boolean opForOwnsPlanet = contract.getSystem().getFactions(campaign.getLocalDate()) .contains(contract.getEnemyCode()); boolean spawnConventional = opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforAeroChance(); // aerotechs are rarer, so spawn them less often boolean spawnAerotech = !opForOwnsPlanet && Compute.d6() > MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforAeroChance() / 2; ArrayList<Entity> aircraft = new ArrayList<>(); Entity aero; if (spawnConventional) { // skill level is 0-4 where 0 is "ultra-green" and 4 is "elite badass" for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel(); unitCount++) { aero = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.CONV_FIGHTER, EntityWeightClass.WEIGHT_LIGHT, campaign); if (aero != null) { aircraft.add(aero); } } } else if (spawnAerotech) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel(); unitCount++) { // compute weight class int weightClass = randomAeroWeights[Compute.d6() - 1]; aero = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.AERO, weightClass, campaign); if (aero != null) { aircraft.add(aero); } } } if (!aircraft.isEmpty()) { /* Must set per-entity start pos for units after start of scenarios. Reinforcements * arrive from the enemy home edge, which is not necessarily the start pos. */ final int deployRound = Compute.d6() + 2; // deploy the new aircraft some time after the start of the game aircraft.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(enemyHome); en.setDeployRound(deployRound); }); boolean isAeroMap = getTerrainType() == TER_LOW_ATMO || getTerrainType() == TER_SPACE; AtBDynamicScenarioFactory.populateAeroBombs(aircraft, campaign, !isAeroMap); BotForce bf = getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, aircraft); bf.setName(bf.getName() + " (Air Support)"); addBotForce(bf, campaign); } } /** * Potentially generates some scrubs (turrets and/or infantry) to be randomly added to the opposing force. * @param campaign The campaign for which the scrubs are being generated. */ protected void addScrubReinforcements(Campaign campaign) { // if the campaign is configured to it and we are in a standard scenario or big battle // if the opfor owns the planet, and the opfor is defender we have a 1/3 chance of seeing 1-5 hostile turrets, one per "pip" of difficulty. // if the opfor owns the planet, and the opfor is defender we have a 1/3 chance of seeing 1-5 hostile conventional infantry, one per "pip". // if the opfor does not own the planet, we have a 1/6 chance of seeing 1-5 hostile battle armor, one per "pip" of difficulty. if (!(campaign.getCampaignOptions().getAllowOpforLocalUnits() && isAttacker() && (isStandardMission() || isBigBattle()))) { return; } AtBContract contract = getContract(campaign); boolean opForOwnsPlanet = contract.getSystem().getFactions(campaign.getLocalDate()) .contains(contract.getEnemyCode()); boolean spawnTurrets = opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforLocalUnitChance(); boolean spawnConventionalInfantry = opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforLocalUnitChance(); // battle armor is more rare boolean spawnBattleArmor = !opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforLocalUnitChance() / 2; boolean isTurretAppropriateTerrain = (getTerrainType() == TER_HEAVYURBAN) || (getTerrainType() == TER_LIGHTURBAN); boolean isInfantryAppropriateTerrain = isTurretAppropriateTerrain || (getTerrainType() == TER_WOODED); ArrayList<Entity> scrubs = new ArrayList<>(); // don't bother spawning turrets if there won't be anything to put them on if (spawnTurrets && isTurretAppropriateTerrain) { // skill level is 0-4 where 0 is "ultra-green" and 4 is "elite badass" and drives the number of extra units addTurrets(scrubs, campaign.getCampaignOptions().getSkillLevel() + 1, contract.getEnemySkill(), contract.getEnemyQuality(), campaign, contract.getEnemy()); } if (spawnConventionalInfantry && isInfantryAppropriateTerrain) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel(); unitCount++) { Entity infantry = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.INFANTRY, EntityWeightClass.WEIGHT_LIGHT, campaign); if (infantry != null) { scrubs.add(infantry); } } } if (spawnBattleArmor && isInfantryAppropriateTerrain) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel(); unitCount++) { // some factions don't have access to battle armor, so they get conventional infantry instead Entity generatedUnit = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.BATTLE_ARMOR, EntityWeightClass.WEIGHT_LIGHT, campaign); if (generatedUnit != null) { scrubs.add(generatedUnit); } else { Entity infantry = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.INFANTRY, EntityWeightClass.WEIGHT_LIGHT, campaign); if (infantry != null) { scrubs.add(infantry); } } } } if (!scrubs.isEmpty()) { /* Must set per-entity start pos for units after start of scenarios. Scrubs start in the center of the map. */ scrubs.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(Board.START_CENTER); // if it's a short range enemy unit, it has a chance to be hidden based on // the option being enabled and the difficulty if (campaign.getGameOptions().booleanOption(OptionsConstants.ADVANCED_HIDDEN_UNITS) && (en.getMaxWeaponRange() <= 4) && (Compute.randomInt(4) <= campaign.getCampaignOptions().getSkillLevel())) { en.setHidden(true); } }); BotForce bf = getEnemyBotForce(getContract(campaign), Board.START_CENTER, enemyHome, scrubs); bf.setName(bf.getName() + " (Local Forces)"); addBotForce(bf, campaign); } } /** * Worker method that adds a DropShip and related objective to the scenario. * @param campaign */ protected void addDropship(Campaign campaign) { Entity dropship = AtBDynamicScenarioFactory.getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.DROPSHIP, AtBDynamicScenarioFactory.UNIT_WEIGHT_UNSPECIFIED, campaign); if (dropship != null) { alliesPlayer.add(dropship); attachedUnitIds.add(UUID.fromString(dropship.getExternalIdAsString())); getExternalIDLookup().put(dropship.getExternalIdAsString(), dropship); ScenarioObjective dropshipObjective = new ScenarioObjective(); dropshipObjective.setDescription("The employer has provided a DropShip for your use in this battle. Ensure it survives. Losing it will result in a 5 point penalty to your contract score."); dropshipObjective.setObjectiveCriterion(ObjectiveCriterion.Preserve); dropshipObjective.setPercentage(100); dropshipObjective.addUnit(dropship.getExternalIdAsString()); // update the contract score by -5 if the objective is failed. ObjectiveEffect failureEffect = new ObjectiveEffect(); failureEffect.effectType = ObjectiveEffectType.ContractScoreUpdate; failureEffect.howMuch = -5; dropshipObjective.addFailureEffect(failureEffect); getScenarioObjectives().add(dropshipObjective); } } /* Convenience methods for frequently-used arguments */ protected BotForce getAllyBotForce(AtBContract c, int start, int home, List<Entity> entities) { return new BotForce(c.getAllyBotName(), 1, start, home, entities, c.getAllyCamouflage().clone(), c.getAllyColour()); } protected BotForce getEnemyBotForce(AtBContract c, int start, List<Entity> entities) { return getEnemyBotForce(c, start, start, entities); } protected BotForce getEnemyBotForce(AtBContract c, int start, int home, List<Entity> entities) { return new BotForce(c.getEnemyBotName(), 2, start, home, entities, c.getEnemyCamouflage().clone(), c.getEnemyColour()); } @Override public void generateStub(Campaign c) { super.generateStub(c); alliesPlayerStub = generateEntityStub(alliesPlayer); alliesPlayer.clear(); if (null != bigBattleAllies) { bigBattleAllies.clear(); } if (null != specMissionEnemies) { specMissionEnemies.clear(); } } protected void setObjectives(Campaign c, AtBContract contract) { getScenarioObjectives().clear(); } @Override protected void writeToXMLEnd(final PrintWriter pw, int indent) { indent++; MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "attacker", isAttacker()); MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "lanceForceId", lanceForceId); MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "lanceRole", lanceRole.name()); MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "deploymentDelay", deploymentDelay); MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "lanceCount", lanceCount); MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "rerollsRemaining", rerollsRemaining); if (null != bigBattleAllies && !bigBattleAllies.isEmpty()) { MekHqXmlUtil.writeSimpleXMLOpenTag(pw, indent++, "bigBattleAllies"); for (Entity entity : bigBattleAllies) { if (entity != null) { MekHqXmlUtil.writeEntityWithCrewToXML(pw, indent, entity, bigBattleAllies); } } MekHqXmlUtil.writeSimpleXMLCloseTag(pw, --indent, "bigBattleAllies"); } else if (!alliesPlayer.isEmpty()) { MekHqXmlUtil.writeSimpleXMLOpenTag(pw, indent++, "alliesPlayer"); for (Entity entity : alliesPlayer) { if (entity != null) { MekHqXmlUtil.writeEntityWithCrewToXML(pw, indent, entity, alliesPlayer); } } MekHqXmlUtil.writeSimpleXMLCloseTag(pw, --indent, "alliesPlayer"); } if (!alliesPlayerStub.isEmpty()) { MekHqXmlUtil.writeSimpleXMLOpenTag(pw, indent++, "alliesPlayerStub"); for (String stub : alliesPlayerStub) { MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "entityStub", stub); } MekHqXmlUtil.writeSimpleXMLCloseTag(pw, --indent, "alliesPlayerStub"); } if (!attachedUnitIds.isEmpty()) { MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "attachedUnits", getCsvFromList(attachedUnitIds)); } if (!survivalBonus.isEmpty()) { MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "survivalBonus", getCsvFromList(survivalBonus)); } if (null != specMissionEnemies && !specMissionEnemies.isEmpty()) { MekHqXmlUtil.writeSimpleXMLOpenTag(pw, indent++, "specMissionEnemies"); for (int i = 0; i < specMissionEnemies.size(); i++) { MekHqXmlUtil.writeSimpleXMLOpenTag(pw, indent++, "playerWeight", "class", i); for (Entity entity : specMissionEnemies.get(i)) { if (entity != null) { MekHqXmlUtil.writeEntityWithCrewToXML(pw, indent, entity, specMissionEnemies.get(i)); } } MekHqXmlUtil.writeSimpleXMLCloseTag(pw, --indent, "playerWeight"); } MekHqXmlUtil.writeSimpleXMLCloseTag(pw, --indent, "specMissionEnemies"); } if (!transportLinkages.isEmpty()) { MekHqXmlUtil.writeSimpleXMLOpenTag(pw, indent++, "transportLinkages"); for (String key : transportLinkages.keySet()) { MekHqXmlUtil.writeSimpleXMLOpenTag(pw, indent++, "transportLinkage"); MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "transportID", key); MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "transportedUnits", transportLinkages.get(key)); MekHqXmlUtil.writeSimpleXMLCloseTag(pw, --indent, "transportLinkage"); } MekHqXmlUtil.writeSimpleXMLCloseTag(pw, --indent, "transportLinkages"); } if (!numPlayerMinefields.isEmpty()) { MekHqXmlUtil.writeSimpleXMLOpenTag(pw, indent++, "numPlayerMinefields"); for (int key : numPlayerMinefields.keySet()) { MekHqXmlUtil.writeSimpleXMLOpenTag(pw, indent++, "numPlayerMinefield"); MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "minefieldType", key); MekHqXmlUtil.writeSimpleXMLTag(pw, indent, "minefieldCount", numPlayerMinefields.get(key).toString()); MekHqXmlUtil.writeSimpleXMLCloseTag(pw, --indent, "numPlayerMinefield"); } MekHqXmlUtil.writeSimpleXMLCloseTag(pw, --indent, "numPlayerMinefields"); } super.writeToXMLEnd(pw, --indent); } @Override protected void loadFieldsFromXmlNode(final Node wn, final Version version, final Campaign campaign) throws ParseException { super.loadFieldsFromXmlNode(wn, version, campaign); NodeList nl = wn.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); try { if (wn2.getNodeName().equalsIgnoreCase("attacker")) { setAttacker(Boolean.parseBoolean(wn2.getTextContent().trim())); } else if (wn2.getNodeName().equalsIgnoreCase("lanceForceId")) { lanceForceId = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("lanceRole")) { lanceRole = AtBLanceRole.parseFromString(wn2.getTextContent().trim()); } else if (wn2.getNodeName().equalsIgnoreCase("deploymentDelay")) { deploymentDelay = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("usingFixedMap")) { setUsingFixedMap(Boolean.parseBoolean(wn2.getTextContent().trim())); } else if (wn2.getNodeName().equalsIgnoreCase("lanceCount")) { lanceCount = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("rerollsRemaining")) { rerollsRemaining = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("alliesPlayer")) { NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MekHqXmlUtil.parseSingleEntityMul((Element) wn3, campaign.getGameOptions()); } catch (Exception e) { LogManager.getLogger().error("Error loading allied unit in scenario", e); } if (en != null) { alliesPlayer.add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } else if (wn2.getNodeName().equalsIgnoreCase("bigBattleAllies")) { bigBattleAllies = new ArrayList<>(); NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MekHqXmlUtil.parseSingleEntityMul((Element) wn3, campaign.getGameOptions()); } catch (Exception e) { LogManager.getLogger().error("Error loading allied unit in scenario", e); } if (en != null) { bigBattleAllies.add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } else if (wn2.getNodeName().equalsIgnoreCase("specMissionEnemies")) { specMissionEnemies = new ArrayList<>(); for (int i = 0; i < 4; i++) { specMissionEnemies.add(new ArrayList<>()); } NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("playerWeight")) { int weightClass = Integer.parseInt(wn3.getAttributes().getNamedItem("class").getTextContent()); NodeList nl3 = wn3.getChildNodes(); for (int j = 0; j < nl3.getLength(); j++) { Node wn4 = nl3.item(j); if (wn4.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MekHqXmlUtil.parseSingleEntityMul((Element) wn4, campaign.getGameOptions()); } catch (Exception e) { LogManager.getLogger().error("Error loading enemy unit in scenario", e); } if (null != en) { specMissionEnemies.get(weightClass).add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } } } else if (wn2.getNodeName().equalsIgnoreCase("alliesPlayerStub")) { alliesPlayerStub = getEntityStub(wn2); } else if (wn2.getNodeName().equalsIgnoreCase("attachedUnits")) { String[] ids = wn2.getTextContent().split(","); for (String s : ids) { attachedUnitIds.add(UUID.fromString(s)); } } else if (wn2.getNodeName().equalsIgnoreCase("survivalBonus")) { String[] ids = wn2.getTextContent().split(","); for (String s : ids) { survivalBonus.add(UUID.fromString(s)); } } else if (wn2.getNodeName().equalsIgnoreCase("transportLinkages")) { try { transportLinkages = loadTransportLinkages(wn2); } catch (Exception e) { LogManager.getLogger().error("Error loading transport linkages in scenario", e); } } else if (wn2.getNodeName().equalsIgnoreCase("numPlayerMinefields")) { try { loadMinefieldCounts(wn2); } catch (Exception e) { LogManager.getLogger().error("Error loading minefield counts in scenario", e); } } } catch (Exception e) { LogManager.getLogger().error("", e); } } /* In the event a discrepancy occurs between a RAT entry and the unit lookup name, * remove the entry from the list of entities that give survival bonuses * to avoid an critical error that prevents battle resolution. */ ArrayList<UUID> toRemove = new ArrayList<>(); for (UUID uid : survivalBonus) { if (!entityIds.containsKey(uid)) { toRemove.add(uid); } } survivalBonus.removeAll(toRemove); } private static Map<String, List<String>> loadTransportLinkages(Node wn) { NodeList nl = wn.getChildNodes(); Map<String, List<String>> transportLinkages = new HashMap<>(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("transportLinkage")) { loadTransportLinkage(wn2, transportLinkages); } } return transportLinkages; } private static void loadTransportLinkage(Node wn, Map<String, List<String>> transportLinkages) { NodeList nl = wn.getChildNodes(); String transportID = null; List<String> transportedUnitIDs = null; for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("transportID")) { transportID = wn2.getTextContent().trim(); } else if (wn2.getNodeName().equalsIgnoreCase("transportedUnits")) { transportedUnitIDs = Arrays.asList(wn2.getTextContent().split(",")); } } if ((transportID != null) && (transportedUnitIDs != null)) { transportLinkages.put(transportID, transportedUnitIDs); } } /** * Worker function that loads the minefield counts for the player */ private void loadMinefieldCounts(Node wn) throws NumberFormatException { NodeList nl = wn.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("numPlayerMinefield")) { NodeList minefieldNodes = wn2.getChildNodes(); int minefieldType = 0; int minefieldCount = 0; for (int minefieldIndex = 0; minefieldIndex < minefieldNodes.getLength(); minefieldIndex++) { Node wn3 = minefieldNodes.item(minefieldIndex); if (wn3.getNodeName().equalsIgnoreCase("minefieldType")) { minefieldType = Integer.parseInt(wn3.getTextContent()); } else if (wn3.getNodeName().equalsIgnoreCase("minefieldCount")) { minefieldCount = Integer.parseInt(wn3.getTextContent()); } } numPlayerMinefields.put(minefieldType, minefieldCount); } } } protected String getCsvFromList(List<?> list) { StringJoiner retVal = new StringJoiner(","); for (Object item : list) { retVal.add(item.toString()); } return retVal.toString(); } public AtBContract getContract(Campaign c) { return (AtBContract) c.getMission(getMissionId()); } /** * Gets all the entities that are part of the given entity list and are * not in this scenario's transport linkages as a transported unit. */ public List<Entity> filterUntransportedUnits(List<Entity> entities) { List<Entity> retVal = new ArrayList<>(); // assemble a set of transported units for easier lookup Set<String> transportedUnits = new HashSet<>(); for (List<String> transported : getTransportLinkages().values()) { transportedUnits.addAll(transported); } for (Entity entity : entities) { if (!transportedUnits.contains(entity.getExternalIdAsString())) { retVal.add(entity); } } return retVal; } public int getLanceForceId() { return lanceForceId; } public AtBLanceRole getLanceRole() { return lanceRole; } public Lance getLance(Campaign c) { return c.getLances().get(lanceForceId); } public void setLance(Lance l) { lanceForceId = l.getForceId(); } public boolean isAttacker() { return attacker; } public void setAttacker(boolean attacker) { this.attacker = attacker; } public List<Entity> getAlliesPlayer() { return alliesPlayer; } public List<UUID> getAttachedUnitIds() { return attachedUnitIds; } public List<UUID> getSurvivalBonusIds() { return survivalBonus; } public Entity getEntity(UUID id) { return entityIds.get(id); } public List<String> getAlliesPlayerStub() { return alliesPlayerStub; } public int getDeploymentDelay() { return deploymentDelay; } public void setDeploymentDelay(int delay) { this.deploymentDelay = delay; } public int getLanceCount() { return lanceCount; } public void setLanceCount(int lanceCount) { this.lanceCount = lanceCount; } public int getRerollsRemaining() { return rerollsRemaining; } public void useReroll() { rerollsRemaining--; } public void setRerolls(int rerolls) { rerollsRemaining = rerolls; } public int getEnemyHome() { return enemyHome; } public void setEnemyHome(int enemyHome) { this.enemyHome = enemyHome; } public int getNumPlayerMinefields(int minefieldType) { return numPlayerMinefields.containsKey(minefieldType) ? numPlayerMinefields.get(minefieldType) : 0; } public void setNumPlayerMinefields(int minefieldType, int numPlayerMinefields) { this.numPlayerMinefields.put(minefieldType, numPlayerMinefields); } public Map<String, List<String>> getTransportLinkages() { return transportLinkages; } public void setTransportLinkages(HashMap<String, List<String>> transportLinkages) { this.transportLinkages = transportLinkages; } /** * Adds a transport-cargo pair to the internal transport relationship store. * @param transport * @param cargo */ public void addTransportRelationship(String transport, String cargo) { if (!transportLinkages.containsKey(transport)) { transportLinkages.put(transport, new ArrayList<>()); } transportLinkages.get(transport).add(cargo); } @Override public boolean isFriendlyUnit(Entity entity, Campaign campaign) { return getAlliesPlayer().stream().anyMatch(unit -> unit.getExternalIdAsString().equals(entity.getExternalIdAsString())) || super.isFriendlyUnit(entity, campaign); } public String getBattlefieldControlDescription() { return getResourceBundle().getString("battleDetails.common.winnerControlsBattlefield"); } public String getDeploymentInstructions() { if (this.isBigBattle()) { return getResourceBundle().getString("battleDetails.deployEightMeks"); } else if (isSpecialMission()) { return getResourceBundle().getString("battleDetails.deploySingleMek"); } else { return ""; } } @Override public boolean canStartScenario(Campaign c) { return c.getLocalDate().equals(getDate()) && super.canStartScenario(c); } }
jzisser9/mekhq
MekHQ/src/mekhq/campaign/mission/AtBScenario.java
46,070
/* * AtBScenario.java * * Copyright (C) 2014-2021 - The MegaMek Team. All Rights Reserved. * Copyright (c) 2014 Carl Spain. All rights reserved. * * This file is part of MekHQ. * * MekHQ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MekHQ is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MekHQ. If not, see <http://www.gnu.org/licenses/>. */ package mekhq.campaign.mission; import megamek.Version; import megamek.codeUtilities.ObjectUtility; import megamek.common.*; import megamek.common.annotations.Nullable; import megamek.common.enums.SkillLevel; import megamek.common.icons.Camouflage; import megamek.common.options.OptionsConstants; import megamek.common.util.EncodeControl; import mekhq.MHQConstants; import mekhq.MekHQ; import mekhq.utilities.MHQXMLUtility; import mekhq.campaign.Campaign; import mekhq.campaign.againstTheBot.AtBConfiguration; import mekhq.campaign.force.Force; import mekhq.campaign.force.Lance; import mekhq.campaign.market.unitMarket.AtBMonthlyUnitMarket; import mekhq.campaign.mission.ObjectiveEffect.ObjectiveEffectType; import mekhq.campaign.mission.ScenarioObjective.ObjectiveCriterion; import mekhq.campaign.mission.atb.IAtBScenario; import mekhq.campaign.mission.enums.AtBLanceRole; import mekhq.campaign.personnel.SkillType; import mekhq.campaign.rating.IUnitRating; import mekhq.campaign.unit.Unit; import mekhq.campaign.universe.*; import org.apache.logging.log4j.LogManager; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.PrintWriter; import java.text.ParseException; import java.time.LocalDate; import java.util.*; /** * @author Neoancient */ public abstract class AtBScenario extends Scenario implements IAtBScenario { //region Variable Declarations public static final int DYNAMIC = -1; public static final int BASEATTACK = 0; public static final int EXTRACTION = 1; public static final int CHASE = 2; public static final int HOLDTHELINE = 3; public static final int BREAKTHROUGH = 4; public static final int HIDEANDSEEK = 5; public static final int STANDUP = 6; public static final int RECONRAID = 7; public static final int PROBE = 8; public static final int OFFICERDUEL = 9; //Special Mission public static final int ACEDUEL = 10; //Special Mission public static final int AMBUSH = 11; //Special Mission public static final int CIVILIANHELP = 12; //Special Mission public static final int ALLIEDTRAITORS = 13; //Special Mission public static final int PRISONBREAK = 14; //Special Mission public static final int STARLEAGUECACHE1 = 15; //Special Mission public static final int STARLEAGUECACHE2 = 16; //Special Mission public static final int ALLYRESCUE = 17; //Big Battle public static final int CIVILIANRIOT = 18; //Big Battle public static final int CONVOYRESCUE = 19; //Big Battle public static final int CONVOYATTACK = 20; //Big Battle public static final int PIRATEFREEFORALL = 21; //Big Battle public static final int FORCE_MEK = 0; public static final int FORCE_VEHICLE = 1; public static final int FORCE_MIXED = 2; public static final int FORCE_NOVA = 3; public static final int FORCE_VEENOVA = 4; public static final int FORCE_INFANTRY = 5; public static final int FORCE_BA = 6; public static final int FORCE_AERO = 7; public static final int FORCE_PROTOMEK = 8; public static final String[] forceTypeNames = { "Mek", "Vehicle", "Mixed", "Nova", "Nova", "Infantry", "Battle Armor", "Aerospace", "ProtoMek" }; public static final String[] antiRiotWeapons = { "ISERSmallLaser", "Small Laser", "Small Laser Prototype", "ISSmallPulseLaser", "ISSmallXPulseLaser", "Small Re-engineered Laser", "ISSmallVSPLaser", "CLERMicroLaser", "CLERSmallLaser", "ER Small Laser (CP)", "CLHeavySmallLaser", "CLImprovedSmallHeavyLaser", "ClSmall Laser", "CLERSmallPulseLaser", "CLMicroPulseLaser", "CLSmallPulseLaser", "CLSmallChemLaser", "Heavy Machine Gun", "Light Machine Gun", "Machine Gun", "Heavy Rifle", "Light Rifle", "Medium Rifle", "CLHeavyMG", "CLLightMG", "CLMG", "Flamer", "ER Flamer", "CLFlamer", "CLERFlamer", "Vehicle Flamer", "Heavy Flamer", "CLVehicleFlamer", "CLHeavyFlamer" }; /* The starting position chart in the AtB rules includes the four * corner positions as well, but this creates some conflict with * setting the home edge for the bot, which only includes the four * sides. */ protected static final int [] startPos = { Board.START_N, Board.START_E, Board.START_S, Board.START_W }; private static final int[] randomAeroWeights = { EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_HEAVY }; public static final int NO_LANCE = -1; private boolean attacker; private int lanceForceId; // -1 if scenario is not generated for a specific lance (special mission, big battle) private AtBLanceRole lanceRole; /* set when scenario is created in case it is changed for the next week before the scenario is resolved; specifically affects scenarios generated for scout lances, in which the deployment may be delayed for slower units */ private int deploymentDelay; private int lanceCount; private int rerollsRemaining; private int enemyHome; private List<Entity> alliesPlayer; private List<String> alliesPlayerStub; /* Special missions cannot generate the enemy until the unit is * added, but needs the Campaign object which is not passed * by addForce or addUnit. Instead we generate all possibilities * (one for each weight class) when the scenario is created and * choose the correct one when a unit is deployed. */ private List<List<Entity>> specMissionEnemies; /* Big battles have a similar problem for attached allies. Though * we could generate the maximum number (4) and remove them as * the player deploys additional units, they would be lost if * any units are undeployed. */ private List<Entity> bigBattleAllies; /* Units that need to be tracked for possible contract breaches * (for destruction), or bonus rolls (for survival). */ private List<UUID> attachedUnitIds; private List<UUID> survivalBonus; private Map<UUID, Entity> entityIds; // key-value pairs linking transports and the units loaded onto them. private Map<String, List<String>> transportLinkages; private Map<Integer, Integer> numPlayerMinefields; protected final transient ResourceBundle defaultResourceBundle = ResourceBundle.getBundle("mekhq.resources.AtBScenarioBuiltIn", MekHQ.getMHQOptions().getLocale(), new EncodeControl()); //endregion Variable Declarations public AtBScenario () { super(); lanceForceId = -1; lanceRole = AtBLanceRole.UNASSIGNED; alliesPlayer = new ArrayList<>(); alliesPlayerStub = new ArrayList<>(); attachedUnitIds = new ArrayList<>(); survivalBonus = new ArrayList<>(); entityIds = new HashMap<>(); transportLinkages = new HashMap<>(); numPlayerMinefields = new HashMap<>(); deploymentDelay = 0; lanceCount = 0; rerollsRemaining = 0; } public void initialize(Campaign c, Lance lance, boolean attacker, LocalDate date) { setAttacker(attacker); alliesPlayer = new ArrayList<>(); botForces = new ArrayList<>(); alliesPlayerStub = new ArrayList<>(); botForcesStubs = new ArrayList<>(); attachedUnitIds = new ArrayList<>(); survivalBonus = new ArrayList<>(); entityIds = new HashMap<>(); if (null == lance) { lanceForceId = -1; lanceRole = AtBLanceRole.UNASSIGNED; } else { this.lanceForceId = lance.getForceId(); lanceRole = lance.getRole(); setMissionId(lance.getMissionId()); for (UUID id : c.getForce(lance.getForceId()).getAllUnits(true)) { entityIds.put(id, c.getUnit(id).getEntity()); } } light = PlanetaryConditions.L_DAY; weather = PlanetaryConditions.WE_NONE; wind = PlanetaryConditions.WI_NONE; fog = PlanetaryConditions.FOG_NONE; atmosphere = PlanetaryConditions.ATMO_STANDARD; gravity = (float) 1.0; deploymentDelay = 0; setDate(date); lanceCount = 0; rerollsRemaining = 0; if (isStandardMission()) { setName(getScenarioTypeDescription() + (isAttacker() ? " (Attacker)" : " (Defender)")); } else { setName(getScenarioTypeDescription()); } initBattle(c); } public String getDesc() { return getScenarioTypeDescription() + (isStandardMission() ? (isAttacker() ? " (Attacker)" : " (Defender)") : ""); } @Override public boolean isStandardMission() { return !isSpecialMission() && !isBigBattle(); } @Override public boolean isSpecialMission() { return false; } @Override public boolean isBigBattle() { return false; } @Override public ResourceBundle getResourceBundle() { return defaultResourceBundle; } /** * Determines battle conditions: terrain, weather, map. * * @param campaign */ private void initBattle(Campaign campaign) { setTerrain(); if (campaign.getCampaignOptions().getUseLightConditions()) { setLightConditions(); } if (campaign.getCampaignOptions().getUseWeatherConditions()) { setWeather(); } if (campaign.getCampaignOptions().getUsePlanetaryConditions() && null != campaign.getMission(getMissionId())) { setPlanetaryConditions(campaign.getMission(getMissionId()), campaign); } setMapSize(); setMapFile(); if (isStandardMission()) { lanceCount = 1; } else if (isBigBattle()) { lanceCount = 2; } if (null != getLance(campaign)) { getLance(campaign).refreshCommander(campaign); if (null != getLance(campaign).getCommander(campaign).getSkill(SkillType.S_TACTICS)) { rerollsRemaining = getLance(campaign).getCommander(campaign).getSkill(SkillType.S_TACTICS).getLevel(); } } } public void setTerrain() { setTerrainType(terrainChart[Compute.d6(2) - 2]); } public void setLightConditions() { setLight(PlanetaryConditions.L_DAY); int roll = Compute.randomInt(10) + 1; if (roll < 6) { setLight(PlanetaryConditions.L_DAY); } else if (roll < 8) { setLight(PlanetaryConditions.L_DUSK); } else if (roll == 8) { setLight(PlanetaryConditions.L_FULL_MOON); } else if (roll == 9) { setLight(PlanetaryConditions.L_MOONLESS); } else { setLight(PlanetaryConditions.L_PITCH_BLACK); } } public void setWeather() { setWeather(PlanetaryConditions.WE_NONE); setWind(PlanetaryConditions.WI_NONE); setFog(PlanetaryConditions.FOG_NONE); int roll = Compute.randomInt(10) + 1; int r2 = Compute.d6(); if (roll == 6) { if (r2 < 4) { setWeather(PlanetaryConditions.WE_LIGHT_RAIN); } else if (r2 < 6) { setWeather(PlanetaryConditions.WE_MOD_RAIN); } else { setWeather(PlanetaryConditions.WE_HEAVY_RAIN); } } else if (roll == 7) { if (r2 < 4) { setWeather(PlanetaryConditions.WE_LIGHT_SNOW); } else if (r2 < 6) { setWeather(PlanetaryConditions.WE_MOD_SNOW); } else { setWeather(PlanetaryConditions.WE_HEAVY_SNOW); } } else if (roll == 8) { if (r2 < 4) { setWind(PlanetaryConditions.WI_LIGHT_GALE); } else if (r2 < 6) { setWind(PlanetaryConditions.WI_MOD_GALE); } else { setWind(PlanetaryConditions.WI_STRONG_GALE); } } else if (roll == 9) { if (r2 == 1) { setWind(PlanetaryConditions.WI_STORM); } else if (r2 == 2) { setWeather(PlanetaryConditions.WE_DOWNPOUR); } else if (r2 == 3) { setWeather(PlanetaryConditions.WE_SLEET); } else if (r2 == 4) { setWeather(PlanetaryConditions.WE_ICE_STORM); } else if (r2 == 5) { // tornadoes are classified as wind rather than weather. setWind(PlanetaryConditions.WI_TORNADO_F13); } else if (r2 == 6) { setWind(PlanetaryConditions.WI_TORNADO_F4); } } else if (roll > 9) { if (r2 < 5) { setFog(PlanetaryConditions.FOG_LIGHT); } else { setFog(PlanetaryConditions.FOG_HEAVY); } } // roll < 6 can be ignored, as it would just return nothing } public void setPlanetaryConditions(Mission mission, Campaign campaign) { if (null != mission) { PlanetarySystem psystem = Systems.getInstance().getSystemById(mission.getSystemId()); //assume primary planet for now Planet p = psystem.getPrimaryPlanet(); if (null != p) { setAtmosphere(ObjectUtility.nonNull(p.getPressure(campaign.getLocalDate()), getAtmosphere())); setGravity(ObjectUtility.nonNull(p.getGravity(), getGravity()).floatValue()); } } } public void setMapSize() { int roll = Compute.randomInt(20) + 1; if (roll < 6) { setMapSizeX(20); setMapSizeY(10); } else if (roll < 11) { setMapSizeX(10); setMapSizeY(20); } else if (roll < 13) { setMapSizeX(30); setMapSizeY(10); } else if (roll < 15) { setMapSizeX(10); setMapSizeY(30); } else if (roll < 19) { setMapSizeX(20); setMapSizeY(20); } else if (roll == 19) { setMapSizeX(40); setMapSizeY(10); } else { setMapSizeX(10); setMapSizeY(40); } } public int getMapX() { int base = getMapSizeX() + 5 * lanceCount; return Math.max(base, 20); } public int getMapY() { int base = getMapSizeY() + 5 * lanceCount; return Math.max(base, 20); } public int getBaseMapX() { return (5 * getLanceCount()) + getMapSizeX(); } public int getBaseMapY() { return (5 * getLanceCount()) + getMapSizeY(); } public void setMapFile() { final String[][] maps = { {"Sandy-hills", "Hills-craters", "Hills", "Wooded-hills", "Cliffs", "Town-hills"}, //hills {"Sandy-valley", "Rocky-valley", "Light-craters", "Heavy-craters", "Rubble-mountain", "Cliffs"}, //badlands {"Muddy-swamp", "Lake-marsh", "Lake-high", "Wooded-lake", "Swamp", "Wooded-swamp"}, //wetlands {"Town-mining", "Town-wooded", "Town-generic", "Town-farming", "Town-ruin", "Town-mountain"}, //light urban {"Savannah", "Dust-bowl", "Sandy-hills", "Town-ruin", "Town-generic", "Some-trees"}, //flatlands {"Some-trees", "Wooded-lake", "Woods-medium", "Wooded-hills", "Woods-deep", "Wooded-valley"}, //wooded {"Fortress-city", "Fortress-city", "Town-concrete", "Town-concrete", "City-high", "City-dense"}, //heavy urban {"River-huge", "Woods-river", "Sandy-river", "Rubble-river", "Seaport", "River-wetlands"}, //coastal {"Mountain-lake", "Cliffs-lake", "Rubble-mountain", "Cliffs", "Mountain-medium", "Mountain-high"} //mountains }; int actualTerrainType = getTerrainType(); // we want to make sure the terrain type we pick is in bounds, if ((getTerrainType() < 0) || (getTerrainType() >= maps.length)) { actualTerrainType = Compute.randomInt(maps.length); } setMap(maps[actualTerrainType][Compute.d6() - 1]); } public boolean canRerollTerrain() { return canRerollMap(); } public boolean canRerollMapSize() { return true; } public boolean canRerollMap() { return true; } public boolean canRerollLight() { return true; } public boolean canRerollWeather() { return true; } /** * Determines whether a unit is eligible to deploy to the scenario. The * default is true, but some special missions and big battles restrict * the participants. * * @param unit * @param campaign * @return true if the unit is eligible, otherwise false */ @Override public boolean canDeploy(Unit unit, Campaign campaign) { if (isBigBattle() && (getForces(campaign).getAllUnits(true).size() > 7)) { return false; } else { return !isSpecialMission() || (getForces(campaign).getAllUnits(true).size() <= 0); } } /** * Determines whether a force is eligible to deploy to a scenario by * checking all units contained in the force * * @param force * @param campaign * @return true if the force is eligible to deploy, otherwise false */ public boolean canDeploy(Force force, Campaign campaign) { Vector<UUID> units = force.getAllUnits(true); if (isBigBattle() && getForces(campaign).getAllUnits(true).size() + units.size() > 8) { return false; } else if (isSpecialMission() && getForces(campaign).getAllUnits(true).size() + units.size() > 0) { return false; } for (UUID id : units) { if (!canDeploy(campaign.getUnit(id), campaign)) { return false; } } return true; } /** * Determines whether a list of units is eligible to deploy to the scenario. * * @param units * @param campaign * @return true if all units in the list are eligible, otherwise false */ @Override public boolean canDeployUnits(Vector<Unit> units, Campaign campaign) { if (isBigBattle()) { return getForces(campaign).getAllUnits(true).size() + units.size() <= 8; } else if (isSpecialMission()) { return getForces(campaign).getAllUnits(true).size() + units.size() <= 1; } for (Unit unit : units) { if (!canDeploy(unit, campaign)) { return false; } } return true; } /** * Determines whether a list of forces is eligible to deploy to the scenario. * * @param forces list of forces * @param c the campaign that the forces are part of * @return true if all units in all forces in the list are eligible, otherwise false */ @Override public boolean canDeployForces(Vector<Force> forces, Campaign c) { int total = 0; for (Force force : forces) { Vector<UUID> units = force.getAllUnits(true); total += units.size(); if (isBigBattle()) { return getForces(c).getAllUnits(true).size() + units.size() <= 8; } else if (isSpecialMission()) { return getForces(c).getAllUnits(true).size() + units.size() <= 0; } for (UUID id : units) { if (!canDeploy(c.getUnit(id), c)) { return false; } } } if (isBigBattle()) { return getForces(c).getAllUnits(true).size() + total <= 8; } else if (isSpecialMission()) { return getForces(c).getAllUnits(true).size() + total <= 0; } return true; } /** * Corrects the enemy (special missions) and allies (big battles) * as necessary based on player deployments. This ought to be called * when the scenario details are displayed or the scenario is started. * * @param campaign */ public void refresh(Campaign campaign) { if (isStandardMission()) { setObjectives(campaign, getContract(campaign)); return; } Vector<UUID> deployed = getForces(campaign).getAllUnits(true); if (isBigBattle()) { int numAllies = Math.min(4, 8 - deployed.size()); alliesPlayer.clear(); for (int i = 0; i < numAllies; i++) { alliesPlayer.add(bigBattleAllies.get(i)); getExternalIDLookup().put(bigBattleAllies.get(i).getExternalIdAsString(), bigBattleAllies.get(i)); } setObjectives(campaign, getContract(campaign)); } else { if (deployed.isEmpty()) { return; } int weight = campaign.getUnit(deployed.get(0)).getEntity().getWeightClass() - 1; /* In the event that Star League Cache 1 generates a primitive 'Mech, * the player can keep the 'Mech without a battle so no enemy * units are generated. */ if (specMissionEnemies == null ) { setForces(campaign); } if ((specMissionEnemies != null) && (getBotForces().get(0) != null) && (specMissionEnemies.get(weight) != null)) { getBotForces().get(0).setFixedEntityList(specMissionEnemies.get(weight)); } setObjectives(campaign, getContract(campaign)); } } /** * Determines enemy and allied forces for the scenario. The forces for a standard * battle are based on the player's deployed lance. The enemy forces for * special missions depend on the weight class of the player's deployed * unit and the number of allies in big battles varies according to the * number the player deploys. Since the various possibilities are rather * limited, all possibilities are generated and the most appropriate is * chosen rather than rerolling every time the player changes. This is * both for efficiency and to prevent shopping. * * @param campaign */ public void setForces(Campaign campaign) { if (isStandardMission()) { setStandardMissionForces(campaign); } else if (isSpecialMission()) { setSpecialMissionForces(campaign); } else { setBigBattleForces(campaign); } setObjectives(campaign, getContract(campaign)); } /** * Generates attached allied units (bot or player controlled), the main * enemy force, any enemy reinforcements, and any additional forces * (such as civilian). * * @param campaign */ private void setStandardMissionForces(Campaign campaign) { /* Find the number of attached units required by the command rights clause */ int attachedUnitWeight = EntityWeightClass.WEIGHT_MEDIUM; if (lanceRole.isScouting() || lanceRole.isTraining()) { attachedUnitWeight = EntityWeightClass.WEIGHT_LIGHT; } int numAttachedPlayer = 0; int numAttachedBot = 0; if (getContract(campaign).getContractType().isCadreDuty()) { numAttachedPlayer = 3; } else if (campaign.getFactionCode().equals("MERC")) { switch (getContract(campaign).getCommandRights()) { case INTEGRATED: if (campaign.getCampaignOptions().getPlayerControlsAttachedUnits()) { numAttachedPlayer = 2; } else { numAttachedBot = 2; } break; case HOUSE: if (campaign.getCampaignOptions().getPlayerControlsAttachedUnits()) { numAttachedPlayer = 1; } else { numAttachedBot = 1; } break; case LIAISON: numAttachedPlayer = 1; break; default: break; } } /* The entities in the attachedAllies list will be added to the player's forces * in MM and don't require a separate BotForce */ final Camouflage camouflage = getContract(campaign).getAllyCamouflage(); for (int i = 0; i < numAttachedPlayer; i++) { Entity en = getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.MEK, attachedUnitWeight, campaign); if (null != en) { alliesPlayer.add(en); attachedUnitIds.add(UUID.fromString(en.getExternalIdAsString())); getExternalIDLookup().put(en.getExternalIdAsString(), en); if (!campaign.getCampaignOptions().getAttachedPlayerCamouflage()) { en.setCamouflage(camouflage.clone()); } } else { LogManager.getLogger().error("Entity for player-controlled allies is null"); } } /* The allyBot list will be passed to the BotForce constructor */ ArrayList<Entity> allyEntities = new ArrayList<>(); for (int i = 0; i < numAttachedBot; i++) { Entity en = getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.MEK, attachedUnitWeight, campaign); if (null != en) { allyEntities.add(en); attachedUnitIds.add(UUID.fromString(en.getExternalIdAsString())); } else { LogManager.getLogger().error("Entity for ally bot is null"); } } ArrayList<Entity> enemyEntities = new ArrayList<>(); setExtraMissionForces(campaign, allyEntities, enemyEntities); addAeroReinforcements(campaign); addScrubReinforcements(campaign); /* Possible enemy reinforcements */ int roll = Compute.d6(); if (roll > 3) { ArrayList<Entity> reinforcements = new ArrayList<>(); if (roll == 6) { addLance(reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_ASSAULT, campaign, 8); } else { addLance(reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_ASSAULT, campaign, 6); } /* Must set per-entity start pos for units after start of scenarios. Reinforcements * arrive from the enemy home edge, which is not necessarily the start pos. */ final int enemyDir = enemyHome; reinforcements.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(enemyDir); }); if (campaign.getCampaignOptions().getAllowOpforLocalUnits()) { reinforcements.addAll(AtBDynamicScenarioFactory.fillTransports(this, reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), campaign)); } BotForce bf = getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, reinforcements); bf.setName(bf.getName() + " (Reinforcements)"); addBotForce(bf, campaign); } if (campaign.getCampaignOptions().getUseDropShips()) { if (canAddDropShips()) { boolean dropshipFound = false; for (UUID id : campaign.getForces().getAllUnits(true)) { if ((campaign.getUnit(id).getEntity().getEntityType() & Entity.ETYPE_DROPSHIP) != 0 && campaign.getUnit(id).isAvailable()) { addUnit(id); campaign.getUnit(id).setScenarioId(getId()); dropshipFound = true; break; } } if (!dropshipFound) { addDropship(campaign); } for (int i = 0; i < Compute.d6() - 3; i++) { addLance(enemyEntities, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), AtBMonthlyUnitMarket.getRandomWeight(campaign, UnitType.MEK, getContract(campaign).getEnemy()), EntityWeightClass.WEIGHT_ASSAULT, campaign); } } else if (getLanceRole().isScouting()) { /* Set allied forces to deploy in (6 - speed) turns just as player's units, * but only if not deploying by DropShip. */ alliesPlayer.stream().filter(Objects::nonNull).forEach(entity -> { int speed = entity.getWalkMP(); if (entity.getJumpMP() > 0) { if (entity instanceof megamek.common.Infantry) { speed = entity.getJumpMP(); } else { speed++; } } entity.setDeployRound(Math.max(0, 6 - speed)); }); allyEntities.stream().filter(Objects::nonNull).forEach(entity -> { int speed = entity.getWalkMP(); if (entity.getJumpMP() > 0) { if (entity instanceof megamek.common.Infantry) { speed = entity.getJumpMP(); } else { speed++; } } entity.setDeployRound(Math.max(0, 6 - speed)); }); } } // aaand for fun, run everyone through the crew upgrader if (campaign.getCampaignOptions().useAbilities()) { AtBDynamicScenarioFactory.upgradeBotCrews(this, campaign); } } @Override public void setExtraMissionForces(Campaign campaign, ArrayList<Entity> allyEntities, ArrayList<Entity> enemyEntities) { int enemyStart; int playerHome; playerHome = startPos[Compute.randomInt(4)]; setStart(playerHome); enemyStart = getStart() + 4; if (enemyStart > 8) { enemyStart -= 8; } enemyHome = enemyStart; if (!allyEntities.isEmpty()) { addBotForce(getAllyBotForce(getContract(campaign), getStart(), playerHome, allyEntities), campaign); } addEnemyForce(enemyEntities, getLance(campaign).getWeightClass(campaign), campaign); addBotForce(getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, enemyEntities), campaign); } @Override public boolean canAddDropShips() { return false; } /** * Generate four sets of forces: one for each weight class the player * can choose to deploy. * * @param campaign */ private void setSpecialMissionForces(Campaign campaign) { //enemy must always be the first on the botforce list so we can find it on refresh() specMissionEnemies = new ArrayList<>(); ArrayList<Entity> enemyEntities = new ArrayList<>(); ArrayList<Entity> allyEntities = new ArrayList<>(); setExtraMissionForces(campaign, allyEntities, enemyEntities); } public List<List<Entity>> getSpecMissionEnemies() { return specMissionEnemies; } /** * Generates enemy forces and four allied units that may be used if the player * deploys fewer than eight of his or her own units. * * @param campaign */ private void setBigBattleForces(Campaign campaign) { ArrayList<Entity> enemyEntities = new ArrayList<>(); ArrayList<Entity> allyEntities = new ArrayList<>(); setExtraMissionForces(campaign, allyEntities, enemyEntities); bigBattleAllies = new ArrayList<>(); bigBattleAllies.addAll(alliesPlayer); } protected void addEnemyForce(List<Entity> list, int weightClass, Campaign c) { addEnemyForce(list, weightClass, EntityWeightClass.WEIGHT_ASSAULT, 0, 0, c); } /** * Generates the enemy force based on the weight class of the lance deployed * by the player. Certain scenario types may set a maximum weight class for * enemy units or modify the roll. * * @param list All generated enemy entities are added to this list. * @param weightClass The weight class of the player's lance. * @param maxWeight The maximum weight class of each generated enemy entity * @param rollMod Modifier to the enemy lances roll. * @param weightMod Modifier to the weight class of enemy lances. * @param campaign */ protected void addEnemyForce(List<Entity> list, int weightClass, int maxWeight, int rollMod, int weightMod, Campaign campaign) { String org = AtBConfiguration.getParentFactionType(getContract(campaign).getEnemyCode()); String lances = campaign.getAtBConfig().selectBotLances(org, weightClass, rollMod / 20f); int maxLances = Math.min(lances.length(), campaign.getCampaignOptions().getSkillLevel() + 1); for (int i = 0; i < maxLances; i++) { addEnemyLance(list, AtBConfiguration.decodeWeightStr(lances, i) + weightMod, maxWeight, campaign); } if (campaign.getCampaignOptions().getAllowOpforLocalUnits()) { list.addAll(AtBDynamicScenarioFactory.fillTransports(this, list, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), campaign)); } } /** * Generates an enemy lance of a given weight class. * * @param list Generated enemy entities are added to this list. * @param weight Weight class of the enemy lance. * @param maxWeight Maximum weight of enemy entities. * @param campaign The current campaign */ private void addEnemyLance(List<Entity> list, int weight, int maxWeight, Campaign campaign) { if (weight < EntityWeightClass.WEIGHT_LIGHT) { weight = EntityWeightClass.WEIGHT_LIGHT; } if (weight > EntityWeightClass.WEIGHT_ASSAULT) { weight = EntityWeightClass.WEIGHT_ASSAULT; } addLance(list, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), weight, maxWeight, campaign); lanceCount++; } /** * Determines the most appropriate RAT and uses it to generate a random Entity * * @param faction The faction code to use for locating the correct RAT and assigning a crew name * @param skill The {@link SkillLevel} that represents the skill level of the overall force. * @param quality The equipment rating of the force. * @param unitType The UnitTableData constant for the type of unit to generate. * @param weightClass The weight class of the unit to generate * @param campaign The current campaign * @return A new Entity with crew. */ protected @Nullable Entity getEntity(String faction, SkillLevel skill, int quality, int unitType, int weightClass, Campaign campaign) { return AtBDynamicScenarioFactory.getEntity(faction, skill, quality, unitType, weightClass, false, campaign); } /** * Units that exceed the maximum weight for individual entities in the scenario * are replaced in the lance by two lighter units. * * @param weights A string of single-character letter codes for the weights of the units in the lance (e.g. "LMMH") * @param maxWeight The maximum weight allowed for the force by the parameters of the scenario type * @return A new String of the same format as weights */ private String adjustForMaxWeight(String weights, int maxWeight) { String retVal = weights; if (maxWeight == EntityWeightClass.WEIGHT_HEAVY) { //Hide and Seek (defender) retVal = weights.replaceAll("A", "LM"); } else if (maxWeight == EntityWeightClass.WEIGHT_MEDIUM) { //Probe, Recon Raid (attacker) retVal = weights.replaceAll("A", "MM"); retVal = retVal.replaceAll("H", "LM"); } return retVal; } /** * Adjust weights of units in a lance for factions that do not fit the typical * weight distribution. * * @param weights A string of single-character letter codes for the weights of the units in the lance (e.g. "LMMH") * @param faction The code of the faction to which the force belongs. * @return A new String of the same format as weights */ private String adjustWeightsForFaction(String weights, String faction) { /* Official AtB rules only specify DC, LA, and FWL; I have added * variations for some Clans. */ String retVal = weights; if (faction.equals("DC")) { retVal = weights.replaceFirst("MM", "LH"); } if ((faction.equals("LA") || faction.equals("CCO") || faction.equals("CGB")) && weights.matches("[LM]{3,}")) { retVal = weights.replaceFirst("M", "H"); } if (faction.equals("FWL") || faction.equals("CIH")) { retVal = weights.replaceFirst("HA", "HH"); } return retVal; } /* * Convenience functions overloaded to provide default values. */ protected void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, Campaign campaign) { addLance(list, faction, skill, quality, weightClass, EntityWeightClass.WEIGHT_ASSAULT, campaign, 0); } protected void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign c) { addLance(list, faction, skill, quality, weightClass, maxWeight, c, 0); } /** * * Generates a lance of the indicated weight class. If the faction is Clan, * calls addStar instead. If the faction is CS/WoB, calls addLevelII. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { if (Factions.getInstance().getFaction(faction).isClan()) { addStar(list, faction, skill, quality, weightClass, maxWeight, campaign, arrivalTurn); return; } if (faction.equals("CS") || faction.equals("WOB")) { addLevelII(list, faction, skill, quality, weightClass, maxWeight, campaign, arrivalTurn); return; } String weights = adjustForMaxWeight(campaign.getAtBConfig() .selectBotUnitWeights(AtBConfiguration.ORG_IS, weightClass), maxWeight); int forceType = FORCE_MEK; if (campaign.getCampaignOptions().getUseVehicles()) { int totalWeight = campaign.getCampaignOptions().getOpforLanceTypeMechs() + campaign.getCampaignOptions().getOpforLanceTypeMixed() + campaign.getCampaignOptions().getOpforLanceTypeVehicles(); if (totalWeight > 0) { int roll = Compute.randomInt(totalWeight); if (roll < campaign.getCampaignOptions().getOpforLanceTypeVehicles()) { forceType = FORCE_VEHICLE; } else if (roll < campaign.getCampaignOptions().getOpforLanceTypeVehicles() + campaign.getCampaignOptions().getOpforLanceTypeMixed()) { forceType = FORCE_MIXED; } } } if (forceType == FORCE_MEK && campaign.getCampaignOptions().getRegionalMechVariations()) { weights = adjustWeightsForFaction(weights, faction); } int[] unitTypes = new int[weights.length()]; Arrays.fill(unitTypes, (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK); /* Distribute vehicles randomly(-ish) through mixed units */ if (forceType == FORCE_MIXED) { for (int i = 0; i < weights.length() / 2; i++) { int j = Compute.randomInt(weights.length()); while (unitTypes[j] == UnitType.TANK) { j++; if (j >= weights.length()) { j = 0; } } unitTypes[j] = UnitType.TANK; } } for (int i = 0; i < weights.length(); i++) { Entity en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } if ((unitTypes[i] == UnitType.TANK) && campaign.getCampaignOptions().getDoubleVehicles()) { en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates a Star of the indicated weight class. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addStar(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { int forceType = FORCE_MEK; /* 1 chance in 12 of a Nova, per AtB rules; CHH/CSL * close to 1/2, no chance for CBS. Added a chance to encounter * a vehicle Star in Clan second-line (rating C or lower) units, * or all unit ratings for CHH/CSL and CBS. */ int roll = Compute.d6(2); int novaTarget = 11; if (faction.equals("CHH") || faction.equals("CSL")) { novaTarget = 8; } else if (faction.equals("CBS")) { novaTarget = TargetRoll.AUTOMATIC_FAIL; } int vehicleTarget = 4; if (!faction.equals("CHH") && !faction.equals("CSL") && !faction.equals("CBS")) { vehicleTarget -= quality; } if (roll >= novaTarget) { forceType = FORCE_NOVA; } else if (campaign.getCampaignOptions().getClanVehicles() && roll <= vehicleTarget) { forceType = FORCE_VEHICLE; } String weights = adjustForMaxWeight(campaign.getAtBConfig() .selectBotUnitWeights(AtBConfiguration.ORG_CLAN, weightClass), maxWeight); int unitType = (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK; if (campaign.getCampaignOptions().getRegionalMechVariations()) { if (unitType == UnitType.MEK) { weights = adjustWeightsForFaction(weights, faction); } /* medium vees are rare among the Clans, FM:CC, p. 8 */ if (unitType == UnitType.TANK) { weights = adjustWeightsForFaction(weights, "DC"); } } int unitsPerPoint; switch (unitType) { case UnitType.TANK: case UnitType.AERO: unitsPerPoint = 2; break; case UnitType.PROTOMEK: unitsPerPoint = 5; break; case UnitType.MEK: case UnitType.INFANTRY: case UnitType.BATTLE_ARMOR: default: unitsPerPoint = 1; break; } /* Ensure Novas use Frontline tables to get best chance at Omnis */ int tmpQuality = quality; if (forceType == FORCE_NOVA && quality < IUnitRating.DRAGOON_B) { tmpQuality = IUnitRating.DRAGOON_B; } for (int point = 0; point < weights.length(); point++) { for (int unit = 0; unit < unitsPerPoint; unit++) { Entity en = getEntity(faction, skill, tmpQuality, unitType, AtBConfiguration.decodeWeightStr(weights, point), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } if (forceType == FORCE_NOVA) { unitType = UnitType.BATTLE_ARMOR; for (int i = 0; i < 5; i++) { Entity en = getEntity(faction, skill, quality, unitType, -1, campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates a ComStar/WoB Level II of the indicated weight class. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addLevelII(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { String weights = adjustForMaxWeight(campaign.getAtBConfig() .selectBotUnitWeights(AtBConfiguration.ORG_CS, weightClass), maxWeight); int forceType = FORCE_MEK; int roll = Compute.d6(); if (roll < 4) { forceType = FORCE_VEHICLE; } else if (roll < 6) { forceType = FORCE_MIXED; } int[] unitTypes = new int[weights.length()]; Arrays.fill(unitTypes, (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK); /* Distribute vehicles randomly(-ish) through mixed units */ if (forceType == FORCE_MIXED) { for (int i = 0; i < weights.length() / 2; i++) { int j = Compute.randomInt(weights.length()); while (unitTypes[j] == UnitType.TANK) { j++; if (j >= weights.length()) { j = 0; } } unitTypes[j] = UnitType.TANK; } } for (int i = 0; i < weights.length(); i++) { Entity en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } if (unitTypes[i] == UnitType.TANK && campaign.getCampaignOptions().getDoubleVehicles()) { en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates the indicated number of civilian entities. * * @param list Generated entities are added to this list * @param num The number of civilian entities to generate * @param campaign */ protected void addCivilianUnits(List<Entity> list, int num, Campaign campaign) { list.addAll(AtBDynamicScenarioFactory.generateCivilianUnits(num, campaign)); } /** * Generates the indicated number of turret entities. * * @param list Generated entities are added to this list * @param num The number of turrets to generate * @param skill The skill level of the turret operators * @param quality The quality level of the turrets * @param campaign The campaign for which the turrets are being generated. * @param faction The faction the turrets are being generated for */ protected void addTurrets(List<Entity> list, int num, SkillLevel skill, int quality, Campaign campaign, Faction faction) { list.addAll(AtBDynamicScenarioFactory.generateTurrets(num, skill, quality, campaign, faction)); } /** * Potentially generates and adds a force of enemy aircraft to the mix of opposing force. * @param campaign The campaign for which the aircraft are being generated. */ protected void addAeroReinforcements(Campaign campaign) { // if the campaign is configured to it and we're in a 'standard' scenario or 'big battle' (don't add extra units to special scenarios) // if the opfor owns the planet, we have a user-defined chance of seeing 1-5 hostile conventional aircraft, // one per "pip" of difficulty. // if the opfor does not own the planet, we have a (slightly lower) user-defined chance of seeing 1-5 hostile aerotechs, // one per "pip" of difficulty. // if generating aeros (crude approximation), we have a 1/2 chance of a light, 1/3 chance of medium and 1/6 chance of heavy if (!(campaign.getCampaignOptions().getAllowOpforAeros() && (isStandardMission() || isBigBattle()))) { return; } AtBContract contract = getContract(campaign); boolean opForOwnsPlanet = contract.getSystem().getFactions(campaign.getLocalDate()) .contains(contract.getEnemyCode()); boolean spawnConventional = opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforAeroChance(); // aerotechs are rarer, so spawn them less often boolean spawnAerotech = !opForOwnsPlanet && Compute.d6() > MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforAeroChance() / 2; ArrayList<Entity> aircraft = new ArrayList<>(); Entity aero; if (spawnConventional) { // skill level is 0-4 where 0 is "ultra-green" and 4 is "elite badass" for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel(); unitCount++) { aero = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.CONV_FIGHTER, EntityWeightClass.WEIGHT_LIGHT, campaign); if (aero != null) { aircraft.add(aero); } } } else if (spawnAerotech) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel(); unitCount++) { // compute weight class int weightClass = randomAeroWeights[Compute.d6() - 1]; aero = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.AERO, weightClass, campaign); if (aero != null) { aircraft.add(aero); } } } if (!aircraft.isEmpty()) { /* Must set per-entity start pos for units after start of scenarios. Reinforcements * arrive from the enemy home edge, which is not necessarily the start pos. */ final int deployRound = Compute.d6() + 2; // deploy the new aircraft some time after the start of the game aircraft.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(enemyHome); en.setDeployRound(deployRound); }); boolean isAeroMap = getTerrainType() == TER_LOW_ATMO || getTerrainType() == TER_SPACE; AtBDynamicScenarioFactory.populateAeroBombs(aircraft, campaign, !isAeroMap); BotForce bf = getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, aircraft); bf.setName(bf.getName() + " (Air Support)"); addBotForce(bf, campaign); } } /** * Potentially generates some scrubs (turrets and/or infantry) to be randomly added to the opposing force. * @param campaign The campaign for which the scrubs are being generated. */ protected void addScrubReinforcements(Campaign campaign) { // if the campaign is configured to it and we are in a standard scenario or big battle // if the opfor owns the planet, and the opfor is defender we have a 1/3 chance of seeing 1-5 hostile turrets, one per "pip" of difficulty. // if the opfor owns the planet, and the opfor is defender we have a 1/3 chance of seeing 1-5 hostile conventional infantry, one per "pip". // if the opfor does not own the planet, we have a 1/6 chance of seeing 1-5 hostile battle armor, one per "pip" of difficulty. if (!(campaign.getCampaignOptions().getAllowOpforLocalUnits() && isAttacker() && (isStandardMission() || isBigBattle()))) { return; } AtBContract contract = getContract(campaign); boolean opForOwnsPlanet = contract.getSystem().getFactions(campaign.getLocalDate()) .contains(contract.getEnemyCode()); boolean spawnTurrets = opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforLocalUnitChance(); boolean spawnConventionalInfantry = opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforLocalUnitChance(); // battle armor is more rare boolean spawnBattleArmor = !opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforLocalUnitChance() / 2; boolean isTurretAppropriateTerrain = (getTerrainType() == TER_HEAVYURBAN) || (getTerrainType() == TER_LIGHTURBAN); boolean isInfantryAppropriateTerrain = isTurretAppropriateTerrain || (getTerrainType() == TER_WOODED); ArrayList<Entity> scrubs = new ArrayList<>(); // don't bother spawning turrets if there won't be anything to put them on if (spawnTurrets && isTurretAppropriateTerrain) { // skill level is 0-4 where 0 is "ultra-green" and 4 is "elite badass" and drives the number of extra units addTurrets(scrubs, campaign.getCampaignOptions().getSkillLevel() + 1, contract.getEnemySkill(), contract.getEnemyQuality(), campaign, contract.getEnemy()); } if (spawnConventionalInfantry && isInfantryAppropriateTerrain) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel(); unitCount++) { Entity infantry = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.INFANTRY, EntityWeightClass.WEIGHT_LIGHT, campaign); if (infantry != null) { scrubs.add(infantry); } } } if (spawnBattleArmor && isInfantryAppropriateTerrain) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel(); unitCount++) { // some factions don't have access to battle armor, so they get conventional infantry instead Entity generatedUnit = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.BATTLE_ARMOR, EntityWeightClass.WEIGHT_LIGHT, campaign); if (generatedUnit != null) { scrubs.add(generatedUnit); } else { Entity infantry = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.INFANTRY, EntityWeightClass.WEIGHT_LIGHT, campaign); if (infantry != null) { scrubs.add(infantry); } } } } if (!scrubs.isEmpty()) { /* Must set per-entity start pos for units after start of scenarios. Scrubs start in the center of the map. */ scrubs.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(Board.START_CENTER); // if it's a short range enemy unit, it has a chance to be hidden based on // the option being enabled and the difficulty if (campaign.getGameOptions().booleanOption(OptionsConstants.ADVANCED_HIDDEN_UNITS) && (en.getMaxWeaponRange() <= 4) && (Compute.randomInt(4) <= campaign.getCampaignOptions().getSkillLevel())) { en.setHidden(true); } }); BotForce bf = getEnemyBotForce(getContract(campaign), Board.START_CENTER, enemyHome, scrubs); bf.setName(bf.getName() + " (Local Forces)"); addBotForce(bf, campaign); } } /** * Worker method that adds a DropShip and related objective to the scenario. * @param campaign */ protected void addDropship(Campaign campaign) { Entity dropship = AtBDynamicScenarioFactory.getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.DROPSHIP, AtBDynamicScenarioFactory.UNIT_WEIGHT_UNSPECIFIED, campaign); if (dropship != null) { alliesPlayer.add(dropship); attachedUnitIds.add(UUID.fromString(dropship.getExternalIdAsString())); getExternalIDLookup().put(dropship.getExternalIdAsString(), dropship); ScenarioObjective dropshipObjective = new ScenarioObjective(); dropshipObjective.setDescription("The employer has provided a DropShip for your use in this battle. Ensure it survives. Losing it will result in a 5 point penalty to your contract score."); dropshipObjective.setObjectiveCriterion(ObjectiveCriterion.Preserve); dropshipObjective.setPercentage(100); dropshipObjective.addUnit(dropship.getExternalIdAsString()); // update the contract score by -5 if the objective is failed. ObjectiveEffect failureEffect = new ObjectiveEffect(); failureEffect.effectType = ObjectiveEffectType.ContractScoreUpdate; failureEffect.howMuch = -5; dropshipObjective.addFailureEffect(failureEffect); getScenarioObjectives().add(dropshipObjective); } } /* Convenience methods for frequently-used arguments */ protected BotForce getAllyBotForce(AtBContract c, int start, int home, List<Entity> entities) { return new BotForce(c.getAllyBotName(), 1, start, home, entities, c.getAllyCamouflage().clone(), c.getAllyColour()); } protected BotForce getEnemyBotForce(AtBContract c, int start, List<Entity> entities) { return getEnemyBotForce(c, start, start, entities); } protected BotForce getEnemyBotForce(AtBContract c, int start, int home, List<Entity> entities) { return new BotForce(c.getEnemyBotName(), 2, start, home, entities, c.getEnemyCamouflage().clone(), c.getEnemyColour()); } @Override public void generateStub(Campaign c) { super.generateStub(c); alliesPlayerStub = generateEntityStub(alliesPlayer); alliesPlayer.clear(); if (null != bigBattleAllies) { bigBattleAllies.clear(); } if (null != specMissionEnemies) { specMissionEnemies.clear(); } } protected void setObjectives(Campaign c, AtBContract contract) { getScenarioObjectives().clear(); } @Override protected void writeToXMLEnd(final PrintWriter pw, int indent) { indent++; MHQXMLUtility.writeSimpleXMLTag(pw, indent, "attacker", isAttacker()); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "lanceForceId", lanceForceId); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "lanceRole", lanceRole.name()); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "deploymentDelay", deploymentDelay); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "lanceCount", lanceCount); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "rerollsRemaining", rerollsRemaining); if (null != bigBattleAllies && !bigBattleAllies.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "bigBattleAllies"); for (Entity entity : bigBattleAllies) { if (entity != null) { MHQXMLUtility.writeEntityWithCrewToXML(pw, indent, entity, bigBattleAllies); } } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "bigBattleAllies"); } else if (!alliesPlayer.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "alliesPlayer"); for (Entity entity : alliesPlayer) { if (entity != null) { MHQXMLUtility.writeEntityWithCrewToXML(pw, indent, entity, alliesPlayer); } } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "alliesPlayer"); } if (!alliesPlayerStub.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "alliesPlayerStub"); for (String stub : alliesPlayerStub) { MHQXMLUtility.writeSimpleXMLTag(pw, indent, "entityStub", stub); } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "alliesPlayerStub"); } if (!attachedUnitIds.isEmpty()) { MHQXMLUtility.writeSimpleXMLTag(pw, indent, "attachedUnits", getCsvFromList(attachedUnitIds)); } if (!survivalBonus.isEmpty()) { MHQXMLUtility.writeSimpleXMLTag(pw, indent, "survivalBonus", getCsvFromList(survivalBonus)); } if (null != specMissionEnemies && !specMissionEnemies.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "specMissionEnemies"); for (int i = 0; i < specMissionEnemies.size(); i++) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "playerWeight", "class", i); for (Entity entity : specMissionEnemies.get(i)) { if (entity != null) { MHQXMLUtility.writeEntityWithCrewToXML(pw, indent, entity, specMissionEnemies.get(i)); } } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "playerWeight"); } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "specMissionEnemies"); } if (!transportLinkages.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "transportLinkages"); for (String key : transportLinkages.keySet()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "transportLinkage"); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "transportID", key); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "transportedUnits", transportLinkages.get(key)); MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "transportLinkage"); } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "transportLinkages"); } if (!numPlayerMinefields.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "numPlayerMinefields"); for (int key : numPlayerMinefields.keySet()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "numPlayerMinefield"); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "minefieldType", key); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "minefieldCount", numPlayerMinefields.get(key).toString()); MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "numPlayerMinefield"); } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "numPlayerMinefields"); } super.writeToXMLEnd(pw, --indent); } @Override protected void loadFieldsFromXmlNode(final Node wn, final Version version, final Campaign campaign) throws ParseException { super.loadFieldsFromXmlNode(wn, version, campaign); NodeList nl = wn.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); try { if (wn2.getNodeName().equalsIgnoreCase("attacker")) { setAttacker(Boolean.parseBoolean(wn2.getTextContent().trim())); } else if (wn2.getNodeName().equalsIgnoreCase("lanceForceId")) { lanceForceId = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("lanceRole")) { lanceRole = AtBLanceRole.parseFromString(wn2.getTextContent().trim()); } else if (wn2.getNodeName().equalsIgnoreCase("deploymentDelay")) { deploymentDelay = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("usingFixedMap")) { setUsingFixedMap(Boolean.parseBoolean(wn2.getTextContent().trim())); } else if (wn2.getNodeName().equalsIgnoreCase("lanceCount")) { lanceCount = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("rerollsRemaining")) { rerollsRemaining = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("alliesPlayer")) { NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MHQXMLUtility.parseSingleEntityMul((Element) wn3, campaign); } catch (Exception ex) { LogManager.getLogger().error("Error loading allied unit in scenario", ex); } if (en != null) { alliesPlayer.add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } else if (wn2.getNodeName().equalsIgnoreCase("bigBattleAllies")) { bigBattleAllies = new ArrayList<>(); NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MHQXMLUtility.parseSingleEntityMul((Element) wn3, campaign); } catch (Exception ex) { LogManager.getLogger().error("Error loading allied unit in scenario", ex); } if (en != null) { bigBattleAllies.add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } else if (wn2.getNodeName().equalsIgnoreCase("specMissionEnemies")) { specMissionEnemies = new ArrayList<>(); for (int i = 0; i < 4; i++) { specMissionEnemies.add(new ArrayList<>()); } NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("playerWeight")) { int weightClass = Integer.parseInt(wn3.getAttributes().getNamedItem("class").getTextContent()); NodeList nl3 = wn3.getChildNodes(); for (int j = 0; j < nl3.getLength(); j++) { Node wn4 = nl3.item(j); if (wn4.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MHQXMLUtility.parseSingleEntityMul((Element) wn4, campaign); } catch (Exception ex) { LogManager.getLogger().error("Error loading enemy unit in scenario", ex); } if (null != en) { specMissionEnemies.get(weightClass).add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } } } else if (wn2.getNodeName().equalsIgnoreCase("alliesPlayerStub")) { alliesPlayerStub = getEntityStub(wn2); } else if (wn2.getNodeName().equalsIgnoreCase("attachedUnits")) { String[] ids = wn2.getTextContent().split(","); for (String s : ids) { attachedUnitIds.add(UUID.fromString(s)); } } else if (wn2.getNodeName().equalsIgnoreCase("survivalBonus")) { String[] ids = wn2.getTextContent().split(","); for (String s : ids) { survivalBonus.add(UUID.fromString(s)); } } else if (wn2.getNodeName().equalsIgnoreCase("transportLinkages")) { try { transportLinkages = loadTransportLinkages(wn2); } catch (Exception e) { LogManager.getLogger().error("Error loading transport linkages in scenario", e); } } else if (wn2.getNodeName().equalsIgnoreCase("numPlayerMinefields")) { try { loadMinefieldCounts(wn2); } catch (Exception e) { LogManager.getLogger().error("Error loading minefield counts in scenario", e); } } } catch (Exception e) { LogManager.getLogger().error("", e); } } /* In the event a discrepancy occurs between a RAT entry and the unit lookup name, * remove the entry from the list of entities that give survival bonuses * to avoid an critical error that prevents battle resolution. */ ArrayList<UUID> toRemove = new ArrayList<>(); for (UUID uid : survivalBonus) { if (!entityIds.containsKey(uid)) { toRemove.add(uid); } } survivalBonus.removeAll(toRemove); } private static Map<String, List<String>> loadTransportLinkages(Node wn) { NodeList nl = wn.getChildNodes(); Map<String, List<String>> transportLinkages = new HashMap<>(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("transportLinkage")) { loadTransportLinkage(wn2, transportLinkages); } } return transportLinkages; } private static void loadTransportLinkage(Node wn, Map<String, List<String>> transportLinkages) { NodeList nl = wn.getChildNodes(); String transportID = null; List<String> transportedUnitIDs = null; for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("transportID")) { transportID = wn2.getTextContent().trim(); } else if (wn2.getNodeName().equalsIgnoreCase("transportedUnits")) { transportedUnitIDs = Arrays.asList(wn2.getTextContent().split(",")); } } if ((transportID != null) && (transportedUnitIDs != null)) { transportLinkages.put(transportID, transportedUnitIDs); } } /** * Worker function that loads the minefield counts for the player */ private void loadMinefieldCounts(Node wn) throws NumberFormatException { NodeList nl = wn.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("numPlayerMinefield")) { NodeList minefieldNodes = wn2.getChildNodes(); int minefieldType = 0; int minefieldCount = 0; for (int minefieldIndex = 0; minefieldIndex < minefieldNodes.getLength(); minefieldIndex++) { Node wn3 = minefieldNodes.item(minefieldIndex); if (wn3.getNodeName().equalsIgnoreCase("minefieldType")) { minefieldType = Integer.parseInt(wn3.getTextContent()); } else if (wn3.getNodeName().equalsIgnoreCase("minefieldCount")) { minefieldCount = Integer.parseInt(wn3.getTextContent()); } } numPlayerMinefields.put(minefieldType, minefieldCount); } } } protected String getCsvFromList(List<?> list) { StringJoiner retVal = new StringJoiner(","); for (Object item : list) { retVal.add(item.toString()); } return retVal.toString(); } public AtBContract getContract(Campaign c) { return (AtBContract) c.getMission(getMissionId()); } /** * Gets all the entities that are part of the given entity list and are * not in this scenario's transport linkages as a transported unit. */ public List<Entity> filterUntransportedUnits(List<Entity> entities) { List<Entity> retVal = new ArrayList<>(); // assemble a set of transported units for easier lookup Set<String> transportedUnits = new HashSet<>(); for (List<String> transported : getTransportLinkages().values()) { transportedUnits.addAll(transported); } for (Entity entity : entities) { if (!transportedUnits.contains(entity.getExternalIdAsString())) { retVal.add(entity); } } return retVal; } public int getLanceForceId() { return lanceForceId; } public AtBLanceRole getLanceRole() { return lanceRole; } public Lance getLance(Campaign c) { return c.getLances().get(lanceForceId); } public void setLance(Lance l) { lanceForceId = l.getForceId(); } public boolean isAttacker() { return attacker; } public void setAttacker(boolean attacker) { this.attacker = attacker; } public List<Entity> getAlliesPlayer() { return alliesPlayer; } public List<UUID> getAttachedUnitIds() { return attachedUnitIds; } public List<UUID> getSurvivalBonusIds() { return survivalBonus; } public Entity getEntity(UUID id) { return entityIds.get(id); } public List<String> getAlliesPlayerStub() { return alliesPlayerStub; } public int getDeploymentDelay() { return deploymentDelay; } public void setDeploymentDelay(int delay) { this.deploymentDelay = delay; } public int getLanceCount() { return lanceCount; } public void setLanceCount(int lanceCount) { this.lanceCount = lanceCount; } public int getRerollsRemaining() { return rerollsRemaining; } public void useReroll() { rerollsRemaining--; } public void setRerolls(int rerolls) { rerollsRemaining = rerolls; } public int getEnemyHome() { return enemyHome; } public void setEnemyHome(int enemyHome) { this.enemyHome = enemyHome; } public int getNumPlayerMinefields(int minefieldType) { return numPlayerMinefields.containsKey(minefieldType) ? numPlayerMinefields.get(minefieldType) : 0; } public void setNumPlayerMinefields(int minefieldType, int numPlayerMinefields) { this.numPlayerMinefields.put(minefieldType, numPlayerMinefields); } public Map<String, List<String>> getTransportLinkages() { return transportLinkages; } public void setTransportLinkages(HashMap<String, List<String>> transportLinkages) { this.transportLinkages = transportLinkages; } /** * Adds a transport-cargo pair to the internal transport relationship store. * @param transport * @param cargo */ public void addTransportRelationship(String transport, String cargo) { if (!transportLinkages.containsKey(transport)) { transportLinkages.put(transport, new ArrayList<>()); } transportLinkages.get(transport).add(cargo); } @Override public boolean isFriendlyUnit(Entity entity, Campaign campaign) { return getAlliesPlayer().stream().anyMatch(unit -> unit.getExternalIdAsString().equals(entity.getExternalIdAsString())) || super.isFriendlyUnit(entity, campaign); } public String getBattlefieldControlDescription() { return getResourceBundle().getString("battleDetails.common.winnerControlsBattlefield"); } public String getDeploymentInstructions() { if (this.isBigBattle()) { return getResourceBundle().getString("battleDetails.deployEightMeks"); } else if (isSpecialMission()) { return getResourceBundle().getString("battleDetails.deploySingleMek"); } else { return ""; } } @Override public boolean canStartScenario(Campaign c) { return c.getLocalDate().equals(getDate()) && super.canStartScenario(c); } }
CyberSys/mekhq
MekHQ/src/mekhq/campaign/mission/AtBScenario.java
46,071
/* * Copyright (c) 2018. Aberic - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.service.impl; import cn.aberic.fabric.dao.entity.CA; import cn.aberic.fabric.dao.entity.League; import cn.aberic.fabric.dao.entity.Org; import cn.aberic.fabric.dao.entity.Peer; import cn.aberic.fabric.dao.mapper.*; import cn.aberic.fabric.service.CAService; import cn.aberic.fabric.utils.CacheUtil; import cn.aberic.fabric.utils.DateUtil; import cn.aberic.fabric.utils.FabricHelper; import cn.aberic.fabric.utils.MD5Util; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; /** * 作者:Aberic on 2018/7/12 21:11 * 邮箱:abericyang@gmail.com */ @Slf4j @Service("caService") public class CAServiceImpl implements CAService { @Resource private LeagueMapper leagueMapper; @Resource private OrgMapper orgMapper; @Resource private PeerMapper peerMapper; @Resource private CAMapper caMapper; @Resource private ChannelMapper channelMapper; @Resource private ChaincodeMapper chaincodeMapper; @Override public int add(CA ca, MultipartFile skFile, MultipartFile certificateFile) { if (null == skFile || null == certificateFile) { log.debug("ca cert is null"); return 0; } if (null != caMapper.check(ca)) { log.debug("had the same ca in this peer"); return 0; } ca = resetCa(ca); try { ca.setSk(new String(IOUtils.toByteArray(skFile.getInputStream()), Charset.forName("UTF-8"))); ca.setCertificate(new String(IOUtils.toByteArray(certificateFile.getInputStream()), Charset.forName("UTF-8"))); } catch (IOException e) { e.printStackTrace(); } ca.setDate(DateUtil.getCurrent("yyyy-MM-dd")); CacheUtil.removeHome(); return caMapper.add(ca); } @Override public int update(CA ca, MultipartFile skFile, MultipartFile certificateFile) { FabricHelper.obtain().removeChaincodeManager(channelMapper.list(ca.getPeerId()), chaincodeMapper); CacheUtil.removeHome(); CacheUtil.removeFlagCA(ca.getFlag()); ca = resetCa(ca); if (StringUtils.isEmpty(ca.getCertificate()) || StringUtils.isEmpty(ca.getSk())) { return caMapper.updateWithNoFile(ca); } try { ca.setSk(new String(IOUtils.toByteArray(skFile.getInputStream()))); ca.setCertificate(new String(IOUtils.toByteArray(certificateFile.getInputStream()), "UTF-8")); } catch (IOException e) { e.printStackTrace(); } return caMapper.update(ca); } @Override public List<CA> listAll() { return caMapper.listAll(); } @Override public List<CA> listById(int id) { return caMapper.list(id); } @Override public CA get(int id) { return caMapper.get(id); } @Override public CA getByFlag(String flag) { return caMapper.getByFlag(flag); } @Override public int countById(int id) { return caMapper.count(id); } @Override public int count() { return caMapper.countAll(); } @Override public int delete(int id) { FabricHelper.obtain().removeChaincodeManager(channelMapper.list(caMapper.get(id).getPeerId()), chaincodeMapper); return caMapper.delete(id); } @Override public List<Peer> getFullPeers() { List<Peer> peers = peerMapper.listAll(); for (Peer peer : peers) { Org org = orgMapper.get(peer.getOrgId()); peer.setOrgName(org.getMspId()); League league = leagueMapper.get(org.getLeagueId()); peer.setLeagueName(league.getName()); } return peers; } @Override public List<Peer> getPeersByCA(CA ca) { Org org = orgMapper.get(peerMapper.get(ca.getPeerId()).getOrgId()); List<Peer> peers = peerMapper.list(org.getId()); League league = leagueMapper.get(orgMapper.get(org.getId()).getLeagueId()); for (Peer peer : peers) { peer.setLeagueName(league.getName()); peer.setOrgName(org.getMspId()); } return peers; } @Override public List<CA> listFullCA() { List<CA> cas = caMapper.listAll(); for (CA ca: cas) { Peer peer = peerMapper.get(ca.getPeerId()); Org org = orgMapper.get(peer.getOrgId()); ca.setPeerName(peer.getName()); ca.setOrgName(org.getMspId()); ca.setLeagueName(leagueMapper.get(org.getLeagueId()).getName()); } return cas; } private CA resetCa(CA ca) { Peer peer = peerMapper.get(ca.getPeerId()); Org org = orgMapper.get(peer.getOrgId()); League league = leagueMapper.get(org.getLeagueId()); // ca.setName(String.format("%s-%s", ca.getName(), ca.getPeerId())); ca.setLeagueName(league.getName()); ca.setOrgName(org.getMspId()); ca.setPeerName(peer.getName()); ca.setFlag(MD5Util.md516(league.getName() + org.getMspId() + peer.getName() + ca.getName())); return ca; } }
aberic/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/service/impl/CAServiceImpl.java
46,072
/* * AtBScenario.java * * Copyright (C) 2014-2021 - The MegaMek Team. All Rights Reserved. * Copyright (c) 2014 Carl Spain. All rights reserved. * * This file is part of MekHQ. * * MekHQ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MekHQ is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MekHQ. If not, see <http://www.gnu.org/licenses/>. */ package mekhq.campaign.mission; import megamek.client.ui.swing.lobby.LobbyUtility; import megamek.common.*; import megamek.common.enums.SkillLevel; import megamek.common.icons.Camouflage; import megamek.common.options.OptionsConstants; import megamek.common.util.EncodeControl; import megamek.common.util.StringUtil; import mekhq.*; import mekhq.campaign.Campaign; import mekhq.campaign.againstTheBot.AtBConfiguration; import mekhq.campaign.force.Force; import mekhq.campaign.force.Lance; import mekhq.campaign.market.unitMarket.AtBMonthlyUnitMarket; import mekhq.campaign.mission.ObjectiveEffect.ObjectiveEffectType; import mekhq.campaign.mission.ScenarioObjective.ObjectiveCriterion; import mekhq.campaign.mission.atb.IAtBScenario; import mekhq.campaign.mission.enums.AtBLanceRole; import mekhq.campaign.personnel.SkillType; import mekhq.campaign.rating.IUnitRating; import mekhq.campaign.unit.Unit; import mekhq.campaign.universe.*; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.PrintWriter; import java.text.ParseException; import java.time.LocalDate; import java.util.*; /** * @author Neoancient */ public abstract class AtBScenario extends Scenario implements IAtBScenario { //region Variable Declarations private static final long serialVersionUID = 1148105510264408943L; public static final int DYNAMIC = -1; public static final int BASEATTACK = 0; public static final int EXTRACTION = 1; public static final int CHASE = 2; public static final int HOLDTHELINE = 3; public static final int BREAKTHROUGH = 4; public static final int HIDEANDSEEK = 5; public static final int STANDUP = 6; public static final int RECONRAID = 7; public static final int PROBE = 8; public static final int OFFICERDUEL = 9; //Special Mission public static final int ACEDUEL = 10; //Special Mission public static final int AMBUSH = 11; //Special Mission public static final int CIVILIANHELP = 12; //Special Mission public static final int ALLIEDTRAITORS = 13; //Special Mission public static final int PRISONBREAK = 14; //Special Mission public static final int STARLEAGUECACHE1 = 15; //Special Mission public static final int STARLEAGUECACHE2 = 16; //Special Mission public static final int ALLYRESCUE = 17; //Big Battle public static final int CIVILIANRIOT = 18; //Big Battle public static final int CONVOYRESCUE = 19; //Big Battle public static final int CONVOYATTACK = 20; //Big Battle public static final int PIRATEFREEFORALL = 21; //Big Battle public static final int TER_LOW_ATMO = -2; public static final int TER_SPACE = -1; public static final int TER_HILLS = 0; public static final int TER_BADLANDS = 1; public static final int TER_WETLANDS = 2; public static final int TER_LIGHTURBAN = 3; public static final int TER_FLATLANDS = 4; public static final int TER_WOODED = 5; public static final int TER_HEAVYURBAN = 6; public static final int TER_COASTAL = 7; public static final int TER_MOUNTAINS = 8; public static final String[] terrainTypes = {"Hills", "Badlands", "Wetlands", "Light Urban", "Flatlands", "Wooded", "Heavy Urban", "Coastal", "Mountains" }; public static final int FORCE_MEK = 0; public static final int FORCE_VEHICLE = 1; public static final int FORCE_MIXED = 2; public static final int FORCE_NOVA = 3; public static final int FORCE_VEENOVA = 4; public static final int FORCE_INFANTRY = 5; public static final int FORCE_BA = 6; public static final int FORCE_AERO = 7; public static final int FORCE_PROTOMEK = 8; public static final String[] forceTypeNames = { "Mek", "Vehicle", "Mixed", "Nova", "Nova", "Infantry", "Battle Armor", "Aerospace", "ProtoMek" }; public static final int[] terrainChart = { TER_HILLS, TER_BADLANDS, TER_WETLANDS, TER_LIGHTURBAN, TER_HILLS, TER_FLATLANDS, TER_WOODED, TER_HEAVYURBAN, TER_COASTAL, TER_WOODED, TER_MOUNTAINS }; public static final String[] antiRiotWeapons = { "ISERSmallLaser", "Small Laser", "Small Laser Prototype", "ISSmallPulseLaser", "ISSmallXPulseLaser", "Small Re-engineered Laser", "ISSmallVSPLaser", "CLERMicroLaser", "CLERSmallLaser", "ER Small Laser (CP)", "CLHeavySmallLaser", "CLImprovedSmallHeavyLaser", "ClSmall Laser", "CLERSmallPulseLaser", "CLMicroPulseLaser", "CLSmallPulseLaser", "CLSmallChemLaser", "Heavy Machine Gun", "Light Machine Gun", "Machine Gun", "Heavy Rifle", "Light Rifle", "Medium Rifle", "CLHeavyMG", "CLLightMG", "CLMG", "Flamer", "ER Flamer", "CLFlamer", "CLERFlamer", "Vehicle Flamer", "Heavy Flamer", "CLVehicleFlamer", "CLHeavyFlamer" }; /* The starting position chart in the AtB rules includes the four * corner positions as well, but this creates some conflict with * setting the home edge for the bot, which only includes the four * sides. */ protected static final int [] startPos = { Board.START_N, Board.START_E, Board.START_S, Board.START_W }; private static final int[] randomAeroWeights = { EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_HEAVY }; public static final int NO_LANCE = -1; private boolean attacker; private int lanceForceId; // -1 if scenario is not generated for a specific lance (special mission, big battle) private AtBLanceRole lanceRole; /* set when scenario is created in case it is changed for the next week before the scenario is resolved; specifically affects scenarios generated for scout lances, in which the deployment may be delayed for slower units */ private int terrainType; private int light; private int weather; private int wind; private int fog; private int atmosphere; private float gravity; private int start; private int deploymentDelay; private int mapSizeX; private int mapSizeY; private String map; private boolean usingFixedMap; private int lanceCount; private int rerollsRemaining; private int enemyHome; private List<Entity> alliesPlayer; protected List<BotForce> botForces; private List<String> alliesPlayerStub; private List<BotForceStub> botForceStubs; /* Special missions cannot generate the enemy until the unit is * added, but needs the Campaign object which is not passed * by addForce or addUnit. Instead we generate all possibilities * (one for each weight class) when the scenario is created and * choose the correct one when a unit is deployed. */ private List<List<Entity>> specMissionEnemies; /* Big battles have a similar problem for attached allies. Though * we could generate the maximum number (4) and remove them as * the player deploys additional units, they would be lost if * any units are undeployed. */ private List<Entity> bigBattleAllies; /* Units that need to be tracked for possible contract breaches * (for destruction), or bonus rolls (for survival). */ private List<UUID> attachedUnitIds; private List<UUID> survivalBonus; private Map<UUID, Entity> entityIds; // key-value pairs linking transports and the units loaded onto them. private Map<String, List<String>> transportLinkages; protected Map<String, Entity> externalIDLookup; private Map<Integer, Integer> numPlayerMinefields; protected static ResourceBundle defaultResourceBundle = ResourceBundle.getBundle("mekhq.resources.AtBScenarioBuiltIn", new EncodeControl()); //$NON-NLS-1$ //endregion Variable Declarations public AtBScenario () { super(); lanceForceId = -1; lanceRole = AtBLanceRole.UNASSIGNED; alliesPlayer = new ArrayList<>(); botForces = new ArrayList<>(); alliesPlayerStub = new ArrayList<>(); botForceStubs = new ArrayList<>(); attachedUnitIds = new ArrayList<>(); survivalBonus = new ArrayList<>(); entityIds = new HashMap<>(); transportLinkages = new HashMap<>(); externalIDLookup = new HashMap<>(); numPlayerMinefields = new HashMap<>(); light = PlanetaryConditions.L_DAY; weather = PlanetaryConditions.WE_NONE; wind = PlanetaryConditions.WI_NONE; fog = PlanetaryConditions.FOG_NONE; atmosphere = PlanetaryConditions.ATMO_STANDARD; gravity = (float) 1.0; deploymentDelay = 0; lanceCount = 0; rerollsRemaining = 0; } public void initialize(Campaign c, Lance lance, boolean attacker, LocalDate date) { setAttacker(attacker); alliesPlayer = new ArrayList<>(); botForces = new ArrayList<>(); alliesPlayerStub = new ArrayList<>(); botForceStubs = new ArrayList<>(); attachedUnitIds = new ArrayList<>(); survivalBonus = new ArrayList<>(); entityIds = new HashMap<>(); if (null == lance) { lanceForceId = -1; lanceRole = AtBLanceRole.UNASSIGNED; } else { this.lanceForceId = lance.getForceId(); lanceRole = lance.getRole(); setMissionId(lance.getMissionId()); for (UUID id : c.getForce(lance.getForceId()).getAllUnits(true)) { entityIds.put(id, c.getUnit(id).getEntity()); } } light = PlanetaryConditions.L_DAY; weather = PlanetaryConditions.WE_NONE; wind = PlanetaryConditions.WI_NONE; fog = PlanetaryConditions.FOG_NONE; atmosphere = PlanetaryConditions.ATMO_STANDARD; gravity = (float) 1.0; deploymentDelay = 0; setDate(date); lanceCount = 0; rerollsRemaining = 0; if (isStandardMission()) { setName(getScenarioTypeDescription() + (isAttacker() ? " (Attacker)" : " (Defender)")); } else { setName(getScenarioTypeDescription()); } initBattle(c); } public String getDesc() { return getScenarioTypeDescription() + (isStandardMission() ? (isAttacker() ? " (Attacker)" : " (Defender)") : ""); } @Override public boolean isStandardMission() { return !isSpecialMission() && !isBigBattle(); } @Override public boolean isSpecialMission() { return false; } @Override public boolean isBigBattle() { return false; } @Override public ResourceBundle getResourceBundle() { return defaultResourceBundle; } /** * Determines battle conditions: terrain, weather, map. * * @param campaign */ private void initBattle(Campaign campaign) { setTerrain(); if (campaign.getCampaignOptions().getUseLightConditions()) { setLightConditions(); } if (campaign.getCampaignOptions().getUseWeatherConditions()) { setWeather(); } if (campaign.getCampaignOptions().getUsePlanetaryConditions() && null != campaign.getMission(getMissionId())) { setPlanetaryConditions(campaign.getMission(getMissionId()), campaign); } setMapSize(); setMapFile(); if (isStandardMission()) { lanceCount = 1; } else if (isBigBattle()) { lanceCount = 2; } if (null != getLance(campaign)) { getLance(campaign).refreshCommander(campaign); if (null != getLance(campaign).getCommander(campaign).getSkill(SkillType.S_TACTICS)) { rerollsRemaining = getLance(campaign).getCommander(campaign).getSkill(SkillType.S_TACTICS).getLevel(); } } } public void setTerrain() { terrainType = terrainChart[Compute.d6(2) - 2]; } public void setLightConditions() { light = PlanetaryConditions.L_DAY; int roll = Compute.randomInt(10) + 1; if (roll < 6) light = PlanetaryConditions.L_DAY; else if (roll < 8) light = PlanetaryConditions.L_DUSK; else if (roll == 8) light = PlanetaryConditions.L_FULL_MOON; else if (roll == 9) light = PlanetaryConditions.L_MOONLESS; else light = PlanetaryConditions.L_PITCH_BLACK; } public void setWeather() { weather = PlanetaryConditions.WE_NONE; wind = PlanetaryConditions.WI_NONE; fog = PlanetaryConditions.FOG_NONE; int roll = Compute.randomInt(10) + 1; int r2 = Compute.d6(); if (roll == 6) { if (r2 < 4) weather = PlanetaryConditions.WE_LIGHT_RAIN; else if (r2 < 6) weather = PlanetaryConditions.WE_MOD_RAIN; else weather = PlanetaryConditions.WE_HEAVY_RAIN; } else if (roll == 7) { if (r2 < 4) weather = PlanetaryConditions.WE_LIGHT_SNOW; else if (r2 < 6) weather = PlanetaryConditions.WE_MOD_SNOW; else weather = PlanetaryConditions.WE_HEAVY_SNOW; } else if (roll == 8) { if (r2 < 4) wind = PlanetaryConditions.WI_LIGHT_GALE; else if (r2 < 6) wind = PlanetaryConditions.WI_MOD_GALE; else wind = PlanetaryConditions.WI_STRONG_GALE; } else if (roll == 9) { if (r2 == 1) wind = PlanetaryConditions.WI_STORM; else if (r2 == 2) weather = PlanetaryConditions.WE_DOWNPOUR; else if (r2 == 3) weather = PlanetaryConditions.WE_SLEET; else if (r2 == 4) weather = PlanetaryConditions.WE_ICE_STORM; else if (r2 == 5) wind = PlanetaryConditions.WI_TORNADO_F13; // tornadoes are classified as wind rather than weather. else if (r2 == 6) wind = PlanetaryConditions.WI_TORNADO_F4; } else if (roll > 9) { if (r2 < 5) fog = PlanetaryConditions.FOG_LIGHT; else fog = PlanetaryConditions.FOG_HEAVY; } // roll < 6 can be ignored, as it would just return nothing } public void setPlanetaryConditions(Mission mission, Campaign campaign) { if (null != mission) { PlanetarySystem psystem = Systems.getInstance().getSystemById(mission.getSystemId()); //assume primary planet for now Planet p = psystem.getPrimaryPlanet(); if (null != p) { atmosphere = Utilities.nonNull(p.getPressure(campaign.getLocalDate()), atmosphere); gravity = Utilities.nonNull(p.getGravity(), gravity).floatValue(); } } } public void setMapSize() { int roll = Compute.randomInt(20) + 1; if (roll < 6) { mapSizeX = 20; mapSizeY = 10; } else if (roll < 11) { mapSizeX = 10; mapSizeY = 20; } else if (roll < 13) { mapSizeX = 30; mapSizeY = 10; } else if (roll < 15) { mapSizeX = 10; mapSizeY = 30; } else if (roll < 19) { mapSizeX = 20; mapSizeY = 20; } else if (roll == 19) { mapSizeX = 40; mapSizeY = 10; } else { mapSizeX = 10; mapSizeY = 40; } } public int getMapX() { int base = mapSizeX + 5 * lanceCount; return Math.max(base, 20); } public int getMapY() { int base = mapSizeY + 5 * lanceCount; return Math.max(base, 20); } public int getBaseMapX() { return (5 * getLanceCount()) + getMapSizeX(); } public int getBaseMapY() { return (5 * getLanceCount()) + getMapSizeY(); } public void setMapFile() { final String[][] maps = { {"Sandy-hills", "Hills-craters", "Hills", "Wooded-hills", "Cliffs", "Town-hills"}, //hills {"Sandy-valley", "Rocky-valley", "Light-craters", "Heavy-craters", "Rubble-mountain", "Cliffs"}, //badlands {"Muddy-swamp", "Lake-marsh", "Lake-high", "Wooded-lake", "Swamp", "Wooded-swamp"}, //wetlands {"Town-mining", "Town-wooded", "Town-generic", "Town-farming", "Town-ruin", "Town-mountain"}, //light urban {"Savannah", "Dust-bowl", "Sandy-hills", "Town-ruin", "Town-generic", "Some-trees"}, //flatlands {"Some-trees", "Wooded-lake", "Woods-medium", "Wooded-hills", "Woods-deep", "Wooded-valley"}, //wooded {"Fortress-city", "Fortress-city", "Town-concrete", "Town-concrete", "City-high", "City-dense"}, //heavy urban {"River-huge", "Woods-river", "Sandy-river", "Rubble-river", "Seaport", "River-wetlands"}, //coastal {"Mountain-lake", "Cliffs-lake", "Rubble-mountain", "Cliffs", "Mountain-medium", "Mountain-high"} //mountains }; int actualTerrainType = terrainType; // we want to make sure the terrain type we pick is in bounds, if ((terrainType < 0) || (terrainType >= maps.length)) { actualTerrainType = Compute.randomInt(maps.length); } map = maps[actualTerrainType][Compute.d6() - 1]; } public boolean canRerollTerrain() { return canRerollMap(); } public boolean canRerollMapSize() { return true; } public boolean canRerollMap() { return true; } public boolean canRerollLight() { return true; } public boolean canRerollWeather() { return true; } /** * Determines whether a unit is eligible to deploy to the scenario. The * default is true, but some special missions and big battles restrict * the participants. * * @param unit * @param campaign * @return true if the unit is eligible, otherwise false */ public boolean canDeploy(Unit unit, Campaign campaign) { if (isBigBattle() && (getForces(campaign).getAllUnits(true).size() > 7)) { return false; } else { return !isSpecialMission() || (getForces(campaign).getAllUnits(true).size() <= 0); } } /** * Determines whether a force is eligible to deploy to a scenario by * checking all units contained in the force * * @param force * @param campaign * @return true if the force is eligible to deploy, otherwise false */ public boolean canDeploy(Force force, Campaign campaign) { Vector<UUID> units = force.getAllUnits(true); if (isBigBattle() && getForces(campaign).getAllUnits(true).size() + units.size() > 8) { return false; } else if (isSpecialMission() && getForces(campaign).getAllUnits(true).size() + units.size() > 0) { return false; } for (UUID id : units) { if (!canDeploy(campaign.getUnit(id), campaign)) { return false; } } return true; } /** * Determines whether a list of units is eligible to deploy to the scenario. * * @param units * @param campaign * @return true if all units in the list are eligible, otherwise false */ public boolean canDeployUnits(Vector<Unit> units, Campaign campaign) { if (isBigBattle()) { return getForces(campaign).getAllUnits(true).size() + units.size() <= 8; } else if (isSpecialMission()) { return getForces(campaign).getAllUnits(true).size() + units.size() <= 1; } for (Unit unit : units) { if (!canDeploy(unit, campaign)) { return false; } } return true; } /** * Determines whether a list of forces is eligible to deploy to the scenario. * * @param forces list of forces * @param c the campaign that the forces are part of * @return true if all units in all forces in the list are eligible, otherwise false */ public boolean canDeployForces(Vector<Force> forces, Campaign c) { int total = 0; for (Force force : forces) { Vector<UUID> units = force.getAllUnits(true); total += units.size(); if (isBigBattle()) { return getForces(c).getAllUnits(true).size() + units.size() <= 8; } else if (isSpecialMission()) { return getForces(c).getAllUnits(true).size() + units.size() <= 0; } for (UUID id : units) { if (!canDeploy(c.getUnit(id), c)) { return false; } } } if (isBigBattle()) { return getForces(c).getAllUnits(true).size() + total <= 8; } else if (isSpecialMission()) { return getForces(c).getAllUnits(true).size() + total <= 0; } return true; } /** * Corrects the enemy (special missions) and allies (big battles) * as necessary based on player deployments. This ought to be called * when the scenario details are displayed or the scenario is started. * * @param campaign */ public void refresh(Campaign campaign) { if (isStandardMission()) { setObjectives(campaign, getContract(campaign)); return; } Vector<UUID> deployed = getForces(campaign).getAllUnits(true); if (isBigBattle()) { int numAllies = Math.min(4, 8 - deployed.size()); alliesPlayer.clear(); for (int i = 0; i < numAllies; i++) { alliesPlayer.add(bigBattleAllies.get(i)); externalIDLookup.put(bigBattleAllies.get(i).getExternalIdAsString(), bigBattleAllies.get(i)); } setObjectives(campaign, getContract(campaign)); } else { if (deployed.size() == 0) { return; } int weight = campaign.getUnit(deployed.get(0)).getEntity().getWeightClass() - 1; /* In the event that Star League Cache 1 generates a primitive 'Mech, * the player can keep the 'Mech without a battle so no enemy * units are generated. */ if (specMissionEnemies == null ) { setForces(campaign); } if (specMissionEnemies != null && botForces.get(0) != null && specMissionEnemies.get(weight) != null) { botForces.get(0).setEntityList(specMissionEnemies.get(weight)); } setObjectives(campaign, getContract(campaign)); } } /** * Determines enemy and allied forces for the scenario. The forces for a standard * battle are based on the player's deployed lance. The enemy forces for * special missions depend on the weight class of the player's deployed * unit and the number of allies in big battles varies according to the * number the player deploys. Since the various possibilities are rather * limited, all possibilities are generated and the most appropriate is * chosen rather than rerolling every time the player changes. This is * both for efficiency and to prevent shopping. * * @param campaign */ public void setForces(Campaign campaign) { if (isStandardMission()) { setStandardMissionForces(campaign); } else if (isSpecialMission()) { setSpecialMissionForces(campaign); } else { setBigBattleForces(campaign); } setObjectives(campaign, getContract(campaign)); } /** * Generates attached allied units (bot or player controlled), the main * enemy force, any enemy reinforcements, and any additional forces * (such as civilian). * * @param campaign */ private void setStandardMissionForces(Campaign campaign) { /* Find the number of attached units required by the command rights clause */ int attachedUnitWeight = EntityWeightClass.WEIGHT_MEDIUM; if (lanceRole.isScouting() || lanceRole.isTraining()) { attachedUnitWeight = EntityWeightClass.WEIGHT_LIGHT; } int numAttachedPlayer = 0; int numAttachedBot = 0; if (getContract(campaign).getContractType().isCadreDuty()) { numAttachedPlayer = 3; } else if (campaign.getFactionCode().equals("MERC")) { switch (getContract(campaign).getCommandRights()) { case INTEGRATED: if (campaign.getCampaignOptions().getPlayerControlsAttachedUnits()) { numAttachedPlayer = 2; } else { numAttachedBot = 2; } break; case HOUSE: if (campaign.getCampaignOptions().getPlayerControlsAttachedUnits()) { numAttachedPlayer = 1; } else { numAttachedBot = 1; } break; case LIAISON: numAttachedPlayer = 1; break; default: break; } } /* The entities in the attachedAllies list will be added to the player's forces * in MM and don't require a separate BotForce */ final Camouflage camouflage = getContract(campaign).getAllyCamouflage(); for (int i = 0; i < numAttachedPlayer; i++) { Entity en = getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.MEK, attachedUnitWeight, campaign); if (null != en) { alliesPlayer.add(en); attachedUnitIds.add(UUID.fromString(en.getExternalIdAsString())); externalIDLookup.put(en.getExternalIdAsString(), en); if (!campaign.getCampaignOptions().getAttachedPlayerCamouflage()) { en.setCamouflage(camouflage.clone()); } } else { MekHQ.getLogger().error("Entity for player-controlled allies is null"); } } /* The allyBot list will be passed to the BotForce constructor */ ArrayList<Entity> allyEntities = new ArrayList<>(); for (int i = 0; i < numAttachedBot; i++) { Entity en = getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.MEK, attachedUnitWeight, campaign); if (null != en) { allyEntities.add(en); attachedUnitIds.add(UUID.fromString(en.getExternalIdAsString())); } else { MekHQ.getLogger().error("Entity for ally bot is null"); } } ArrayList<Entity> enemyEntities = new ArrayList<>(); setExtraMissionForces(campaign, allyEntities, enemyEntities); addAeroReinforcements(campaign); addScrubReinforcements(campaign); /* Possible enemy reinforcements */ int roll = Compute.d6(); if (roll > 3) { ArrayList<Entity> reinforcements = new ArrayList<>(); if (roll == 6) { addLance(reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_ASSAULT, campaign, 8); } else { addLance(reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_ASSAULT, campaign, 6); } /* Must set per-entity start pos for units after start of scenarios. Reinforcements * arrive from the enemy home edge, which is not necessarily the start pos. */ final int enemyDir = enemyHome; reinforcements.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(enemyDir); }); if (campaign.getCampaignOptions().getAllowOpforLocalUnits()) { reinforcements.addAll(AtBDynamicScenarioFactory.fillTransports(this, reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), campaign)); } BotForce bf = getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, reinforcements); bf.setName(bf.getName() + " (Reinforcements)"); addBotForce(bf); } if (campaign.getCampaignOptions().getUseDropShips()) { if (canAddDropShips()) { boolean dropshipFound = false; for (UUID id : campaign.getForces().getAllUnits(true)) { if ((campaign.getUnit(id).getEntity().getEntityType() & Entity.ETYPE_DROPSHIP) != 0 && campaign.getUnit(id).isAvailable()) { addUnit(id); campaign.getUnit(id).setScenarioId(getId()); dropshipFound = true; break; } } if (!dropshipFound) { addDropship(campaign); } for (int i = 0; i < Compute.d6() - 3; i++) { addLance(enemyEntities, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), AtBMonthlyUnitMarket.getRandomWeight(campaign, UnitType.MEK, getContract(campaign).getEnemy()), EntityWeightClass.WEIGHT_ASSAULT, campaign); } } else if (getLanceRole().isScouting()) { /* Set allied forces to deploy in (6 - speed) turns just as player's units, * but only if not deploying by DropShip. */ alliesPlayer.stream().filter(Objects::nonNull).forEach(entity -> { int speed = entity.getWalkMP(); if (entity.getJumpMP() > 0) { if (entity instanceof megamek.common.Infantry) { speed = entity.getJumpMP(); } else { speed++; } } entity.setDeployRound(Math.max(0, 6 - speed)); }); allyEntities.stream().filter(Objects::nonNull).forEach(entity -> { int speed = entity.getWalkMP(); if (entity.getJumpMP() > 0) { if (entity instanceof megamek.common.Infantry) { speed = entity.getJumpMP(); } else { speed++; } } entity.setDeployRound(Math.max(0, 6 - speed)); }); } } // aaand for fun, run everyone through the crew upgrader if (campaign.getCampaignOptions().useAbilities()) { AtBDynamicScenarioFactory.upgradeBotCrews(this); } } @Override public void setExtraMissionForces(Campaign campaign, ArrayList<Entity> allyEntities, ArrayList<Entity> enemyEntities) { int enemyStart; int playerHome; start = playerHome = startPos[Compute.randomInt(4)]; enemyStart = start + 4; if (enemyStart > 8) { enemyStart -= 8; } enemyHome = enemyStart; if (allyEntities.size() > 0) { addBotForce(getAllyBotForce(getContract(campaign), start, playerHome, allyEntities)); } addEnemyForce(enemyEntities, getLance(campaign).getWeightClass(campaign), campaign); addBotForce(getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, enemyEntities)); } @Override public boolean canAddDropShips() { return false; } /** * Generate four sets of forces: one for each weight class the player * can choose to deploy. * * @param campaign */ private void setSpecialMissionForces(Campaign campaign) { //enemy must always be the first on the botforce list so we can find it on refresh() specMissionEnemies = new ArrayList<>(); ArrayList<Entity> enemyEntities = new ArrayList<>(); ArrayList<Entity> allyEntities = new ArrayList<>(); setExtraMissionForces(campaign, allyEntities, enemyEntities); } public List<List<Entity>> getSpecMissionEnemies() { return specMissionEnemies; } /** * Generates enemy forces and four allied units that may be used if the player * deploys fewer than eight of his or her own units. * * @param campaign */ private void setBigBattleForces(Campaign campaign) { ArrayList<Entity> enemyEntities = new ArrayList<>(); ArrayList<Entity> allyEntities = new ArrayList<>(); setExtraMissionForces(campaign, allyEntities, enemyEntities); bigBattleAllies = new ArrayList<>(); bigBattleAllies.addAll(alliesPlayer); } protected void addEnemyForce(List<Entity> list, int weightClass, Campaign c) { addEnemyForce(list, weightClass, EntityWeightClass.WEIGHT_ASSAULT, 0, 0, c); } /** * Generates the enemy force based on the weight class of the lance deployed * by the player. Certain scenario types may set a maximum weight class for * enemy units or modify the roll. * * @param list All generated enemy entities are added to this list. * @param weightClass The weight class of the player's lance. * @param maxWeight The maximum weight class of each generated enemy entity * @param rollMod Modifier to the enemy lances roll. * @param weightMod Modifier to the weight class of enemy lances. * @param campaign */ protected void addEnemyForce(List<Entity> list, int weightClass, int maxWeight, int rollMod, int weightMod, Campaign campaign) { String org = AtBConfiguration.getParentFactionType(getContract(campaign).getEnemyCode()); String lances = campaign.getAtBConfig().selectBotLances(org, weightClass, rollMod / 20f); int maxLances = Math.min(lances.length(), campaign.getCampaignOptions().getSkillLevel() + 1); for (int i = 0; i < maxLances; i++) { addEnemyLance(list, AtBConfiguration.decodeWeightStr(lances, i) + weightMod, maxWeight, campaign); } if (campaign.getCampaignOptions().getAllowOpforLocalUnits()) { list.addAll(AtBDynamicScenarioFactory.fillTransports(this, list, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), campaign)); } } /** * Generates an enemy lance of a given weight class. * * @param list Generated enemy entities are added to this list. * @param weight Weight class of the enemy lance. * @param maxWeight Maximum weight of enemy entities. * @param campaign */ private void addEnemyLance(List<Entity> list, int weight, int maxWeight, Campaign campaign) { if (weight < EntityWeightClass.WEIGHT_LIGHT) { weight = EntityWeightClass.WEIGHT_LIGHT; } if (weight > EntityWeightClass.WEIGHT_ASSAULT) { weight = EntityWeightClass.WEIGHT_ASSAULT; } addLance(list, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), weight, maxWeight, campaign); lanceCount++; } /** * Determines the most appropriate RAT and uses it to generate a random Entity * * @param faction The faction code to use for locating the correct RAT and assigning a crew name * @param skill The {@link SkillLevel} that represents the skill level of the overall force. * @param quality The equipment rating of the force. * @param unitType The UnitTableData constant for the type of unit to generate. * @param weightClass The weight class of the unit to generate * @param campaign * @return A new Entity with crew. */ protected Entity getEntity(String faction, SkillLevel skill, int quality, int unitType, int weightClass, Campaign campaign) { return AtBDynamicScenarioFactory.getEntity(faction, skill, quality, unitType, weightClass, false, campaign); } /** * Units that exceed the maximum weight for individual entities in the scenario * are replaced in the lance by two lighter units. * * @param weights A string of single-character letter codes for the weights of the units in the lance (e.g. "LMMH") * @param maxWeight The maximum weight allowed for the force by the parameters of the scenario type * @return A new String of the same format as weights */ private String adjustForMaxWeight(String weights, int maxWeight) { String retVal = weights; if (maxWeight == EntityWeightClass.WEIGHT_HEAVY) { //Hide and Seek (defender) retVal = weights.replaceAll("A", "LM"); } else if (maxWeight == EntityWeightClass.WEIGHT_MEDIUM) { //Probe, Recon Raid (attacker) retVal = weights.replaceAll("A", "MM"); retVal = retVal.replaceAll("H", "LM"); } return retVal; } /** * Adjust weights of units in a lance for factions that do not fit the typical * weight distribution. * * @param weights A string of single-character letter codes for the weights of the units in the lance (e.g. "LMMH") * @param faction The code of the faction to which the force belongs. * @return A new String of the same format as weights */ private String adjustWeightsForFaction(String weights, String faction) { /* Official AtB rules only specify DC, LA, and FWL; I have added * variations for some Clans. */ String retVal = weights; if (faction.equals("DC")) { retVal = weights.replaceFirst("MM", "LH"); } if ((faction.equals("LA") || faction.equals("CCO") || faction.equals("CGB")) && weights.matches("[LM]{3,}")) { retVal = weights.replaceFirst("M", "H"); } if (faction.equals("FWL") || faction.equals("CIH")) { retVal = weights.replaceFirst("HA", "HH"); } return retVal; } /* * Convenience functions overloaded to provide default values. */ protected void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, Campaign campaign) { addLance(list, faction, skill, quality, weightClass, EntityWeightClass.WEIGHT_ASSAULT, campaign, 0); } protected void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign c) { addLance(list, faction, skill, quality, weightClass, maxWeight, c, 0); } /** * * Generates a lance of the indicated weight class. If the faction is Clan, * calls addStar instead. If the faction is CS/WoB, calls addLevelII. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { if (Factions.getInstance().getFaction(faction).isClan()) { addStar(list, faction, skill, quality, weightClass, maxWeight, campaign, arrivalTurn); return; } if (faction.equals("CS") || faction.equals("WOB")) { addLevelII(list, faction, skill, quality, weightClass, maxWeight, campaign, arrivalTurn); return; } String weights = adjustForMaxWeight(campaign.getAtBConfig() .selectBotUnitWeights(AtBConfiguration.ORG_IS, weightClass), maxWeight); int forceType = FORCE_MEK; if (campaign.getCampaignOptions().getUseVehicles()) { int totalWeight = campaign.getCampaignOptions().getOpforLanceTypeMechs() + campaign.getCampaignOptions().getOpforLanceTypeMixed() + campaign.getCampaignOptions().getOpforLanceTypeVehicles(); if (totalWeight > 0) { int roll = Compute.randomInt(totalWeight); if (roll < campaign.getCampaignOptions().getOpforLanceTypeVehicles()) { forceType = FORCE_VEHICLE; } else if (roll < campaign.getCampaignOptions().getOpforLanceTypeVehicles() + campaign.getCampaignOptions().getOpforLanceTypeMixed()) { forceType = FORCE_MIXED; } } } if (forceType == FORCE_MEK && campaign.getCampaignOptions().getRegionalMechVariations()) { weights = adjustWeightsForFaction(weights, faction); } int[] unitTypes = new int[weights.length()]; Arrays.fill(unitTypes, (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK); /* Distribute vehicles randomly(-ish) through mixed units */ if (forceType == FORCE_MIXED) { for (int i = 0; i < weights.length() / 2; i++) { int j = Compute.randomInt(weights.length()); while (unitTypes[j] == UnitType.TANK) { j++; if (j >= weights.length()) { j = 0; } } unitTypes[j] = UnitType.TANK; } } for (int i = 0; i < weights.length(); i++) { Entity en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } if ((unitTypes[i] == UnitType.TANK) && campaign.getCampaignOptions().getDoubleVehicles()) { en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates a Star of the indicated weight class. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addStar(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { int forceType = FORCE_MEK; /* 1 chance in 12 of a Nova, per AtB rules; CHH/CSL * close to 1/2, no chance for CBS. Added a chance to encounter * a vehicle Star in Clan second-line (rating C or lower) units, * or all unit ratings for CHH/CSL and CBS. */ int roll = Compute.d6(2); int novaTarget = 11; if (faction.equals("CHH") || faction.equals("CSL")) { novaTarget = 8; } else if (faction.equals("CBS")) { novaTarget = TargetRoll.AUTOMATIC_FAIL; } int vehicleTarget = 4; if (!faction.equals("CHH") && !faction.equals("CSL") && !faction.equals("CBS")) { vehicleTarget -= quality; } if (roll >= novaTarget) { forceType = FORCE_NOVA; } else if (campaign.getCampaignOptions().getClanVehicles() && roll <= vehicleTarget) { forceType = FORCE_VEHICLE; } String weights = adjustForMaxWeight(campaign.getAtBConfig() .selectBotUnitWeights(AtBConfiguration.ORG_CLAN, weightClass), maxWeight); int unitType = (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK; if (campaign.getCampaignOptions().getRegionalMechVariations()) { if (unitType == UnitType.MEK) { weights = adjustWeightsForFaction(weights, faction); } /* medium vees are rare among the Clans, FM:CC, p. 8 */ if (unitType == UnitType.TANK) { weights = adjustWeightsForFaction(weights, "DC"); } } int unitsPerPoint; switch (unitType) { case UnitType.TANK: case UnitType.AERO: unitsPerPoint = 2; break; case UnitType.PROTOMEK: unitsPerPoint = 5; break; case UnitType.MEK: case UnitType.INFANTRY: case UnitType.BATTLE_ARMOR: default: unitsPerPoint = 1; break; } /* Ensure Novas use Frontline tables to get best chance at Omnis */ int tmpQuality = quality; if (forceType == FORCE_NOVA && quality < IUnitRating.DRAGOON_B) { tmpQuality = IUnitRating.DRAGOON_B; } for (int point = 0; point < weights.length(); point++) { for (int unit = 0; unit < unitsPerPoint; unit++) { Entity en = getEntity(faction, skill, tmpQuality, unitType, AtBConfiguration.decodeWeightStr(weights, point), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } if (forceType == FORCE_NOVA) { unitType = UnitType.BATTLE_ARMOR; for (int i = 0; i < 5; i++) { Entity en = getEntity(faction, skill, quality, unitType, -1, campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates a ComStar/WoB Level II of the indicated weight class. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addLevelII(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { String weights = adjustForMaxWeight(campaign.getAtBConfig() .selectBotUnitWeights(AtBConfiguration.ORG_CS, weightClass), maxWeight); int forceType = FORCE_MEK; int roll = Compute.d6(); if (roll < 4) { forceType = FORCE_VEHICLE; } else if (roll < 6) { forceType = FORCE_MIXED; } int[] unitTypes = new int[weights.length()]; Arrays.fill(unitTypes, (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK); /* Distribute vehicles randomly(-ish) through mixed units */ if (forceType == FORCE_MIXED) { for (int i = 0; i < weights.length() / 2; i++) { int j = Compute.randomInt(weights.length()); while (unitTypes[j] == UnitType.TANK) { j++; if (j >= weights.length()) { j = 0; } } unitTypes[j] = UnitType.TANK; } } for (int i = 0; i < weights.length(); i++) { Entity en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } if (unitTypes[i] == UnitType.TANK && campaign.getCampaignOptions().getDoubleVehicles()) { en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates the indicated number of civilian entities. * * @param list Generated entities are added to this list * @param num The number of civilian entities to generate * @param campaign */ protected void addCivilianUnits(List<Entity> list, int num, Campaign campaign) { list.addAll(AtBDynamicScenarioFactory.generateCivilianUnits(num, campaign)); } /** * Generates the indicated number of turret entities. * * @param list Generated entities are added to this list * @param num The number of turrets to generate * @param skill The skill level of the turret operators * @param quality The quality level of the turrets * @param campaign The campaign for which the turrets are being generated. * @param faction The faction the turrets are being generated for */ protected void addTurrets(List<Entity> list, int num, SkillLevel skill, int quality, Campaign campaign, Faction faction) { list.addAll(AtBDynamicScenarioFactory.generateTurrets(num, skill, quality, campaign, faction)); } /** * Potentially generates and adds a force of enemy aircraft to the mix of opposing force. * @param campaign The campaign for which the aircraft are being generated. */ protected void addAeroReinforcements(Campaign campaign) { // if the campaign is configured to it and we're in a 'standard' scenario or 'big battle' (don't add extra units to special scenarios) // if the opfor owns the planet, we have a user-defined chance of seeing 1-5 hostile conventional aircraft, // one per "pip" of difficulty. // if the opfor does not own the planet, we have a (slightly lower) user-defined chance of seeing 1-5 hostile aerotechs, // one per "pip" of difficulty. // if generating aeros (crude approximation), we have a 1/2 chance of a light, 1/3 chance of medium and 1/6 chance of heavy if (!(campaign.getCampaignOptions().getAllowOpforAeros() && (isStandardMission() || isBigBattle()))) { return; } AtBContract contract = getContract(campaign); boolean opForOwnsPlanet = contract.getSystem().getFactions(campaign.getLocalDate()) .contains(contract.getEnemyCode()); boolean spawnConventional = opForOwnsPlanet && Compute.d6() >= MekHqConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforAeroChance(); // aerotechs are rarer, so spawn them less often boolean spawnAerotech = !opForOwnsPlanet && Compute.d6() > MekHqConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforAeroChance() / 2; ArrayList<Entity> aircraft = new ArrayList<>(); Entity aero; if (spawnConventional) { // skill level is 0-4 where 0 is "ultra-green" and 4 is "elite badass" for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel(); unitCount++) { aero = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.CONV_FIGHTER, EntityWeightClass.WEIGHT_LIGHT, campaign); if (aero != null) { aircraft.add(aero); } } } else if (spawnAerotech) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel(); unitCount++) { // compute weight class int weightClass = randomAeroWeights[Compute.d6() - 1]; aero = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.AERO, weightClass, campaign); if (aero != null) { aircraft.add(aero); } } } if (!aircraft.isEmpty()) { /* Must set per-entity start pos for units after start of scenarios. Reinforcements * arrive from the enemy home edge, which is not necessarily the start pos. */ final int deployRound = Compute.d6() + 2; // deploy the new aircraft some time after the start of the game aircraft.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(enemyHome); en.setDeployRound(deployRound); }); boolean isAeroMap = getTerrainType() == TER_LOW_ATMO || getTerrainType() == TER_SPACE; AtBDynamicScenarioFactory.populateAeroBombs(aircraft, campaign, !isAeroMap); BotForce bf = getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, aircraft); bf.setName(bf.getName() + " (Air Support)"); addBotForce(bf); } } /** * Potentially generates some scrubs (turrets and/or infantry) to be randomly added to the opposing force. * @param campaign The campaign for which the scrubs are being generated. */ protected void addScrubReinforcements(Campaign campaign) { // if the campaign is configured to it and we are in a standard scenario or big battle // if the opfor owns the planet, and the opfor is defender we have a 1/3 chance of seeing 1-5 hostile turrets, one per "pip" of difficulty. // if the opfor owns the planet, and the opfor is defender we have a 1/3 chance of seeing 1-5 hostile conventional infantry, one per "pip". // if the opfor does not own the planet, we have a 1/6 chance of seeing 1-5 hostile battle armor, one per "pip" of difficulty. if (!(campaign.getCampaignOptions().getAllowOpforLocalUnits() && isAttacker() && (isStandardMission() || isBigBattle()))) { return; } AtBContract contract = getContract(campaign); boolean opForOwnsPlanet = contract.getSystem().getFactions(campaign.getLocalDate()) .contains(contract.getEnemyCode()); boolean spawnTurrets = opForOwnsPlanet && Compute.d6() >= MekHqConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforLocalUnitChance(); boolean spawnConventionalInfantry = opForOwnsPlanet && Compute.d6() >= MekHqConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforLocalUnitChance(); // battle armor is more rare boolean spawnBattleArmor = !opForOwnsPlanet && Compute.d6() >= MekHqConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpforLocalUnitChance() / 2; boolean isTurretAppropriateTerrain = (terrainType == TER_HEAVYURBAN) || (terrainType == TER_LIGHTURBAN); boolean isInfantryAppropriateTerrain = isTurretAppropriateTerrain || terrainType == TER_WOODED; ArrayList<Entity> scrubs = new ArrayList<>(); // don't bother spawning turrets if there won't be anything to put them on if (spawnTurrets && isTurretAppropriateTerrain) { // skill level is 0-4 where 0 is "ultra-green" and 4 is "elite badass" and drives the number of extra units addTurrets(scrubs, campaign.getCampaignOptions().getSkillLevel() + 1, contract.getEnemySkill(), contract.getEnemyQuality(), campaign, contract.getEnemy()); } if (spawnConventionalInfantry && isInfantryAppropriateTerrain) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel(); unitCount++) { Entity infantry = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.INFANTRY, EntityWeightClass.WEIGHT_LIGHT, campaign); if (infantry != null) { scrubs.add(infantry); } } } if (spawnBattleArmor && isInfantryAppropriateTerrain) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel(); unitCount++) { // some factions don't have access to battle armor, so they get conventional infantry instead Entity generatedUnit = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.BATTLE_ARMOR, EntityWeightClass.WEIGHT_LIGHT, campaign); if (generatedUnit != null) { scrubs.add(generatedUnit); } else { Entity infantry = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.INFANTRY, EntityWeightClass.WEIGHT_LIGHT, campaign); if (infantry != null) { scrubs.add(infantry); } } } } if (!scrubs.isEmpty()) { /* Must set per-entity start pos for units after start of scenarios. Scrubs start in the center of the map. */ scrubs.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(Board.START_CENTER); // if it's a short range enemy unit, it has a chance to be hidden based on // the option being enabled and the difficulty if (campaign.getGameOptions().booleanOption(OptionsConstants.ADVANCED_HIDDEN_UNITS) && (en.getMaxWeaponRange() <= 4) && (Compute.randomInt(4) <= campaign.getCampaignOptions().getSkillLevel())) { en.setHidden(true); } }); BotForce bf = getEnemyBotForce(getContract(campaign), Board.START_CENTER, enemyHome, scrubs); bf.setName(bf.getName() + " (Local Forces)"); addBotForce(bf); } } /** * Worker method that adds a DropShip and related objective to the scenario. * @param campaign */ protected void addDropship(Campaign campaign) { Entity dropship = AtBDynamicScenarioFactory.getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.DROPSHIP, AtBDynamicScenarioFactory.UNIT_WEIGHT_UNSPECIFIED, campaign); if (dropship != null) { alliesPlayer.add(dropship); attachedUnitIds.add(UUID.fromString(dropship.getExternalIdAsString())); externalIDLookup.put(dropship.getExternalIdAsString(), dropship); ScenarioObjective dropshipObjective = new ScenarioObjective(); dropshipObjective.setDescription("The employer has provided a DropShip for your use in this battle. Ensure it survives. Losing it will result in a 5 point penalty to your contract score."); dropshipObjective.setObjectiveCriterion(ObjectiveCriterion.Preserve); dropshipObjective.setPercentage(100); dropshipObjective.addUnit(dropship.getExternalIdAsString()); // update the contract score by -5 if the objective is failed. ObjectiveEffect failureEffect = new ObjectiveEffect(); failureEffect.effectType = ObjectiveEffectType.ContractScoreUpdate; failureEffect.howMuch = -5; dropshipObjective.addFailureEffect(failureEffect); getScenarioObjectives().add(dropshipObjective); } } /* Convenience methods for frequently-used arguments */ protected BotForce getAllyBotForce(AtBContract c, int start, int home, List<Entity> entities) { return new BotForce(c.getAllyBotName(), 1, start, home, entities, c.getAllyCamouflage().clone(), c.getAllyColour()); } protected BotForce getEnemyBotForce(AtBContract c, int start, List<Entity> entities) { return getEnemyBotForce(c, start, start, entities); } protected BotForce getEnemyBotForce(AtBContract c, int start, int home, List<Entity> entities) { return new BotForce(c.getEnemyBotName(), 2, start, home, entities, c.getEnemyCamouflage().clone(), c.getEnemyColour()); } public List<String> generateEntityStub(List<Entity> entities) { List<String> stub = new ArrayList<>(); for (Entity en : entities) { if (null == en) { stub.add("<html><font color='red'>No random assignment table found for faction</font></html>"); } else { stub.add("<html>" + en.getCrew().getName() + " (" + en.getCrew().getGunnery() + "/" + en.getCrew().getPiloting() + "), " + "<i>" + en.getShortName() + "</i>" + "</html>"); } } return stub; } public BotForceStub generateBotStub(BotForce bf) { return new BotForceStub("<html>" + bf.getName() + " <i>" + ((bf.getTeam() == 1) ? "Allied" : "Enemy") + "</i>" + " Start: " + IStartingPositions.START_LOCATION_NAMES[bf.getStart()] + " BV: " + bf.getTotalBV() + "</html>", generateEntityStub(bf.getEntityList())); } @Override public void generateStub(Campaign c) { super.generateStub(c); for (BotForce bf : botForces) { botForceStubs.add(generateBotStub(bf)); } alliesPlayerStub = generateEntityStub(alliesPlayer); botForces.clear(); alliesPlayer.clear(); if (null != bigBattleAllies) { bigBattleAllies.clear(); } if (null != specMissionEnemies) { specMissionEnemies.clear(); } } protected void setObjectives(Campaign c, AtBContract contract) { getScenarioObjectives().clear(); } @Override protected void writeToXmlEnd(PrintWriter pw1, int indent) { MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "attacker", isAttacker()); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "lanceForceId", lanceForceId); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "lanceRole", lanceRole.name()); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "terrainType", terrainType); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "light", light); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "weather", weather); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "wind", wind); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "fog", fog); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "atmosphere", atmosphere); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "gravity", gravity); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "start", start); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "deploymentDelay", deploymentDelay); pw1.println(MekHqXmlUtil.indentStr(indent+1) +"<mapSize>" + mapSizeX + "," + mapSizeY +"</mapSize>"); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "map", map); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "usingFixedMap", isUsingFixedMap()); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "lanceCount", lanceCount); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "rerollsRemaining", rerollsRemaining); if (null != bigBattleAllies && bigBattleAllies.size() > 0) { pw1.println(MekHqXmlUtil.indentStr(indent+1) + "<bigBattleAllies>"); for (Entity entity : bigBattleAllies) { if (entity != null) { pw1.println(writeEntityWithCrewToXmlString(entity, indent+2, bigBattleAllies)); } } pw1.println(MekHqXmlUtil.indentStr(indent+1) + "</bigBattleAllies>"); } else if (alliesPlayer.size() > 0) { pw1.println(MekHqXmlUtil.indentStr(indent+1)+"<alliesPlayer>"); for (Entity entity : alliesPlayer) { if (entity != null) { pw1.println(writeEntityWithCrewToXmlString(entity, indent+2, alliesPlayer)); } } pw1.println(MekHqXmlUtil.indentStr(indent+1)+"</alliesPlayer>"); } for (BotForce botForce : botForces) { pw1.println(MekHqXmlUtil.indentStr(indent+1)+"<botForce>"); botForce.writeToXml(pw1, indent+1); pw1.println(MekHqXmlUtil.indentStr(indent+1)+"</botForce>"); } if (alliesPlayerStub.size() > 0) { pw1.println(MekHqXmlUtil.indentStr(indent+1) + "<alliesPlayerStub>"); for (String stub : alliesPlayerStub) { MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+2, "entityStub", MekHqXmlUtil.escape(stub)); } pw1.println(MekHqXmlUtil.indentStr(indent+1) + "</alliesPlayerStub>"); } for (BotForceStub bot : botForceStubs) { pw1.println(MekHqXmlUtil.indentStr(indent+1) + "<botForceStub name=\"" + MekHqXmlUtil.escape(bot.getName()) + "\">"); for (String entity : bot.getEntityList()) { MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+2, "entityStub", MekHqXmlUtil.escape(entity)); } pw1.println(MekHqXmlUtil.indentStr(indent+1) + "</botForceStub>"); } if (attachedUnitIds.size() > 0) { MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "attachedUnits", getCsvFromList(attachedUnitIds)); } if (survivalBonus.size() > 0) { MekHqXmlUtil.writeSimpleXmlTag(pw1, indent+1, "survivalBonus", getCsvFromList(survivalBonus)); } if (null != specMissionEnemies && specMissionEnemies.size() > 0) { pw1.println(MekHqXmlUtil.indentStr(indent+1) + "<specMissionEnemies>"); for (int i = 0; i < specMissionEnemies.size(); i++) { pw1.println(MekHqXmlUtil.indentStr(indent+2) + "<playerWeight class=\"" + i + "\">"); for (Entity entity : specMissionEnemies.get(i)) { if (entity != null) { pw1.println(writeEntityWithCrewToXmlString(entity, indent+3, specMissionEnemies.get(i))); } } pw1.println(MekHqXmlUtil.indentStr(indent+2) + "</playerWeight>"); } pw1.println(MekHqXmlUtil.indentStr(indent+1) + "</specMissionEnemies>"); } if (transportLinkages.size() > 0) { pw1.println(MekHqXmlUtil.indentStr(indent+1) + "<transportLinkages>"); for (String key : transportLinkages.keySet()) { pw1.println(MekHqXmlUtil.indentStr(indent+2) + "<transportLinkage>"); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 3, "transportID", key); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 3, "transportedUnits", String.join(",", transportLinkages.get(key))); pw1.println(MekHqXmlUtil.indentStr(indent+2) + "</transportLinkage>"); } pw1.println(MekHqXmlUtil.indentStr(indent+1) + "</transportLinkages>"); } if (numPlayerMinefields.size() > 0) { MekHqXmlUtil.writeSimpleXMLOpenIndentedLine(pw1, indent + 1, "numPlayerMinefields"); for (int key : numPlayerMinefields.keySet()) { MekHqXmlUtil.writeSimpleXMLOpenIndentedLine(pw1, indent + 2, "numPlayerMinefield"); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 3, "minefieldType", key); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 3, "minefieldCount", numPlayerMinefields.get(key).toString()); MekHqXmlUtil.writeSimpleXMLCloseIndentedLine(pw1, indent + 2, "numPlayerMinefield"); } MekHqXmlUtil.writeSimpleXMLCloseIndentedLine(pw1, indent + 1, "numPlayerMinefields"); } super.writeToXmlEnd(pw1, indent); } /* MekHqXmlUtil.writeEntityToXmlString does not include the crew, * as crew is handled by the Person class in MekHQ. This utility * function will insert a pilot tag (and also a deployment attribute, * which is also not added by the MekHqXmlUtil method). */ public static String writeEntityWithCrewToXmlString(Entity tgtEnt, int indentLvl, List<Entity> list) { String retVal = MekHqXmlUtil.writeEntityToXmlString(tgtEnt, indentLvl, list); StringBuilder crew = new StringBuilder(MekHqXmlUtil.indentStr(indentLvl + 1)); crew.append("<crew crewType=\"").append(tgtEnt.getCrew().getCrewType().toString().toLowerCase()) .append("\" size=\"").append(tgtEnt.getCrew().getSize()); if (tgtEnt.getCrew().getInitBonus() != 0) { crew.append("\" initB=\"").append(tgtEnt.getCrew().getInitBonus()); } if (tgtEnt.getCrew().getCommandBonus() != 0) { crew.append("\" commandB=\"").append(tgtEnt.getCrew().getCommandBonus()); } if (tgtEnt instanceof Mech) { crew.append("\" autoeject=\"").append(((Mech) tgtEnt).isAutoEject()); } crew.append("\" ejected=\"").append(tgtEnt.getCrew().isEjected()).append("\">\n"); for (int pos = 0; pos < tgtEnt.getCrew().getSlotCount(); pos++) { crew.append(MekHqXmlUtil.indentStr(indentLvl + 2)).append("<crewMember slot=\"") .append(pos).append("\" name=\"").append(MekHqXmlUtil.escape(tgtEnt.getCrew().getName(pos))) .append("\" nick=\"").append(MekHqXmlUtil.escape(tgtEnt.getCrew().getNickname(pos))) .append("\" gender=\"").append(tgtEnt.getCrew().getGender(pos).name()) .append("\" gunnery=\"").append(tgtEnt.getCrew().getGunnery(pos)) .append("\" piloting=\"").append(tgtEnt.getCrew().getPiloting(pos)); if (tgtEnt.getCrew().getToughness(pos) != 0) { crew.append("\" toughness=\"").append(tgtEnt.getCrew().getToughness(pos)); } if (tgtEnt.getCrew().isDead(pos) || tgtEnt.getCrew().getHits(pos) >= Crew.DEATH) { crew.append("\" hits=\"Dead"); } else if (tgtEnt.getCrew().getHits(pos) > 0) { crew.append("\" hits=\"").append(tgtEnt.getCrew().getHits(pos)); } crew.append("\" externalId=\"").append(tgtEnt.getCrew().getExternalIdAsString(pos)); String extraData = tgtEnt.getCrew().writeExtraDataToXMLLine(pos); if (!StringUtil.isNullOrEmpty(extraData)) { crew.append(extraData); } crew.append("\"/>\n"); } crew.append(MekHqXmlUtil.indentStr(indentLvl + 1)).append("</crew>\n"); return retVal.replaceFirst(">", ">\n" + crew + "\n"); } @Override protected void loadFieldsFromXmlNode(final Node wn, final Version version) throws ParseException { super.loadFieldsFromXmlNode(wn, version); NodeList nl = wn.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); try { if (wn2.getNodeName().equalsIgnoreCase("attacker")) { setAttacker(Boolean.parseBoolean(wn2.getTextContent().trim())); } else if (wn2.getNodeName().equalsIgnoreCase("lanceForceId")) { lanceForceId = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("lanceRole")) { lanceRole = AtBLanceRole.parseFromString(wn2.getTextContent().trim()); } else if (wn2.getNodeName().equalsIgnoreCase("terrainType")) { terrainType = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("light")) { light = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("weather")) { weather = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("wind")) { wind = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("fog")) { fog = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("atmosphere")) { atmosphere = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("gravity")) { gravity = Float.parseFloat(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("start")) { start = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("deploymentDelay")) { deploymentDelay = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("mapSize")) { String []xy = wn2.getTextContent().split(","); mapSizeX = Integer.parseInt(xy[0]); mapSizeY = Integer.parseInt(xy[1]); } else if (wn2.getNodeName().equalsIgnoreCase("map")) { map = wn2.getTextContent().trim(); } else if (wn2.getNodeName().equalsIgnoreCase("usingFixedMap")) { setUsingFixedMap(Boolean.parseBoolean(wn2.getTextContent().trim())); } else if (wn2.getNodeName().equalsIgnoreCase("lanceCount")) { lanceCount = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("rerollsRemaining")) { rerollsRemaining = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("alliesPlayer")) { NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MekHqXmlUtil.getEntityFromXmlString(wn3); } catch (Exception e) { MekHQ.getLogger().error("Error loading allied unit in scenario", e); } if (en != null) { alliesPlayer.add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } else if (wn2.getNodeName().equalsIgnoreCase("bigBattleAllies")) { bigBattleAllies = new ArrayList<>(); NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MekHqXmlUtil.getEntityFromXmlString(wn3); } catch (Exception e) { MekHQ.getLogger().error("Error loading allied unit in scenario", e); } if (en != null) { bigBattleAllies.add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } else if (wn2.getNodeName().equalsIgnoreCase("specMissionEnemies")) { specMissionEnemies = new ArrayList<>(); for (int i = 0; i < 4; i++) { specMissionEnemies.add(new ArrayList<>()); } NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("playerWeight")) { int weightClass = Integer.parseInt(wn3.getAttributes().getNamedItem("class").getTextContent()); NodeList nl3 = wn3.getChildNodes(); for (int j = 0; j < nl3.getLength(); j++) { Node wn4 = nl3.item(j); if (wn4.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MekHqXmlUtil.getEntityFromXmlString(wn4); } catch (Exception e) { MekHQ.getLogger().error("Error loading enemy unit in scenario", e); } if (null != en) { specMissionEnemies.get(weightClass).add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } } } else if (wn2.getNodeName().equalsIgnoreCase("botForce")) { BotForce bf = new BotForce(); try { bf.setFieldsFromXmlNode(wn2, version); } catch (Exception e) { MekHQ.getLogger().error("Error loading bot force in scenario", e); bf = null; } if (bf != null) { addBotForce(bf); } } else if (wn2.getNodeName().equalsIgnoreCase("alliesPlayerStub")) { alliesPlayerStub = getEntityStub(wn2); } else if (wn2.getNodeName().equalsIgnoreCase("botForceStub")) { String name = MekHqXmlUtil.unEscape(wn2.getAttributes().getNamedItem("name").getTextContent()); List<String> stub = getEntityStub(wn2); botForceStubs.add(new BotForceStub(name, stub)); } else if (wn2.getNodeName().equalsIgnoreCase("attachedUnits")) { String[] ids = wn2.getTextContent().split(","); for (String s : ids) { attachedUnitIds.add(UUID.fromString(s)); } } else if (wn2.getNodeName().equalsIgnoreCase("survivalBonus")) { String[] ids = wn2.getTextContent().split(","); for (String s : ids) { survivalBonus.add(UUID.fromString(s)); } } else if (wn2.getNodeName().equalsIgnoreCase("transportLinkages")) { try { transportLinkages = loadTransportLinkages(wn2); } catch (Exception e) { MekHQ.getLogger().error("Error loading transport linkages in scenario", e); } } else if (wn2.getNodeName().equalsIgnoreCase("numPlayerMinefields")) { try { loadMinefieldCounts(wn2); } catch (Exception e) { MekHQ.getLogger().error("Error loading minefield counts in scenario", e); } } } catch (Exception e) { MekHQ.getLogger().error(e); } } /* In the event a discrepancy occurs between a RAT entry and the unit lookup name, * remove the entry from the list of entities that give survival bonuses * to avoid an critical error that prevents battle resolution. */ ArrayList<UUID> toRemove = new ArrayList<>(); for (UUID uid : survivalBonus) { if (!entityIds.containsKey(uid)) { toRemove.add(uid); } } survivalBonus.removeAll(toRemove); } private static Map<String, List<String>> loadTransportLinkages(Node wn) { NodeList nl = wn.getChildNodes(); Map<String, List<String>> transportLinkages = new HashMap<>(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("transportLinkage")) { loadTransportLinkage(wn2, transportLinkages); } } return transportLinkages; } private static void loadTransportLinkage(Node wn, Map<String, List<String>> transportLinkages) { NodeList nl = wn.getChildNodes(); String transportID = null; List<String> transportedUnitIDs = null; for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("transportID")) { transportID = wn2.getTextContent().trim(); } else if (wn2.getNodeName().equalsIgnoreCase("transportedUnits")) { transportedUnitIDs = Arrays.asList(wn2.getTextContent().split(",")); } } if ((transportID != null) && (transportedUnitIDs != null)) { transportLinkages.put(transportID, transportedUnitIDs); } } /** * Worker function that loads the minefield counts for the player */ private void loadMinefieldCounts(Node wn) throws NumberFormatException { NodeList nl = wn.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("numPlayerMinefield")) { NodeList minefieldNodes = wn2.getChildNodes(); int minefieldType = 0; int minefieldCount = 0; for (int minefieldIndex = 0; minefieldIndex < minefieldNodes.getLength(); minefieldIndex++) { Node wn3 = minefieldNodes.item(minefieldIndex); if (wn3.getNodeName().equalsIgnoreCase("minefieldType")) { minefieldType = Integer.parseInt(wn3.getTextContent()); } else if (wn3.getNodeName().equalsIgnoreCase("minefieldCount")) { minefieldCount = Integer.parseInt(wn3.getTextContent()); } } numPlayerMinefields.put(minefieldType, minefieldCount); } } } private List<String> getEntityStub(Node wn) { List<String> stub = new ArrayList<>(); NodeList nl = wn.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("entityStub")) { stub.add(MekHqXmlUtil.unEscape(wn2.getTextContent())); } } return stub; } protected String getCsvFromList(List<?> list) { StringJoiner retVal = new StringJoiner(","); for (Object item : list) { retVal.add(item.toString()); } return retVal.toString(); } public AtBContract getContract(Campaign c) { return (AtBContract) c.getMission(getMissionId()); } /** * Gets all the entities that are part of the given entity list and are * not in this scenario's transport linkages as a transported unit. */ public List<Entity> filterUntransportedUnits(List<Entity> entities) { List<Entity> retVal = new ArrayList<>(); // assemble a set of transported units for easier lookup Set<String> transportedUnits = new HashSet<>(); for (List<String> transported : getTransportLinkages().values()) { transportedUnits.addAll(transported); } for (Entity entity : entities) { if (!transportedUnits.contains(entity.getExternalIdAsString())) { retVal.add(entity); } } return retVal; } public int getLanceForceId() { return lanceForceId; } public AtBLanceRole getLanceRole() { return lanceRole; } public Lance getLance(Campaign c) { return c.getLances().get(lanceForceId); } public void setLance(Lance l) { lanceForceId = l.getForceId(); } public boolean isAttacker() { return attacker; } public void setAttacker(boolean attacker) { this.attacker = attacker; } public List<Entity> getAlliesPlayer() { return alliesPlayer; } public List<UUID> getAttachedUnitIds() { return attachedUnitIds; } public List<UUID> getSurvivalBonusIds() { return survivalBonus; } public Entity getEntity(UUID id) { return entityIds.get(id); } public List<BotForce> getBotForces() { return botForces; } public void addBotForce(BotForce botForce) { botForces.add(botForce); // put all bot units into the external ID lookup. for (Entity entity : botForce.getEntityList()) { getExternalIDLookup().put(entity.getExternalIdAsString(), entity); } } public BotForce getBotForce(int i) { return botForces.get(i); } public void removeBotForce(int i) { botForces.remove(i); } public int getNumBots() { return getStatus().isCurrent() ? botForces.size() : botForceStubs.size(); } public List<String> getAlliesPlayerStub() { return alliesPlayerStub; } public List<BotForceStub> getBotForceStubs() { return botForceStubs; } public int getTerrainType() { return terrainType; } public void setTerrainType(int terrainType) { this.terrainType = terrainType; } public int getLight() { return light; } public void setLight(int light) { this.light = light; } public int getWeather() { return weather; } public void setWeather(int weather) { this.weather = weather; } public int getWind() { return wind; } public void setWind(int wind) { this.wind = wind; } public int getFog() { return fog; } public void setFog(int fog) { this.fog = fog; } public int getAtmosphere() { return atmosphere; } public void setAtmosphere(int atmosphere) { this.atmosphere = atmosphere; } public float getGravity() { return gravity; } public void setGravity(float gravity) { this.gravity = gravity; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getDeploymentDelay() { return deploymentDelay; } public void setDeploymentDelay(int delay) { this.deploymentDelay = delay; } public int getMapSizeX() { return mapSizeX; } public void setMapSizeX(int mapSizeX) { this.mapSizeX = mapSizeX; } public int getMapSizeY() { return mapSizeY; } public void setMapSizeY(int mapSizeY) { this.mapSizeY = mapSizeY; } public String getMap() { return map; } public void setMap(String map) { this.map = map; } public String getMapForDisplay() { if (!isUsingFixedMap()) { return getMap(); } else { MapSettings ms = MapSettings.getInstance(); return LobbyUtility.cleanBoardName(getMap(), ms); } } public boolean isUsingFixedMap() { return usingFixedMap; } public void setUsingFixedMap(boolean usingFixedMap) { this.usingFixedMap = usingFixedMap; } public int getLanceCount() { return lanceCount; } public void setLanceCount(int lanceCount) { this.lanceCount = lanceCount; } public int getRerollsRemaining() { return rerollsRemaining; } public void useReroll() { rerollsRemaining--; } public void setRerolls(int rerolls) { rerollsRemaining = rerolls; } public int getEnemyHome() { return enemyHome; } public void setEnemyHome(int enemyHome) { this.enemyHome = enemyHome; } public int getNumPlayerMinefields(int minefieldType) { return numPlayerMinefields.containsKey(minefieldType) ? numPlayerMinefields.get(minefieldType) : 0; } public void setNumPlayerMinefields(int minefieldType, int numPlayerMinefields) { this.numPlayerMinefields.put(minefieldType, numPlayerMinefields); } public Map<String, List<String>> getTransportLinkages() { return transportLinkages; } public void setTransportLinkages(HashMap<String, List<String>> transportLinkages) { this.transportLinkages = transportLinkages; } /** * Adds a transport-cargo pair to the internal transport relationship store. * @param transport * @param cargo */ public void addTransportRelationship(String transport, String cargo) { if (!transportLinkages.containsKey(transport)) { transportLinkages.put(transport, new ArrayList<>()); } transportLinkages.get(transport).add(cargo); } public Map<String, Entity> getExternalIDLookup() { return externalIDLookup; } public void setExternalIDLookup(HashMap<String, Entity> externalIDLookup) { this.externalIDLookup = externalIDLookup; } @Override public boolean isFriendlyUnit(Entity entity, Campaign campaign) { return getAlliesPlayer().stream().anyMatch(unit -> unit.getExternalIdAsString().equals(entity.getExternalIdAsString())) || super.isFriendlyUnit(entity, campaign); } public String getBattlefieldControlDescription() { return getResourceBundle().getString("battleDetails.common.winnerControlsBattlefield"); } public String getDeploymentInstructions() { if (this.isBigBattle()) { return getResourceBundle().getString("battleDetails.deployEightMeks"); } else if (isSpecialMission()) { return getResourceBundle().getString("battleDetails.deploySingleMek"); } else { return ""; } } }
bellmit/mekhq
MekHQ/src/mekhq/campaign/mission/AtBScenario.java
46,073
package com.cheng.bigtalkdesignpatterns.mediator; /** * Created by Administrator on 2015/12/23. */ public class ConcreteColleague1 extends Colleague { public ConcreteColleague1(Mediator _mediator) { super(_mediator); } public void send(String _msg) { mediator.send(_msg, this); } public void notify(String _msg) { System.out.println("同事1得到信息:" + _msg); } }
YYwishp/AndroidStudyDemo
DesignPatternStudy/src/main/java/com/cheng/bigtalkdesignpatterns/mediator/ConcreteColleague1.java
46,074
package com.cheng.bigtalkdesignpatterns.mediator; /** * Created by Administrator on 2015/12/23. */ public class ConcreteColleague2 extends Colleague { public ConcreteColleague2(Mediator _mediator) { super(_mediator); } public void send(String _msg) { mediator.send(_msg, this); } public void notify(String _msg) { System.out.println("同事2得到信息:" + _msg); } }
YYwishp/AndroidStudyDemo
DesignPatternStudy/src/main/java/com/cheng/bigtalkdesignpatterns/mediator/ConcreteColleague2.java
46,075
package com.faforever.client.config; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.guava.GuavaCache; import org.springframework.cache.interceptor.CacheErrorHandler; import org.springframework.cache.interceptor.CacheResolver; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.cache.interceptor.SimpleCacheErrorHandler; import org.springframework.cache.interceptor.SimpleKeyGenerator; import org.springframework.cache.support.SimpleCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Arrays; import static com.faforever.client.config.CacheNames.ACHIEVEMENTS; import static com.faforever.client.config.CacheNames.ACHIEVEMENT_IMAGES; import static com.faforever.client.config.CacheNames.AVAILABLE_AVATARS; import static com.faforever.client.config.CacheNames.AVATARS; import static com.faforever.client.config.CacheNames.COOP_LEADERBOARD; import static com.faforever.client.config.CacheNames.COOP_MAPS; import static com.faforever.client.config.CacheNames.COUNTRY_FLAGS; import static com.faforever.client.config.CacheNames.FEATURED_MODS; import static com.faforever.client.config.CacheNames.FEATURED_MOD_FILES; import static com.faforever.client.config.CacheNames.GLOBAL_LEADERBOARD; import static com.faforever.client.config.CacheNames.LADDER_1V1_LEADERBOARD; import static com.faforever.client.config.CacheNames.MAPS; import static com.faforever.client.config.CacheNames.MAP_PREVIEW; import static com.faforever.client.config.CacheNames.MODS; import static com.faforever.client.config.CacheNames.MOD_THUMBNAIL; import static com.faforever.client.config.CacheNames.NEWS; import static com.faforever.client.config.CacheNames.RATING_HISTORY; import static com.faforever.client.config.CacheNames.STATISTICS; import static com.faforever.client.config.CacheNames.THEME_IMAGES; import static com.faforever.client.config.CacheNames.URL_PREVIEW; import static com.google.common.cache.CacheBuilder.newBuilder; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; @Configuration @EnableCaching public class CacheConfig extends CachingConfigurerSupport { @Bean @Override public CacheManager cacheManager() { SimpleCacheManager simpleCacheManager = new SimpleCacheManager(); simpleCacheManager.setCaches(Arrays.asList( new GuavaCache(STATISTICS, newBuilder().maximumSize(10).expireAfterWrite(20, MINUTES).build()), new GuavaCache(ACHIEVEMENTS, newBuilder().expireAfterWrite(10, MINUTES).build()), new GuavaCache(MODS, newBuilder().expireAfterWrite(10, MINUTES).build()), new GuavaCache(MAPS, newBuilder().expireAfterWrite(10, MINUTES).build()), new GuavaCache(GLOBAL_LEADERBOARD, newBuilder().maximumSize(1).expireAfterAccess(5, MINUTES).build()), new GuavaCache(LADDER_1V1_LEADERBOARD, newBuilder().maximumSize(1).expireAfterAccess(5, MINUTES).build()), new GuavaCache(AVAILABLE_AVATARS, newBuilder().expireAfterAccess(30, SECONDS).build()), new GuavaCache(COOP_MAPS, newBuilder().expireAfterAccess(10, SECONDS).build()), new GuavaCache(NEWS, newBuilder().expireAfterWrite(1, MINUTES).build()), new GuavaCache(RATING_HISTORY, newBuilder().expireAfterWrite(1, MINUTES).build()), new GuavaCache(COOP_LEADERBOARD, newBuilder().expireAfterWrite(1, MINUTES).build()), new GuavaCache(FEATURED_MODS, newBuilder().build()), new GuavaCache(FEATURED_MOD_FILES, newBuilder().expireAfterWrite(10, MINUTES).build()), // Images should only be cached as long as they are in use. This avoids loading an image multiple times, while // at the same time it doesn't prevent unused images from being garbage collected. new GuavaCache(ACHIEVEMENT_IMAGES, newBuilder().weakValues().build()), new GuavaCache(AVATARS, newBuilder().weakValues().build()), new GuavaCache(URL_PREVIEW, newBuilder().weakValues().expireAfterAccess(30, MINUTES).build()), new GuavaCache(MAP_PREVIEW, newBuilder().weakValues().build()), new GuavaCache(COUNTRY_FLAGS, newBuilder().weakValues().build()), new GuavaCache(THEME_IMAGES, newBuilder().weakValues().build()), new GuavaCache(MOD_THUMBNAIL, newBuilder().weakValues().build() ))); return simpleCacheManager; } @Override public CacheResolver cacheResolver() { return null; } @Bean @Override public KeyGenerator keyGenerator() { return new SimpleKeyGenerator(); } @Override public CacheErrorHandler errorHandler() { return new SimpleCacheErrorHandler(); } }
FAForever/downlords-faf-client
src/main/java/com/faforever/client/config/CacheConfig.java
46,076
package core.db; import core.model.series.Liga; import java.sql.Types; public final class LigaTable extends AbstractTable { /** tablename **/ public final static String TABLENAME = "LIGA"; LigaTable(JDBCAdapter adapter){ super(TABLENAME,adapter); } @Override protected void initColumns() { columns = new ColumnDescriptor[]{ ColumnDescriptor.Builder.newInstance().setColumnName("HRF_ID").setGetter((o) -> ((Liga) o).getHrfId()).setSetter((o, v) -> ((Liga) o).setHrfId((int) v)).setType(Types.INTEGER).isNullable(false).isPrimaryKey(true).build(), ColumnDescriptor.Builder.newInstance().setColumnName("LigaName").setGetter((o) -> ((Liga) o).getLiga()).setSetter((o, v) -> ((Liga) o).setLiga((String) v)).setType(Types.VARCHAR).isNullable(false).setLength(127).build(), ColumnDescriptor.Builder.newInstance().setColumnName("Punkte").setGetter((o) -> ((Liga) o).getPunkte()).setSetter((o, v) -> ((Liga) o).setPunkte((int) v)).setType(Types.INTEGER).isNullable(false).build(), ColumnDescriptor.Builder.newInstance().setColumnName("ToreFuer").setGetter((o) -> ((Liga) o).getToreFuer()).setSetter((o, v) -> ((Liga) o).setToreFuer((int) v)).setType(Types.INTEGER).isNullable(false).build(), ColumnDescriptor.Builder.newInstance().setColumnName("ToreGegen").setGetter((o) -> ((Liga) o).getToreGegen()).setSetter((o, v) -> ((Liga) o).setToreGegen((int) v)).setType(Types.INTEGER).isNullable(false).build(), ColumnDescriptor.Builder.newInstance().setColumnName("Platz").setGetter((o) -> ((Liga) o).getPlatzierung()).setSetter((o, v) -> ((Liga) o).setPlatzierung((int) v)).setType(Types.INTEGER).isNullable(false).build(), ColumnDescriptor.Builder.newInstance().setColumnName("Spieltag").setGetter((o) -> ((Liga) o).getSpieltag()).setSetter((o, v) -> ((Liga) o).setSpieltag((int) v)).setType(Types.INTEGER).isNullable(false).build() }; } @Override protected String[] getCreateIndexStatement() { return new String[] { "CREATE INDEX ILIGA_1 ON " + getTableName() + "(" + columns[0].getColumnName() + ")"}; } /** * store league */ void saveLiga(int hrfId, Liga liga) { if ( liga != null) { liga.setHrfId(hrfId); store(liga); } } Liga getLiga(int hrfID) { return loadOne(Liga.class, hrfID); } }
ddusann/HO
src/main/java/core/db/LigaTable.java
46,077
/* * Copyright (c) 2018. Aberic - aberic@qq.com - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.controller; import cn.aberic.fabric.dao.entity.Channel; import cn.aberic.fabric.dao.entity.League; import cn.aberic.fabric.dao.entity.Org; import cn.aberic.fabric.dao.entity.Peer; import cn.aberic.fabric.service.*; import cn.aberic.fabric.utils.SpringUtil; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import javax.annotation.Resource; import java.util.List; /** * 描述: * * @author : Aberic 【2018/6/4 15:01】 */ @CrossOrigin @RestController @RequestMapping("channel") public class ChannelController { @Resource private ChannelService channelService; @Resource private PeerService peerService; @Resource private OrgService orgService; @Resource private LeagueService leagueService; @PostMapping(value = "submit") public ModelAndView submit(@ModelAttribute Channel channel, @RequestParam("intent") String intent, @RequestParam("id") int id) { switch (intent) { case "add": channelService.add(channel); break; case "edit": channel.setId(id); channelService.update(channel); break; } return new ModelAndView(new RedirectView("list")); } @GetMapping(value = "add") public ModelAndView add() { ModelAndView modelAndView = new ModelAndView("channelSubmit"); modelAndView.addObject("intentLittle", SpringUtil.get("enter")); modelAndView.addObject("submit", SpringUtil.get("submit")); modelAndView.addObject("intent", "add"); modelAndView.addObject("channel", new Channel()); modelAndView.addObject("peers", peerService.listAll()); return modelAndView; } @GetMapping(value = "edit") public ModelAndView edit(@RequestParam("id") int id) { ModelAndView modelAndView = new ModelAndView("channelSubmit"); modelAndView.addObject("intentLittle", SpringUtil.get("edit")); modelAndView.addObject("submit", SpringUtil.get("modify")); modelAndView.addObject("intent", "edit"); Channel channel = channelService.get(id); Org org = orgService.get(peerService.get(channel.getPeerId()).getOrgId()); channel.setOrgName(org.getMspId()); List<Peer> peers = peerService.listById(org.getId()); League league = leagueService.get(orgService.get(org.getId()).getLeagueId()); channel.setLeagueName(league.getName()); for (Peer peer : peers) { peer.setLeagueName(league.getName()); peer.setOrgName(org.getMspId()); } modelAndView.addObject("channel", channel); modelAndView.addObject("peers", peers); return modelAndView; } @GetMapping(value = "delete") public ModelAndView delete(@RequestParam("id") int id) { channelService.delete(id); return new ModelAndView(new RedirectView("list")); } @GetMapping(value = "list") public ModelAndView list() { ModelAndView modelAndView = new ModelAndView("channels"); modelAndView.addObject("channels", channelService.listAll()); return modelAndView; } }
aberic/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/controller/ChannelController.java
46,117
package libgdx.implementations.startgame; import libgdx.constants.Language; import libgdx.game.Game; import libgdx.implementations.skelgame.GameIdEnum; import libgdx.implementations.geoquiz.QuizGame; import libgdx.utils.startgame.test.DefaultAppInfoService; public class StartGameQuiz { public static void main(String[] args) { QuizGame game = new QuizGame( new DefaultAppInfoService() { @Override public String getGameIdPrefix() { return GameIdEnum.quizgame.name(); } @Override public float gameScreenTopMargin() { return super.gameScreenTopMargin(); } @Override public String getAppName() { return getTitle(); } @Override public String getLanguage() { return "en"; } }); libgdx.utils.startgame.StartGame.main(game, args); } public static String getTitle() { switch (Language.valueOf(Game.getInstance().getAppInfoService().getLanguage())) { case cs: return "Světová geografie"; case da: return "Verdensgeografi"; case de: return "Weltgeografie"; case el: return "Παγκόσμια γεωγραφία"; case en: return "World Geography"; case es: return "Geografia mundial"; case fi: return "Maailman maantiede"; case fr: return "Géographie du monde"; case hi: return "विश्व का भूगोल"; case hr: return "Svjetska geografija"; case hu: return "Világföldrajz"; case id: return "Geografi dunia"; case it: return "Geografia mondiale"; case ja: return "世界の地理"; case ko: return "세계 지리"; case ms: return "Geografi Dunia"; case nl: return "Wereld Aardrijkskunde"; case no: return "Verdensgeografi"; case pl: return "Geografia świata"; case pt: return "Geografia mundial"; case ro: return "Geografia lumii"; case ru: return "Мировая география"; case sk: return "Svetová geografia"; case sv: return "Världsgeografi"; case th: return "ภูมิศาสตร์โลก"; case tr: return "Dünya coğrafyası"; case uk: return "Світова географія"; case vi: return "Địa lý thế giới"; case zh: return "世界地理"; } return null; } }
horeab/SkelQuizGame
src/main/java/libgdx/implementations/startgame/StartGameQuiz.java
46,150
// Given a collection of integers that might contain duplicates, nums, return all possible subsets. // Note: The solution set must not contain duplicate subsets. // For example, // If nums = [1,2,2], a solution is: // [ // [2], // [1], // [1,2,2], // [2,2], // [1,2], // [] // ] public class SubsetsII { public List<List<Integer>> subsetsWithDup(int[] nums) { Arrays.sort(nums); List<List<Integer>> result = new ArrayList<List<Integer>>(); if(nums.length == 0 || nums == null) { return result; } helper(nums, new ArrayList<Integer>(), 0, result); return result; } public void helper(int[] nums, ArrayList<Integer> current, int index, List<List<Integer>> result) { result.add(current); for(int i = index; i < nums.length; i++) { if(i > index && nums[i] == nums[i - 1]) { continue; } ArrayList<Integer> newCurrent = new ArrayList<Integer>(current); newCurrent.add(nums[i]); helper(nums, newCurrent, i + 1, result); } } }
kdn251/interviews
company/facebook/SubsetsII.java
46,159
/* * Copyright (C) 2019 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import java.time.Duration; /** This class is for {@code com.google.common.base} use only! */ @J2ktIncompatible @GwtIncompatible // java.time.Duration @ElementTypesAreNonnullByDefault final class Internal { /** * Returns the number of nanoseconds of the given duration without throwing or overflowing. * * <p>Instead of throwing {@link ArithmeticException}, this method silently saturates to either * {@link Long#MAX_VALUE} or {@link Long#MIN_VALUE}. This behavior can be useful when decomposing * a duration in order to call a legacy API which requires a {@code long, TimeUnit} pair. */ @SuppressWarnings({ // We use this method only for cases in which we need to decompose to primitives. "GoodTime-ApiWithNumericTimeUnit", "GoodTime-DecomposeToPrimitive", // We use this method only from within APIs that require a Duration. "Java7ApiChecker", }) @IgnoreJRERequirement static long toNanosSaturated(Duration duration) { // Using a try/catch seems lazy, but the catch block will rarely get invoked (except for // durations longer than approximately +/- 292 years). try { return duration.toNanos(); } catch (ArithmeticException tooBig) { return duration.isNegative() ? Long.MIN_VALUE : Long.MAX_VALUE; } } private Internal() {} }
google/guava
android/guava/src/com/google/common/base/Internal.java
46,189
/* * Copyright (C) 2014 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.eventbus; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Objects.requireNonNull; import com.google.common.collect.Queues; import java.util.Iterator; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; /** * Handler for dispatching events to subscribers, providing different event ordering guarantees that * make sense for different situations. * * <p><b>Note:</b> The dispatcher is orthogonal to the subscriber's {@code Executor}. The dispatcher * controls the order in which events are dispatched, while the executor controls how (i.e. on which * thread) the subscriber is actually called when an event is dispatched to it. * * @author Colin Decker */ @ElementTypesAreNonnullByDefault abstract class Dispatcher { /** * Returns a dispatcher that queues events that are posted reentrantly on a thread that is already * dispatching an event, guaranteeing that all events posted on a single thread are dispatched to * all subscribers in the order they are posted. * * <p>When all subscribers are dispatched to using a <i>direct</i> executor (which dispatches on * the same thread that posts the event), this yields a breadth-first dispatch order on each * thread. That is, all subscribers to a single event A will be called before any subscribers to * any events B and C that are posted to the event bus by the subscribers to A. */ static Dispatcher perThreadDispatchQueue() { return new PerThreadQueuedDispatcher(); } /** * Returns a dispatcher that queues events that are posted in a single global queue. This behavior * matches the original behavior of AsyncEventBus exactly, but is otherwise not especially useful. * For async dispatch, an {@linkplain #immediate() immediate} dispatcher should generally be * preferable. */ static Dispatcher legacyAsync() { return new LegacyAsyncDispatcher(); } /** * Returns a dispatcher that dispatches events to subscribers immediately as they're posted * without using an intermediate queue to change the dispatch order. This is effectively a * depth-first dispatch order, vs. breadth-first when using a queue. */ static Dispatcher immediate() { return ImmediateDispatcher.INSTANCE; } /** Dispatches the given {@code event} to the given {@code subscribers}. */ abstract void dispatch(Object event, Iterator<Subscriber> subscribers); /** Implementation of a {@link #perThreadDispatchQueue()} dispatcher. */ private static final class PerThreadQueuedDispatcher extends Dispatcher { // This dispatcher matches the original dispatch behavior of EventBus. /** Per-thread queue of events to dispatch. */ private final ThreadLocal<Queue<Event>> queue = new ThreadLocal<Queue<Event>>() { @Override protected Queue<Event> initialValue() { return Queues.newArrayDeque(); } }; /** Per-thread dispatch state, used to avoid reentrant event dispatching. */ private final ThreadLocal<Boolean> dispatching = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; @Override void dispatch(Object event, Iterator<Subscriber> subscribers) { checkNotNull(event); checkNotNull(subscribers); // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get Queue<Event> queueForThread = requireNonNull(queue.get()); queueForThread.offer(new Event(event, subscribers)); if (!dispatching.get()) { dispatching.set(true); try { Event nextEvent; while ((nextEvent = queueForThread.poll()) != null) { while (nextEvent.subscribers.hasNext()) { nextEvent.subscribers.next().dispatchEvent(nextEvent.event); } } } finally { dispatching.remove(); queue.remove(); } } } private static final class Event { private final Object event; private final Iterator<Subscriber> subscribers; private Event(Object event, Iterator<Subscriber> subscribers) { this.event = event; this.subscribers = subscribers; } } } /** Implementation of a {@link #legacyAsync()} dispatcher. */ private static final class LegacyAsyncDispatcher extends Dispatcher { // This dispatcher matches the original dispatch behavior of AsyncEventBus. // // We can't really make any guarantees about the overall dispatch order for this dispatcher in // a multithreaded environment for a couple of reasons: // // 1. Subscribers to events posted on different threads can be interleaved with each other // freely. (A event on one thread, B event on another could yield any of // [a1, a2, a3, b1, b2], [a1, b2, a2, a3, b2], [a1, b2, b3, a2, a3], etc.) // 2. It's possible for subscribers to actually be dispatched to in a different order than they // were added to the queue. It's easily possible for one thread to take the head of the // queue, immediately followed by another thread taking the next element in the queue. That // second thread can then dispatch to the subscriber it took before the first thread does. // // All this makes me really wonder if there's any value in queueing here at all. A dispatcher // that simply loops through the subscribers and dispatches the event to each would actually // probably provide a stronger order guarantee, though that order would obviously be different // in some cases. /** Global event queue. */ private final ConcurrentLinkedQueue<EventWithSubscriber> queue = Queues.newConcurrentLinkedQueue(); @Override void dispatch(Object event, Iterator<Subscriber> subscribers) { checkNotNull(event); while (subscribers.hasNext()) { queue.add(new EventWithSubscriber(event, subscribers.next())); } EventWithSubscriber e; while ((e = queue.poll()) != null) { e.subscriber.dispatchEvent(e.event); } } private static final class EventWithSubscriber { private final Object event; private final Subscriber subscriber; private EventWithSubscriber(Object event, Subscriber subscriber) { this.event = event; this.subscriber = subscriber; } } } /** Implementation of {@link #immediate()}. */ private static final class ImmediateDispatcher extends Dispatcher { private static final ImmediateDispatcher INSTANCE = new ImmediateDispatcher(); @Override void dispatch(Object event, Iterator<Subscriber> subscribers) { checkNotNull(event); while (subscribers.hasNext()) { subscribers.next().dispatchEvent(event); } } } }
google/guava
android/guava/src/com/google/common/eventbus/Dispatcher.java
46,191
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * Utility methods and classes for I/O; for example input streams, output streams, readers, writers, * and files. * * <p>At the core of this package are the Source/Sink types: {@link ByteSource ByteSource}, {@link * CharSource CharSource}, {@link ByteSink ByteSink} and {@link CharSink CharSink}. They are * factories for I/O streams that provide many convenience methods that handle both opening and * closing streams for you. * * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a> * library. For more information on Sources and Sinks as well as other features of this package, see * <a href="https://github.com/google/guava/wiki/IOExplained">I/O Explained</a> on the Guava wiki. * * @author Chris Nokleberg */ @CheckReturnValue @ParametersAreNonnullByDefault package com.google.common.io; import com.google.errorprone.annotations.CheckReturnValue; import javax.annotation.ParametersAreNonnullByDefault;
google/guava
android/guava/src/com/google/common/io/package-info.java
46,192
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.servant; /** * King. */ public class King implements Royalty { private boolean isDrunk; private boolean isHungry = true; private boolean isHappy; private boolean complimentReceived; @Override public void getFed() { isHungry = false; } @Override public void getDrink() { isDrunk = true; } public void receiveCompliments() { complimentReceived = true; } @Override public void changeMood() { if (!isHungry && isDrunk) { isHappy = true; } if (complimentReceived) { isHappy = false; } } @Override public boolean getMood() { return isHappy; } }
smedals/java-design-patterns
servant/src/main/java/com/iluwatar/servant/King.java
46,196
/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ /* * Source: * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/Striped64.java?revision=1.9 */ package com.google.common.hash; import com.google.common.annotations.GwtIncompatible; import java.util.Random; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A package-local class holding common representation and mechanics for classes supporting dynamic * striping on 64bit values. The class extends Number so that concrete subclasses must publicly do * so. */ @GwtIncompatible @ElementTypesAreNonnullByDefault abstract class Striped64 extends Number { /* * This class maintains a lazily-initialized table of atomically * updated variables, plus an extra "base" field. The table size * is a power of two. Indexing uses masked per-thread hash codes. * Nearly all declarations in this class are package-private, * accessed directly by subclasses. * * Table entries are of class Cell; a variant of AtomicLong padded * to reduce cache contention on most processors. Padding is * overkill for most Atomics because they are usually irregularly * scattered in memory and thus don't interfere much with each * other. But Atomic objects residing in arrays will tend to be * placed adjacent to each other, and so will most often share * cache lines (with a huge negative performance impact) without * this precaution. * * In part because Cells are relatively large, we avoid creating * them until they are needed. When there is no contention, all * updates are made to the base field. Upon first contention (a * failed CAS on base update), the table is initialized to size 2. * The table size is doubled upon further contention until * reaching the nearest power of two greater than or equal to the * number of CPUS. Table slots remain empty (null) until they are * needed. * * A single spinlock ("busy") is used for initializing and * resizing the table, as well as populating slots with new Cells. * There is no need for a blocking lock; when the lock is not * available, threads try other slots (or the base). During these * retries, there is increased contention and reduced locality, * which is still better than alternatives. * * Per-thread hash codes are initialized to random values. * Contention and/or table collisions are indicated by failed * CASes when performing an update operation (see method * retryUpdate). Upon a collision, if the table size is less than * the capacity, it is doubled in size unless some other thread * holds the lock. If a hashed slot is empty, and lock is * available, a new Cell is created. Otherwise, if the slot * exists, a CAS is tried. Retries proceed by "double hashing", * using a secondary hash (Marsaglia XorShift) to try to find a * free slot. * * The table size is capped because, when there are more threads * than CPUs, supposing that each thread were bound to a CPU, * there would exist a perfect hash function mapping threads to * slots that eliminates collisions. When we reach capacity, we * search for this mapping by randomly varying the hash codes of * colliding threads. Because search is random, and collisions * only become known via CAS failures, convergence can be slow, * and because threads are typically not bound to CPUS forever, * may not occur at all. However, despite these limitations, * observed contention rates are typically low in these cases. * * It is possible for a Cell to become unused when threads that * once hashed to it terminate, as well as in the case where * doubling the table causes no thread to hash to it under * expanded mask. We do not try to detect or remove such cells, * under the assumption that for long-running instances, observed * contention levels will recur, so the cells will eventually be * needed again; and for short-lived ones, it does not matter. */ /** * Padded variant of AtomicLong supporting only raw accesses plus CAS. The value field is placed * between pads, hoping that the JVM doesn't reorder them. * * <p>JVM intrinsics note: It would be possible to use a release-only form of CAS here, if it were * provided. */ static final class Cell { volatile long p0, p1, p2, p3, p4, p5, p6; volatile long value; volatile long q0, q1, q2, q3, q4, q5, q6; Cell(long x) { value = x; } final boolean cas(long cmp, long val) { return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long valueOffset; static { try { UNSAFE = getUnsafe(); Class<?> ak = Cell.class; valueOffset = UNSAFE.objectFieldOffset(ak.getDeclaredField("value")); } catch (Exception e) { throw new Error(e); } } } /** * ThreadLocal holding a single-slot int array holding hash code. Unlike the JDK8 version of this * class, we use a suboptimal int[] representation to avoid introducing a new type that can impede * class-unloading when ThreadLocals are not removed. */ static final ThreadLocal<int @Nullable []> threadHashCode = new ThreadLocal<>(); /** Generator of new random hash codes */ static final Random rng = new Random(); /** Number of CPUS, to place bound on table size */ static final int NCPU = Runtime.getRuntime().availableProcessors(); /** Table of cells. When non-null, size is a power of 2. */ @CheckForNull transient volatile Cell[] cells; /** * Base value, used mainly when there is no contention, but also as a fallback during table * initialization races. Updated via CAS. */ transient volatile long base; /** Spinlock (locked via CAS) used when resizing and/or creating Cells. */ transient volatile int busy; /** Package-private default constructor */ Striped64() {} /** CASes the base field. */ final boolean casBase(long cmp, long val) { return UNSAFE.compareAndSwapLong(this, baseOffset, cmp, val); } /** CASes the busy field from 0 to 1 to acquire lock. */ final boolean casBusy() { return UNSAFE.compareAndSwapInt(this, busyOffset, 0, 1); } /** * Computes the function of current and new value. Subclasses should open-code this update * function for most uses, but the virtualized form is needed within retryUpdate. * * @param currentValue the current value (of either base or a cell) * @param newValue the argument from a user update call * @return result of the update function */ abstract long fn(long currentValue, long newValue); /** * Handles cases of updates involving initialization, resizing, creating new Cells, and/or * contention. See above for explanation. This method suffers the usual non-modularity problems of * optimistic retry code, relying on rechecked sets of reads. * * @param x the value * @param hc the hash code holder * @param wasUncontended false if CAS failed before call */ final void retryUpdate(long x, @CheckForNull int[] hc, boolean wasUncontended) { int h; if (hc == null) { threadHashCode.set(hc = new int[1]); // Initialize randomly int r = rng.nextInt(); // Avoid zero to allow xorShift rehash h = hc[0] = (r == 0) ? 1 : r; } else h = hc[0]; boolean collide = false; // True if last slot nonempty for (; ; ) { Cell[] as; Cell a; int n; long v; if ((as = cells) != null && (n = as.length) > 0) { if ((a = as[(n - 1) & h]) == null) { if (busy == 0) { // Try to attach new Cell Cell r = new Cell(x); // Optimistically create if (busy == 0 && casBusy()) { boolean created = false; try { // Recheck under lock Cell[] rs; int m, j; if ((rs = cells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) { rs[j] = r; created = true; } } finally { busy = 0; } if (created) break; continue; // Slot is now non-empty } } collide = false; } else if (!wasUncontended) // CAS already known to fail wasUncontended = true; // Continue after rehash else if (a.cas(v = a.value, fn(v, x))) break; else if (n >= NCPU || cells != as) collide = false; // At max size or stale else if (!collide) collide = true; else if (busy == 0 && casBusy()) { try { if (cells == as) { // Expand table unless stale Cell[] rs = new Cell[n << 1]; for (int i = 0; i < n; ++i) rs[i] = as[i]; cells = rs; } } finally { busy = 0; } collide = false; continue; // Retry with expanded table } h ^= h << 13; // Rehash h ^= h >>> 17; h ^= h << 5; hc[0] = h; // Record index for next time } else if (busy == 0 && cells == as && casBusy()) { boolean init = false; try { // Initialize table if (cells == as) { Cell[] rs = new Cell[2]; rs[h & 1] = new Cell(x); cells = rs; init = true; } } finally { busy = 0; } if (init) break; } else if (casBase(v = base, fn(v, x))) break; // Fall back on using base } } /** Sets base and all cells to the given value. */ final void internalReset(long initialValue) { Cell[] as = cells; base = initialValue; if (as != null) { int n = as.length; for (int i = 0; i < n; ++i) { Cell a = as[i]; if (a != null) a.value = initialValue; } } } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long baseOffset; private static final long busyOffset; static { try { UNSAFE = getUnsafe(); Class<?> sk = Striped64.class; baseOffset = UNSAFE.objectFieldOffset(sk.getDeclaredField("base")); busyOffset = UNSAFE.objectFieldOffset(sk.getDeclaredField("busy")); } catch (Exception e) { throw new Error(e); } } /** * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. Replace with a simple call * to Unsafe.getUnsafe when integrating into a jdk. * * @return a sun.misc.Unsafe */ @SuppressWarnings("removal") // b/318391980 private static sun.misc.Unsafe getUnsafe() { try { return sun.misc.Unsafe.getUnsafe(); } catch (SecurityException tryReflectionInstead) { } try { return java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { @Override public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (java.lang.reflect.Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) return k.cast(x); } throw new NoSuchFieldError("the Unsafe"); } }); } catch (java.security.PrivilegedActionException e) { throw new RuntimeException("Could not initialize intrinsics", e.getCause()); } } }
google/guava
guava/src/com/google/common/hash/Striped64.java
46,198
/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ /* * Source: * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/Striped64.java?revision=1.9 */ package com.google.common.cache; import com.google.common.annotations.GwtIncompatible; import java.util.Random; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A package-local class holding common representation and mechanics for classes supporting dynamic * striping on 64bit values. The class extends Number so that concrete subclasses must publicly do * so. */ @GwtIncompatible @ElementTypesAreNonnullByDefault abstract class Striped64 extends Number { /* * This class maintains a lazily-initialized table of atomically * updated variables, plus an extra "base" field. The table size * is a power of two. Indexing uses masked per-thread hash codes. * Nearly all declarations in this class are package-private, * accessed directly by subclasses. * * Table entries are of class Cell; a variant of AtomicLong padded * to reduce cache contention on most processors. Padding is * overkill for most Atomics because they are usually irregularly * scattered in memory and thus don't interfere much with each * other. But Atomic objects residing in arrays will tend to be * placed adjacent to each other, and so will most often share * cache lines (with a huge negative performance impact) without * this precaution. * * In part because Cells are relatively large, we avoid creating * them until they are needed. When there is no contention, all * updates are made to the base field. Upon first contention (a * failed CAS on base update), the table is initialized to size 2. * The table size is doubled upon further contention until * reaching the nearest power of two greater than or equal to the * number of CPUS. Table slots remain empty (null) until they are * needed. * * A single spinlock ("busy") is used for initializing and * resizing the table, as well as populating slots with new Cells. * There is no need for a blocking lock; when the lock is not * available, threads try other slots (or the base). During these * retries, there is increased contention and reduced locality, * which is still better than alternatives. * * Per-thread hash codes are initialized to random values. * Contention and/or table collisions are indicated by failed * CASes when performing an update operation (see method * retryUpdate). Upon a collision, if the table size is less than * the capacity, it is doubled in size unless some other thread * holds the lock. If a hashed slot is empty, and lock is * available, a new Cell is created. Otherwise, if the slot * exists, a CAS is tried. Retries proceed by "double hashing", * using a secondary hash (Marsaglia XorShift) to try to find a * free slot. * * The table size is capped because, when there are more threads * than CPUs, supposing that each thread were bound to a CPU, * there would exist a perfect hash function mapping threads to * slots that eliminates collisions. When we reach capacity, we * search for this mapping by randomly varying the hash codes of * colliding threads. Because search is random, and collisions * only become known via CAS failures, convergence can be slow, * and because threads are typically not bound to CPUS forever, * may not occur at all. However, despite these limitations, * observed contention rates are typically low in these cases. * * It is possible for a Cell to become unused when threads that * once hashed to it terminate, as well as in the case where * doubling the table causes no thread to hash to it under * expanded mask. We do not try to detect or remove such cells, * under the assumption that for long-running instances, observed * contention levels will recur, so the cells will eventually be * needed again; and for short-lived ones, it does not matter. */ /** * Padded variant of AtomicLong supporting only raw accesses plus CAS. The value field is placed * between pads, hoping that the JVM doesn't reorder them. * * <p>JVM intrinsics note: It would be possible to use a release-only form of CAS here, if it were * provided. */ static final class Cell { volatile long p0, p1, p2, p3, p4, p5, p6; volatile long value; volatile long q0, q1, q2, q3, q4, q5, q6; Cell(long x) { value = x; } final boolean cas(long cmp, long val) { return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long valueOffset; static { try { UNSAFE = getUnsafe(); Class<?> ak = Cell.class; valueOffset = UNSAFE.objectFieldOffset(ak.getDeclaredField("value")); } catch (Exception e) { throw new Error(e); } } } /** * ThreadLocal holding a single-slot int array holding hash code. Unlike the JDK8 version of this * class, we use a suboptimal int[] representation to avoid introducing a new type that can impede * class-unloading when ThreadLocals are not removed. */ static final ThreadLocal<int @Nullable []> threadHashCode = new ThreadLocal<>(); /** Generator of new random hash codes */ static final Random rng = new Random(); /** Number of CPUS, to place bound on table size */ static final int NCPU = Runtime.getRuntime().availableProcessors(); /** Table of cells. When non-null, size is a power of 2. */ @CheckForNull transient volatile Cell[] cells; /** * Base value, used mainly when there is no contention, but also as a fallback during table * initialization races. Updated via CAS. */ transient volatile long base; /** Spinlock (locked via CAS) used when resizing and/or creating Cells. */ transient volatile int busy; /** Package-private default constructor */ Striped64() {} /** CASes the base field. */ final boolean casBase(long cmp, long val) { return UNSAFE.compareAndSwapLong(this, baseOffset, cmp, val); } /** CASes the busy field from 0 to 1 to acquire lock. */ final boolean casBusy() { return UNSAFE.compareAndSwapInt(this, busyOffset, 0, 1); } /** * Computes the function of current and new value. Subclasses should open-code this update * function for most uses, but the virtualized form is needed within retryUpdate. * * @param currentValue the current value (of either base or a cell) * @param newValue the argument from a user update call * @return result of the update function */ abstract long fn(long currentValue, long newValue); /** * Handles cases of updates involving initialization, resizing, creating new Cells, and/or * contention. See above for explanation. This method suffers the usual non-modularity problems of * optimistic retry code, relying on rechecked sets of reads. * * @param x the value * @param hc the hash code holder * @param wasUncontended false if CAS failed before call */ final void retryUpdate(long x, @CheckForNull int[] hc, boolean wasUncontended) { int h; if (hc == null) { threadHashCode.set(hc = new int[1]); // Initialize randomly int r = rng.nextInt(); // Avoid zero to allow xorShift rehash h = hc[0] = (r == 0) ? 1 : r; } else h = hc[0]; boolean collide = false; // True if last slot nonempty for (; ; ) { Cell[] as; Cell a; int n; long v; if ((as = cells) != null && (n = as.length) > 0) { if ((a = as[(n - 1) & h]) == null) { if (busy == 0) { // Try to attach new Cell Cell r = new Cell(x); // Optimistically create if (busy == 0 && casBusy()) { boolean created = false; try { // Recheck under lock Cell[] rs; int m, j; if ((rs = cells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) { rs[j] = r; created = true; } } finally { busy = 0; } if (created) break; continue; // Slot is now non-empty } } collide = false; } else if (!wasUncontended) // CAS already known to fail wasUncontended = true; // Continue after rehash else if (a.cas(v = a.value, fn(v, x))) break; else if (n >= NCPU || cells != as) collide = false; // At max size or stale else if (!collide) collide = true; else if (busy == 0 && casBusy()) { try { if (cells == as) { // Expand table unless stale Cell[] rs = new Cell[n << 1]; for (int i = 0; i < n; ++i) rs[i] = as[i]; cells = rs; } } finally { busy = 0; } collide = false; continue; // Retry with expanded table } h ^= h << 13; // Rehash h ^= h >>> 17; h ^= h << 5; hc[0] = h; // Record index for next time } else if (busy == 0 && cells == as && casBusy()) { boolean init = false; try { // Initialize table if (cells == as) { Cell[] rs = new Cell[2]; rs[h & 1] = new Cell(x); cells = rs; init = true; } } finally { busy = 0; } if (init) break; } else if (casBase(v = base, fn(v, x))) break; // Fall back on using base } } /** Sets base and all cells to the given value. */ final void internalReset(long initialValue) { Cell[] as = cells; base = initialValue; if (as != null) { int n = as.length; for (int i = 0; i < n; ++i) { Cell a = as[i]; if (a != null) a.value = initialValue; } } } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long baseOffset; private static final long busyOffset; static { try { UNSAFE = getUnsafe(); Class<?> sk = Striped64.class; baseOffset = UNSAFE.objectFieldOffset(sk.getDeclaredField("base")); busyOffset = UNSAFE.objectFieldOffset(sk.getDeclaredField("busy")); } catch (Exception e) { throw new Error(e); } } /** * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. Replace with a simple call * to Unsafe.getUnsafe when integrating into a jdk. * * @return a sun.misc.Unsafe */ @SuppressWarnings("removal") // b/318391980 private static sun.misc.Unsafe getUnsafe() { try { return sun.misc.Unsafe.getUnsafe(); } catch (SecurityException tryReflectionInstead) { } try { return java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { @Override public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (java.lang.reflect.Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) return k.cast(x); } throw new NoSuchFieldError("the Unsafe"); } }); } catch (java.security.PrivilegedActionException e) { throw new RuntimeException("Could not initialize intrinsics", e.getCause()); } } }
google/guava
guava/src/com/google/common/cache/Striped64.java
46,208
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.common; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; public enum Priority { IMMEDIATE((byte) 0), URGENT((byte) 1), HIGH((byte) 2), NORMAL((byte) 3), LOW((byte) 4), LANGUID((byte) 5); public static Priority readFrom(StreamInput input) throws IOException { return fromByte(input.readByte()); } public static void writeTo(Priority priority, StreamOutput output) throws IOException { output.writeByte(priority.value); } public static Priority fromByte(byte b) { return switch (b) { case 0 -> IMMEDIATE; case 1 -> URGENT; case 2 -> HIGH; case 3 -> NORMAL; case 4 -> LOW; case 5 -> LANGUID; default -> throw new IllegalArgumentException("can't find priority for [" + b + "]"); }; } private final byte value; Priority(byte value) { this.value = value; } /** * @return whether tasks of {@code this} priority will run after those of priority {@code p}. * For instance, {@code Priority.URGENT.after(Priority.IMMEDIATE)} returns {@code true}. */ public boolean after(Priority p) { return this.compareTo(p) > 0; } /** * @return whether tasks of {@code this} priority will run no earlier than those of priority {@code p}. * For instance, {@code Priority.URGENT.sameOrAfter(Priority.IMMEDIATE)} returns {@code true}. */ public boolean sameOrAfter(Priority p) { return this.compareTo(p) >= 0; } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/common/Priority.java
46,219
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.escape; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; /** * Methods factored out so that they can be emulated differently in GWT. * * @author Jesse Wilson */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault final class Platform { private Platform() {} /** Returns a thread-local 1024-char array. */ static char[] charBufferFromThreadLocal() { // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get return requireNonNull(DEST_TL.get()); } /** * A thread-local destination buffer to keep us from creating new buffers. The starting size is * 1024 characters. If we grow past this we don't put it back in the threadlocal, we just keep * going and grow as needed. */ private static final ThreadLocal<char[]> DEST_TL = new ThreadLocal<char[]>() { @Override protected char[] initialValue() { return new char[1024]; } }; }
google/guava
android/guava/src/com/google/common/escape/Platform.java
46,223
// Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. // For example, // Given [[0, 30],[5, 10],[15, 20]], // return 2. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class MeetingRoomsII { public int minMeetingRooms(Interval[] intervals) { int[] starts = new int[intervals.length]; int[] ends = new int[intervals.length]; for(int i=0; i<intervals.length; i++) { starts[i] = intervals[i].start; ends[i] = intervals[i].end; } Arrays.sort(starts); Arrays.sort(ends); int rooms = 0; int endsItr = 0; for(int i=0; i<starts.length; i++) { if(starts[i]<ends[endsItr]) { rooms++; } else { endsItr++; } } return rooms; } }
kdn251/interviews
leetcode/sort/MeetingRoomsII.java
46,226
// There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. // The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses. // Note: // All costs are positive integers. // Follow up: // Could you solve it in O(nk) runtime? public class PaintHouseII { public int minCostII(int[][] costs) { if(costs == null|| costs.length == 0) { return 0; } int m = costs.length; int n = costs[0].length; int min1 = -1; int min2 = -1; for(int i = 0; i < m; i++) { int last1 = min1; int last2 = min2; min1 = -1; min2 = -1; for(int j = 0; j < n; j++) { if(j != last1) { costs[i][j] += last1 < 0 ? 0 : costs[i - 1][last1]; } else { costs[i][j] += last2 < 0 ? 0 : costs[i - 1][last2]; } if(min1 < 0 || costs[i][j] < costs[i][min1]) { min2 = min1; min1 = j; } else if(min2 < 0 || costs[i][j] < costs[i][min2]) { min2 = j; } } } return costs[m - 1][min1]; } }
kdn251/interviews
company/facebook/PaintHouseII.java
46,233
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2018 Uber Technologies, Inc. */ module org.elasticsearch.h3 { exports org.elasticsearch.h3; }
elastic/elasticsearch
libs/h3/src/main/java/module-info.java
46,234
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ module org.elasticsearch.vec { requires org.elasticsearch.nativeaccess; requires org.apache.lucene.core; exports org.elasticsearch.vec to org.elasticsearch.server; }
elastic/elasticsearch
libs/vec/src/main/java/module-info.java
46,235
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ module org.elasticsearch.geo { exports org.elasticsearch.geometry; exports org.elasticsearch.geometry.utils; exports org.elasticsearch.geometry.simplify; }
elastic/elasticsearch
libs/geo/src/main/java/module-info.java
46,236
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ module org.elasticsearch.lz4 { requires org.lz4.java; exports org.elasticsearch.lz4; }
elastic/elasticsearch
libs/lz4/src/main/java/module-info.java
46,240
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projectt; import icons.FontAwesome; import java.awt.Color; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import jiconfont.swing.IconFontSwing; /** * * @author Marinos */ public class Admin_Supplies extends javax.swing.JFrame { /** * Creates new form Admin_Supplies */ public Admin_Supplies() { IconFontSwing.register(FontAwesome.getIconFont()); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jTextField5 = new javax.swing.JTextField(); jTextField6 = new javax.swing.JTextField(); jTextField7 = new javax.swing.JTextField(); jTextField8 = new javax.swing.JTextField(); jTextField9 = new javax.swing.JTextField(); jTextField10 = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); back_Button = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(150, 235, 240)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/A4AD5659B5D44610AB530DF0BAB8279D.jpeg"))); // NOI18N jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jTextField1.setFont(new java.awt.Font("Tahoma", 1, 30)); // NOI18N jTextField1.setText("Φόρμα Προμηθειών"); jTextField1.setBorder(null); jTextField1.setFocusable(false); jButton1.setBackground(new java.awt.Color(0, 0, 0)); jButton1.setForeground(new java.awt.Color(255, 255, 255)); jButton1.setText("Υπολογισμός και Παραγγελία"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel2.setText("Μάσκες"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel3.setText("Γάντια "); jLabel3.setToolTipText(""); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel4.setText("Γάζες"); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel5.setText("Χειρουργικές Φόρμες"); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel6.setText("Νάρθηκες"); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel7.setText("Ράμματα"); jLabel8.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel9.setText("Σύριγγες"); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel10.setText("Κρεβάτια"); jTextField3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField3.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField4.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField5.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField6.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField7.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField8.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField9.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField10.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel11.setForeground(new java.awt.Color(255, 0, 0)); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(120, 120, 120)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jButton1) .addContainerGap()))) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(47, 47, 47) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(246, 246, 246) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField8, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE) .addComponent(jTextField9) .addComponent(jTextField10))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(223, 223, 223) .addComponent(jTextField7, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jLabel5) .addGap(160, 160, 160) .addComponent(jTextField6, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(266, 266, 266) .addComponent(jTextField5)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(86, 86, 86)))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 24, Short.MAX_VALUE)) .addGap(29, 29, 29) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addGap(29, 29, 29) .addComponent(jLabel4)) .addComponent(jTextField5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29) .addComponent(jLabel5)) .addComponent(jTextField6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(1, 1, 1) .addComponent(jLabel8) .addGap(29, 29, 29) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(1, 1, 1) .addComponent(jButton1) .addContainerGap()) ); jTextField2.setBackground(new java.awt.Color(150, 235, 240)); jTextField2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField2.setText("ΤΜΗΜΑ ΠΡΟΜΗΘΕΙΩΝ"); jTextField2.setBorder(null); jTextField2.setFocusable(false); back_Button.setIcon(IconFontSwing.buildIcon(FontAwesome.ARROW_CIRCLE_LEFT, 50, Color.black)); back_Button.setBorderPainted(false); back_Button.setContentAreaFilled(false); back_Button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { back_ButtonActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(back_Button, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(309, 309, 309) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 170, Short.MAX_VALUE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(back_Button, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(30, 30, 30) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void displayFail(){ JOptionPane.showMessageDialog(this,("Συμπληρώστε όλα τα πεδία!")); } private void saveSupplies(){ int mm = Integer.parseInt(jTextField3.getText().trim()); int gg =Integer.parseInt(jTextField4.getText().trim()); int gaa = Integer.parseInt(jTextField5.getText().trim()); int fxx = Integer.parseInt(jTextField6.getText().trim()); int nn = Integer.parseInt(jTextField7.getText().trim()); int rr = Integer.parseInt(jTextField8.getText().trim()); int ss = Integer.parseInt(jTextField9.getText().trim()); int kk = Integer.parseInt(jTextField10.getText().trim()); try{ java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", ""); String query = "SELECT stock FROM supplies WHERE supply='maskes'"; PreparedStatement pst = con.prepareStatement(query); ResultSet rs = pst.executeQuery(); String query1 = "SELECT stock FROM supplies WHERE supply='gantia'"; PreparedStatement pst1 = con.prepareStatement(query1); ResultSet rs1 = pst1.executeQuery(); String query2 = "SELECT stock FROM supplies WHERE supply='gazes'"; PreparedStatement pst2 = con.prepareStatement(query2); ResultSet rs2 = pst2.executeQuery(); String query3 = "SELECT stock FROM supplies WHERE supply='formes_xeirourgeiou'"; PreparedStatement pst3 = con.prepareStatement(query3); ResultSet rs3 = pst3.executeQuery(); String query4 = "SELECT stock FROM supplies WHERE supply='narthikes'"; PreparedStatement pst4 = con.prepareStatement(query4); ResultSet rs4 = pst4.executeQuery(); String query5 = "SELECT stock FROM supplies WHERE supply='rammata'"; PreparedStatement pst5 = con.prepareStatement(query5); ResultSet rs5 = pst5.executeQuery(); String query6 = "SELECT stock FROM supplies WHERE supply='surigges'"; PreparedStatement pst6 = con.prepareStatement(query6); ResultSet rs6 = pst6.executeQuery(); String query7 = "SELECT stock FROM supplies WHERE supply='krevatia'"; PreparedStatement pst7 = con.prepareStatement(query7); ResultSet rs7 = pst7.executeQuery(); int m = (Integer) rs.getInt("stock"); int g = (Integer) rs1.getInt("stock"); int ga = (Integer) rs2.getInt("stock"); int fx = (Integer) rs3.getInt("stock"); int n = (Integer) rs4.getInt("stock"); int r = (Integer) rs5.getInt("stock"); int s = (Integer) rs6.getInt("stock"); int k = (Integer) rs7.getInt("stock"); int m1 = m + mm; int g1 = g +gg ; int ga1 = ga + gaa; int fx1 = fx + fxx; int n1 = n + nn; int r1 = r + rr; int s1 = s + ss; int k1 = k + kk; String queryy= "UPDATE supplies SET stock ='"+m1+"' WHERE supply='maskes'"; PreparedStatement pstt = con.prepareStatement(queryy); int rss = pstt.executeUpdate(); String queryy1= "UPDATE supplies SET price ='"+g1+"' WHERE supply='gantia'"; PreparedStatement pstt1 = con.prepareStatement(queryy1); int rss1 = pstt1.executeUpdate(); String queryy2= "UPDATE supplies SET price ='"+ga1+"' WHERE supply='gazes'"; PreparedStatement pstt2 = con.prepareStatement(queryy2); int rss2 = pstt2.executeUpdate(); String queryy3= "UPDATE supplies SET price ='"+fx1+"' WHERE supply='formes_xeirourgeiou'"; PreparedStatement pstt3 = con.prepareStatement(queryy3); int rss3 = pst3.executeUpdate(); String queryy4= "UPDATE supplies SET price ='"+n1+"' WHERE supply='narthikes'"; PreparedStatement pstt4 = con.prepareStatement(queryy4); int rss4 = pst4.executeUpdate(); String queryy5= "UPDATE supplies SET price ='"+r1+"' WHERE supply='rammata'"; PreparedStatement pstt5 = con.prepareStatement(queryy5); int rss5 = pstt5.executeUpdate(); String queryy6= "UPDATE supplies SET price ='"+s1+"' WHERE supply='surigges'"; PreparedStatement pstt6 = con.prepareStatement(queryy6); int rss6 = pstt6.executeUpdate(); String queryy7= "UPDATE supplies SET price ='"+k1+"' WHERE supply='krevatia'"; PreparedStatement pstt7 = con.prepareStatement(queryy7); int rss7 = pstt7.executeUpdate(); }catch (SQLException ex) { Logger.getLogger(Admin_Supplies.class.getName()).log(Level.SEVERE, null, ex); } } private void updatePrice(){ String m = jTextField3.getText(); String g =jTextField4.getText(); String ga = jTextField5.getText(); String fx = jTextField6.getText(); String n = jTextField7.getText(); String r= jTextField8.getText(); String s= jTextField9.getText(); String k= jTextField10.getText(); //validateFeilds(); if(jTextField3.getText().trim().isEmpty() || jTextField4.getText().trim().isEmpty() || jTextField5.getText().trim().isEmpty() || jTextField6.getText().trim().isEmpty() ||jTextField7.getText().trim().isEmpty() ||jTextField8.getText().trim().isEmpty() ||jTextField9.getText().trim().isEmpty() ||jTextField10.getText().trim().isEmpty() ) { displayFail(); } else{ try { float m1 = (Float.parseFloat(m) * 0.50f); float g1 = (Float.parseFloat(g) * 0.20f); float ga1 = (Float.parseFloat(ga) * 0.30f); float fx1 = (Float.parseFloat(fx) * 15.00f); float n1 = (Float.parseFloat(n) * 1.20f); float r1 = (Float.parseFloat(r) * 0.40f); float s1 = (Float.parseFloat(s) * 0.60f); float k1 = (Float.parseFloat(k) * 50.40f); Class.forName("com.mysql.cj.jdbc.Driver"); java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", ""); String query= "UPDATE supplies SET price ='"+m1+"' WHERE supply='maskes'"; PreparedStatement pst = con.prepareStatement(query); int rs = pst.executeUpdate(); String query1= "UPDATE supplies SET price ='"+g1+"' WHERE supply='gantia'"; PreparedStatement pst1 = con.prepareStatement(query1); int rs1 = pst1.executeUpdate(); String query2= "UPDATE supplies SET price ='"+ga1+"' WHERE supply='gazes'"; PreparedStatement pst2 = con.prepareStatement(query2); int rs2 = pst2.executeUpdate(); String query3= "UPDATE supplies SET price ='"+fx1+"' WHERE supply='formes_xeirourgeiou'"; PreparedStatement pst3 = con.prepareStatement(query3); int rs3 = pst3.executeUpdate(); String query4= "UPDATE supplies SET price ='"+n1+"' WHERE supply='narthikes'"; PreparedStatement pst4 = con.prepareStatement(query4); int rs4 = pst4.executeUpdate(); String query5= "UPDATE supplies SET price ='"+r1+"' WHERE supply='rammata'"; PreparedStatement pst5 = con.prepareStatement(query5); int rs5 = pst5.executeUpdate(); String query6= "UPDATE supplies SET price ='"+s1+"' WHERE supply='surigges'"; PreparedStatement pst6 = con.prepareStatement(query6); int rs6 = pst6.executeUpdate(); String query7= "UPDATE supplies SET price ='"+k1+"' WHERE supply='krevatia'"; PreparedStatement pst7 = con.prepareStatement(query7); int rs7 = pst7.executeUpdate(); } catch(Exception e) { JOptionPane.showMessageDialog(null,e); } } } private void select_Calculate(){ new Final_Supplies().setVisible(true); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: saveSupplies(); updatePrice(); select_Calculate(); }//GEN-LAST:event_jButton1ActionPerformed private void back_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_back_ButtonActionPerformed // TODO add your handling code here: dispose(); new Admin().setVisible(true); }//GEN-LAST:event_back_ButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Admin_Supplies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Admin_Supplies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Admin_Supplies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Admin_Supplies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Admin_Supplies().setVisible(true); //show_SuppliesForm(); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton back_Button; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField10; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField6; private javax.swing.JTextField jTextField7; private javax.swing.JTextField jTextField8; private javax.swing.JTextField jTextField9; // End of variables declaration//GEN-END:variables }
alexkou/Software_Engineering_Project
src/projectt/Admin_Supplies.java
46,257
package com.baeldung.nonalphanumeric; import org.junit.Test; import static org.junit.Assert.*; public class NonAlphaNumRegexCheckerUnitTest { @Test public void whenStrLatinOrHasNonAlphaNum_ThenRetTrue() { //alphabets with special character String str1 = "W$nder^ful"; //digits with special character String str2 = "123$%45"; //alphabets and digits with special characters String str3 = "W@nd$r123$%45"; //Error message String ERROR_MSG = "Test failed, no alphanumeric char found in "; assertTrue(ERROR_MSG + str1, NonAlphaNumRegexChecker.isNonAlphanumeric(str1)); assertTrue(ERROR_MSG + str2, NonAlphaNumRegexChecker.isNonAlphanumeric(str2)); assertTrue(ERROR_MSG + str3, NonAlphaNumRegexChecker.isNonAlphanumeric(str3)); } @Test public void whenStrLatinOrHasNoNonAlphaNum_ThenRetFalse() { //only alphabets String str1 = "Wonderful"; //only digits String str2 = "12345"; //mix of alphabet and digit String str3 = "5Won6der1234"; //Error message String ERROR_MSG = "Test failed, non alphanumeric char found in "; assertFalse(ERROR_MSG + str1, NonAlphaNumRegexChecker.isNonAlphanumeric(str1)); assertFalse(ERROR_MSG + str2, NonAlphaNumRegexChecker.isNonAlphanumeric(str2)); assertFalse(ERROR_MSG + str3, NonAlphaNumRegexChecker.isNonAlphanumeric(str3)); } @Test public void whenStrNonLatinOrHasNonAlphaNum_ThenRetTrue() { //special character in Georgian text String str1 = "##მშვენიერი@"; //special character with Turkish text String str2 = "müthiş#$"; //No special character in Georgian text String str3 = "მშვენიერი"; //Error message String ERROR_MSG = "Test failed, no alphanumeric char found in "; assertTrue(ERROR_MSG + str1, NonAlphaNumRegexChecker.isNonAlphanumeric(str1)); assertTrue(ERROR_MSG + str2, NonAlphaNumRegexChecker.isNonAlphanumeric(str2)); assertTrue(ERROR_MSG + str3, NonAlphaNumRegexChecker.isNonAlphanumeric(str3)); } @Test public void whenStrAnyLangOrHasNonAlphaNum_ThenRetTrue() { //special character in Georgian text String str1 = "##მშვენიერი@"; //special character with Turkish text String str2 = "müthiş#$"; //Error message String ERROR_MSG = "Test failed, no alphanumeric char found in "; assertTrue(ERROR_MSG + str1, NonAlphaNumRegexChecker.containsNonAlphanumeric(str1)); assertTrue(ERROR_MSG + str2, NonAlphaNumRegexChecker.containsNonAlphanumeric(str2)); } @Test public void whenStrAnyLangOrHasNoNonAlphaNum_ThenRetFalse() { //Georgian text with no special char String str1 = "მშვენიერი"; //Turkish text with no special char String str2 = "müthiş"; //Latin text with no special char String str3 = "Wonderful"; //Error message String ERROR_MSG = "Test failed, no alphanumeric char found in "; assertFalse(ERROR_MSG + str1, NonAlphaNumRegexChecker.containsNonAlphanumeric(str1)); assertFalse(ERROR_MSG + str2, NonAlphaNumRegexChecker.containsNonAlphanumeric(str2)); assertFalse(ERROR_MSG + str3, NonAlphaNumRegexChecker.containsNonAlphanumeric(str3)); } @Test public void givenLang_whenStrHasDiffLangOrHasNonAlphaNum_ThenRetTrue() { String script1 = Character.UnicodeScript.MYANMAR.name(); //script used for Burmese Lang //text in Burmese with special char String str1 = "အံ့ဩ%စ##ရာ"; //special character and english char in Burmese String str2 = "အံ့ADFဩစ%ရာ*^"; //English character in Burmese String str3 = "အံ့ဩစTရာWon"; //Error message String ERROR_MSG = "Test failed, no alphanumeric char found in "; assertTrue(ERROR_MSG + str1, NonAlphaNumRegexChecker.containsNonAlphanumeric(str1, script1)); assertTrue(ERROR_MSG + str2, NonAlphaNumRegexChecker.containsNonAlphanumeric(str2, script1)); assertTrue(ERROR_MSG + str3, NonAlphaNumRegexChecker.containsNonAlphanumeric(str3, script1)); } @Test public void givenLang_whenStrHasSameLangOrHasNoNonAlphaNum_ThenRetFalse() { String script1 = Character.UnicodeScript.MYANMAR.name(); //script used for Burmese Lang String script2 = Character.UnicodeScript.GREEK.name(); //text in Burmese String str1 = "အံ့ဩစရာ"; //text in Greek String str2 = "Εκπληκτικός"; //Error message String ERROR_MSG = "Test failed, alphanumeric char found in "; assertFalse(ERROR_MSG + str1, NonAlphaNumRegexChecker.containsNonAlphanumeric(str1, script1)); assertFalse(ERROR_MSG + str2, NonAlphaNumRegexChecker.containsNonAlphanumeric(str2, script2)); } }
eugenp/tutorials
core-java-modules/core-java-string-operations-6/src/test/java/com/baeldung/nonalphanumeric/NonAlphaNumRegexCheckerUnitTest.java
46,258
package com.baeldung.nonalphanumeric; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class NonAlphaNumericCheckerUnitTest { @Test public void whenStrLatinOrHasNonAlphaNum_ThenRetTrue() { String latin = Character.UnicodeScript.LATIN.name(); //alphabets with special character String str1 = "W$nder^ful"; //digits with special character String str2 = "123$%45"; //alphabets and digits with special characters String str3 = "W@nd$r123$%45"; //Error message String ERROR_MSG = "Test failed, no alphanumeric char found in "; assertTrue(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str1, latin)); assertTrue(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str2, latin)); assertTrue(ERROR_MSG + str3, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str3, latin)); } @Test public void whenStrLatinOrHasNoNonAlphaNum_ThenRetFalse() { String latin = Character.UnicodeScript.LATIN.name(); //only alphabets String str1 = "Wonderful"; //only digits String str2 = "12345"; //mix of alphabet and digit String str3 = "5Won6der1234"; //Error message String ERROR_MSG = "Test failed, non alphanumeric char found in "; assertFalse(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str1, latin)); assertFalse(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str2, latin)); assertFalse(ERROR_MSG + str3, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str3, latin)); } @Test public void whenStrNonLatinOrHasNonAlphaNum_ThenRetTrue() { String latin = Character.UnicodeScript.LATIN.name(); //special character in Georgian text String str1 = "##მშვენიერი@"; //special character with Turkish text String str2 = "müthiş#$"; //No special character in Georgian text String str3 = "მშვენიერი"; //Error message String ERROR_MSG = "Test failed, no alphanumeric char found in "; assertTrue(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str1, latin)); assertTrue(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str2, latin)); assertTrue(ERROR_MSG + str3, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str3, latin)); } @Test public void whenStrAnyLangOrHasNonAlphaNum_ThenRetTrue() { //special character in Georgian text String str1 = "##მშვენიერი@"; //special character with Turkish text String str2 = "müthiş#$"; //Error message String ERROR_MSG = "Test failed, no alphanumeric char found in "; assertTrue(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericAnyLangScript(str1)); assertTrue(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericAnyLangScript(str2)); } @Test public void whenStrAnyLangOrHasNoNonAlphaNum_ThenRetFalse() { //Georgian text with no special char String str1 = "მშვენიერი"; //Turkish text with no special char String str2 = "müthiş"; //Latin text with no special char String str3 = "Wonderful"; //Error message String ERROR_MSG = "Test failed, no alphanumeric char found in "; assertFalse(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericAnyLangScript(str1)); assertFalse(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericAnyLangScript(str2)); assertFalse(ERROR_MSG + str3, NonAlphaNumericChecker.isNonAlphanumericAnyLangScript(str3)); } @Test public void givenLang_whenStrHasDiffLangOrHasNonAlphaNum_ThenRetTrue() { String script1 = Character.UnicodeScript.MYANMAR.name(); //script used for Burmese Lang //text in Burmese with special char String str1 = "အံ့ဩ%စ##ရာ"; //special character and english char in Burmese String str2 = "အံ့ADFဩစ%ရာ*^"; //English character in Burmese String str3 = "အံ့ဩစTရာWon"; //Error message String ERROR_MSG = "Test failed, no alphanumeric char found in "; assertTrue(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str1, script1)); assertTrue(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str2, script1)); assertTrue(ERROR_MSG + str3, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str3, script1)); } @Test public void givenLang_whenStrHasSameLangOrHasNoNonAlphaNum_ThenRetFalse() { String script1 = Character.UnicodeScript.MYANMAR.name(); //script used for Burmese Lang String script2 = Character.UnicodeScript.GREEK.name(); //text in Burmese String str1 = "အံ့ဩစရာ"; //text in Greek String str2 = "Εκπληκτικός"; //Error message String ERROR_MSG = "Test failed, alphanumeric char found in "; assertFalse(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str1, script1)); assertFalse(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str2, script2)); } @Test public void givenComLangImpl_whenStrAnyLangOrHasNonAlphaNum_ThenRetTrue() { //special character in Georgian text String str1 = "##მშვენიერი@"; //special character with Turkish text String str2 = "müthiş#$"; //Error message String ERROR_MSG = "Test failed, no alphanumeric char found in "; assertTrue(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str1)); assertTrue(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str2)); } @Test public void givenComLangImpl_whenStrAnyLangOrHasNoNonAlphaNum_ThenRetFalse() { //Georgian text with no special char String str1 = "მშვენიერი"; //Turkish text with no special char String str2 = "müthiş"; //Latin text with no special char String str3 = "Wonderful"; //Burmese in Myanmar script // String str4 = "အံ့ဩစရာ"; //only digits String str5 = "3465"; //Error message String ERROR_MSG = "Test failed, alphanumeric char found in "; assertFalse(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str1)); assertFalse(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str2)); assertFalse(ERROR_MSG + str3, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str3)); //StringUtils.isAlphanumeric is unable to support supplementary unicode character and hence fails //assertFalse(ERROR_MSG + str4, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str4)); assertFalse(ERROR_MSG + str5, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str5)); } }
eugenp/tutorials
core-java-modules/core-java-string-operations-6/src/test/java/com/baeldung/nonalphanumeric/NonAlphaNumericCheckerUnitTest.java
46,265
package cn.kk.kkdict.beans; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.nio.ByteBuffer; import org.junit.Before; import org.junit.Test; import cn.kk.kkdict.utils.ArrayHelper; import cn.kk.kkdict.utils.Helper; public class DictByteBufferRowTest { private static ByteBuffer bb1; private static ByteBuffer bb2; private static ByteBuffer bb3; private static ByteBuffer bb4; private static ByteBuffer bb5; private static ByteBuffer bb6; private static DictByteBufferRow row1; private static DictByteBufferRow row2; private static DictByteBufferRow row3; private static DictByteBufferRow row4; private static DictByteBufferRow row5; private static DictByteBufferRow row6; private static String test1 = "ks═اَدَب▫krc═Адабият▫koi═Лыддьӧтан▫kn═ಸಾಹಿತ್ಯ▫kk═Әдебиет▫kab═Tasekla▫kaa═A'debiyat▫ka═ლიტერატურა▫jv═Sastra▫is═Bókmenntir▫io═Literaturo▫ie═Literatura▫ia═Litteratura▫hy═Գրականություն▫ht═Literati▫hr═Književnost▫hif═Literature▫hi═साहित्य▫he═ספרות▫haw═Moʻokalaleo▫hak═Vùn-ho̍k▫gv═Lettyraght▫gu═સાહિત્ય▫gl═Literatura▫gd═Litreachas▫gan═文學▫ga═Litríocht▫fy═Literatuer▫fur═Leterature▫frr═Literatuur▫frp═Litèratura▫fo═Bókmentir▫fiu-vro═Kirändüs▫fa═ادبیات▫ext═Literatura▫eu═Literatura▫et═Kirjandus▫eo═Literaturo▫el═Λογοτεχνία▫dv═އަދަބިއްޔާތު▫diq═Edebiyat▫da═Litteratur▫cy═Llenyddiaeth▫cv═Литература▫csb═Lëteratura▫co═Littiratura▫ceb═Katitikan▫bs═Književnost▫br═Lennegezh▫bo═རྩོམ་རིག་ཡི་གེའི་རིག་པ།▫bn═সাহিত্য▫bg═Литература▫be-x-old═Літаратура▫be═Літаратура▫bat-smg═Literatūra▫bar═Literadua▫ba═Әҙәбиәт▫az═Ədəbiyyat▫ay═Qillqatata▫ast═Lliteratura▫as═সাহিত্য▫ar═أدب▫an═Literatura▫am═ሥነ ጽሑፍ▫af═Letterkunde▫tr═Edebiyat▫id═Sastra▫ko═문학▫hu═Irodalom▫cs═Literatura▫fi═Kirjallisuus▫no═Litteratur▫ca═Literatura▫uk═Література▫vi═Văn chương▫sv═Litteratur▫pt═Literatura▫ja═文学▫ru═Литература▫es═Literatura▫pl═Literatura▫it═Letteratura▫nl═Literatuur▫fr═Littérature▫de═Literatur▫en═Literature▫zh-yue═文學▫zh-min-nan═Bûn-ha̍k▫zea═Literatuur▫za═Vwnzyoz▫yo═Lítíréṣọ̀▫yi═ליטעראטור▫xmf═ლიტერატურა▫wuu═文学▫wo═Njàngat▫war═Panuratan▫wa═Belès letes▫vec═Łiteratura▫ur═ادب▫tt═Ädäbiät▫tl═Panitikan▫th═วรรณกรรม▫tg═Адабиёт▫te═సాహిత్యం▫ta═இலக்கியம்▫sw═Fasihi▫su═Sastra▫stq═Flugge Literatuur▫sr═Књижевност▫sq═Letërsia▫so═Suugaan▫sl═Književnost▫sk═Literatúra▫simple═Literature▫sh═Književnost▫sco═Leiteratur▫scn═Littiratura▫sa═प्राचीन साहित्यम्▫rw═Ubuvanganzo▫rue═Література▫roa-rup═Literatura▫ro═Literatură▫qu═Simi kapchiy▫ps═ادبيات▫pnb═ساہت▫pap═Literatura▫pam═Literatura▫os═Литературæ▫oc═Literatura▫nrm═Littéthatuthe▫nov═Literature▫nn═Litteratur▫new═साहित्य▫ne═साहित्य▫n▫nds═Literatur▫nap═Litteratura▫nah═Tlahcuilōcāyōtl▫my═စာပေ▫mwl═Literatura▫ms═Kesusasteraan▫mr═साहित्य▫mn═Утга зохиол▫ml═സാഹിത്യം▫mk═Литература▫map-bms═Sastra▫lv═Literatūra▫lt═Literatūra▫lo═ວັນນະຄະດີ▫li═Literatuur▫lbe═Адабият▫lb═Literatur▫lad═Literatura▫la═Litterae▫ky═Адабият▫kv═Гижӧмбур▫ku═Wêje▫nl═Literatuur▫zh═文学▫bat_smg═Literatūra▫zh_yue═文學▫sw═Fasihi andishi▫stq═Literatuur (Begriepskläärengssiede)"; private static String test2 = "sl═Seznam jezikovnih družin in jezikov‹源wiki_sl▫cs═Seznam jazyků a jazykových rodin‹源1‹源2‹源3▫ja═言語のグループの一覧‹源wiki_sl"; private static String test3 = " sl═Seznam jezikovnih družin in jezikov‹源1‹源2‹源3 "; private static String test4 = "sl═Seznam jezikovnih družin in jezikov"; private static String test5 = ""; private static String test6 = " sl═Seznam jezikovnih družin in jezikov‹源wiki_sl▫cs═Seznam jazyků a jazykových rodin‹源1‹源2‹源3▫ja═言語のグループの一覧‹源wiki_sl▫krc═Адабият"; @Before public void setUp() { bb1 = ByteBuffer.wrap(test1.getBytes(Helper.CHARSET_UTF8)); bb2 = ByteBuffer.wrap(test2.getBytes(Helper.CHARSET_UTF8)); bb3 = ByteBuffer.wrap(test3.getBytes(Helper.CHARSET_UTF8)); bb4 = ByteBuffer.wrap(test4.getBytes(Helper.CHARSET_UTF8)); bb5 = ByteBuffer.wrap(test5.getBytes(Helper.CHARSET_UTF8)); bb6 = ByteBuffer.wrap(test6.getBytes(Helper.CHARSET_UTF8)); row1 = DictByteBufferRow.parse(bb1); row2 = DictByteBufferRow.parse(bb2); row3 = DictByteBufferRow.parse(ArrayHelper.trimP(bb3)); row4 = DictByteBufferRow.parse(bb4); row5 = DictByteBufferRow.parse(bb5); row6 = DictByteBufferRow.parse(bb6); } @Test public void testHasAttribute() { assertTrue(row3.hasFirstValueAttributes(0)); assertTrue(row3.hasFirstValueAttribute(0, ByteBuffer.wrap("源2".getBytes(Helper.CHARSET_UTF8)))); assertTrue(row3.hasFirstValueAttribute(0, ByteBuffer.wrap("源1".getBytes(Helper.CHARSET_UTF8)))); assertFalse(row3.hasFirstValueAttribute(0, ByteBuffer.wrap("源".getBytes(Helper.CHARSET_UTF8)))); assertFalse(row3.hasFirstValueAttribute(0, ByteBuffer.wrap("‹源2‹源3".getBytes(Helper.CHARSET_UTF8)))); } @Test public void testEquals() { String t1 = "sl═Seznam jezikovnih družin in jezikov‹源wiki_sl▫cs═Seznam jazyků a jazykových rodin‹源1‹源2‹源3▫ja═言語のグループの一覧‹源wiki_sl"; String t2 = "sl═Seznam jezikovnih družin in jezikov‹源wiki_sl▫cs═Seznam jazyků a jazykových rodin‹源1‹源2▫ja═言語のグループの一覧‹源wiki_sl"; String t3 = " sl═Seznam jezikovnih družin in jezikov‹源wiki_sl▫cs═Seznam jazyků a jazykových rodin‹源1‹源2‹源3▫ja═言語のグループの一覧‹源wiki_sl▫krc═Адабият"; String t4 = ""; String t5 = " sl═Seznam jezikovnih družin in jezikov‹源1‹源2‹源3 "; String t6 = " sl═Seznam jezikovnih družin in jezikov‹源1‹源2‹源3"; String t7 = "sl═Seznam jezikovnih družin in jezikov‹源wiki_sl▫ja═言語のグループの一覧‹源wiki_sl▫cs═Seznam jazyků a jazykových rodin‹源1‹源2‹源3"; ByteBuffer b1 = ByteBuffer.wrap(t1.getBytes(Helper.CHARSET_UTF8)); ByteBuffer b2 = ByteBuffer.wrap(t2.getBytes(Helper.CHARSET_UTF8)); ByteBuffer b3 = ArrayHelper.trimP(ByteBuffer.wrap(t3.getBytes(Helper.CHARSET_UTF8))); ByteBuffer b4 = ByteBuffer.wrap(t4.getBytes(Helper.CHARSET_UTF8)); ByteBuffer b5 = ArrayHelper.trimP(ByteBuffer.wrap(t5.getBytes(Helper.CHARSET_UTF8))); ByteBuffer b6 = ArrayHelper.trimP(ByteBuffer.wrap(t6.getBytes(Helper.CHARSET_UTF8))); ByteBuffer b7 = ArrayHelper.trimP(ByteBuffer.wrap(t7.getBytes(Helper.CHARSET_UTF8))); DictByteBufferRow r1 = DictByteBufferRow.parse(b1); DictByteBufferRow r1c = DictByteBufferRow.parse(b1, true); DictByteBufferRow r2 = DictByteBufferRow.parse(b2); DictByteBufferRow r2c = DictByteBufferRow.parse(b2, true); DictByteBufferRow r3 = DictByteBufferRow.parse(b3); DictByteBufferRow r3c = DictByteBufferRow.parse(b3, true); DictByteBufferRow r4 = DictByteBufferRow.parse(b4); DictByteBufferRow r4c = DictByteBufferRow.parse(b4, true); DictByteBufferRow r5 = DictByteBufferRow.parse(b5); DictByteBufferRow r5c = DictByteBufferRow.parse(b5, true); DictByteBufferRow r6 = DictByteBufferRow.parse(b6); DictByteBufferRow r7 = DictByteBufferRow.parse(b7); assertFalse(r1.equals(r2)); assertFalse(r2.equals(r1)); assertFalse(r1.equals(r4)); assertFalse(r4.equals(r1)); assertFalse(r3.equals(r2)); assertFalse(r2.equals(r3)); assertFalse(r4.equals(r5)); assertFalse(r5.equals(r4)); assertFalse(r1.equals(r3)); assertFalse(r3.equals(r1)); assertTrue(r1.equals(r7)); assertTrue(r7.equals(r1)); assertTrue(r1.equals(r1)); assertTrue(r1.equals(r1c)); assertTrue(r2.equals(r2c)); assertTrue(r3.equals(r3c)); assertTrue(r4.equals(r4c)); assertTrue(r5.equals(r5c)); assertTrue(r1c.equals(r1)); assertTrue(r5.equals(r5)); assertTrue(r6.equals(r5)); } @Test public void testGetAttribute() { assertEquals("", ArrayHelper.toStringP(row1.getFirstValueAttribute(0, 0))); assertEquals("", ArrayHelper.toStringP(row1.getFirstValueAttribute(3, 0))); assertEquals("源1", ArrayHelper.toStringP(row3.getFirstValueAttribute(0, 0))); assertEquals("源2", ArrayHelper.toStringP(row3.getFirstValueAttribute(0, 1))); assertEquals("源3", ArrayHelper.toStringP(row3.getFirstValueAttribute(0, 2))); assertEquals("源wiki_sl", ArrayHelper.toStringP(row2.getFirstValueAttribute(2, 0))); assertEquals("源1", ArrayHelper.toStringP(row2.getFirstValueAttribute(1, 0))); assertEquals("源2", ArrayHelper.toStringP(row2.getFirstValueAttribute(1, 1))); assertEquals("源3", ArrayHelper.toStringP(row2.getFirstValueAttribute(1, 2))); assertEquals("", ArrayHelper.toStringP(row5.getFirstValueAttribute(3, 0))); assertEquals("", ArrayHelper.toStringP(row6.getFirstValueAttribute(3, 0))); } @Test public void testGetAttributes() { assertEquals("", ArrayHelper.toStringP(row1.getFirstValueAttributes(0))); assertEquals("", ArrayHelper.toStringP(row1.getFirstValueAttributes(3))); assertEquals("源1‹源2‹源3", ArrayHelper.toStringP(row3.getFirstValueAttributes(0))); assertEquals("源wiki_sl", ArrayHelper.toStringP(row2.getFirstValueAttributes(2))); assertEquals("", ArrayHelper.toStringP(row5.getFirstValueAttributes(3))); } @Test public void testGetAttributesSize() { assertEquals(0, row1.getFirstValueAttributesSize(0)); assertEquals(0, row1.getFirstValueAttributesSize(3)); assertEquals(3, row3.getFirstValueAttributesSize(0)); assertEquals(3, row2.getFirstValueAttributesSize(1)); assertEquals(1, row2.getFirstValueAttributesSize(2)); assertEquals(0, row5.getFirstValueAttributesSize(3)); assertEquals(0, row6.getFirstValueAttributesSize(3)); } @Test public void testGetDefinitionWithAttributes() { assertEquals("ks═اَدَب", ArrayHelper.toStringP(row1.getDefinitionWithAttributes(0))); assertEquals("kn═ಸಾಹಿತ್ಯ", ArrayHelper.toStringP(row1.getDefinitionWithAttributes(3))); assertEquals("sl═Seznam jezikovnih družin in jezikov‹源1‹源2‹源3", ArrayHelper.toStringP(row3.getDefinitionWithAttributes(0))); assertEquals("ja═言語のグループの一覧‹源wiki_sl", ArrayHelper.toStringP(row2.getDefinitionWithAttributes(2))); assertEquals("", ArrayHelper.toStringP(row5.getDefinitionWithAttributes(3))); assertEquals("krc═Адабият", ArrayHelper.toStringP(row6.getDefinitionWithAttributes(3))); } @Test public void testGetLanguage() { assertEquals("ks", ArrayHelper.toStringP(row1.getLanguage(0))); assertEquals("kn", ArrayHelper.toStringP(row1.getLanguage(3))); assertEquals("sl", ArrayHelper.toStringP(row3.getLanguage(0))); assertEquals("ja", ArrayHelper.toStringP(row2.getLanguage(2))); assertEquals("", ArrayHelper.toStringP(row5.getLanguage(3))); assertEquals("krc", ArrayHelper.toStringP(row6.getLanguage(3))); } @Test public void testGetValue() { assertEquals("اَدَب", ArrayHelper.toStringP(row1.getFirstValue(0))); assertEquals("ಸಾಹಿತ್ಯ", ArrayHelper.toStringP(row1.getFirstValue(3))); assertEquals("Seznam jezikovnih družin in jezikov", ArrayHelper.toStringP(row3.getFirstValue(0))); assertEquals("言語のグループの一覧", ArrayHelper.toStringP(row2.getFirstValue(2))); assertEquals("", ArrayHelper.toStringP(row5.getFirstValue(3))); assertEquals("Адабият", ArrayHelper.toStringP(row6.getFirstValue(3))); } @Test public void testGetValueWithAttributes() { assertEquals("اَدَب", ArrayHelper.toStringP(row1.getFirstValueWithAttributes(0))); assertEquals("ಸಾಹಿತ್ಯ", ArrayHelper.toStringP(row1.getFirstValueWithAttributes(3))); assertEquals("Seznam jezikovnih družin in jezikov‹源1‹源2‹源3", ArrayHelper.toStringP(row3.getFirstValueWithAttributes(0))); assertEquals("言語のグループの一覧‹源wiki_sl", ArrayHelper.toStringP(row2.getFirstValueWithAttributes(2))); assertEquals("", ArrayHelper.toStringP(row5.getFirstValueWithAttributes(3))); assertEquals("Адабият", ArrayHelper.toStringP(row6.getFirstValueWithAttributes(3))); } @Test public void testIsLinkedBy() { String t1 = "sl═Seznam jezikovnih družin in jezikov‹源wiki_sl▫cs═Seznam jazyků a jazykových rodin‹源1‹源2‹源3▫ja═言語ープの一覧‹源wiki_sl"; String t2 = "sl═Seznam in jezikov‹源wiki_sl▫cs═Seznam jazyků a jazykových rodin‹源1‹源2▫ja═言語のグループ‹源wiki_sl"; String t3 = " sl═Seznam jezikovnih družin in jezikov‹源wiki_sl▫cs═Seznam rodin‹源1‹源2‹源3▫ja═ープの一覧‹源wiki_sl▫krc═Адабият"; String t4 = ""; String t5 = " sl═Seznam jezikovnih družin in jezikov‹源1‹源2‹源3 "; String t6 = " sl═Seznam jezikovnih družin in jezikov‹源1‹源2‹源3"; ByteBuffer b1 = ByteBuffer.wrap(t1.getBytes(Helper.CHARSET_UTF8)); ByteBuffer b2 = ByteBuffer.wrap(t2.getBytes(Helper.CHARSET_UTF8)); ByteBuffer b3 = ArrayHelper.trimP(ByteBuffer.wrap(t3.getBytes(Helper.CHARSET_UTF8))); ByteBuffer b4 = ByteBuffer.wrap(t4.getBytes(Helper.CHARSET_UTF8)); ByteBuffer b5 = ArrayHelper.trimP(ByteBuffer.wrap(t5.getBytes(Helper.CHARSET_UTF8))); ByteBuffer b6 = ArrayHelper.trimP(ByteBuffer.wrap(t6.getBytes(Helper.CHARSET_UTF8))); DictByteBufferRow r1 = DictByteBufferRow.parse(b1); DictByteBufferRow r1c = DictByteBufferRow.parse(b1, true); DictByteBufferRow r2 = DictByteBufferRow.parse(b2); DictByteBufferRow r2c = DictByteBufferRow.parse(b2, true); DictByteBufferRow r3 = DictByteBufferRow.parse(b3); DictByteBufferRow r3c = DictByteBufferRow.parse(b3, true); DictByteBufferRow r4 = DictByteBufferRow.parse(b4); DictByteBufferRow r4c = DictByteBufferRow.parse(b4, true); DictByteBufferRow r5 = DictByteBufferRow.parse(b5); DictByteBufferRow r5c = DictByteBufferRow.parse(b5, true); DictByteBufferRow r6 = DictByteBufferRow.parse(b6); assertFalse(r2.isLinkedBy(r3)); assertFalse(r3.isLinkedBy(r2)); assertFalse(r4.isLinkedBy(r4c)); assertFalse(r4.isLinkedBy(r1)); assertFalse(r1.isLinkedBy(r4)); assertFalse(r5.isLinkedBy(r2)); assertFalse(r2.isLinkedBy(r5)); assertTrue(r5.isLinkedBy(r1)); assertTrue(r1.isLinkedBy(r5)); assertTrue(r6.isLinkedBy(r1)); assertTrue(r1.isLinkedBy(r6)); assertTrue(r1.isLinkedBy(r2)); assertTrue(r2.isLinkedBy(r1)); assertTrue(r3.isLinkedBy(r1)); assertTrue(r1.isLinkedBy(r3)); assertTrue(r1.isLinkedBy(r1)); assertTrue(r1.isLinkedBy(r1c)); assertTrue(r2.isLinkedBy(r2c)); assertTrue(r3.isLinkedBy(r3c)); assertTrue(r5.isLinkedBy(r5c)); assertTrue(r1c.isLinkedBy(r1)); assertTrue(r5.isLinkedBy(r5)); assertTrue(r6.isLinkedBy(r5)); } @Test public void testParseByteBuffer() { assertEquals(163, row1.size()); assertEquals(3, row2.size()); assertEquals(1, row3.size()); assertEquals(1, row4.size()); assertEquals(0, row5.size()); assertEquals(4, row6.size()); } }
xuantuan58/dict4cn
importer/test/cn/kk/kkdict/beans/DictByteBufferRowTest.java
46,295
package UserInterfaces.GraphicsComponents; /** * Enumeration όλων των ειδών του παιχνιδιού * * @author Δημήτριος Παντελεήμων Γιακάτος * @author Χατζηεμμανουήλ Θεμιστοκλής * @version 1.0.0 */ public enum Mode { Basic, Double, Triple, Duel }
dpgiakatos/MemoryGame
UserInterfaces/GraphicsComponents/Mode.java
46,322
package UserInterfaces.GraphicsComponents; /** * Enumeration όλων των Panel/παραθύρων της εφαρμογής * * @author Δημήτριος Παντελεήμων Γιακάτος * @author Χατζηεμμανουήλ Θεμιστοκλής * @version 1.0.0 */ public enum PanelName { HOME, ABOUT, HELP, SCORE, DIFFICULTY, GAME, GAME_DUEL }
dpgiakatos/MemoryGame
UserInterfaces/GraphicsComponents/PanelName.java
46,342
package gr.aueb.dmst.pijavaparty.proderp.dao; import gr.aueb.dmst.pijavaparty.proderp.entity.COrderItem; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * COrderItemDao.java - a class for interacting and modifying the fields of a * customer's items. * * @author Athina P. * @see COrderItem */ public class COrderItemDao extends Dao implements CompositeEntityI<COrderItem> { private static final String GETALL = "SELECT * FROM C_order_items"; private static final String GETBYIDS = "SELECT * FROM C_order_items WHERE c_order_id = ? AND product_id = ?"; private static final String GETITEMSPERCORDER = "SELECT * FROM C_order_items WHERE c_order_id = ?"; private static final String INSERT = "INSERT INTO C_order_items VALUES (?, ?, ?)"; private static final String DELETE = "DELETE FROM C_order_items WHERE c_order_id = ? AND product_id = ?"; private COrderDao co = new COrderDao(); private ProductDao pr = new ProductDao(); /** * Retrieve customer order items from database * * @return A COrderItem data type List. */ @Override public List<COrderItem> getAll() { List<COrderItem> corders = new ArrayList(); Statement st = null; ResultSet rs = null; try { st = getConnection().createStatement(); rs = st.executeQuery(GETALL); while (rs.next()) { corders.add(new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3)));//δεν υπαρχει η getById στην COrdrDao } } catch (SQLException ex) { Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex); } finally { closeStatementAndResultSet(rs, st); } return corders; } /** * Get a customer's order item with a specific id. * * @param coid COrder's id. * @param prid Product's id. * @return A COrderItem data type object. */ public COrderItem getByIds(int coid, int prid) { PreparedStatement pst = null; ResultSet rs = null; try { pst = getConnection().prepareStatement(GETBYIDS); pst.setInt(1, coid); pst.setInt(2, prid); rs = pst.executeQuery(); if (rs.next()) { return new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3)); } } catch (SQLException ex) { Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex); } finally { closeStatementAndResultSet(rs, pst); } return null; } /** * Get items of a specific COrder. * * @param coid COrder's id. * @return A COrderItem data type List. */ public List<COrderItem> getItemsPerCOrder(int coid) { List<COrderItem> coi = new ArrayList(); PreparedStatement pst = null; ResultSet rs = null; try { pst = getConnection().prepareStatement(GETITEMSPERCORDER); pst.setInt(1, coid); rs = pst.executeQuery(); while (rs.next()) { coi.add(new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3))); } } catch (SQLException ex) { Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex); } finally { closeStatementAndResultSet(rs, pst); } return coi; } /** * Insert a new customer's item. * * @param coi An object of type COrderItem. */ @Override public void insert(COrderItem coi) { PreparedStatement pst = null; try { pst = getConnection().prepareStatement(INSERT); pst.setInt(1, coi.getCorder().getId()); pst.setInt(2, coi.getProduct().getId()); pst.setInt(3, coi.getQuantity()); pst.execute(); } catch (SQLException ex) { Logger.getLogger(ProductRawMaterialDao.class.getName()).log(Level.SEVERE, null, ex);//εδω τι θα μπει; } finally { closeStatementAndResultSet(pst); } } /** * Delete a customer's item with a specific id. * * @param cordId COrder's id. * @param pId Product's id. */ @Override public void delete(int cordId, int pId) { PreparedStatement pst = null; try { pst = getConnection().prepareStatement(DELETE); pst.setInt(1, cordId); pst.setInt(2, pId); pst.execute(); closeStatementAndResultSet(pst); } catch (SQLException ex) { Logger.getLogger(ProductRawMaterialDao.class.getName()).log(Level.SEVERE, null, ex);//εδω τι θα μπει; } finally { closeStatementAndResultSet(pst); } } }
AthinaDavari/JavaAssignment
proderp/src/main/java/gr/aueb/dmst/pijavaparty/proderp/dao/COrderItemDao.java
46,359
import javax.swing.tree.TreeCellRenderer; public class BSTree { private TreeNode root; public BSTree() { // Default constructor root = null; } // End of: Default constructor public boolean isEmpty() { return (root == null); } // End of function: isEmpty() public void insertElement(int newData) { if (this.isEmpty()) root = new TreeNode(newData); else this.insertNode(newData, root); } // End of function: insertElement() private void insertNode(int newData, TreeNode newNode) { if (newData < newNode.getNodeData()) { if (newNode.getLeftNode() == null) newNode.setLeftNode(new TreeNode(newData)); else insertNode(newData, newNode.getLeftNode()); } else { if (newNode.getRightNode() == null) newNode.setRightNode(new TreeNode(newData)); else insertNode(newData, newNode.getRightNode()); } } // End of function: insertNode() // ΕΝΘΕΜΑΤΙΚΗ ΔΙΕΛΕΥΣΗ (InOrderTraversal) ΑΠΟ ΤΟΥΣ ΚΟΜΒΟΥΣ ΤΟΥ ΔΥΑΔΙΚΟΥ ΔΕΝΤΡΟΥ public void InOrderTraversal() { inOrder(root); } // End of function: InOrderTraversal() private void inOrder(TreeNode node) { if (node == null) return; inOrder(node.getLeftNode()); System.out.println(node.getNodeData() + " "); // <--- ΠΡΟΣΟΧΗ ΕΔΩ! inOrder(node.getRightNode()); } // End of function: inOrder() // ΠΡΟΘΕΜΑΤΙΚΗ ΔΙΕΛΕΥΣΗ (PreOrderTraversal) ΑΠΟ ΤΟΥΣ ΚΟΜΒΟΥΣ ΤΟΥ ΔΥΑΔΙΚΟΥ ΔΕΝΤΡΟΥ public void PreOrderTraversal() { preOrder(root); } // End of function: PreOrderTraversal() private void preOrder(TreeNode node) { if (node == null) return; System.out.println(node.getNodeData() + " "); // <--- ΠΡΟΣΟΧΗ ΕΔΩ! preOrder(node.getLeftNode()); preOrder(node.getRightNode()); } // End of function: preOrder() // ΕΠΙΘΕΜΑΤΙΚΗ/ΜΕΤΑΘΕΜΑΤΙΚΗ ΔΙΕΛΕΥΣΗ (PostOrderTraversal) ΑΠΟ ΤΟΥΣ ΚΟΜΒΟΥΣ ΤΟΥ ΔΥΑΔΙΚΟΥ ΔΕΝΤΡΟΥ public void PostOrderTraversal() { preOrder(root); } // End of function: PostOrderTraversal() private void postOrder(TreeNode node) { if (node == null) return; postOrder(node.getLeftNode()); postOrder(node.getRightNode()); System.out.println(node.getNodeData() + " "); // <--- ΠΡΟΣΟΧΗ ΕΔΩ! } // End of function: postOrder() // ΔΥΑΔΙΚΑ ΔΕΝΤΡΑ public int countNodes() { // ΜΕΤΡΗΣΗ ΤΝ ΚΟΜΒΩΝ/ΑΚΜΩΝ ΤΟΥ ΔΕΝΤΡΟΥ return countNodes(root); } // End of function: countNodes() private int countNodes(TreeNode node) { if (node == null) return 0; else return countNodes(node.getLeftNode()) + countNodes(node.getRightNode()) + 1; } // End of function: countNodes() public int countLeafs() { // ΜΕΤΡΗΣΗ ΤΩΝ ΦΥΛΩΝ/ΚΟΡΥΦΩΝ ΤΟΥ ΔΕΝΤΡΟΥ return countLeafs(root); } // End of function: countLeafs() private int countLeafs(TreeNode node) { // ΜΕΤΡΗΣΗ ΤΩΝ ΦΥΛΩΝ/ΚΟΡΥΦΩΝ ΤΟΥ ΔΕΝΤΡΟΥ if (node == null) return 0; else { int count = 0; count += countLeafs(node.getLeftNode()); count += countLeafs(node.getRightNode()); if ((node.getLeftNode() == null) && (node.getRightNode() == null)) count++; return count; } } // End of function: countLeafs() }
panosale/DIPAE_DataStructures_3rd_Term
_CommonStaff/BinaryTree/src/BSTree.java
46,389
import java.util.List; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import gf.Questionnaire; import gf.TestAPI; import gf.SQLConnection; public class Main { public static void main(String[] args) throws Exception { // Get a database connection Connection conn = SQLConnection.getConnection(); // Make Login or Signup Scanner sc = new Scanner(System.in); String username = null; String password = null; System.out.println("Welcome to Gen5 wine somellier!"); System.out.println("Do you have an account? Yes or No?"); String yesNo = sc.nextLine(); User user = new User(); //Login if (yesNo.toLowerCase().contains("yes")) { login(username, password, conn, sc, user); //Signup } else if (yesNo.toLowerCase().contains("no")) { signUp(username, password, conn, sc, user); } System.out.println(user.getUsername()); Questionnaire questionnaire = new Questionnaire(); List<String> userResponses = questionnaire.collectUserResponses(); String request1 = "Find 5 wines that are: " + userResponses.get(1) + "and " + userResponses.get(3) + ".Please display them ONLY like this: name, color, flavor."; // Print user responses System.out.println("User Responses: " + userResponses); // Get a database connection Connection conn = SQLConnection.getConnection(); // Second request useing the wines in the DB String winetable = getStringTable(userResponses.get(3), conn); String request2 = "Please select 3 of the wines below that go best with " + userResponses.get(0) + ", are ideal " + userResponses.get(2) + " and are best for " + userResponses.get(4) + "experienses." + "Please diplay them ONLY by their name. Here are the wines: " + winetable; try { // Use GPT-3.5 to analyze responses and get wine recommendations ArrayList<String> gptResponse1 = TestAPI.getWineRecommendations(request1); // Display the recommended wines to the user System.out.println("Recommended Wines:"); System.out.println(gptResponse1); // Save the wines in DB try { saveWinesInDB(gptResponse1, conn); System.out.println("All good"); } catch (SQLException e) { System.err.println("SQL error: " + e.getMessage()); } finally { // Close the connection when done if (conn != null) { try { conn.close(); } catch (SQLException e) { System.err.println("Error closing connection: " + e.getMessage()); } } } // Call GPT again to select the final wines //!!ΕΔΩ ΠΕΤΑΕΙ ERROR!! ArrayList<String> gptResponse2 = TestAPI.getWineRecommendations(request2); System.out.println(gptResponse2); } catch (Exception e) { e.printStackTrace(); } } // Put the wines of the gpt response in the ArrayLists public static void saveWinesInDB(ArrayList<String> gptWineList, Connection conn) throws SQLException { PreparedStatement a = null; for (String wine : gptWineList) { String[] owine = wine.split(","); if (owine[1].toLowerCase().contains("white".toLowerCase())){ putWineInTable("WhiteWines", owine, conn, a); } else if (owine[1].toLowerCase().contains("red".toLowerCase())){ putWineInTable("RedWines", owine, conn, a); } else if (owine[1].toLowerCase().contains("ros".toLowerCase())){ putWineInTable("RoseWines", owine, conn, a); } else { System.out.println("Unknown Wine Category"); } } } // Get INSERT PreparedStatement in SQL public static PreparedStatement makeSQLStatementInsert (String tablename, String wname, String wcolor, String wflavor, Connection conn) throws SQLException { String sql = " insert into " + tablename + "(w_name, w_color, w_flavor)" + " values (?, ?, ?)"; PreparedStatement preparedStmt = conn.prepareStatement(sql); //preparedStmt.setString (1, key); preparedStmt.setString (1, wname); preparedStmt.setString (2, wcolor); preparedStmt.setString (3, wflavor); return preparedStmt; } // Get the String table from DB table public static String getStringTable(String userResponse, Connection conn) throws SQLException { if (userResponse == "White") { return makeSQLStatementSelect("WhiteWines", conn); } else if (userResponse == "Red") { return makeSQLStatementSelect("RedWines", conn); } else if (userResponse == "Rose") { return makeSQLStatementSelect("RoseWines", conn); } else { return null; } } // Get a String table using SELECT public static String makeSQLStatementSelect(String table, Connection conn) throws SQLException { String sql = "select w_name from " + table; PreparedStatement preparedStatement = conn.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); // Process the result set and store values in a StringBuilder StringBuilder resultString = new StringBuilder(); while (resultSet.next()) { String columnValue = resultSet.getString("w_name"); resultString.append(columnValue).append(", "); } // Remove the trailing comma and space if (resultString.length() > 0) { resultString.setLength(resultString.length() - 2); } return resultString.toString(); } // Check if value exists in DB public static boolean valueExists(Connection conn, String tableName, String value) throws SQLException { String sql = "SELECT COUNT(*) FROM " + tableName + " WHERE w_name = ?"; PreparedStatement preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1, value); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { int count = resultSet.getInt(1); return count > 0; } return false; } // Check if wine exists and then put in DB public static void putWineInTable(String tablename, String[] owine, Connection conn, PreparedStatement a) throws SQLException { boolean yn = valueExists(conn, tablename, owine[0]); if (yn == false){ a = makeSQLStatementInsert(tablename, owine[0], owine[1], owine[2], conn); a.executeUpdate(); } else if (yn == true){ System.out.println("Wine " + owine[1] + " allready exists"); } } public static void login(String username, String password, Connection conn, Scanner sc, User user) throws SQLException { boolean passExist = true; boolean userExist = true; do { System.out.println("Enter username:"); username = sc.nextLine(); userExist = valueExists(conn, "users", username, "username"); System.out.println("Enter password:"); password = sc.nextLine(); passExist = valueExists(conn, "users", password, "user_password"); if (!passExist || !userExist) { System.out.println("Invalid Username or Password, try again."); } if (password.contains("exit") ) { break; } } while(!passExist || !userExist); user.setUsername(username); user.setPassword(password); } public static void signUp(String username, String password, Connection conn, Scanner sc, User user) throws SQLException{ username = null; do { System.out.println("Create username:"); username = sc.nextLine(); if (valueExists(conn, "users", username, "username")) { System.out.println("Username already exists please try again"); } if (username.contains("exit")) { break; } } while (valueExists(conn, "users", username, "username")); System.out.println("Create password:"); password = sc.nextLine(); user.setUsername(username); user.setPassword(password); user.addUser(conn); } }
kateriTs/GrapeVin
GrapeVin/GrapeVin/Main.java
46,501
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JDialog.java to edit this template */ package wifipasswords; import javax.swing.Icon; import resources.utils.ResourceBundleManager; import javax.swing.filechooser.FileNameExtensionFilter; /** * * @author dionysis */ public class SaveImage extends javax.swing.JDialog { private Icon icon; private String name; private String pass; /** * Creates new form SaveImage */ public SaveImage(Icon icon,String name,String pass) { this.icon=icon; this.name=name; this.pass=pass; initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { credPanel = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jPanel9 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jPanel10 = new javax.swing.JPanel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); credPanel.setBackground(new java.awt.Color(255, 255, 255)); credPanel.setMaximumSize(new java.awt.Dimension(391, 458)); credPanel.setMinimumSize(new java.awt.Dimension(391, 458)); jLabel6.setBackground(new java.awt.Color(255, 255, 255)); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N jLabel6.setForeground(new java.awt.Color(0, 0, 0)); jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel6.setText("Wi-Fi"); jPanel9.setBackground(new java.awt.Color(255, 255, 255)); jLabel7.setBackground(new java.awt.Color(255, 255, 255)); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel7.setForeground(new java.awt.Color(0, 0, 0)); jLabel7.setText("όνομα:"); jLabel8.setBackground(new java.awt.Color(255, 255, 255)); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel8.setForeground(new java.awt.Color(0, 0, 0)); jLabel8.setText("Κωδικός:"); jLabel11.setBackground(new java.awt.Color(255, 255, 255)); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel11.setForeground(new java.awt.Color(0, 0, 0)); jLabel11.setText(name); jLabel12.setBackground(new java.awt.Color(255, 255, 255)); jLabel12.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel12.setForeground(new java.awt.Color(0, 0, 0)); jLabel12.setText(pass); javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel11, javax.swing.GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE)) .addContainerGap()) .addComponent(jSeparator1) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(9, 9, 9) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(21, Short.MAX_VALUE)) ); jPanel10.setBackground(new java.awt.Color(255, 255, 255)); jLabel9.setBackground(new java.awt.Color(255, 255, 255)); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel9.setForeground(new java.awt.Color(0, 0, 0)); jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel9.setText("QR Code"); jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel10.setIcon(icon); javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10); jPanel10.setLayout(jPanel10Layout); jPanel10Layout.setHorizontalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel10Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel10Layout.setVerticalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel10Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel9) .addGap(0, 0, 0) .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout credPanelLayout = new javax.swing.GroupLayout(credPanel); credPanel.setLayout(credPanelLayout); credPanelLayout.setHorizontalGroup( credPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(credPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(credPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); credPanelLayout.setVerticalGroup( credPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(credPanelLayout.createSequentialGroup() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, Short.MAX_VALUE) .addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setAlwaysOnTop(true); setBackground(new java.awt.Color(51, 51, 51)); setIconImage(null); setIconImages(null); setMinimumSize(new java.awt.Dimension(468, 680)); setModalityType(java.awt.Dialog.ModalityType.TOOLKIT_MODAL); setResizable(false); setType(java.awt.Window.Type.UTILITY); jPanel2.setBackground(new java.awt.Color(80, 80, 80)); jPanel2.setForeground(new java.awt.Color(51, 51, 51)); jPanel2.setMinimumSize(new java.awt.Dimension(434, 690)); jPanel2.setPreferredSize(new java.awt.Dimension(434, 690)); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setForeground(new java.awt.Color(0, 0, 0)); jPanel1.setMaximumSize(new java.awt.Dimension(391, 507)); jPanel1.setMinimumSize(new java.awt.Dimension(391, 507)); jPanel1.setPreferredSize(new java.awt.Dimension(391, 507)); jLabel1.setBackground(new java.awt.Color(255, 255, 255)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pictures/wifi_icon (Custom).png"))); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setVerticalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setOpaque(true); jLabel2.setBackground(jPanel1.getBackground()); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel2.setForeground(jPanel1.getForeground()); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText(ResourceBundleManager.getString("messageImageTitle")); jLabel3.setBackground(jPanel1.getBackground()); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel3.setForeground(jPanel1.getForeground()); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText(ResourceBundleManager.getString("messageNetworkTitle")); jLabel5.setBackground(jPanel1.getBackground()); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel5.setForeground(jPanel1.getForeground()); jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel5.setText(name); jLabel4.setBackground(jPanel1.getBackground()); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel4.setForeground(jPanel1.getForeground()); jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel4.setText(ResourceBundleManager.getString("messagePasswordTitle")); jLabel13.setBackground(jPanel1.getBackground()); jLabel13.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel13.setForeground(jPanel1.getForeground()); jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel13.setText(pass); jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel14.setIcon(icon); jLabel15.setBackground(jPanel1.getBackground()); jLabel15.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel15.setForeground(jPanel1.getForeground()); jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel15.setText(ResourceBundleManager.getString("messageScanQr")); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(139, 139, 139) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel13) .addGap(18, 18, 18) .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel15) .addGap(20, 20, 20)) ); jLabel17.setBackground(jPanel1.getBackground()); jLabel17.setFont(new java.awt.Font("Segoe Print", 0, 12)); // NOI18N jLabel17.setForeground(new java.awt.Color(255, 204, 102)); jLabel17.setText(ResourceBundleManager.getString("previewImage")+" :"); jLabel19.setBackground(jPanel1.getBackground()); jLabel19.setFont(new java.awt.Font("Segoe Print", 0, 18)); // NOI18N jLabel19.setForeground(new java.awt.Color(255, 204, 102)); jLabel19.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel19.setText(ResourceBundleManager.getString("saveCredImageTitle")); jPanel3.setBackground(new java.awt.Color(80, 80, 80)); jButton1.setFont(new java.awt.Font("Segoe Print", 0, 12)); // NOI18N jButton1.setText(ResourceBundleManager.getString("imageButtonSave")); jButton1.setFocusable(false); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(133, 133, 133) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(0, 0, 0) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(29, 29, 29) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel19, javax.swing.GroupLayout.PREFERRED_SIZE, 434, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel19, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(2, 2, 2) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(0, 0, 0)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 642, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed PanelToImageSaver.savePanelAsImage(jPanel1,this); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel credPanel; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel9; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; // End of variables declaration//GEN-END:variables }
DionysisTheodosis/JavaAps
WifiToolBox/src/wifipasswords/SaveImage.java
46,538
package gr.aueb.cf.ch3; import java.util.Scanner; /** * οσο ο χρηστης δινει θετικους ακεραιους * τους μετραμε μεχρι ο χρηστης να δωσει αρνιτικο */ public class PositiveCoutApp { public static void main(String[] args) { int inputNum = 0; int count = 0; Scanner scanner = new Scanner(System.in); System.out.println("Please insert a num (negative for Quit"); inputNum = scanner.nextInt(); while (inputNum >= 0){ count++; System.out.println("Please insert a num (negative for Quit"); inputNum = scanner.nextInt(); } System.out.println("Count" + count); } }
GregoryPerifanos/Coding-Factory-5-Class-Projects
src/gr/aueb/cf/ch3/PositiveCoutApp.java
46,550
package gr.athenainnovation.imis.fusion.gis.virtuoso; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.hp.hpl.jena.graph.BulkUpdateHandler; import com.hp.hpl.jena.query.ParameterizedSparqlString; import com.hp.hpl.jena.shared.JenaException; import com.hp.hpl.jena.update.UpdateExecutionFactory; import com.hp.hpl.jena.update.UpdateFactory; import com.hp.hpl.jena.update.UpdateProcessor; import com.hp.hpl.jena.update.UpdateRequest; import gr.athenainnovation.imis.fusion.gis.core.Link; import gr.athenainnovation.imis.fusion.gis.gui.workers.DBConfig; import static gr.athenainnovation.imis.fusion.gis.gui.workers.FusionState.ANSI_RESET; import static gr.athenainnovation.imis.fusion.gis.gui.workers.FusionState.ANSI_YELLOW; import gr.athenainnovation.imis.fusion.gis.gui.workers.GraphConfig; import gr.athenainnovation.imis.fusion.gis.utils.Constants; import gr.athenainnovation.imis.fusion.gis.utils.Log; import gr.athenainnovation.imis.fusion.gis.utils.Patterns; import gr.athenainnovation.imis.fusion.gis.utils.Utilities; import static gr.athenainnovation.imis.fusion.gis.utils.Utilities.isURLToLocalInstance; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Scanner; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.didion.jwnl.JWNL; import net.didion.jwnl.JWNLException; import net.didion.jwnl.data.IndexWord; import net.didion.jwnl.data.IndexWordSet; import net.didion.jwnl.data.PointerType; import net.didion.jwnl.data.Synset; import net.didion.jwnl.data.Word; import net.didion.jwnl.data.relationship.AsymmetricRelationship; import net.didion.jwnl.data.relationship.Relationship; import net.didion.jwnl.data.relationship.RelationshipFinder; import net.didion.jwnl.data.relationship.RelationshipList; import net.didion.jwnl.dictionary.Dictionary; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.apache.jena.atlas.web.auth.HttpAuthenticator; import org.apache.jena.atlas.web.auth.SimpleAuthenticator; import org.apache.log4j.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.en.EnglishAnalyzer; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.util.Version; import virtuoso.jdbc4.VirtuosoConnection; import virtuoso.jdbc4.VirtuosoException; import virtuoso.jdbc4.VirtuosoPreparedStatement; import virtuoso.jena.driver.VirtGraph; import virtuoso.jena.driver.VirtuosoUpdateFactory; import virtuoso.jena.driver.VirtuosoUpdateRequest; /** * Forms appropriate triples from the PostGIS database and inserts them in the * virtuoso specified graph. * */ public final class VirtuosoImporter { private static final Logger LOG = Log.getClassFAGILogger(VirtuosoImporter.class); private final TripleHandler trh; private String transformationID; private final Connection virt_conn; private final VirtGraph set; private final DBConfig db_c; private final GraphConfig gr_c; private int wordnetDepth; private int maxParentDepth; private double raiseToPower; private double wordWeight; private double textWeight; private double typeWeight; private double simThreshold; // Ωιρτθοσο Ιμπορτερ Στατε private boolean initialized = false; // Used during property matching private HashMap< String, MetadataChain> propertiesA; private HashMap< String, MetadataChain> propertiesB; private HashMap<String, HashSet<ScoredMatch>> foundA = new HashMap<>(); private HashMap<String, HashSet<ScoredMatch>> foundB = new HashMap<>(); private HashSet<String> recoveredWords = null; private HashSet<String> uniquePropertiesA = new HashSet<>(); private HashSet<String> uniquePropertiesB = new HashSet<>(); private HashSet<String> nonMatchedPropertiesA = new HashSet<>(); private HashSet<String> nonMatchedPropertiesB = new HashSet<>(); public VirtuosoImporter(final DBConfig dbConfig, String transformationID, final String fusedGraph, final boolean checkboxIsSelected, final GraphConfig graphConfig) { db_c = dbConfig; gr_c = graphConfig; this.transformationID = transformationID; propertiesA = Maps.newHashMap(); propertiesB = Maps.newHashMap(); set = getVirtuosoSet(fusedGraph, dbConfig.getDBURL(), dbConfig.getUsername(), dbConfig.getPassword()); virt_conn = set.getConnection(); try { Scanner scn = null; if (SystemUtils.IS_OS_MAC_OSX) { scn = new Scanner(new File("/home/nick/Projects/fagi-gis.ini")); } if (SystemUtils.IS_OS_LINUX) { scn = new Scanner(new File("/home/nick/Projects/fagi-gis.ini")); } if (SystemUtils.IS_OS_WINDOWS) { scn = new Scanner(new File("/home/nick/Projects/fagi-gis.ini")); } while (scn.hasNext()) { String prop = scn.next(); String[] vals = prop.split(":"); vals[1].trim(); vals[0].trim(); //System.out.println(vals[0] + " " + vals[1]); if (vals[0].equals("wordnet-depth")) { wordnetDepth = Integer.parseInt(vals[1]); } else if (vals[0].equals("max-parent")) { maxParentDepth = Integer.parseInt(vals[1]); } else if (vals[0].equals("raise-to-power")) { raiseToPower = Integer.parseInt(vals[1]); } else if (vals[0].equals("text-match-weight")) { textWeight = Double.parseDouble(vals[1]); } else if (vals[0].equals("word-match-weight")) { wordWeight = Double.parseDouble(vals[1]); } else if (vals[0].equals("type-match-weight")) { typeWeight = Double.parseDouble(vals[1]); } else if (vals[0].equals("sim-threshold")) { simThreshold = Double.parseDouble(vals[1]); } } } catch (IOException ioe) { //System.out.println("File not found"); wordnetDepth = 5; maxParentDepth = 4; raiseToPower = 1.0; wordWeight = 1.0f; textWeight = 1.0f; typeWeight = 1.0f; simThreshold = 1.0f; } trh = new BulkLoader(graphConfig, fusedGraph, dbConfig.getDBName(), set, graphConfig.getEndpointT()); //trh = new BulkLoader(graphConfig, gr_c.getTargetTempGraph(), dbConfig.getDBName(), set, graphConfig.getEndpointT()); trh.init(); } public String getTransformationID() { return transformationID; } public void setTransformationID(String transformationID) { this.transformationID = transformationID; } public void tempFunc() throws SQLException { final String askWik = "sparql with <http://localhost:8890/wik> select distinct(?p) where { ?s ?p ?o } "; final String askUni = "sparql with <http://localhost:8890/uni> select distinct(?p) where { ?s ?p ?o } "; final String askOsm = "sparql with <http://localhost:8890/osm> select distinct(?p) where { ?s ?p ?o } "; PrintWriter wOsm = null; PrintWriter wUni = null; PrintWriter wWik = null; HashMap<String, List<String>> hs = new HashMap<>(); try { //create a temporary file File oOsm = new File("osm_predicates.txt"); File oWik = new File("wik_predicates.txt"); File oUni = new File("uni_predicates.txt"); // This will output the full path where the file will be written to... //System.out.println(oOsm.getCanonicalPath()); wOsm = new PrintWriter(new FileWriter(oOsm)); wUni = new PrintWriter(new FileWriter(oUni)); wWik = new PrintWriter(new FileWriter(oWik)); PreparedStatement tempStmt; ResultSet rs; tempStmt = virt_conn.prepareStatement(askWik); rs = tempStmt.executeQuery(); PrintWriter wRef = wWik; while (rs.next()) { String s = rs.getString(1); //System.out.println(s); s = URLDecoder.decode(s, "UTF-8"); //System.out.println(s); String main = StringUtils.substringAfter(s, "#"); if (main.equals("")) { main = StringUtils.substring(s, StringUtils.lastIndexOf(s, "/") + 1); } wRef.print(s + " -> " + main); Matcher mat = Patterns.PATTERN_WORD_BREAKER.matcher(main); List<String> toks = new ArrayList<String>(); while (mat.find()) { toks.add(mat.group()); } if (toks.isEmpty()) { wRef.println(); continue; } wRef.print(" : [ "); for (int i = 0; i < toks.size() - 1; i++) { if (!hs.containsKey(toks.get(i))) { List<String> lst = new ArrayList<>(); lst.add(toks.get(i)); hs.put(toks.get(i), lst); } else { boolean found = false; for (String ret : hs.get(toks.get(i))) { if (ret.equals(toks.get(i))) { found = true; break; } } if (!found) { hs.get(toks.get(i)).add(toks.get(i)); } } wRef.print(toks.get(i) + ", "); } wRef.println(toks.get(toks.size() - 1) + " ]"); if (toks.get(toks.size() - 1).equals("SIREN")) //System.out.println(toks.get(toks.size()-1)); { if (!hs.containsKey(toks.get(toks.size() - 1))) { List<String> lst = new ArrayList<>(); lst.add(toks.get(toks.size() - 1)); hs.put(toks.get(toks.size() - 1), lst); } else { boolean found = false; for (String ret : hs.get(toks.get(toks.size() - 1))) { if (ret.equals(toks.get(toks.size() - 1))) { found = true; break; } } if (!found) { hs.get(toks.get(toks.size() - 1)).add(toks.get(toks.size() - 1)); } } } } tempStmt.close(); rs.close(); tempStmt = virt_conn.prepareStatement(askOsm); rs = tempStmt.executeQuery(); wRef = wOsm; while (rs.next()) { String s = rs.getString(1); //System.out.println(s); s = URLDecoder.decode(s, "UTF-8"); //System.out.println(s); String main = StringUtils.substringAfter(s, "#"); if (main.equals("")) { main = StringUtils.substring(s, StringUtils.lastIndexOf(s, "/") + 1); } wRef.print(s + " -> " + main); Matcher mat = Patterns.PATTERN_WORD_BREAKER.matcher(main); List<String> toks = new ArrayList<String>(); while (mat.find()) { toks.add(mat.group()); } if (toks.isEmpty()) { wRef.println(); continue; } wRef.print(" : [ "); for (int i = 0; i < toks.size() - 1; i++) { if (!hs.containsKey(toks.get(i))) { List<String> lst = new ArrayList<>(); lst.add(toks.get(i)); hs.put(toks.get(i), lst); } else { boolean found = false; for (String ret : hs.get(toks.get(i))) { if (ret.equals(toks.get(i))) { found = true; break; } } if (!found) { hs.get(toks.get(i)).add(toks.get(i)); } } wRef.print(toks.get(i) + ", "); } wRef.println(toks.get(toks.size() - 1) + " ]"); if (!hs.containsKey(toks.get(toks.size() - 1))) { List<String> lst = new ArrayList<>(); lst.add(toks.get(toks.size() - 1)); hs.put(toks.get(toks.size() - 1), lst); } else { boolean found = false; for (String ret : hs.get(toks.get(toks.size() - 1))) { if (ret.equals(toks.get(toks.size() - 1))) { found = true; break; } } if (!found) { hs.get(toks.get(toks.size() - 1)).add(toks.get(toks.size() - 1)); } } } tempStmt.close(); rs.close(); tempStmt = virt_conn.prepareStatement(askUni); rs = tempStmt.executeQuery(); wRef = wUni; while (rs.next()) { String s = rs.getString(1); //System.out.println(s); s = URLDecoder.decode(s, "UTF-8"); //System.out.println(s); String main = StringUtils.substringAfter(s, "#"); if (main.equals("")) { main = StringUtils.substring(s, StringUtils.lastIndexOf(s, "/") + 1); } wRef.print(s + " -> " + main); Matcher mat = Patterns.PATTERN_WORD_BREAKER.matcher(main); List<String> toks = new ArrayList<String>(); while (mat.find()) { toks.add(mat.group()); } if (toks.isEmpty()) { wRef.println(); continue; } wRef.print(" : [ "); for (int i = 0; i < toks.size() - 1; i++) { if (!hs.containsKey(toks.get(i))) { List<String> lst = new ArrayList<>(); lst.add(toks.get(i)); hs.put(toks.get(i), lst); } else { boolean found = false; for (String ret : hs.get(toks.get(i))) { if (ret.equals(toks.get(i))) { found = true; break; } } if (!found) { hs.get(toks.get(i)).add(toks.get(i)); } } wRef.print(toks.get(i) + ", "); } wRef.println(toks.get(toks.size() - 1) + " ]"); if (!hs.containsKey(toks.get(toks.size() - 1))) { List<String> lst = new ArrayList<>(); lst.add(toks.get(toks.size() - 1)); hs.put(toks.get(toks.size() - 1), lst); } else { boolean found = false; for (String ret : hs.get(toks.get(toks.size() - 1))) { if (ret.equals(toks.get(toks.size() - 1))) { found = true; break; } } if (!found) { hs.get(toks.get(toks.size() - 1)).add(toks.get(toks.size() - 1)); } } } tempStmt.close(); rs.close(); File oAll = new File("all_words.txt"); PrintWriter wAll = new PrintWriter(new FileWriter(oAll)); for (Map.Entry pairs : hs.entrySet()) { List<String> lst = (List<String>) pairs.getValue(); } wAll.close(); wOsm.close(); wWik.close(); wUni.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { // Close the writer regardless of what happens... wOsm.close(); wUni.close(); wWik.close(); } catch (Exception e) { } } } //inserts the data in virtuoso public void importGeometriesToVirtuoso(final String fusedGraph) { //imports the geometries in the fused graph Statement stmt = null; Connection connection = null; //System.out.println("Upload of geometries about to commence"); try { connection = DriverManager.getConnection(Constants.DB_URL + db_c.getDBName(), db_c.getDBUsername(), db_c.getDBPassword()); //String deleteQuery; String subject; String fusedGeometry; stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); //select from source dataset in postgis. The transformations will take place from A to B dataset. String selectFromPostGIS = "SELECT DISTINCT subject_a, subject_b, ST_AsText(geom) FROM fused_geometries"; try (ResultSet rs = stmt.executeQuery(selectFromPostGIS)) { clearBulkLoadHistory(); System.out.println("Query executed"); //List<Triple> lst = new ArrayList<>(); int p = 0; //System.out.println("Happens"); while (rs.next()) { if ( gr_c.isDominantA()) subject = rs.getString("subject_a"); else subject = rs.getString("subject_b"); fusedGeometry = rs.getString("ST_AsText"); //System.out.println("Inserting "+subject + " " + fusedGeometry); if (!(transformationID.equals("Keep both"))) { //if transformation is NOT "keep both" -> delete previous geometry trh.deleteAllWgs84(subject); trh.deleteAllGeom(subject); trh.addGeomTriple(subject, fusedGeometry); } else { if (rs.isFirst()) { trh.deleteAllGeom(subject); trh.addGeomTriple(subject, fusedGeometry); //System.out.println("Geom added for "+subject); } else { //insert second geometry //System.out.println("Geom added for "+subject); trh.addGeomTriple(subject, fusedGeometry); } } } } } catch (SQLException ex) { //out.close(); LOG.warn(ex.getMessage(), ex); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(VirtuosoImporter.class.getName()).log(Level.SEVERE, null, ex); } } if (connection != null) { try { connection.close(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(VirtuosoImporter.class.getName()).log(Level.SEVERE, null, ex); } } } } //inserts the data in virtuoso public void importGeometriesToVirtuoso() { //imports the geometries in the graph A importGeometriesToVirtuoso(null); } public static boolean isLocalEndpoint(String url) throws UnknownHostException { // Check if the address is a valid special local or loop back int start = url.lastIndexOf("//"); int last = url.substring(start).indexOf(":"); //System.out.println(start+" "+last); String address = url.substring(start + 2, last + start); //System.out.println("Address "+address); InetAddress addr = InetAddress.getByName(address); if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()) { return true; } // Check if the address is defined on any interface try { return NetworkInterface.getByInetAddress(addr) != null; } catch (SocketException e) { return false; } } public boolean insertLinksMetadataChains(List<Link> links, final String fusedGraph, boolean scanProperties, boolean swpped) { //metadata go in the new fusedGraph. the method is called from FuserWorker boolean success = true; long starttime, endtime; long startTime, endTime; // For compatibility with the CLI version if (!scanProperties) { createLinksGraph(links); } //createDelWGSGraph(((FileBulkLoader)trh).getDelWGSList()); //createDelGeomGraph(((FileBulkLoader)trh).getDelGeomList()); StringBuilder getFromB = new StringBuilder(); StringBuilder getFromA = new StringBuilder(); final String dropMetaAGraph = "SPARQL CLEAR GRAPH <" + gr_c.getMetadataGraphA() + ">"; final String dropMetaBGraph = "SPARQL CLEAR GRAPH <" + gr_c.getMetadataGraphB() + ">"; final String createMetaAGraph = "SPARQL CREATE GRAPH <" + gr_c.getMetadataGraphA() + ">"; final String createMetaBGraph = "SPARQL CREATE GRAPH <" + gr_c.getMetadataGraphB() + ">"; PreparedStatement tempStmt; try { tempStmt = virt_conn.prepareStatement(dropMetaAGraph); tempStmt.execute(); tempStmt.close(); tempStmt = virt_conn.prepareStatement(dropMetaBGraph); tempStmt.execute(); tempStmt.close(); tempStmt = virt_conn.prepareStatement(createMetaAGraph); //tempStmt.execute(); tempStmt.close(); tempStmt = virt_conn.prepareStatement(createMetaBGraph); //tempStmt.execute(); tempStmt.close(); } catch (SQLException ex) { LOG.trace("SQLException thrown during temp graph creation"); LOG.debug("SQLException thrown during temp graph creation : " + ex.getMessage()); LOG.debug("SQLException thrown during temp graph creation : " + ex.getSQLState()); success = false; return success; } starttime = System.nanoTime(); //testThreads(links); endtime = System.nanoTime(); //LOG.info(ANSI_YELLOW + "Thread test lasted " + ((endtime - starttime) / 1000000000f) + "" + ANSI_RESET); boolean isEndpointALocal = false; boolean isEndpointBLocal = false; isEndpointALocal = isURLToLocalInstance(gr_c.getEndpointA()); //"localhost" for localhost isEndpointBLocal = isURLToLocalInstance(gr_c.getEndpointB()); //"localhost" for localhost //gr_c.setLocalA(isEndpointALocal); //gr_c.setLocalB(isEndpointBLocal); //System.out.println("is it " + isEndpointALocal); //System.out.println(isEndpointBLocal); starttime = System.nanoTime(); getFromA.append("sparql INSERT\n"); if (scanProperties) { getFromA.append(" { GRAPH <").append(gr_c.getMetadataGraphA()).append("> {\n"); } else { getFromA.append(" { GRAPH <").append(gr_c.getTargetGraph()).append("" + "> {\n"); } if (gr_c.isDominantA()) { getFromA.append(" ?s ?p ?o1 . \n"); } else { getFromA.append(" ?o ?p ?o1 . \n"); } getFromA.append(" ?o1 ?p4 ?o3 .\n"); getFromA.append(" ?o3 ?p5 ?o4 .\n"); getFromA.append(" ?o4 ?p6 ?o5\n"); getFromA.append("} }\nWHERE\n"); getFromA.append("{\n"); getFromA.append(" GRAPH <" + gr_c.getLinksGraph() + "> { ?s <http://www.w3.org/2002/07/owl#sameAs> ?o } .\n"); if (isEndpointALocal) { getFromA.append(" GRAPH <").append(gr_c.getGraphA()).append("> { {?s ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3 . OPTIONAL { ?o3 ?p5 ?o4 . OPTIONAL { ?o4 ?p6 ?o5 .} } } }\n"); } else { getFromA.append(" SERVICE <" + gr_c.getEndpointA() + "> { GRAPH <").append(gr_c.getGraphA()).append("> { {?s ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3 . OPTIONAL { ?o3 ?p5 ?o4 . OPTIONAL { ?o4 ?p6 ?o5 .} } } } }\n"); } getFromA.append("\n"); getFromA.append(" FILTER(!regex(?p,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n"); getFromA.append(" FILTER(!regex(?p, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n"); getFromA.append(" FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n"); getFromA.append(" FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n"); getFromA.append(" FILTER(!regex(?p4,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n"); getFromA.append(" FILTER(!regex(?p4, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n"); getFromA.append(" FILTER(!regex(?p4, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n"); getFromA.append(" FILTER(!regex(?p4, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n"); getFromA.append("}"); getFromB.append("sparql INSERT\n"); if (scanProperties) { getFromB.append(" { GRAPH <").append(gr_c.getMetadataGraphB()).append("> {\n"); } else { getFromB.append(" { GRAPH <").append(gr_c.getTargetGraph()).append("" + "> {\n"); } if (gr_c.isDominantA()) { getFromB.append(" ?s ?p ?o1 . \n"); } else { getFromB.append(" ?o ?p ?o1 . \n"); } getFromB.append(" ?o1 ?p4 ?o3 .\n"); getFromB.append(" ?o3 ?p5 ?o4 .\n"); getFromB.append(" ?o4 ?p6 ?o5\n"); getFromB.append("} }\nWHERE\n"); getFromB.append("{\n"); getFromB.append(" GRAPH <" + gr_c.getLinksGraph() + "> { ?s <http://www.w3.org/2002/07/owl#sameAs> ?o } .\n"); if (isEndpointBLocal) { getFromB.append(" GRAPH <").append(gr_c.getGraphB()).append("> { {?o ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3 . OPTIONAL { ?o3 ?p5 ?o4 . OPTIONAL { ?o4 ?p6 ?o5 .} } } }\n"); } else { getFromB.append(" SERVICE <" + gr_c.getEndpointB() + "> { GRAPH <").append(gr_c.getGraphB()).append("> { {?o ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3 . OPTIONAL { ?o3 ?p5 ?o4 . OPTIONAL { ?o4 ?p6 ?o5 .} } } } }\n"); } getFromB.append("\n"); getFromB.append(" FILTER(!regex(?p,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n"); getFromB.append(" FILTER(!regex(?p, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n"); getFromB.append(" FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n"); getFromB.append(" FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n"); getFromB.append(" FILTER(!regex(?p4,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n"); getFromB.append(" FILTER(!regex(?p4, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n"); getFromB.append(" FILTER(!regex(?p4, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n"); getFromB.append(" FILTER(!regex(?p4, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n"); getFromB.append("}"); System.out.println("GET FROM B \n" + getFromB); System.out.println("GET FROM A \n" + getFromA); int count = 0; int i = 0; while (i < links.size()) { success = createLinksGraphBatch(links, i); if (!success) { break; } /* int tries = 0; startTime = System.nanoTime(); while (tries < Constants.MAX_SPARQL_TRIES) { LOG.debug("SQLException thrown during temp graph populating Try : " + (tries + 1)); endTime = System.nanoTime(); LOG.info("Uploading A lasted "+Utilities.nanoToSeconds(endTime-startTime));*/ int tries = 0; startTime = System.nanoTime(); while (tries < Constants.MAX_SPARQL_TRIES) { try (PreparedStatement getFromBStmt = virt_conn.prepareStatement(getFromA.toString())) { starttime = System.nanoTime(); getFromBStmt.executeUpdate(); } catch (SQLException ex) { LOG.trace("SQLException thrown during temp graph B populating"); LOG.debug("SQLException thrown during temp graph B populating Try : " + (tries + 1)); LOG.debug("SQLException thrown during temp graph B populating : " + ex.getMessage()); LOG.debug("SQLException thrown during temp graph B populating : " + ex.getSQLState()); tries++; } } if ( tries == Constants.MAX_SPARQL_TRIES) { success = false; return success; } endTime = System.nanoTime(); LOG.info("Uploading A lasted " + Utilities.nanoToSeconds(endTime - startTime)); tries = 0; startTime = System.nanoTime(); while (tries < Constants.MAX_SPARQL_TRIES) { try (PreparedStatement getFromAStmt = virt_conn.prepareStatement(getFromA.toString())) { starttime = System.nanoTime(); getFromAStmt.executeUpdate(); } catch (SQLException ex) { LOG.trace("SQLException thrown during temp graph A populating"); LOG.debug("SQLException thrown during temp graph A populating Try : " + (tries + 1)); LOG.debug("SQLException thrown during temp graph A populating : " + ex.getMessage()); LOG.debug("SQLException thrown during temp graph A populating : " + ex.getSQLState()); tries++; } } if ( tries == Constants.MAX_SPARQL_TRIES) { success = false; return success; } endTime = System.nanoTime(); LOG.info("Uploading B lasted " + Utilities.nanoToSeconds(endTime - startTime)); //endtime = System.nanoTime(); //LOG.info("Metadata main parsed in " + (endtime - starttime) / 1000000000f); i += Constants.BATCH_SIZE; count++; } //System.out.println("THE BOOL IS " + success); return success; //endtime = System.nanoTime(); //LOG.info("Metadata parsed in "+(endtime-starttime)/1000000000f); //endtime = System.nanoTime(); //LOG.info(ANSI_YELLOW+"Metadata parsed in "+((endtime-starttime)/1000000000f) +""+ANSI_RESET); } public int compareTypes(String l, String r) { if (Patterns.PATTERN_INT.matcher(l).find() && Patterns.PATTERN_INT.matcher(r).find()) { return 1; } if (Patterns.PATTERN_DATE.matcher(l).find() && Patterns.PATTERN_DATE.matcher(r).find()) { return 1; } if (Patterns.PATTERN_TEXT.matcher(l).find() && Patterns.PATTERN_TEXT.matcher(r).find()) { return 1; } if (Patterns.PATTERN_DECIMAL.matcher(l).find() && Patterns.PATTERN_DECIMAL.matcher(r).find()) { return 1; } if (Patterns.PATTERN_WORD.matcher(l).find() && Patterns.PATTERN_WORD.matcher(r).find()) { return 1; } return 0; } private class SchemaNormalizer { Schema sRef; float textDist; float semDist; float typeDist; public SchemaNormalizer(Schema sRef, float textDist, float semDist, float typeDist) { this.sRef = sRef; this.textDist = textDist; this.semDist = semDist; this.typeDist = typeDist; } } HashMap<String, Schema> schemasA = Maps.newHashMap(); HashMap<String, Schema> schemasB = Maps.newHashMap(); private void scanMatches() { // expand properties chains expandChain(schemasA, propertiesA, ""); expandChain(schemasB, propertiesB, ""); /* for (Map.Entry pairs : schemasA.entrySet()) { String chain = (String) pairs.getKey(); Schema sche = (Schema) pairs.getValue(); System.out.println("A " + chain + " " + sche.predicate + " Size " + sche.indexes.size()); } for (Map.Entry pairs : schemasB.entrySet()) { String chain = (String) pairs.getKey(); Schema sche = (Schema) pairs.getValue(); System.out.println("B " + chain + " " + sche.predicate + " Size " + sche.indexes.size()); } */ List<SchemaMatcher> matchers = new ArrayList<>(); int countA; int countB; float score; float sim; Map<String, List<SchemaNormalizer>> scorer = Maps.newHashMap(); for (Map.Entry pairsA : schemasA.entrySet()) { //String chainA = (String)pairsA.getKey(); Schema scheA = (Schema) pairsA.getValue(); nonMatchedPropertiesA.add(scheA.predicate); if (scheA.indexes.isEmpty()) { //System.out.println("Empty Index A"); continue; } float maxDist = -1.0f; float maxScore = -1.0f; for (Map.Entry pairsB : schemasB.entrySet()) { //String chainB = (String)pairsB.getKey(); Schema scheB = (Schema) pairsB.getValue(); //System.out.println("Would Match "+scheA.predicate + scheB.predicate); nonMatchedPropertiesB.add(scheB.predicate); score = 0; sim = 0; if (scheB.indexes.isEmpty()) { //System.out.println("Empty Index A"); continue; } SchemaMatcher m = new SchemaMatcher(scheA, scheB); countA = 0; //System.out.println("Matching "+scheA.predicate + scheB.predicate); //System.out.println("Main "+main); for (IndexWord iwA : scheA.indexes) { countA++; countB = 0; for (IndexWord iwB : scheB.indexes) { //System.out.println("Scoring : " + iwA.getLemma() + " and " + iwB.getLemma()); countB++; float tmpScore = calculateAsymmetricRelationshipOperation(iwA, iwB, m); score += tmpScore; //System.out.println("Score : "+tmpScore); } } //System.out.println(); float jaro_dist = 0; float jaro_dist_norm; int jaroCount = 0; for (String iwA : scheA.words) { countA++; countB = 0; for (String iwB : scheB.words) { jaroCount++; //System.out.println("Jaroing : "+iwA+ " and "+ iwB); jaro_dist += (float) StringUtils.getJaroWinklerDistance(iwA, iwB); } } jaro_dist_norm = jaro_dist / (jaroCount); //System.out.println("Jaro : " + jaro_dist_norm); //scheB.texDist = jaro_dist_norm; if (jaro_dist_norm > maxDist) { maxDist = jaro_dist_norm; } score = score / (scheA.indexes.size() * scheB.indexes.size()); //scheB.semDist = score; if (score > maxScore) { maxScore = score; } //scheB.typeDist = 0.0f; float sim_score = (score + jaro_dist) / 2; //if (sim_score > 0.5) { int same_type = compareTypes(scheA.objectStr, scheB.objectStr); //System.out.print("Sim Score : "+sim_score+" "+same_type+" "); //System.out.print("Type Score : "+scheA.objectStr+" and "+scheB.objectStr+" "+sim_score+" "+same_type+" "); //System.out.print("Jaro distance of "+jaro_dist_norm+" "); //System.out.print("Mul : "+scheA.indexes.size()+" x "+scheB.indexes.size() + " = "+(scheA.indexes.size()*scheB.indexes.size())+" "); //System.out.println("Final : " + (score + jaro_dist_norm + same_type)/3); //scheB.typeDist = same_type; sim_score = (score + jaro_dist_norm + 0.5f * same_type) / 3; //} //System.out.println("Probs ::::::: "+score); SchemaNormalizer snorm = new SchemaNormalizer(scheB, jaro_dist_norm, score, same_type); if (!scorer.containsKey(scheA.predicate + scheB.predicate)) { List<SchemaNormalizer> scheLst = new ArrayList<SchemaNormalizer>(); scheLst.add(snorm); scorer.put(scheA.predicate + scheB.predicate, scheLst); } scorer.get(scheA.predicate + scheB.predicate).add(snorm); //m.score = sim_score; if (!m.matches.isEmpty()) { //System.out.println(m.matches.get(0)); matchers.add(m); } } scheA.texDist = maxDist; scheA.semDist = maxScore; } //System.out.println("Matches "+matchers.size()); //for (SchemaMatcher ma : matchers) { //System.out.println(ma); //} //System.out.println("Total Matches "+foundA.size()); HashMap<String, Schema> schemaPtrsA = Maps.newHashMap(); HashMap<String, Schema> schemaPtrsB = Maps.newHashMap(); //System.out.println("------------------------------------------"); //System.out.println(" NON MATCHED ENTITIES "); //System.out.println("------------------------------------------"); for (SchemaMatcher ma : matchers) { if (!ma.matches.isEmpty()) { //if (!foundA.containsKey(ma.sA.predicate)) { //System.out.println(ma.sA.predicate); //System.out.println(ma.sB.predicate); //System.out.println(nonMatchedPropertiesA); //System.out.println(nonMatchedPropertiesB); nonMatchedPropertiesA.remove(ma.sA.predicate); nonMatchedPropertiesB.remove(ma.sB.predicate); HashSet<ScoredMatch> matchesA = foundA.get(ma.sA.predicate); HashSet<ScoredMatch> matchesB = foundB.get(ma.sB.predicate); SchemaNormalizer selectedSche = null; List<SchemaNormalizer> snormLst = scorer.get(ma.sA.predicate + ma.sB.predicate); for (SchemaNormalizer snorm : snormLst) { if (ma.sB.predicate.equals(snorm.sRef.predicate)) { selectedSche = snorm; break; } } //System.out.println("Scoring "+selectedSche.semDist+" "+selectedSche.textDist+" "+selectedSche.typeDist); //System.out.println("Scoring "+ma.sA.semDist+" "+ma.sA.texDist); float sim_score = 0; if (!ma.sA.predicate.equals(selectedSche.sRef.predicate)) { if (ma.sA.semDist < 0.00000001f) { ma.sA.semDist = 1.0f; } if (ma.sA.texDist < 0.00000001f) { ma.sA.texDist = 1.0f; } sim_score = (float) (wordWeight * ((selectedSche.semDist / ma.sA.semDist)) + (textWeight * (selectedSche.textDist / ma.sA.texDist)) + (typeWeight * (selectedSche.typeDist))) / 3.0f; //System.out.println("Scoring "+ma.sA.predicate+" "+selectedSche.sRef.predicate+" = "+ sim_score); } else { sim_score = 1.0f; } ma.score = sim_score; schemaPtrsA.put(ma.sA.predicate, ma.sA); schemaPtrsA.put(ma.sB.predicate, ma.sB); if (matchesA == null) { matchesA = Sets.newHashSet(); foundA.put(ma.sA.predicate, matchesA); } if (matchesB == null) { matchesB = Sets.newHashSet(); foundB.put(ma.sB.predicate, matchesB); } ScoredMatch scoredA = new ScoredMatch(ma.sB.predicate, ma.score); ScoredMatch scoredB = new ScoredMatch(ma.sA.predicate, ma.score); if (!matchesA.contains(scoredA)) { matchesA.add(scoredA); } if (!matchesB.contains(scoredA)) { matchesB.add(scoredB); } //} //System.out.println("Matched "+ma.sA.predicate+" with "+ ma.sB.predicate + " = "+ma.score); } } } private boolean expandChain(HashMap<String, Schema> lst, HashMap< String, MetadataChain> chains, String chainStr) { boolean success = true; Dictionary dictionary = Dictionary.getInstance(); for (Map.Entry pairs : chains.entrySet()) { MetadataChain chain = (MetadataChain) pairs.getValue(); // Chains are comma separated String pad; if (chain.chains != null) { pad = ","; expandChain(lst, chain.chains, chainStr + chain.predicate + pad); } if (lst.containsKey(chainStr)) { continue; } String pred = chainStr.concat(chain.predicate); //String que = ""; List<String> arrl = new ArrayList<>(); //System.out.println("Chain Link : " + chain.link); //URL normalizer can possibly be truned on here String normalizedLink; try { normalizedLink = URLDecoder.decode(chain.link, "UTF-8"); } catch (UnsupportedEncodingException ex) { LOG.trace("UnsupportedEncodingException thrown during parsing of \"" + chain.link + "\""); LOG.debug("UnsupportedEncodingException thrown during parsing of \"" + chain.link + "\" " + ex.getMessage()); // A bad decoding should not break the whole FAGI continue; } Matcher mat = Patterns.PATTERN_WORD_BREAKER.matcher(normalizedLink); while (mat.find()) { arrl.add(mat.group()); } //System.out.print("Found:"); /*for (String s : arrl) { System.out.print(" " + s); } System.out.println();*/ Schema m = new Schema(); m.predicate = pred; m.objectStr = chain.objectStr; //System.out.println("breaking "+chain.link); Analyzer englishAnalyzer = new EnglishAnalyzer(Version.LUCENE_36); QueryParser englishParser = new QueryParser(Version.LUCENE_36, "", englishAnalyzer); for (String a : arrl) { m.addWord(a); if (recoveredWords.contains(a.toLowerCase())) { //System.out.println("Cancelling " + a); continue; } //System.out.print("Value "+a+" "); //System.out.println("Value : " + a + " stemmed : " + englishParser.parse(a).toString()); IndexWordSet wordSet; try { wordSet = dictionary.lookupAllIndexWords(englishParser.parse(a).toString()); } catch (ParseException ex) { LOG.trace("ParseException thrown during parsing of \"" + a + "\""); LOG.debug("ParseException thrown during parsing of \"" + a + "\" " + ex.getMessage()); // A bad word stem should not break the whole FAGI continue; } catch (JWNLException ex) { LOG.trace("JWNLException thrown during parsing of \"" + a + "\""); LOG.debug("JWNLException thrown during parsing of \"" + a + "\" " + ex.getMessage()); // A bad word look up should not break the whole FAGI continue; } //IndexWordSet wordSet = dictionary.lookupAllIndexWords(a); if (wordSet == null) { continue; } IndexWord[] indices = wordSet.getIndexWordArray(); IndexWord best = null; int bestInt = 0; for (IndexWord idx : indices) { //System.out.println("POS label " + idx.getPOS().getLabel()); if (idx.getPOS().getLabel().equals("noun")) { best = idx; bestInt = 3; } else if (idx.getPOS().getLabel().equals("adjective") && bestInt < 3) { best = idx; bestInt = 2; } else if (idx.getPOS().getLabel().equals("verb") && bestInt < 2) { best = idx; bestInt = 1; } } if (best == null) { //System.out.println("Null Best for " + englishParser.parse(a).toString()); continue; } m.addIndex(best); } //System.out.println("Inserting predicate: "+ pred); lst.put(pred, m); } //System.out.println(); return success; } private void scanChain(HashMap< String, MetadataChain> cont, List<String> chain, List<String> objectChain) { //System.out.print("Chain: "); if (chain.isEmpty()) { return; } String link = chain.get(0); if (link == null) { return; } MetadataChain root = null; if (cont.containsKey(link)) { root = cont.get(link); } else { String main = StringUtils.substringAfter(link, "#"); if (main.equals("")) { main = StringUtils.substring(link, StringUtils.lastIndexOf(link, "/") + 1); } //Analyzer englishAnalyzer = new EnglishAnalyzer(Version.LUCENE_36); //QueryParser englishParser = new QueryParser(Version.LUCENE_36, "", englishAnalyzer); //System.out.println("Parsed "+englishParser.parse(main)); //System.out.println("Main "+main); root = new MetadataChain(main, link, objectChain.get(0)); cont.put(root.predicate, root); //System.out.println(main+" "+root.predicate+" "+link); } for (int i = 1; i < chain.size(); i++) { //System.out.println("Oxi file"); link = chain.get(i); if (link == null) { //System.out.println("null"); return; } if (root.chains != null) { if (root.chains.containsKey(link)) { root = root.chains.get(link); continue; } } String main = StringUtils.substringAfter(link, "#"); if (main.equals("")) { main = StringUtils.substring(link, StringUtils.lastIndexOf(link, "/") + 1); } //System.out.println(main); MetadataChain newChain = new MetadataChain(main, link, objectChain.get(i)); root.addCahin(newChain); root = newChain; //System.out.print(link+" "); } //System.out.println(root); } public SchemaMatchState scanProperties(int optDepth, String linkA, String linkB, Boolean swapped) { boolean success = true; try { if (SystemUtils.IS_OS_MAC_OSX) { JWNL.initialize(new ByteArrayInputStream(getJWNL(Constants.PATH_TO_WORDNET_OS_X).getBytes(StandardCharsets.UTF_8))); } if (SystemUtils.IS_OS_LINUX) { JWNL.initialize(new ByteArrayInputStream(getJWNL(Constants.PATH_TO_WORDNET_LINUX).getBytes(StandardCharsets.UTF_8))); } if (SystemUtils.IS_OS_WINDOWS) { JWNL.initialize(new ByteArrayInputStream(getJWNL(Constants.PATH_TO_WORDNET_WINDOWS).getBytes(StandardCharsets.UTF_8))); } } catch (JWNLException ex) { LOG.trace("JWNLException thrown during set up of the Dictionary"); LOG.debug("JWNLException thrown during set up of the Dictionary : \n" + ex.getMessage()); } try ( // StopWords are stored in a serialized HashSet InputStream file = this.getClass().getResourceAsStream("/stopWords.ser"); InputStream buffer = new BufferedInputStream(file); ObjectInput input = new ObjectInputStream(buffer);) { recoveredWords = (HashSet) input.readObject(); } catch (ClassNotFoundException ex) { LOG.trace("ClassNotFoundException thrown during loading of the StopWords file"); LOG.debug("ClassNotFoundException thrown during loading of the StopWords file : \n" + ex.getMessage()); recoveredWords = new HashSet(); } catch (IOException ex) { LOG.trace("IOException thrown during loading of the StopWords file"); LOG.debug("IOException thrown during loading of the StopWords file : \n" + ex.getMessage()); recoveredWords = new HashSet(); } // Clear previous findings foundA.clear(); foundB.clear(); // If it' s a per link matching if ( linkA != null && linkB != null ) { // If we are using Late Fetch Optimisation we need to create // the temp graphs here if (Constants.LATE_FETCH) { StringBuilder getFromB = new StringBuilder(); StringBuilder getFromA = new StringBuilder(); boolean isEndpointALocal; boolean isEndpointBLocal; isEndpointALocal = isURLToLocalInstance(gr_c.getEndpointA()); //"localhost" for localhost isEndpointBLocal = isURLToLocalInstance(gr_c.getEndpointB()); //"localhost" for localhost getFromA.append("SPARQL INSERT\n"); getFromA.append(" { GRAPH <").append(gr_c.getMetadataGraphA()).append("> {\n"); if (gr_c.isDominantA()) { getFromA.append(" <"+linkA+"> ?p ?o1 . \n"); } else { getFromA.append(" <"+linkB+"> ?p ?o1 . \n"); } getFromA.append(" ?o1 ?p4 ?o3 .\n"); getFromA.append(" ?o3 ?p5 ?o4 .\n"); getFromA.append(" ?o4 ?p6 ?o5\n"); getFromA.append("} }\nWHERE\n"); getFromA.append("{\n"); if (isEndpointALocal) { getFromA.append(" GRAPH <").append(gr_c.getGraphA()).append("> { {<"+linkA+"> ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3 . OPTIONAL { ?o3 ?p5 ?o4 . OPTIONAL { ?o4 ?p6 ?o5 .} } } }\n"); } else { getFromA.append(" SERVICE <" + gr_c.getEndpointA() + "> { GRAPH <").append(gr_c.getGraphA()).append("> { {<"+linkA+"> ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3 . OPTIONAL { ?o3 ?p5 ?o4 . OPTIONAL { ?o4 ?p6 ?o5 .} } } } }\n"); } getFromA.append("\n"); getFromA.append(" FILTER(!regex(?p,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n"); getFromA.append(" FILTER(!regex(?p, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n"); getFromA.append(" FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n"); getFromA.append(" FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n"); getFromA.append(" FILTER(!regex(?p4,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n"); getFromA.append(" FILTER(!regex(?p4, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n"); getFromA.append(" FILTER(!regex(?p4, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n"); getFromA.append(" FILTER(!regex(?p4, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n"); getFromA.append("}"); getFromB.append("sparql INSERT\n"); getFromB.append(" { GRAPH <").append(gr_c.getMetadataGraphB()).append("> {\n"); if (gr_c.isDominantA()) { getFromB.append(" <"+linkA+"> ?p ?o1 . \n"); } else { getFromB.append(" <"+linkB+"> ?p ?o1 . \n"); } getFromB.append(" ?o1 ?p4 ?o3 .\n"); getFromB.append(" ?o3 ?p5 ?o4 .\n"); getFromB.append(" ?o4 ?p6 ?o5 \n"); getFromB.append("} }\nWHERE\n"); getFromB.append("{\n"); if (isEndpointBLocal) { getFromB.append(" GRAPH <").append(gr_c.getGraphB()).append("> { {<"+linkB+"> ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3 . OPTIONAL { ?o3 ?p5 ?o4 . OPTIONAL { ?o4 ?p6 ?o5 .} } } }\n"); } else { getFromB.append(" SERVICE <" + gr_c.getEndpointB() + "> { GRAPH <").append(gr_c.getGraphB()).append("> { {<"+linkB+"> ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3 . OPTIONAL { ?o3 ?p5 ?o4 . OPTIONAL { ?o4 ?p6 ?o5 .} } } } }\n"); } getFromB.append("\n"); getFromB.append(" FILTER(!regex(?p,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n"); getFromB.append(" FILTER(!regex(?p, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n"); getFromB.append(" FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n"); getFromB.append(" FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n"); getFromB.append(" FILTER(!regex(?p4,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n"); getFromB.append(" FILTER(!regex(?p4, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n"); getFromB.append(" FILTER(!regex(?p4, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n"); getFromB.append(" FILTER(!regex(?p4, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n"); getFromB.append("}"); System.out.println("GET FROM B \n" + getFromB); System.out.println("GET FROM A \n" + getFromA); // Populate with data from the Sample Liink set try (PreparedStatement populateDataA = virt_conn.prepareStatement(getFromA.toString()); PreparedStatement populateDataB = virt_conn.prepareStatement(getFromB.toString())) { //starttime = System.nanoTime(); populateDataA.executeUpdate(); populateDataB.executeUpdate(); } catch (SQLException ex) { LOG.trace("SQLException thrown during temp graph populating"); LOG.debug("SQLException thrown during temp graph populating : " + ex.getMessage()); LOG.debug("SQLException thrown during temp graph populating : " + ex.getSQLState()); success = false; } } String link; if (gr_c.isDominantA()) { link = linkA; } else { link = linkB; } for (int i = 0; i < optDepth + 1; i++) { //System.out.println("DEPTH: "+i); StringBuilder query = new StringBuilder(); query.append("SPARQL SELECT ?pa1 ?oa1 "); for (int j = 0; j < i; j++) { int ind = j + 2; int prev = ind - 1; query.append("?pa").append(ind).append(" ?oa").append(ind).append(" "); } query.append("?pb1 ?ob1 "); for (int j = 0; j < i; j++) { int ind = j + 2; query.append("?pb").append(ind).append(" ?ob").append(ind).append(" "); } query.append("\nWHERE\n{\n" + " { GRAPH <").append(gr_c.getMetadataGraphA()).append("> { <" + link + "> ?pa1 ?oa1 "); for (int j = 0; j < i; j++) { int ind = j + 2; int prev = ind - 1; query.append(" . ?oa").append(prev).append(" ?pa").append(ind).append(" ?oa").append(ind).append(" "); } query.append(" } "); query.append("}\n UNION { \n" + " GRAPH <").append(gr_c.getMetadataGraphB()).append("> { <" + link + "> ?pb1 ?ob1 "); for (int j = 0; j < i; j++) { int ind = j + 2; int prev = ind - 1; query.append(" . ?ob").append(prev).append(" ?pb").append(ind).append(" ?ob").append(ind).append(" "); } query.append("} }\n" + "}"); //System.out.println("DEPTH: " + i); //System.out.println("QUERY FOR PREDICATES : " + query.toString()); try (PreparedStatement fetchProperties = virt_conn.prepareStatement(query.toString()); ResultSet propertiesRS = fetchProperties.executeQuery()) { String prevSubject = link; while (propertiesRS.next()) { List<String> chainA = new ArrayList<>(); List<String> chainB = new ArrayList<>(); List<String> objectChainA = new ArrayList<>(); List<String> objectChainB = new ArrayList<>(); for (int j = 0; j <= i; j++) { int step_over = 2 * (i + 1); String predicateA = propertiesRS.getString(2 * (j + 1) - 1); String objectA = propertiesRS.getString(2 * (j + 1)); String predicateB = propertiesRS.getString(2 * (j + 1) + step_over - 1); String objectB = propertiesRS.getString(2 * (j + 1) + step_over); if (predicateA != null) { //predicateA = URLDecoder.decode(predicateA, "UTF-8"); } if (predicateB != null) { //predicateB = URLDecoder.decode(predicateB, "UTF-8"); } /* if (predicateA != null) { if (!uniquePropertiesA.contains(predicateA)) { //uniquePropertiesA.add(predicateA); } if (predicateA.contains("posSeq")) { continue; } if (predicateA.contains("asWKT")) { continue; } if (predicateA.contains("geometry")) { continue; } } if (predicateB != null) { if (!uniquePropertiesB.contains(predicateB)) { //uniquePropertiesB.add(predicateB); } if (predicateB.contains("posSeq")) { continue; } if (predicateB.contains("asWKT")) { continue; } if (predicateB.contains("geometry")) { continue; } } */ chainA.add(predicateA); objectChainA.add(objectA); chainB.add(predicateB); objectChainB.add(objectB); } scanChain(propertiesA, chainA, objectChainA); scanChain(propertiesB, chainB, objectChainB); } } catch (SQLException ex) { LOG.trace("SQLException thrown during set up of the Dictionary"); LOG.debug("SQLException thrown during set up of the Dictionary : \n" + ex.getMessage()); LOG.debug("SQLException thrown during set up of the Dictionary : \n" + ex.getSQLState()); } scanMatches(); propertiesA.clear(); propertiesB.clear(); //propertiesRS.close(); //fetchProperties.close(); } } else { // For bulk matching we need to create a Sample Links Graph // because matching on all links would be very slow final String dropSamplesGraph = "SPARQL DROP SILENT GRAPH <" + gr_c.getSampleLinksGraph() + ">"; final String createSamplesGraph = "SPARQL CREATE GRAPH <" + gr_c.getSampleLinksGraph() + ">"; final String createLinksSample = "SPARQL INSERT\n" + " { GRAPH <" + gr_c.getSampleLinksGraph() + "> {\n" + " ?s ?p ?o\n" + "} }\n" + "WHERE\n" + "{\n" + "{\n" + "SELECT ?s ?p ?o WHERE {\n" + " GRAPH <" + gr_c.getLinksGraph() + "> { ?s ?p ?o }\n" + "} limit " + Constants.SAMPLE_SIZE + "\n" + "}}"; try (PreparedStatement dropSamplesStmt = virt_conn.prepareStatement(dropSamplesGraph); PreparedStatement insertLinksSample = virt_conn.prepareStatement(createLinksSample); PreparedStatement createSamplesStmt = virt_conn.prepareStatement(createSamplesGraph) ) { dropSamplesStmt.execute(); createSamplesStmt.execute(); insertLinksSample.execute(); } catch (SQLException ex) { LOG.trace("SQLException thrown during sample creation"); LOG.debug("SQLException thrown during sample creation : \n" + ex.getMessage()); LOG.debug("SQLException thrown during sample creation : \n" + ex.getSQLState()); return null; } // If we are using Late Fetch Optimisation we need to create // the temp graphs here if (Constants.LATE_FETCH) { StringBuilder getFromB = new StringBuilder(); StringBuilder getFromA = new StringBuilder(); final String dropMetaAGraph = "SPARQL DROP SILENT GRAPH <" + gr_c.getMetadataGraphA() + ">"; final String dropMetaBGraph = "SPARQL DROP SILENT GRAPH <" + gr_c.getMetadataGraphB() + ">"; final String createMetaAGraph = "SPARQL CREATE GRAPH <" + gr_c.getMetadataGraphA() + ">"; final String createMetaBGraph = "SPARQL CREATE GRAPH <" + gr_c.getMetadataGraphB() + ">"; try (PreparedStatement dropMetaAStmt = virt_conn.prepareStatement(dropMetaAGraph); PreparedStatement dropMetaBStmt = virt_conn.prepareStatement(dropMetaBGraph); PreparedStatement createMetaAStmt = virt_conn.prepareStatement(createMetaAGraph); PreparedStatement createMetaBStmt = virt_conn.prepareStatement(createMetaBGraph) ) { //System.out.println("INSIDE META CREATION"); dropMetaAStmt.execute(); //System.out.println("INSIDE META CREATION 1"); dropMetaBStmt.execute(); //System.out.println("INSIDE META CREATION 2"); createMetaAStmt.execute(); //System.out.println("INSIDE META CREATION 3"); createMetaBStmt.execute(); //System.out.println("OUTSIDE META CREATION"); } catch (SQLException ex) { LOG.trace("SQLException thrown during temp graph creation"); LOG.debug("SQLException thrown during temp graph creation : " + ex.getMessage()); LOG.debug("SQLException thrown during temp graph creation : " + ex.getSQLState()); } //testThreads(links); //LOG.info(ANSI_YELLOW + "Thread test lasted " + ((endtime - starttime) / 1000000000f) + "" + ANSI_RESET); boolean isEndpointALocal; boolean isEndpointBLocal; isEndpointALocal = isURLToLocalInstance(gr_c.getEndpointA()); //"localhost" for localhost isEndpointBLocal = isURLToLocalInstance(gr_c.getEndpointB()); //"localhost" for localhost getFromA.append("SPARQL INSERT\n"); getFromA.append(" { GRAPH <").append(gr_c.getMetadataGraphA()).append("> {\n"); if (gr_c.isDominantA()) { getFromA.append(" ?s ?p ?o1 . \n"); } else { getFromA.append(" ?o ?p ?o1 . \n"); } getFromA.append(" ?o1 ?p4 ?o3 .\n"); getFromA.append(" ?o3 ?p5 ?o4 .\n"); getFromA.append(" ?o4 ?p6 ?o5\n"); getFromA.append("} }\nWHERE\n"); getFromA.append("{\n"); getFromA.append(" GRAPH <" + gr_c.getSampleLinksGraph() + "> { "); //if ( swapped ) getFromA.append(" ?s <"+Constants.SAME_AS+"> ?o } .\n"); //else // getFromA.append(" ?o <"+Constants.SAME_AS+"> ?s } .\n"); if (isEndpointALocal) { getFromA.append(" GRAPH <").append(gr_c.getGraphA()).append("> { {?s ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3 . OPTIONAL { ?o3 ?p5 ?o4 . OPTIONAL { ?o4 ?p6 ?o5 .} } } }\n"); } else { getFromA.append(" SERVICE <" + gr_c.getEndpointA() + "> { GRAPH <").append(gr_c.getGraphA()).append("> { {?s ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3 . OPTIONAL { ?o3 ?p5 ?o4 . OPTIONAL { ?o4 ?p6 ?o5 .} } } } }\n"); } getFromA.append("\n"); getFromA.append(" FILTER(!regex(?p,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n"); getFromA.append(" FILTER(!regex(?p, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n"); getFromA.append(" FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n"); getFromA.append(" FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n"); getFromA.append(" FILTER(!regex(?p4,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n"); getFromA.append(" FILTER(!regex(?p4, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n"); getFromA.append(" FILTER(!regex(?p4, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n"); getFromA.append(" FILTER(!regex(?p4, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n"); getFromA.append("}"); getFromB.append("sparql INSERT\n"); getFromB.append(" { GRAPH <").append(gr_c.getMetadataGraphB()).append("> {\n"); if (gr_c.isDominantA()) { getFromB.append(" ?s ?p ?o1 . \n"); } else { getFromB.append(" ?o ?p ?o1 . \n"); } getFromB.append(" ?o1 ?p4 ?o3 .\n"); getFromB.append(" ?o3 ?p5 ?o4 .\n"); getFromB.append(" ?o4 ?p6 ?o5 \n"); getFromB.append("} }\nWHERE\n"); getFromB.append("{\n"); getFromB.append(" GRAPH <" + gr_c.getSampleLinksGraph() + "> { "); //if ( swapped ) getFromB.append(" ?s <"+Constants.SAME_AS+"> ?o } .\n"); //else //getFromB.append(" ?o <"+Constants.SAME_AS+"> ?s } .\n"); if (isEndpointBLocal) { getFromB.append(" GRAPH <").append(gr_c.getGraphB()).append("> { {?o ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3 . OPTIONAL { ?o3 ?p5 ?o4 . OPTIONAL { ?o4 ?p6 ?o5 .} } } }\n"); } else { getFromB.append(" SERVICE <" + gr_c.getEndpointB() + "> { GRAPH <").append(gr_c.getGraphB()).append("> { {?o ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3 . OPTIONAL { ?o3 ?p5 ?o4 . OPTIONAL { ?o4 ?p6 ?o5 .} } } } }\n"); } getFromB.append("\n"); getFromB.append(" FILTER(!regex(?p,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n"); getFromB.append(" FILTER(!regex(?p, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n"); getFromB.append(" FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n"); getFromB.append(" FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n"); getFromB.append(" FILTER(!regex(?p4,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n"); getFromB.append(" FILTER(!regex(?p4, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n"); getFromB.append(" FILTER(!regex(?p4, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n"); getFromB.append(" FILTER(!regex(?p4, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n"); getFromB.append("}"); System.out.println("GET FROM B \n" + getFromB); System.out.println("GET FROM B \n" + getFromA); // Populate with data from the Sample Liink set try (PreparedStatement populateDataA = virt_conn.prepareStatement(getFromA.toString()); PreparedStatement populateDataB = virt_conn.prepareStatement(getFromB.toString())) { //starttime = System.nanoTime(); populateDataA.executeUpdate(); populateDataB.executeUpdate(); } catch (SQLException ex) { LOG.trace("SQLException thrown during temp graph populating"); LOG.debug("SQLException thrown during temp graph populating : " + ex.getMessage()); LOG.debug("SQLException thrown during temp graph populating : " + ex.getSQLState()); success = false; } //endtime = System.nanoTime(); //LOG.info("Metadata main parsed in " + (endtime - starttime) / 1000000000f); //i += Constants.BATCH_SIZE; //count++; // } foundA.clear(); foundB.clear(); for (int i = 0; i < optDepth + 1; i++) { // Dynamically construct properties query StringBuilder query = new StringBuilder(); query.append("sparql SELECT distinct(?s) ?pa1 ?oa1 "); for (int j = 0; j < i; j++) { int ind = j + 2; int prev = ind - 1; query.append("?pa").append(ind).append(" ?oa").append(ind).append(" "); } query.append("?pb1 ?ob1 "); for (int j = 0; j < i; j++) { int ind = j + 2; query.append("?pb").append(ind).append(" ?ob").append(ind).append(" "); } query.append(" WHERE \n {\n"); query.append("SELECT ?s ?pa1 ?oa1 "); for (int j = 0; j < i; j++) { int ind = j + 2; int prev = ind - 1; query.append("?pa").append(ind).append(" ?oa").append(ind).append(" "); } query.append("?pb1 ?ob1 "); for (int j = 0; j < i; j++) { int ind = j + 2; int prev = ind - 1; query.append("?pb").append(ind).append(" ?ob").append(ind).append(" "); } if (gr_c.isDominantA()) { query.append("\nWHERE\n{\n GRAPH <" + gr_c.getSampleLinksGraph() + "> { ?s ?p ?o }\n"); } else { query.append("\nWHERE\n{\n GRAPH <" + gr_c.getSampleLinksGraph() + "> { ?o ?p ?s }\n"); } query.append(" { GRAPH <").append(gr_c.getMetadataGraphA()).append("> { {?s ?pa1 ?oa1} "); for (int j = 0; j < i; j++) { int ind = j + 2; int prev = ind - 1; query.append(" . ?oa").append(prev).append(" ?pa").append(ind).append(" ?oa").append(ind).append(" "); } for (int j = 0; j < i; j++) { query.append(" "); } query.append("}\n } UNION { \n" + " GRAPH <").append(gr_c.getMetadataGraphB()).append("> { {?s ?pb1 ?ob1} "); for (int j = 0; j < i; j++) { int ind = j + 2; int prev = ind - 1; query.append(" . ?ob").append(prev).append(" ?pb").append(ind).append(" ?ob").append(ind).append(" "); } for (int j = 0; j < i; j++) { query.append(" "); } query.append("} }\n" + "}\n" + "} ORDER BY (?s)"); System.out.println("Properties Query : " + query.toString()); String prevSubject = ""; try (PreparedStatement fetchProperties = virt_conn.prepareStatement(query.toString()); ResultSet propertiesRS = fetchProperties.executeQuery()) { List<String> chainA = new ArrayList<>(); List<String> chainB = new ArrayList<>(); List<String> objectChainA = new ArrayList<>(); List<String> objectChainB = new ArrayList<>(); while (propertiesRS.next()) { final String subject = propertiesRS.getString(1); //propertiesRS. if (!prevSubject.equals(subject) && !prevSubject.equals("")) { //if (i == optDepth) { //System.out.println(subject); scanMatches(); propertiesA.clear(); propertiesB.clear(); //} } chainA.clear(); chainB.clear(); objectChainA.clear(); objectChainB.clear(); for (int j = 0; j <= i; j++) { int step_over = 2 * (i + 1); final String predicateA = propertiesRS.getString(2 * (j + 1)); final String objectA = propertiesRS.getString(2 * (j + 1) + 1); final String predicateB = propertiesRS.getString(2 * (j + 1) + step_over); final String objectB = propertiesRS.getString(2 * (j + 1) + 1 + step_over); /*if (objectA != null) { System.out.println("Object A "+objectA+" "+PATTERN_INT.asPredicate().test(objectA)); } if (objectB != null) { System.out.println("Object B "+objectB+" "+PATTERN_INT.asPredicate().test(objectB)); }*/ if (predicateA != null) { //predicateA = URLDecoder.decode(predicateA, "UTF-8"); } if (predicateB != null) { //predicateB = URLDecoder.decode(predicateB, "UTF-8"); } if (predicateA != null) { if (!nonMatchedPropertiesA.contains(predicateA)) { //nonMatchedPropertiesA.add(predicateA); } if (!uniquePropertiesA.contains(predicateA)) { uniquePropertiesA.add(predicateA); } if (predicateA.contains("posSeq")) { //continue; } if (predicateA.contains("asWKT")) { //continue; } if (predicateA.contains("geometry")) { //continue; } } if (predicateB != null) { if (!nonMatchedPropertiesB.contains(predicateB)) { //nonMatchedPropertiesB.add(predicateB); } if (!uniquePropertiesB.contains(predicateB)) { uniquePropertiesB.add(predicateB); } if (predicateB.contains("posSeq")) { //continue; } if (predicateB.contains("asWKT")) { //continue; } if (predicateB.contains("geometry")) { //continue; } } chainA.add(predicateA); objectChainA.add(objectA); chainB.add(predicateB); objectChainB.add(objectB); //System.out.println(" "+predicateA+" "+objectA); //System.out.println(" "+predicateB+" "+objectB); } //System.out.println("Chain A "+chainA); //System.out.println("Chain B "+chainB); scanChain(propertiesA, chainA, objectChainA); scanChain(propertiesB, chainB, objectChainB); prevSubject = subject; } } catch (SQLException ex) { LOG.trace("SQLException thrown during set up of the Dictionary"); LOG.debug("SQLException thrown during set up of the Dictionary : \n" + ex.getMessage()); LOG.debug("SQLException thrown during set up of the Dictionary : \n" + ex.getSQLState()); return null; } scanMatches(); propertiesA.clear(); propertiesB.clear(); } } // Close WordNet resources if (JWNL.isInitialized()) { JWNL.shutdown(); } // A frequncy map of ontology substring in each predicate HashMap<String, Integer> freqMap = Maps.newHashMap(); // Find dominant ontology in Dataset A for (String key : uniquePropertiesA) { //System.out.println(key); // Get meaningful part String onto = Utilities.getPredicateOntology(key); // If previously encountered, bump the number if (freqMap.containsKey(onto)) { freqMap.put(onto, freqMap.get(onto) + 1); } else { freqMap.put(onto, 1); } } int max = -1; String domOntologyA = ""; for (Map.Entry<String, Integer> entry : freqMap.entrySet()) { String key = entry.getKey(); Integer value = entry.getValue(); if (value > max) { if (key.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns")) { continue; } max = value; domOntologyA = key; } //System.out.println("Entry "+key+" : "+value); } // Clear frequencies freqMap.clear(); // Find dominant ontology in Dataset A for (String key : uniquePropertiesB) { //System.out.println(key); String onto = StringUtils.substringBefore(key, "#"); onto = onto.concat("#"); if (onto.equals(key)) { onto = StringUtils.substring(key, 0, StringUtils.lastIndexOf(key, "/")); onto = onto.concat("/"); } //System.out.println("Onto "+onto+" "+StringUtils.lastIndexOf(key, "/")); if (freqMap.containsKey(onto)) { freqMap.put(onto, freqMap.get(onto) + 1); } else { freqMap.put(onto, 1); } } max = -1; String domOntologyB = ""; for (Map.Entry<String, Integer> entry : freqMap.entrySet()) { String key = entry.getKey(); Integer value = (Integer) entry.getValue(); if (value > max) { if (key.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns")) { continue; } max = value; domOntologyB = key; } //System.out.println("Entry "+key+" : "+value); } //System.out.println("Dominant from A "+domOntologyA+", Dominant from B "+domOntologyB); //System.out.println(); //for (String key : uniquePropertiesB) { // System.out.println(key); //} //System.out.println("Found A"); /* Iterator iter = foundA.entrySet().iterator(); while (iter.hasNext()) { Map.Entry pairs = (Map.Entry) iter.next(); HashSet<ScoredMatch> set = (HashSet<ScoredMatch>) pairs.getValue(); //System.out.println("KEY: "+pairs.getKey()); for (ScoredMatch s : set) { //System.out.println(s.getRep()); } } //System.out.println("Found B"); iter = foundB.entrySet().iterator(); while (iter.hasNext()) { Map.Entry pairs = (Map.Entry) iter.next(); HashSet<ScoredMatch> set = (HashSet<ScoredMatch>) pairs.getValue(); //System.out.println("KEY: "+pairs.getKey()); //for(ScoredMatch s : set) { //System.out.println(s.getRep()); //} } */ return new SchemaMatchState(foundA, foundB, domOntologyA, domOntologyB, nonMatchedPropertiesA, nonMatchedPropertiesB); } //int maxParentDepth = 3; private int scanSense(Synset i, Synset j) { //RelationshipList list = RelationshipFinder.getInstance().findRelationships(i, j, PointerType.HYPERNYM); //RelationshipList listLvl1 = RelationshipFinder.getInstance().findRelationships(i, j, PointerType.HYPERNYM, 1); RelationshipList listLvl2; try { listLvl2 = RelationshipFinder.getInstance().findRelationships(i, j, PointerType.HYPERNYM, wordnetDepth); } catch (JWNLException ex) { return -1; } //System.out.println("Hypernym relationship between \"" + start.getLemma() + "\" and \"" + end.getLemma() + "\":"); //int ret = -1; int tom; //int count = 0; int min = 999999; for (Object o : listLvl2) { //System.out.println("List Size " + list.size()); //count++; Relationship rel = (Relationship) o; tom = ((AsymmetricRelationship) rel).getCommonParentIndex(); if (tom < min) { min = tom; } //System.out.println("Common Parent Index: " + tom); //System.out.println("Depth 2: " + rel.getDepth()); //rel.getNodeList().print(); } if (min > maxParentDepth) { return -1; } else { return min; } } private float calculateAsymmetricRelationshipOperation(IndexWord start, IndexWord end, SchemaMatcher m) { // Try to find a relationship between the first sense of <var>start</var> and the first sense of <var>end</var> //System.out.println("Asymetric relationship between \"" + start.getLemma() + "\" and \"" + end.getLemma() + "\":"); if (start == null || end == null) { return (float) 0.0; } //System.out.println("Immediate Relationship "+RelationshipFinder.getInstance().getImmediateRelationship(start, end)); //System.out.println("Immediate Relationship "+RelationshipFinder.getInstance().getImmediateRelationship(end, start)); if (start.getLemma().equals(end.getLemma())) { m.matches.add(end.getLemma()); return (float) 1.0; } //System.out.println("NEW WORD"); //System.out.print(start.getLemma()+" VS "); //System.out.println(end.getLemma()); Synset[] setA = null; Synset[] setB = null; try { setA = start.getSenses(); setB = end.getSenses(); } catch (JWNLException ex) { } if (setA == null || setB == null) { return (float) 0.0; } int min = 99999; int total = 0; int count = 0; for (Synset i : setA) { //System.out.println("YOLO 2 "+i); //System.out.println("START SYM"); Word[] cruise = i.getWords(); for (Word al : cruise) { //System.out.print(al.getLemma()+" "); } //System.out.println(); //System.out.println("END SYM"); count++; for (Synset j : setB) { //System.out.println("Header "+i.getLexFileName()+" VS "+j.getGloss()); //System.out.println("YOLO 3 "+j); int ret = scanSense(i, j); if (ret < 0) { continue; } //System.out.println("RETURN "+ret); if (ret <= min) { //if(ret < min) //System.out.println(); min = ret; //System.out.println("MIN "+ret); //System.out.println("sim("+start.getLemma() + "," + end.getLemma()+") = "+1.0/ret); //System.out.println("MIN\n"+i+"\n"+j); //System.out.println(); for (Word relevant : j.getWords()) { m.matches.add(relevant.getLemma()); } } //total = ret; } } //System.out.println("END WORD "+maxParentDepth); if (min > maxParentDepth) { return (float) 0; } else if (min == 0) { return (float) 0; } else { //return (float) (1.0f - (min/(float)maxParentDepth) ); //System.out.println("MIN : "+min); //ystem.out.println("POW : "+Math.pow((float) (1.0f - (min/(float)maxParentDepth) ), raiseToPower)); //System.out.println("THE POW : "+raiseToPower); return (float) Math.pow((float) (1.0f - (min / (float) (maxParentDepth + 1))), raiseToPower); } } public void printChains() { Iterator it = propertiesA.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); //System.out.println(pairs.getKey() + " = " + (MetadataChain)pairs.getValue()); it.remove(); // avoids a ConcurrentModificationException } } private String getJWNL(String pathToWordnet) { String jwnlXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<jwnl_properties language=\"en\">\n" + " <version publisher=\"Princeton\" number=\"3.0\" language=\"en\"/>\n" + " <dictionary class=\"net.didion.jwnl.dictionary.FileBackedDictionary\">\n" + " <param name=\"morphological_processor\" value=\"net.didion.jwnl.dictionary.morph.DefaultMorphologicalProcessor\">\n" + " <param name=\"operations\">\n" + " <param value=\"net.didion.jwnl.dictionary.morph.LookupExceptionsOperation\"/>\n" + " <param value=\"net.didion.jwnl.dictionary.morph.DetachSuffixesOperation\">\n" + " <param name=\"noun\" value=\"|s=|ses=s|xes=x|zes=z|ches=ch|shes=sh|men=man|ies=y|\"/>\n" + " <param name=\"verb\" value=\"|s=|ies=y|es=e|es=|ed=e|ed=|ing=e|ing=|\"/>\n" + " <param name=\"adjective\" value=\"|er=|est=|er=e|est=e|\"/>\n" + " <param name=\"operations\">\n" + " <param value=\"net.didion.jwnl.dictionary.morph.LookupIndexWordOperation\"/>\n" + " <param value=\"net.didion.jwnl.dictionary.morph.LookupExceptionsOperation\"/>\n" + " </param>\n" + " </param>\n" + " <param value=\"net.didion.jwnl.dictionary.morph.TokenizerOperation\">\n" + " <param name=\"delimiters\">\n" + " <param value=\" \"/>\n" + " <param value=\"-\"/>\n" + " </param>\n" + " <param name=\"token_operations\">\n" + " <param value=\"net.didion.jwnl.dictionary.morph.LookupIndexWordOperation\"/>\n" + " <param value=\"net.didion.jwnl.dictionary.morph.LookupExceptionsOperation\"/>\n" + " <param value=\"net.didion.jwnl.dictionary.morph.DetachSuffixesOperation\">\n" + " <param name=\"noun\" value=\"|s=|ses=s|xes=x|zes=z|ches=ch|shes=sh|men=man|ies=y|\"/>\n" + " <param name=\"verb\" value=\"|s=|ies=y|es=e|es=|ed=e|ed=|ing=e|ing=|\"/>\n" + " <param name=\"adjective\" value=\"|er=|est=|er=e|est=e|\"/>\n" + " <param name=\"operations\">\n" + " <param value=\"net.didion.jwnl.dictionary.morph.LookupIndexWordOperation\"/>\n" + " <param value=\"net.didion.jwnl.dictionary.morph.LookupExceptionsOperation\"/>\n" + " </param>\n" + " </param>\n" + " </param>\n" + " </param>\n" + " </param>\n" + " </param>\n" + " <param name=\"dictionary_element_factory\" value=\"net.didion.jwnl.princeton.data.PrincetonWN17FileDictionaryElementFactory\"/>\n" + " <param name=\"file_manager\" value=\"net.didion.jwnl.dictionary.file_manager.FileManagerImpl\">\n" + " <param name=\"file_type\" value=\"net.didion.jwnl.princeton.file.PrincetonRandomAccessDictionaryFile\"/>\n" + " <param name=\"dictionary_path\" value=\"" + pathToWordnet + "\"/>\n" + " </param>\n" + " </dictionary>\n" + " <resource class=\"PrincetonResource\"/>\n" + "</jwnl_properties>"; return jwnlXML; } public void insertLinksMetadata(List<Link> links) { //metadata go in the graphA, not the new one. the method is called without the fusedGraph from FuserWorker //keep metadata subjects according to the transformation /* long starttime, endtime; createLinksGraph(links); String getFromB; createDelWGSGraph(((FileBulkLoader)trh).getDelWGSList()); createDelGeomGraph(((FileBulkLoader)trh).getDelGeomList()); starttime = System.nanoTime(); boolean isMyDesiredIp = false; final URI u; try { u = new URI("https://help.github.com/articles/error-permission-denied-publickey"); // URI u = new URI("/works/with/me/too"); // URI u = new URI("/can/../do/./more/../sophis?ticated=stuff+too"); if(u.isAbsolute()) { //System.out.println("Yes, i am absolute!"); } else { //System.out.println("Ohh noes, it's a relative URI!"); } try { InetAddress localhost = InetAddress.getLocalHost(); LOG.info(" IP Addr: " + localhost.getHostAddress()); // Just in case this host has multiple IP addresses.... InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName()); if (allMyIps != null && allMyIps.length > 1) { LOG.info(" Full list of IP addresses:"); for (InetAddress allMyIp : allMyIps) { LOG.info(" " + allMyIp); } } } catch (UnknownHostException e) { LOG.info(" (error retrieving server host name)"); } try { LOG.info("Full list of Network Interfaces:"); for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); LOG.info(" " + intf.getName() + " " + intf.getDisplayName()); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { LOG.info(" " + enumIpAddr.nextElement().toString()); } } } catch (SocketException e) { LOG.info(" (error retrieving network interface list)"); } } catch (URISyntaxException ex) { java.util.logging.Logger.getLogger(VirtuosoImporter.class.getName()).log(Level.SEVERE, null, ex); } if (endpointLoc.equals(endpointB)) { getFromB = "INSERT\n" + " { GRAPH <"+targetGraph+"> {\n" + " ?s ?p ?o1 . \n" + " ?o1 ?p4 ?o3 .\n" + " ?o3 ?p5 ?o4\n" + "} }\nWHERE\n" + "{\n" + " GRAPH <"+gr_c.getLinksGraph() +"> { ?s <http://www.w3.org/2002/07/owl#sameAs> ?o } .\n" + " GRAPH <"+graphB+"> { {?o ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3. } OPTIONAL { ?o3 ?p5 ?o4 .} }\n" + "\n" + " FILTER(!regex(?p,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n" + " FILTER(!regex(?p, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n" + " FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n" + " FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n" + "}"; } else { getFromB = "SELECT ?s ?p ?o1 ?p4 ?o3 ?p5 ?o4\n" + "WHERE\n" + "{\n" + " SERVICE <"+endpointLoc+"> { GRAPH <"+gr_c.getLinksGraph()+ "> { ?s <http://www.w3.org/2002/07/owl#sameAs> ?o } }\n" + " GRAPH <"+graphB+"> { {?o ?p ?o1} OPTIONAL { ?o1 ?p4 ?o3. } OPTIONAL { ?o3 ?p5 ?o4 .} }\n" + "\n" + " FILTER(!regex(?p,\"http://www.opengis.net/ont/geosparql#hasGeometry\",\"i\")) \n" + " FILTER(!regex(?p, \"http://www.opengis.net/ont/geosparql#asWKT\", \"i\"))\n" + " FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#lat\", \"i\")) \n" + " FILTER(!regex(?p, \"http://www.w3.org/2003/01/geo/wgs84_pos#long\", \"i\"))\n" + "}"; } //int count = 0; int i = 0; while (i < links.size()) { createLinksGraphBatch(links, i); starttime = System.nanoTime(); UpdateRequest insertFromB = UpdateFactory.create(getFromB); UpdateProcessor insertRemoteB = UpdateExecutionFactory.createRemoteForm(insertFromB, endpointB); insertRemoteB.execute(); endtime = System.nanoTime(); LOG.info("Metadata parsed in "+(endtime-starttime)/1000000000f); i += Constants.BATCH_SIZE; //count++; } endtime = System.nanoTime(); LOG.info(ANSI_YELLOW+"Metadata parsed in "+((endtime-starttime)/1000000000f)+""+ANSI_RESET); */ } /** * Use the Triple Handler to upload data to Virtuoso * */ public void finishUpload() { trh.finish(); } /** * Create connection to Virtuoso through Jena * */ private VirtGraph getVirtuosoSet(String graph, String url, String username, String password) { //Class.forName("virtuoso.jdbc4.Driver"); VirtGraph vSet = null; try { vSet = new VirtGraph(graph, "jdbc:virtuoso://" + url + "/CHARSET=UTF-8", username, password); } catch (JenaException ex) { LOG.trace("JenaException thrown during VirtGraph creatinon"); LOG.debug("JenaException thrown during VirtGraph creatinon : " + ex.getMessage()); } return vSet; } /** * Clean up Virtuoso Importer * * @return success */ public boolean clean() { boolean success = true; try { set.close(); } catch (JenaException ex) { LOG.trace("JenaException thrown during VirtGraph cleanup"); LOG.debug("JenaException thrown during VirtGraph cleanup : " + ex.getMessage()); success = false; } //LOG.info(ANSI_YELLOW+"Virtuoso import is done."+ANSI_RESET); return success; } /** * Virtuoso specific PL/SQL Never should have gone that way....... * * @deprecated Learn from our mistakes... */ private void clearBulkLoadHistory() { //PreparedStatement clearBulkLoadTblStmt; //clearBulkLoadTblStmt = virt_conn.prepareStatement(clearBulkLoadTbl); //clearBulkLoadTblStmt.executeUpdate(); } /** * Create a a graph holding a batch of links starting at nextIndex * * @param lst A List of Link objects to be inserted. * @param nextIndex Offset in the list */ private boolean createLinksGraphBatch(List<Link> lst, int nextIndex) { boolean success = true; final String dropGraph = "sparql DROP SILENT GRAPH <" + gr_c.getLinksGraph() + ">"; final String createGraph = "sparql CREATE GRAPH <" + gr_c.getLinksGraph() + ">"; PreparedStatement dropStmt = null; PreparedStatement createStmt = null; try { long starttime, endtime; dropStmt = virt_conn.prepareStatement(dropGraph); dropStmt.execute(); createStmt = virt_conn.prepareStatement(createGraph); createStmt.execute(); } catch (SQLException ex) { LOG.trace("SQLException thrown during temp graph creation"); LOG.debug("SQLException thrown during temp graph creation : " + ex.getMessage()); LOG.debug("SQLException thrown during temp graph creation : " + ex.getSQLState()); success = false; return success; } finally { try { if (dropStmt != null) { dropStmt.close(); } if (createStmt != null) { createStmt.close(); } } catch (SQLException ex) { LOG.trace("SQLException thrown during statement closing"); LOG.debug("SQLException thrown during statement closing : " + ex.getMessage()); LOG.debug("SQLException thrown during statement closing : " + ex.getSQLState()); } } //BulkInsertLinksBatch(lst, nextIndex); success = SPARQLInsertLinksBatch(lst, nextIndex); //System.out.println("THE BOOL OUT IS " + success); return success; } /** * Create a a graph holding all provided links * * @param lst A List of Link objcts to be inserted. * @return success */ public boolean createLinksGraph(List<Link> lst) { boolean success = true; final String dropGraph = "SPARQL DROP SILENT GRAPH <" + gr_c.getAllLinksGraph() + ">"; final String createGraph = "SPARQL CREATE GRAPH <" + gr_c.getAllLinksGraph() + ">"; PreparedStatement dropStmt = null; PreparedStatement createStmt = null; try { long starttime, endtime; dropStmt = virt_conn.prepareStatement(dropGraph); dropStmt.execute(); createStmt = virt_conn.prepareStatement(createGraph); createStmt.execute(); } catch (SQLException ex) { LOG.trace("SQLException thrown during temp graph creation"); LOG.debug("SQLException thrown during temp graph creation : " + ex.getMessage()); LOG.debug("SQLException thrown during temp graph creation : " + ex.getSQLState()); success = false; return success; } finally { try { if (dropStmt != null) { dropStmt.close(); } if (createStmt != null) { createStmt.close(); } } catch (SQLException ex) { LOG.trace("SQLException thrown during statement closing"); LOG.debug("SQLException thrown during statement closing : " + ex.getMessage()); LOG.debug("SQLException thrown during statement closing : " + ex.getSQLState()); } } //BulkInsertLinks(lst); success = SPARQLInsertLinks(lst); return success; } /** * Insert Links thorugh files * * @deprecated Old insert API thorugh files. Required changes in Virtuoso * INI * @param lst A List of Link objects. * @param nextIndex Offset in the list */ @Deprecated private void BulkInsertLinksBatch(List<Link> lst, int nextIndex) { /* long starttime, endtime; set2 = getVirtuosoSet(""+gr_c.getLinksGraph()+ "", db_c.getDBURL(), db_c.getUsername(), db_c.getPassword()); BulkUpdateHandler buh2 = set2.getBulkUpdateHandler(); LOG.info(ANSI_YELLOW+"Loaded "+lst.size()+" links"+ANSI_RESET); starttime = System.nanoTime(); File f = new File(bulkInsertDir+"bulk_inserts/selected_links.nt"); if (f.exists()){ f.delete(); } //f.mkdirs(); //f.getParentFile().mkdirs(); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f))); links_graph = gr_c.getAllLinksGraph(); String dir = bulkInsertDir.replace("\\", "/"); //System.out.println("DIRECTORY "+dir); final String bulk_insert = "DB.DBA.TTLP_MT (file_to_string_output ('"+dir+"bulk_inserts/selected_links.nt'), '', "+"'"+links_graph+"')"; int i = nextIndex; //System.out.println(i); if ( lst.size() > 0 ) { while (i < lst.size() && i < nextIndex + Constants.BATCH_SIZE ) { Link link = lst.get(i); String triple = "<"+link.getNodeA()+"> <"+Constants.SAME_AS+"> <"+link.getNodeB()+"> ."; out.println(triple); i++; } out.close(); PreparedStatement uploadBulkFileStmt; uploadBulkFileStmt = virt_conn.prepareStatement(bulk_insert); uploadBulkFileStmt.executeUpdate(); } //System.out.println(i); endtime = System.nanoTime(); LOG.info(ANSI_YELLOW+"Links Graph created in "+((endtime-starttime)/1000000000f)+""+ANSI_RESET); starttime = System.nanoTime(); virt_conn.commit(); endtime = System.nanoTime(); LOG.info(ANSI_YELLOW+"Links Graph created in "+((endtime-starttime)/1000000000f)+""+ANSI_RESET); */ } /** * Bulk Insert a batch of Links thrugh SPARQL * * @param lst A List of Link objects. * @param nextIndex Offset in the list * @return success */ private boolean SPARQLInsertLinksBatch(List<Link> l, int nextIndex) { boolean success = true; StringBuilder sb = new StringBuilder(); sb.append("SPARQL WITH <" + gr_c.getLinksGraph() + "> INSERT {"); sb.append("`iri(??)` <" + Constants.SAME_AS + "> `iri(??)` . } "); System.out.println("Statement " + sb.toString()); VirtuosoConnection conn = (VirtuosoConnection) set.getConnection(); try { try (VirtuosoPreparedStatement vstmt = (VirtuosoPreparedStatement) conn.prepareStatement(sb.toString())) { int start = nextIndex; int end = nextIndex + Constants.BATCH_SIZE; if (end > l.size()) { end = l.size(); } for (int i = start; i < end; ++i) { Link link = l.get(i); vstmt.setString(1, link.getNodeA()); vstmt.setString(2, link.getNodeB()); vstmt.addBatch(); } vstmt.executeBatch(); } } catch (VirtuosoException ex) { LOG.trace("VirtuosoException thrown during batch link graph creation"); LOG.debug("VirtuosoException thrown during batch link graph creation : " + ex.getMessage()); LOG.debug("VirtuosoException thrown during batch link graph creation : " + ex.getSQLState()); success = false; return success; } catch (BatchUpdateException ex) { LOG.trace("BatchUpdateException thrown during batch link graph creation"); LOG.debug("BatchUpdateException thrown during batch link graph creation : " + ex.getMessage()); LOG.debug("BatchUpdateException thrown during batch link graph creation : " + ex.getSQLState()); success = false; return success; } System.out.println("THE BOOL IN IS " + success); return success; } /** * Bulk Insert ALL Links thrugh SPARQL * * @param lst A List of Link objects. * @return success */ private boolean SPARQLInsertLinks(List<Link> l) { boolean success = true; StringBuilder sb = new StringBuilder(); sb.append("SPARQL WITH <" + gr_c.getAllLinksGraph() + "> INSERT {"); sb.append("`iri(??)` <" + Constants.SAME_AS + "> `iri(??)` . } "); System.out.println("Statement " + sb.toString()); VirtuosoConnection conn = (VirtuosoConnection) set.getConnection(); try { try (VirtuosoPreparedStatement vstmt = (VirtuosoPreparedStatement) conn.prepareStatement(sb.toString())) { int start = 0; int end = l.size(); for (int i = start; i < end; ++i) { Link link = l.get(i); vstmt.setString(1, link.getNodeA()); vstmt.setString(2, link.getNodeB()); vstmt.addBatch(); } vstmt.executeBatch(); } } catch (VirtuosoException ex) { LOG.trace("VirtuosoException thrown during link graph creation"); LOG.debug("VirtuosoException thrown during link graph creation : " + ex.getMessage()); LOG.debug("VirtuosoException thrown during link graph creation : " + ex.getSQLState()); success = false; return success; } catch (BatchUpdateException ex) { LOG.trace("BatchUpdateException thrown during link graph creation"); LOG.debug("BatchUpdateException thrown during link graph creation : " + ex.getMessage()); LOG.debug("BatchUpdateException thrown during link graph creation : " + ex.getSQLState()); success = false; return success; } return success; } /** * Insert ALL Links thorugh files * * @deprecated Old insert API thorugh files. Required changes in Virtuoso * INI * @param lst A List of Link objects. */ @Deprecated private void BulkInsertLinks(List<Link> lst) { /* set2 = getVirtuosoSet(gr_c.getAllLinksGraph(), db_c.getDBURL(), db_c.getUsername(), db_c.getPassword()); BulkUpdateHandler buh2 = set2.getBulkUpdateHandler(); LOG.info(ANSI_YELLOW+"Loaded "+lst.size()+" links"+ANSI_RESET); long starttime, endtime; starttime = System.nanoTime(); File f = new File(bulkInsertDir+"bulk_inserts/selected_links.nt"); //f.mkdirs(); //f.getParentFile().mkdirs(); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f))); String dir = bulkInsertDir.replace("\\", "/"); //System.out.println("DIRECTORY "+dir); final String bulk_insert = "DB.DBA.TTLP_MT (file_to_string_output ('"+dir+"bulk_inserts/selected_links.nt'), '', " +"'"+ gr_c.getAllLinksGraph()+"')"; //int stop = 0; if ( lst.size() > 0 ) { for(Link link : lst) { //if (stop++ > 1000) break; String triple = "<"+link.getNodeA()+"> <"+Constants.SAME_AS+"> <"+link.getNodeB()+"> ."; out.println(triple); } out.close(); PreparedStatement uploadBulkFileStmt; uploadBulkFileStmt = virt_conn.prepareStatement(bulk_insert); uploadBulkFileStmt.executeUpdate(); } endtime = System.nanoTime(); LOG.info(ANSI_YELLOW+"Links Graph created in "+((endtime-starttime)/1000000000f)+""+ANSI_RESET); starttime = System.nanoTime(); virt_conn.commit(); //endtime = System.nanoTime(); LOG.info(ANSI_YELLOW+"Links Graph created in "+((endtime-starttime)/1000000000f)+""+ANSI_RESET); */ } /** * Create a a graph holding the subjects of entities that contained WGS * Geometry and need to be deleted * * @deprecated Worked only on local graphs. Replaced with Updates through * SPARQL and JDBC * @param lst A List of String subjects to be removed. */ @Deprecated private void createDelWGSGraph(List<String> lst) { /* final String dropGraph = "sparql DROP SILENT GRAPH <http://localhost:8890/DAV/del_wgs>"; final String createGraph = "sparql CREATE GRAPH <http://localhost:8890/DAV/del_wgs>"; PreparedStatement dropStmt; long starttime, endtime; dropStmt = virt_conn.prepareStatement(dropGraph); dropStmt.execute(); PreparedStatement createStmt; createStmt = virt_conn.prepareStatement(createGraph); createStmt.execute(); starttime = System.nanoTime(); File f = new File(bulkInsertDir+"bulk_inserts/deleted_wgs.nt"); //f.getParentFile().mkdirs(); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f))); String dir = bulkInsertDir.replace("\\", "/"); //System.out.println("DIRECTORY "+dir); final String bulk_insert = "DB.DBA.TTLP_MT (file_to_string_output ('"+dir+"bulk_inserts/deleted_wgs.nt'), '', "+"'"+del_wgs_graph+"')"; if ( lst.size() > 0 ) { for(String sub : lst) { String triple = "<"+sub+"> <del> <a> ."; out.println(triple); } out.close(); PreparedStatement uploadBulkFileStmt; uploadBulkFileStmt = virt_conn.prepareStatement(bulk_insert); uploadBulkFileStmt.executeUpdate(); } endtime = System.nanoTime(); LOG.info(ANSI_YELLOW+"Delete WGS Graph created in "+((endtime-starttime)/1000000000f)+""+ANSI_RESET); */ } /** * Create a a graph holding the subjects of entities that contained WKT * Geometry and need to be deleted * * @deprecated Worked only on local graphs. Replaced with Updates through * SPARQL and JDBC * @param lst A List of String subjects to be removed. */ @Deprecated private void createDelGeomGraph(List<String> lst) { /* final String dropGraph = "sparql DROP SILENT GRAPH <http://localhost:8890/DAV/del_geom>"; final String createGraph = "sparql CREATE GRAPH <http://localhost:8890/DAV/del_geom>"; PreparedStatement dropStmt; long starttime, endtime; dropStmt = virt_conn.prepareStatement(dropGraph); dropStmt.execute(); PreparedStatement createStmt; createStmt = virt_conn.prepareStatement(createGraph); createStmt.execute(); starttime = System.nanoTime(); File f = new File(bulkInsertDir+"bulk_inserts/deleted_geom.nt"); //f.getParentFile().mkdirs(); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f))); String dir = bulkInsertDir.replace("\\", "/"); //System.out.println("DIRECTORY "+dir); final String bulk_insert = "DB.DBA.TTLP_MT (file_to_string_output ('"+dir+"bulk_inserts/deleted_geom.nt'), '', "+"'"+del_geom_graph+"')"; if ( lst.size() > 0 ) { for(String sub : lst) { String triple = "<"+sub+"> <del> <"+sub+"_geom> ."; out.println(triple); } out.close(); PreparedStatement uploadBulkFileStmt; uploadBulkFileStmt = virt_conn.prepareStatement(bulk_insert); uploadBulkFileStmt.executeUpdate(); } endtime = System.nanoTime(); LOG.info(ANSI_YELLOW+"Delete Geom Graph created in "+((endtime-starttime)/1000000000f)+""+ANSI_RESET); */ } public boolean isInitialized() { return initialized; } public void setInitialized(boolean initialized) { this.initialized = initialized; } }
GeoKnow/FAGI-gis
fagi-gis/src/main/java/gr/athenainnovation/imis/fusion/gis/virtuoso/VirtuosoImporter.java
46,566
package leitourgika_java; import java.io.*; import java.util.Random; /* Η συγκεκριμένη κλάση αναπαριστά μια γεννήτρια διεργασιών για την προσομοίωση */ public class ProcessGenerator implements Serializable{ private File inputFile; private int randomPid=1; public ProcessGenerator(String filename){ try { this.inputFile = new File(filename); inputFile.createNewFile(); } catch (IOException e) { System.out.println(e); } } //dhmiourgia mias neas dhergasias me psedotuxaia xarakthristika public Process CreateProcess(){ Random randomGenerator = new Random(); int arrivalTime = randomGenerator.nextInt(100); int cpuTotalTime = randomGenerator.nextInt(100);//tuxaios arithmos gia to xrono apasxolhshs tou CPU Process tempProcess = new Process(randomPid,arrivalTime,cpuTotalTime); //Clock.ticks periexei to trexonta xrono //System.out.println("arrivalTime ="+tempProcess.arrivalTime+" cpuTotalTime="+tempProcess.cpuTotalTime+" pid="+tempProcess.pid+" currentState=" +tempProcess.currentState); StoreProcessToFile(tempProcess); randomPid++; return tempProcess; } //apothkeush twn stoixeiwn ths neas diergasias sto arxeio inputfile public void StoreProcessToFile(Process tempProcess){ try{ PrintWriter out = new PrintWriter(new FileWriter(inputFile,true)); out.println("arrivalTime ="+tempProcess.arrivalTime+" cpuTotalTime="+tempProcess.cpuTotalTime+" pid="+tempProcess.pid); out.flush(); out.close(); } catch(Exception e){ System.out.println(e); } } }
mpantogi/routine_scheduling
src/leitourgika_java/ProcessGenerator.java
46,610
404: Not Found
AggelosMps/ProjectTest
demo/src/main/java/com/example/AreaChart.java
46,658
package com.example.washingmachine; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.TimePickerDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.media.MediaPlayer; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.ImageButton; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.snackbar.Snackbar; import java.sql.Time; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class FirstFragment extends AppCompatActivity { boolean voiceOn; boolean normalb = false; boolean lightb = false; boolean strongb = false; boolean pressedSchedule = false; int mHour, mMinute; protected void onCreate(Bundle savedInstanceState) { // Window without namebar requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.fragment_first); voiceOn = getIntent().getBooleanExtra("VOICE_ON", false); // Temperature degrees spinner Spinner spinnerTemperature = findViewById(R.id.spinner); String[] list = {"30 °C", "40 °C", "60 °C", "90 °C"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_item, list); spinnerTemperature.setPrompt("ΕΠΙΛΟΓΗ ΘΕΡΜΟΚΡΑΣΙΑΣ"); spinnerTemperature.setAdapter(adapter); RadioButton normal = findViewById(R.id.radio_normal); RadioButton light = findViewById(R.id.radio_light); RadioButton strong = findViewById(R.id.radio_strong); CheckBox favorite = findViewById(R.id.btnfav); CheckBox extra1 = findViewById(R.id.drybtn); CheckBox extra2 = findViewById(R.id.washbtn); RadioGroup group = findViewById(R.id.group); // Starting arrow image, visible when scheduling laundering is not enable ImageButton start = findViewById(R.id.nextbtn); start.setVisibility(View.VISIBLE); // Next step text TextView startTxt = findViewById(R.id.next); // Question mark image ImageButton helper = findViewById(R.id.helper); // Setting Scheduling laundering Button schedulingProgram = findViewById(R.id.scheduled); TextView datePicker = findViewById(R.id.datePicker); TextView timePicker = findViewById(R.id.timePicker); // Next step in Scheduling program TextView scheduled_start = findViewById(R.id.scheduled_next); TextView cancel_scheduled = findViewById(R.id.cancel_schedule); // Scheduling stuff is invisible by default until user decides to enable the feature datePicker.setVisibility(View.INVISIBLE); timePicker.setVisibility(View.INVISIBLE); scheduled_start.setVisibility(View.INVISIBLE); cancel_scheduled.setVisibility(View.INVISIBLE); // Setting date and time in the divider TextView date = findViewById(R.id.date); TextView clock = findViewById(R.id.clock); Calendar calendar = Calendar.getInstance(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy"); String dateTime = simpleDateFormat.format(calendar.getTime()).toString(); date.setText(dateTime); String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date()); clock.setText(currentTime); // Back to home page ImageButton home = (ImageButton) findViewById(R.id.homepage); home.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.return_to_home); music.start(); } Intent intent = new Intent(FirstFragment.this, MainActivity.class); intent.putExtra("VOICE_ON", voiceOn); startActivity(intent); } }); // Favourite program is checked favorite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean checked = ((CheckBox) v).isChecked(); if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.favorite_program); music.start(); } // Check which checkbox was clicked if (checked) { Snackbar.make(v, "ΕΧΕΤΕ ΕΠΙΛΕΞΕΙ ΤΟ ΑΓΑΠΗΜΕΝΟ ΣΑΣ ΠΡΟΓΡΑΜΜΑ", Snackbar.LENGTH_LONG).setAction("Action", null).show(); // When favourite is checked, all the other choices are not available normal.setEnabled(false); light.setEnabled(false); strong.setEnabled(false); extra1.setEnabled(false); extra2.setEnabled(false); group.clearCheck(); extra1.setChecked(false); extra2.setChecked(false); // Other programs are disabled normalb = false; lightb = false; strongb = false; } else { // If favourite is not checked, other choices are available normal.setEnabled(true); light.setEnabled(true); strong.setEnabled(true); extra1.setEnabled(true); extra2.setEnabled(true); group.clearCheck(); normalb = false; lightb = false; strongb = false; } } }); // Dry option is selected extra1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean checked = ((CheckBox) v).isChecked(); if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.extra_dry_fifteen); music.start(); } // Check which checkbox was clicked if (checked) { Snackbar.make(v, "ΕΧΕΤΕ ΕΠΙΛΕΞΕΙ ΣΤΥΨΙΜΟ", Snackbar.LENGTH_LONG).setAction("Action", null).show(); } } }); // Extra wash option is checked extra2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean checked = ((CheckBox) v).isChecked(); if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.extra_wash_twenty); music.start(); } // Check which checkbox was clicked if (checked) { Snackbar.make(v, "ΕΧΕΤΕ ΕΠΙΛΕΞΕΙ ΞΕΒΓΑΛΜΑ", Snackbar.LENGTH_LONG).setAction("Action", null).show(); } } }); // Helper is pressed helper.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.program_info); music.start(); } Intent intent = new Intent(FirstFragment.this, Helper.class); intent.putExtra("VOICE_ON", voiceOn); startActivity(intent); } }); // Starttxt is equal to next when Scheduling laundering is not checked startTxt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // User has to choose a program for the laundering to start, otherwise a message warns them to choose one if (!normalb && !lightb && !strongb && !favorite.isChecked()) { if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.select_program_to_start); music.start(); } Snackbar.make(view, "ΠΡΕΠΕΙ ΝΑ ΕΠΙΛΕΞΕΤΕ ΠΡΟΓΡΑΜΜΑ ΓΙΑ ΝΑ ΞΕΚΙΝΗΣΕΤΕ", Snackbar.LENGTH_LONG).setAction("Action", null).show(); // Favourite program is checked } else if (favorite.isChecked()) { String text = "ΚΑΝΟΝΙΚΟ 15' ΘΕΡΜΟΚΡΑΣΙΑ 30 ΞΕΒΓΑΛΜΑ ΣΤΥΨΙΜΟ"; int tot = 50; Intent intent = new Intent(FirstFragment.this, Washing.class); // Sending time,wash text for the Washing TextView user's program choices intent.putExtra("WASH_TEXT", text); intent.putExtra("TOTAL_TIME", tot); normalb = false; lightb = false; strongb = false; if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.starting_program); music.start(); } intent.putExtra("VOICE_ON", voiceOn); startActivity(intent); } else { // Normal program is checked if (normalb) { String text = "ΚΑΝΟΝΙΚΟ "; int tot = 15; // Adding temperature degrees to the textview text += spinnerTemperature.getSelectedItem().toString() + "'"; // Adding extra options to laundering and return the sum of the time duration of each choice if (extra1.isChecked()) { text += " ΣΤΥΨΙΜΟ"; tot += 15; } if (extra2.isChecked()) { text += " ΞΕΒΓΑΛΜΑ"; tot += 20; } Intent intent = new Intent(FirstFragment.this, Washing.class); // Sending information to the next fragment intent.putExtra("WASH_TEXT", text); intent.putExtra("TOTAL_TIME", tot); normalb = false; lightb = false; strongb = false; if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.starting_program); music.start(); } intent.putExtra("VOICE_ON", voiceOn); startActivity(intent); // Light program is checked } else if (lightb) { String text = "ΕΛΑΦΡΥ "; int tot = 60; // Adding temperature degrees to the textview text += spinnerTemperature.getSelectedItem().toString() + "'"; // adding extra options to laundering and return the sum of the time duration of each choice if (extra1.isChecked()) { text += " ΣΤΥΨΙΜΟ"; tot += 15; } if (extra2.isChecked()) { text += " ΞΕΒΓΑΛΜΑ"; tot += 20; } Intent intent = new Intent(FirstFragment.this, Washing.class); // Sending information to the next fragment intent.putExtra("WASH_TEXT", text); intent.putExtra("TOTAL_TIME", tot); normalb = false; lightb = false; strongb = false; if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.starting_program); music.start(); } intent.putExtra("VOICE_ON", voiceOn); startActivity(intent); // strong program is checked } else if (strongb) { String text = "ΙΣΧΥΡΟ "; int tot = 60; // Adding temperature degrees to the textview text += spinnerTemperature.getSelectedItem().toString() + "'"; // adding extra options to laundering and add the time duration of each choice if (extra1.isChecked()) { text += " ΣΤΥΨΙΜΟ"; tot += 15; } if (extra2.isChecked()) { text += " ΞΕΒΓΑΛΜΑ"; tot += 20; } Intent intent = new Intent(FirstFragment.this, Washing.class); // Sending information to the next fragment intent.putExtra("WASH_TEXT", text); intent.putExtra("TOTAL_TIME", tot); normalb = false; lightb = false; strongb = false; if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.starting_program); music.start(); } intent.putExtra("VOICE_ON", voiceOn); startActivity(intent); } } } }); // Button for setting time and date to schedule the laundering schedulingProgram.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // button is pressed pressedSchedule=true; int time[]; // User has to choose a program for the laundering to be scheduled, otherwise a message warns them to choose one if (!normalb && !lightb && !strongb && !favorite.isChecked()) { if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.select_program_to_start); music.start(); } Snackbar.make(view, "ΠΡΕΠΕΙ ΝΑ ΕΠΙΛΕΞΕΤΕ ΠΡΟΓΡΑΜΜΑ ΓΙΑ ΝΑ ΞΕΚΙΝΗΣΕΤΕ", Snackbar.LENGTH_LONG).setAction("Action", null).show(); } // favourite program is selected else if (favorite.isChecked()) { String text = "ΚΑΝΟΝΙΚΟ 15' ΘΕΡΜΟΚΡΑΣΙΑ 30 ΞΕΒΓΑΛΜΑ ΣΤΥΨΙΜΟ"; int tot = 50; // only scheduling stuff should be visible datePicker.setVisibility(View.VISIBLE); timePicker.setVisibility(View.VISIBLE); startTxt.setVisibility(View.INVISIBLE); scheduled_start.setVisibility(View.VISIBLE); cancel_scheduled.setVisibility(View.VISIBLE); // setting DatePicker pop-up Calendar mcurrentDate = Calendar.getInstance(); int year = mcurrentDate.get(Calendar.YEAR); int month = mcurrentDate.get(Calendar.MONTH); int day = mcurrentDate.get(Calendar.DAY_OF_MONTH); DatePickerDialog mDatePicker = new DatePickerDialog(FirstFragment.this, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker datepicker, int selectedYear, int selectedMonth, int selectedDay) { // TODO Auto-generated method stub /* Your code to get date and time */ Log.e("ΕΠΙΛΕΞΑΤΕ ", selectedDay + "/ " + selectedMonth + " / " + selectedYear); datePicker.setText("Η ΠΛΥΣΗ ΘΑ ΠΡΑΓΜΑΤΟΠΟΙΗΘΕΙ ΣΤΙΣ:" + selectedDay + "/" + selectedMonth + "/" + selectedYear); } }, year, month, day); // The first available date is today mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis() - 1000); mDatePicker.setTitle("ΕΠΙΛΕΞΤΕ ΗΜΕΡΟΜΗΝΙΑ"); mDatePicker.show(); // setting TimePicker pop-up mHour = mcurrentDate.get(Calendar.HOUR_OF_DAY); mMinute = mcurrentDate.get(Calendar.MINUTE); TimePickerDialog timePickerDialog = new TimePickerDialog(FirstFragment.this, new TimePickerDialog.OnTimeSetListener() { @SuppressLint("SetTextI18n") @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { timePicker.setText("ΚΑΙ ΩΡΑ " + hourOfDay + ":" + String.format("%02d", minute)); } }, mHour, mMinute, false); // We had to hide the cancel button in order to make sure that the user will not be able to skip the TimePicker choice timePickerDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { // This is hiding the "Cancel" button: timePickerDialog.getButton(Dialog.BUTTON_NEGATIVE).setVisibility(View.GONE); } }); timePickerDialog.show(); normalb = false; lightb = false; strongb = false; if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.scheduling_date_time); music.start(); } } else { // normal program is selected if (normalb) { String text = "ΚΑΝΟΝΙΚΟ "; int tot = 15; // Adding temperature degrees to the textview text += spinnerTemperature.getSelectedItem().toString() + "'"; // adding extra options to laundering and return the sum of the time duration of each choice if (extra1.isChecked()) { text += " ΣΤΥΨΙΜΟ"; tot += 15; } if (extra2.isChecked()) { text += " ΞΕΒΓΑΛΜΑ"; tot += 20; } // only scheduling stuff should be visible datePicker.setVisibility(View.VISIBLE); timePicker.setVisibility(View.VISIBLE); startTxt.setVisibility(View.INVISIBLE); scheduled_start.setVisibility(View.VISIBLE); cancel_scheduled.setVisibility(View.VISIBLE); // setting DatePicker pop-up Calendar mcurrentDate = Calendar.getInstance(); int year = mcurrentDate.get(Calendar.YEAR); int month = mcurrentDate.get(Calendar.MONTH); int day = mcurrentDate.get(Calendar.DAY_OF_MONTH); DatePickerDialog mDatePicker = new DatePickerDialog(FirstFragment.this, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker datepicker, int selectedYear, int selectedMonth, int selectedDay) { // TODO Auto-generated method stub /* Your code to get date and time */ Log.e("ΕΠΙΛΕΞΑΤΕ ", selectedDay + "/ " + selectedMonth + " / " + selectedYear); datePicker.setText("Η ΠΛΥΣΗ ΘΑ ΠΡΑΓΜΑΤΟΠΟΙΗΘΕΙ ΣΤΙΣ:" + selectedDay + "/" + selectedMonth + "/" + selectedYear); } }, year, month, day); // The first available date is today mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis() - 1000); mDatePicker.setTitle("ΕΠΙΛΕΞΤΕ ΗΜΕΡΟΜΗΝΙΑ"); mDatePicker.show(); // setting TimePicker pop-up mHour = mcurrentDate.get(Calendar.HOUR_OF_DAY); mMinute = mcurrentDate.get(Calendar.MINUTE); TimePickerDialog timePickerDialog = new TimePickerDialog(FirstFragment.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { timePicker.setText("ΚΑΙ ΩΡΑ " + hourOfDay + ":" + minute); } }, mHour, mMinute, false); // We had to hide the cancel button in order to make sure that the user will not be able to skip the TimePicker choice timePickerDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { // This is hiding the "Cancel" button: timePickerDialog.getButton(Dialog.BUTTON_NEGATIVE).setVisibility(View.GONE); } }); timePickerDialog.show(); normalb = false; lightb = false; strongb = false; if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.scheduling_date_time); music.start(); } } // light program is selected else if (lightb) { String text = "ΕΛΑΦΡΥ "; int tot = 60; // Adding temperature degrees to the textview text += spinnerTemperature.getSelectedItem().toString() + "'"; // adding extra options to laundering and return the sum of the time duration of each choice if (extra1.isChecked()) { text += " ΣΤΥΨΙΜΟ"; tot += 15; } if (extra2.isChecked()) { text += " ΞΕΒΓΑΛΜΑ"; tot += 20; } // only scheduling stuff should be visible datePicker.setVisibility(View.VISIBLE); timePicker.setVisibility(View.VISIBLE); startTxt.setVisibility(View.INVISIBLE); scheduled_start.setVisibility(View.VISIBLE); cancel_scheduled.setVisibility(View.VISIBLE); // setting DatePicker pop-up Calendar mcurrentDate = Calendar.getInstance(); int year = mcurrentDate.get(Calendar.YEAR); int month = mcurrentDate.get(Calendar.MONTH); int day = mcurrentDate.get(Calendar.DAY_OF_MONTH); DatePickerDialog mDatePicker = new DatePickerDialog(FirstFragment.this, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker datepicker, int selectedYear, int selectedMonth, int selectedDay) { // TODO Auto-generated method stub /* Your code to get date and time */ Log.e("ΕΠΙΛΕΞΑΤΕ ", selectedDay + "/ " + selectedMonth + " / " + selectedYear); datePicker.setText("Η ΠΛΥΣΗ ΘΑ ΠΡΑΓΜΑΤΟΠΟΙΗΘΕΙ ΣΤΙΣ:" + selectedDay + "/" + selectedMonth + "/" + selectedYear); } }, year, month, day); // The first available date is today mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis() - 1000); mDatePicker.setTitle("ΕΠΙΛΕΞΤΕ ΗΜΕΡΟΜΗΝΙΑ"); mDatePicker.show(); // setting TimePicker pop-up mHour = mcurrentDate.get(Calendar.HOUR_OF_DAY); mMinute = mcurrentDate.get(Calendar.MINUTE); TimePickerDialog timePickerDialog = new TimePickerDialog(FirstFragment.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { timePicker.setText("ΚΑΙ ΩΡΑ " + hourOfDay + ":" + minute); } }, mHour, mMinute, false); timePickerDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override // We had to hide the cancel button in order to make sure that the user will not be able to skip the TimePicker choice public void onShow(DialogInterface dialog) { // This is hiding the "Cancel" button: timePickerDialog.getButton(Dialog.BUTTON_NEGATIVE).setVisibility(View.GONE); } }); timePickerDialog.show(); normalb = false; lightb = false; strongb = false; if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.scheduling_date_time); music.start(); } } else if (strongb) { // strong program is selected String text = "ΙΣΧΥΡΟ "; int tot = 60; // Adding temperature degrees to the textview text += spinnerTemperature.getSelectedItem().toString() + "'"; // adding extra options to laundering and return the sum of the time duration of each choice if (extra1.isChecked()) { text += " ΣΤΥΨΙΜΟ"; tot += 15; } if (extra2.isChecked()) { text += " ΞΕΒΓΑΛΜΑ"; tot += 20; } // only scheduling stuff should be visible datePicker.setVisibility(View.VISIBLE); timePicker.setVisibility(View.VISIBLE); startTxt.setVisibility(View.INVISIBLE); scheduled_start.setVisibility(View.VISIBLE); cancel_scheduled.setVisibility(View.VISIBLE); // setting DatePicker pop-up Calendar mcurrentDate = Calendar.getInstance(); int year = mcurrentDate.get(Calendar.YEAR); int month = mcurrentDate.get(Calendar.MONTH); int day = mcurrentDate.get(Calendar.DAY_OF_MONTH); DatePickerDialog mDatePicker = new DatePickerDialog(FirstFragment.this, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker datepicker, int selectedYear, int selectedMonth, int selectedDay) { // TODO Auto-generated method stub /* Your code to get date and time */ Log.e("ΕΠΙΛΕΞΑΤΕ ", selectedDay + "/ " + selectedMonth + " / " + selectedYear); datePicker.setText("Η ΠΛΥΣΗ ΘΑ ΠΡΑΓΜΑΤΟΠΟΙΗΘΕΙ ΣΤΙΣ:" + selectedDay + "/" + selectedMonth + "/" + selectedYear); } }, year, month, day); // The first available date is today mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis() - 1000); mDatePicker.setTitle("ΕΠΙΛΕΞΤΕ ΗΜΕΡΟΜΗΝΙΑ"); mDatePicker.show(); // setting TimePicker pop-up mHour = mcurrentDate.get(Calendar.HOUR_OF_DAY); mMinute = mcurrentDate.get(Calendar.MINUTE); TimePickerDialog timePickerDialog = new TimePickerDialog(FirstFragment.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { timePicker.setText("ΚΑΙ ΩΡΑ " + hourOfDay + ":" + minute); } }, mHour, mMinute, false); // We had to hide the cancel button in order to make sure that the user will not be able to skip the TimePicker choice timePickerDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { // This is hiding the "Cancel" button: timePickerDialog.getButton(Dialog.BUTTON_NEGATIVE).setVisibility(View.GONE); } }); timePickerDialog.show(); normalb = false; lightb = false; strongb = false; if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.scheduling_date_time); music.start(); } } } } }); // Button for cancelling the scheduling laundering, visible only in scheduling mode cancel_scheduled.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.cancel_scheduled); music.start(); } Snackbar.make(view, "Η ΠΡΟΓΡΑΜΜΑΤΙΣΜΕΝΗ ΠΛΥΣΗ ΑΚΥΡΩΘΗΚΕ", Snackbar.LENGTH_INDEFINITE).setAction("Action", null).show(); // We do not change intent because after scheduling confirmation, a message is visible to the user Intent intent = new Intent(FirstFragment.this, FirstFragment.class); startActivity(intent); } }); // Scheduled start button, visible only in scheduling mode scheduled_start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.successfully_scheduling); music.start(); } Snackbar.make(view, "Η ΠΛΥΣΗ ΣΑΣ ΠΡΟΓΡΑΜΜΑΤΙΣΤΗΚΕ ΜΕ ΕΠΙΤΥΧΙΑ", Snackbar.LENGTH_LONG).setAction("Action", null).show(); // We do not change intent because after scheduling confirmation, a message is visible to the user // Intent intent = new Intent(FirstFragment.this, MainActivity.class); // intent.putExtra("VOICE_ON", voiceOn); // startActivity(intent); } }); // Starting laundering start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // User has to choose a program for the laundering to start, otherwise a message warns them to choose one if (!normalb && !lightb && !strongb && !favorite.isChecked()) { if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.select_program_to_start); music.start(); } Snackbar.make(view, "ΠΡΕΠΕΙ ΝΑ ΕΠΙΛΕΞΕΤΕ ΠΡΟΓΡΑΜΜΑ ΓΙΑ ΝΑ ΞΕΚΙΝΗΣΕΤΕ", Snackbar.LENGTH_LONG).setAction("Action", null).show(); }else if (pressedSchedule){ // button for scheduling laundering is pressed if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.successfully_scheduling); music.start(); } Snackbar.make(view, "Η ΠΛΥΣΗ ΣΑΣ ΠΡΟΓΡΑΜΜΑΤΙΣΤΗΚΕ ΜΕ ΕΠΙΤΥΧΙΑ", Snackbar.LENGTH_LONG).setAction("Action", null).show(); } else if (favorite.isChecked()) { // favourite program is selected String text = "ΚΑΝΟΝΙΚΟ 15' ΘΕΡΜΟΚΡΑΣΙΑ 30 ΞΕΒΓΑΛΜΑ ΣΤΥΨΙΜΟ"; int tot = 50; Intent intent = new Intent(FirstFragment.this, Washing.class); // Sending information to the next fragment intent.putExtra("WASH_TEXT", text); intent.putExtra("TOTAL_TIME", tot); normalb = false; lightb = false; strongb = false; if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.starting_program); music.start(); } intent.putExtra("VOICE_ON", voiceOn); startActivity(intent); } else { if (normalb) { // normal program is selected String text = "ΚΑΝΟΝΙΚΟ "; int tot = 15; // Adding temperature degrees to the textview text += spinnerTemperature.getSelectedItem().toString() + "'"; // adding extra options to laundering and return the sum of the time duration of each choice if (extra1.isChecked()) { text += " ΣΤΥΨΙΜΟ"; tot += 15; } if (extra2.isChecked()) { text += " ΞΕΒΓΑΛΜΑ"; tot += 20; } Intent intent = new Intent(FirstFragment.this, Washing.class); // Sending information to the next fragment intent.putExtra("WASH_TEXT", text); intent.putExtra("TOTAL_TIME", tot); normalb = false; lightb = false; strongb = false; if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.starting_program); music.start(); } intent.putExtra("VOICE_ON", voiceOn); startActivity(intent); } else if (lightb) { // light program is selected String text = "ΕΛΑΦΡΥ "; int tot = 60; // Adding temperature degrees to the textview text += spinnerTemperature.getSelectedItem().toString() + "'"; // adding extra options to laundering and return the sum of the time duration of each choice if (extra1.isChecked()) { text += " ΣΤΥΨΙΜΟ"; tot += 15; } if (extra2.isChecked()) { text += " ΞΕΒΓΑΛΜΑ"; tot += 20; } Intent intent = new Intent(FirstFragment.this, Washing.class); // Sending information to the next fragment intent.putExtra("WASH_TEXT", text); intent.putExtra("TOTAL_TIME", tot); normalb = false; lightb = false; strongb = false; if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.starting_program); music.start(); } intent.putExtra("VOICE_ON", voiceOn); startActivity(intent); } else if (strongb) { // strong program is selected String text = "ΙΣΧΥΡΟ "; int tot = 60; // Adding temperature degrees to the textview text += spinnerTemperature.getSelectedItem().toString() + "'"; // adding extra options to laundering and return the sum of the time duration of each choice if (extra1.isChecked()) { text += " ΣΤΥΨΙΜΟ"; tot += 15; } if (extra2.isChecked()) { text += " ΞΕΒΓΑΛΜΑ"; tot += 20; } Intent intent = new Intent(FirstFragment.this, Washing.class); // Sending information to the next fragment intent.putExtra("WASH_TEXT", text); intent.putExtra("TOTAL_TIME", tot); normalb = false; lightb = false; strongb = false; if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.starting_program); music.start(); } intent.putExtra("VOICE_ON", voiceOn); startActivity(intent); } } } }); } // Function where the appropriate sound is played based on what program is selected public void onRadioButtonClicked(View view) { // Is the button now checked? boolean checked = ((RadioButton) view).isChecked(); // Check which radio button was clicked switch(view.getId()) { case R.id.radio_normal: if (checked) if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.normal_fifteen); music.start(); } normalb = true; lightb = false; strongb = false; break; case R.id.radio_light: if (checked) if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.light_sixty); music.start(); } normalb = false; lightb = true; strongb = false; break; case R.id.radio_strong: if (checked) if (voiceOn) { MediaPlayer music = MediaPlayer.create(FirstFragment.this, R.raw.strong_sixty); music.start(); } normalb = false; lightb = false; strongb = true; break; } } // We shouldn't use the back button that Android offers @Override public void onBackPressed() { // Do Here what ever you want do on back press; } }
5l1v3r1/Washing-Machine-UI
AndroidApp/app/src/main/java/com/example/washingmachine/FirstFragment.java
46,704
package com.example.findit_ocrarthesis.activities; // TODO: 9/21/2021 extract a class for the location if possible import android.Manifest; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Color; import android.location.Geocoder; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.util.Linkify; import android.util.Log; import android.view.MotionEvent; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentOnAttachListener; import androidx.lifecycle.ViewModelProvider; import com.example.findit_ocrarthesis.R; import com.example.findit_ocrarthesis.app_database.ProfessionalViewModel; import com.example.findit_ocrarthesis.location.LocationMatcher; import com.example.findit_ocrarthesis.ocr.ImageProcessor; import com.example.findit_ocrarthesis.ocr.TessTextRecognizer; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnSuccessListener; import com.google.ar.core.Anchor; import com.google.ar.core.Config; import com.google.ar.core.Frame; import com.google.ar.core.HitResult; import com.google.ar.core.Plane; import com.google.ar.core.Pose; import com.google.ar.core.Session; import com.google.ar.sceneform.AnchorNode; import com.google.ar.sceneform.ArSceneView; import com.google.ar.sceneform.FrameTime; import com.google.ar.sceneform.Node; import com.google.ar.sceneform.Scene; import com.google.ar.sceneform.SceneView; import com.google.ar.sceneform.Sceneform; import com.google.ar.sceneform.math.Quaternion; import com.google.ar.sceneform.math.Vector3; import com.google.ar.sceneform.rendering.ViewRenderable; import com.google.ar.sceneform.ux.ArFragment; import com.google.ar.sceneform.ux.BaseArFragment; import org.opencv.android.OpenCVLoader; import java.lang.ref.WeakReference; import java.text.Normalizer; import java.util.Locale; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static android.text.Html.fromHtml; import static com.example.findit_ocrarthesis.constants.Constants.DEFAULT_LANGUAGE; public class MainActivity extends AppCompatActivity implements FragmentOnAttachListener, BaseArFragment.OnTapArPlaneListener, BaseArFragment.OnSessionConfigurationListener, ArFragment.OnViewCreatedListener, Scene.OnUpdateListener { private ProfessionalViewModel professionalViewModel; private FusedLocationProviderClient fusedLocationClient; public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; private static final String TAG = "MainActivity"; TessTextRecognizer tessTextRecognizer; ImageProcessor imageProcessor; ProgressDialog mProgressDialog ; private ArFragment arFragment; private ViewRenderable viewRenderable; private TextView info_text; private Location current_location; private Anchor currentAnchor = null; private AnchorNode currentAnchorNode; private final ExecutorService executor = Executors.newSingleThreadExecutor(); private final Handler handler = new Handler(Looper.getMainLooper()); private Node titleNode; private String[] PERMISSIONS; private boolean data_exists = false; private boolean on_tap_flag = false; static { if (OpenCVLoader.initDebug()) { Log.d(TAG, "INSTALLED OPEN"); } else { Log.d(TAG, "NOT OPENCV"); } } private String all_info_under_100cm; private String all_info_100cm; private Anchor anchor_plane; private boolean enter = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PERMISSIONS = new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CAMERA }; if(!hasPermission(MainActivity.this, PERMISSIONS)){ ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 1); } fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); findLocation(); professionalViewModel = new ViewModelProvider.AndroidViewModelFactory(MainActivity.this .getApplication()) .create(ProfessionalViewModel.class); getLifecycle().addObserver(professionalViewModel); getSupportFragmentManager().addFragmentOnAttachListener(this); if (savedInstanceState == null) { if (Sceneform.isSupported(this)) { getSupportFragmentManager().beginTransaction() .add(R.id.arFragment, ArFragment.class, null) .commit(); } } loadModels(); } public void loadModels() { WeakReference<MainActivity> weakActivity = new WeakReference<>(this); ViewRenderable.builder() .setView(this, R.layout.view_model_title) .build() .thenAccept(viewRenderable -> { MainActivity activity = weakActivity.get(); if (activity != null) { activity.viewRenderable = viewRenderable; } }) .exceptionally(throwable -> { Toast.makeText(this, "Unable to load model", Toast.LENGTH_LONG).show(); return null; }); } @Override public void onAttachFragment(@NonNull FragmentManager fragmentManager, @NonNull Fragment fragment) { if (fragment.getId() == R.id.arFragment) { arFragment = (ArFragment) fragment; arFragment.setOnSessionConfigurationListener(this); arFragment.setOnViewCreatedListener(this); arFragment.setOnTapArPlaneListener(this); } } @Override public void onViewCreated(ArFragment arFragment, ArSceneView arSceneView) { arFragment.setOnViewCreatedListener(null); // Fine adjust the maximum frame rate arSceneView.setFrameRateFactor(SceneView.FrameRate.FULL); } @Override public void onSessionConfiguration(Session session, Config config) { if (session.isDepthModeSupported(Config.DepthMode.AUTOMATIC)) { config.setDepthMode(Config.DepthMode.AUTOMATIC); } config.setPlaneFindingMode(Config.PlaneFindingMode.VERTICAL); } @Override public void onTapPlane(HitResult hitResult, Plane plane, MotionEvent motionEvent) { if (viewRenderable == null) { Toast.makeText(this, "Loading...", Toast.LENGTH_SHORT).show(); return; } data_exists = false; imageProcessor = new ImageProcessor(arFragment /*BitmapFactory.decodeResource(getResources(), R.drawable.sample)*/); // Bitmap b = captureImage();/* BitmapFactory.decodeResource(getResources(), R.drawable.numsample);*/ tessTextRecognizer = new TessTextRecognizer( this, DEFAULT_LANGUAGE); titleNode = getInfoNode(hitResult, viewRenderable); if(current_location!=null) { // do it in background because it can take a while doTasks(); } } private Node getInfoNode(HitResult hitResult, ViewRenderable viewRenderable) { // Create the Anchor. Anchor anchor = hitResult.createAnchor(); AnchorNode anchorNode = new AnchorNode(anchor); anchorNode.setParent(arFragment.getArSceneView().getScene()); Node intermediateNode = new Node(); intermediateNode.setParent(anchorNode); Vector3 anchorUp = anchorNode.getUp(); intermediateNode.setLookDirection(Vector3.up(), anchorUp); clearAnchor(); currentAnchor = anchor; currentAnchorNode = anchorNode; Node infoNode = new Node(); infoNode.setParent(intermediateNode); infoNode.setEnabled(false); infoNode.setLocalPosition(new Vector3(0.0f, 0.0f, 0.0f)); infoNode.setLocalRotation(Quaternion.axisAngle(new Vector3(1f, 0, 0), -90f)); infoNode.setRenderable(viewRenderable); arFragment.getArSceneView().getScene().addOnUpdateListener(this); arFragment.getArSceneView().getScene().addChild(anchorNode); return infoNode; } private void clearAnchor() { currentAnchor = null; if (currentAnchorNode != null) { arFragment.getArSceneView().getScene().removeChild(currentAnchorNode); currentAnchorNode.getAnchor().detach(); currentAnchorNode.setParent(null); currentAnchorNode = null; } } private void doTasks() { if (mProgressDialog == null) { mProgressDialog = ProgressDialog.show(this, "Processing", "Αναζήτηση πληροφοριών για τον συγκεκριμένο επαγγελματία...", true); } else { mProgressDialog.show(); } executor.execute(() -> { Bitmap bitmap_processed = imageProcessor.doImageProcess(); // imageProcessing final String[] srcText = {tessTextRecognizer.getOCRResult(bitmap_processed)}; // ocr stuff handler.post(() -> { if (srcText[0] != null && !srcText[0].equals("")) { srcText[0] = srcText[0].replaceAll("[\\t\\n\\r]+", " "); srcText[0] = stripAccents(srcText[0]); String[] text_array = srcText[0].toUpperCase().split(" "); // Toast.makeText(this, srcText[0], Toast.LENGTH_SHORT).show(); // for (String text : // text_array) { // retrieveData(text.trim(), current_location); // } getProfInfo("Κωνσταντινουπόλεως 400, Άγιοι Ανάργυροι, 13562, ΑΤΤΙΚΗΣ","ΨΟΥΝΗΣ"); } else { Toast.makeText(this, "Δεν μπόρεσε να αναγνωριστεί κάποιο κείμενο", Toast.LENGTH_SHORT).show(); } mProgressDialog.dismiss(); }); }); } private String stripAccents(String s) { s = Normalizer.normalize(s, Normalizer.Form.NFD); s = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", ""); return s; } public void retrieveData(String srcText, Location curr_location) { professionalViewModel.getAllAddresses(srcText) .observe(MainActivity.this, addresses ->{ for (String strAddress: addresses ) { LocationMatcher locationMatcher = new LocationMatcher(new Geocoder(MainActivity.this, new Locale("el_GR")), strAddress); if (locationMatcher.getDistanceFrom(curr_location) < 20.0){ Toast.makeText(this, "Αντιστοίχηση Διευθύνσεων ολοκληρώθηκε!", Toast.LENGTH_SHORT).show(); getProfInfo(strAddress, srcText); } } on_tap_flag = true; }); } private void getProfInfo(String strAddress, String name) { Toast.makeText(this, "Αντιστοίχηση Διευθύνσεων ολοκληρώθηκε!", Toast.LENGTH_SHORT).show(); professionalViewModel.findAll(strAddress, name).observe(MainActivity.this, info ->{ String[] email = info.getEmail().split(":"); all_info_under_100cm = "<b>" + "Category: " + "</b>" + info.getCategory() + "<br>" + "<b>" + "Description: " + "</b>" + info.getDescription() + "<br>" + "<b>" + "Office Number: " + "</b>" + info.getOfficePhone() + "<br>" + "<b>" + "Mobile Phone: "+ "</b>" + info.getMobilePhone() + "<br>" + "<b>" + "Website: "+ "</b>" + info.getWebsite() + "<br>" + "<b>" + email[0] + " " + "</b>" + email[1] ; all_info_100cm = "<b>" + name + "<br>" + info.getProfName() + "</b>"; titleNode.setEnabled(true); }); } private void findLocation(){ if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } fusedLocationClient.getLastLocation() .addOnSuccessListener(this, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { // Got last known location. In some rare situations this can be null. if (location != null) { current_location = location; } } }); } public boolean checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. new AlertDialog.Builder(this) .setTitle("Location permission required") .setMessage("Please add location permission!") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } }) .create() .show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } return false; } else { return true; } } // @Override // public void onRequestPermissionsResult(int requestCode, // String[] permissions, int[] grantResults) { // super.onRequestPermissionsResult(requestCode, permissions, grantResults); // switch (requestCode) { // case MY_PERMISSIONS_REQUEST_LOCATION: { // // If request is cancelled, the result arrays are empty. // if (grantResults.length > 0 // && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // // permission was granted, yay! Do the // // location-related task you need to do. // if (ContextCompat.checkSelfPermission(this, // Manifest.permission.ACCESS_FINE_LOCATION) // == PackageManager.PERMISSION_GRANTED) { // //Request location updates: // findLocation(); // } // } else { // // permission denied, boo! Disable the // // functionality that depends on this permission. // } // return; // } // } // } private boolean hasPermission(Context context, String... PERMISSIONS){ if(context != null && PERMISSIONS != null){ for (String permission: PERMISSIONS) { if(ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED){ return false; } } } return true; } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 1: { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "Location Permission Granted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Location Permission Denied", Toast.LENGTH_SHORT).show(); } if (grantResults[1] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "Camera Permission Granted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Camera Permission Denied", Toast.LENGTH_SHORT).show(); } } } } public void onUpdate(FrameTime frameTime) { Frame frame = arFragment.getArSceneView().getArFrame(); if (viewRenderable == null) { Toast.makeText(this, "Loading...", Toast.LENGTH_SHORT).show(); return; } if (currentAnchorNode != null && all_info_100cm != null && all_info_under_100cm != null ) { float distanceMeters = distanceCamera(currentAnchor.getPose(), frame.getCamera().getPose()); viewRenderable.setShadowCaster(false); viewRenderable.setShadowReceiver(false); info_text = (TextView) viewRenderable.getView(); info_text.setAutoLinkMask(Linkify.ALL); info_text.setLinkTextColor(Color.rgb(71, 149, 255)); if (distanceMeters < 1.0 && all_info_under_100cm != null && all_info_100cm != null) { info_text.setTextSize(4); info_text.setText(fromHtml(all_info_under_100cm)); } else if (distanceMeters > 1.00 && all_info_under_100cm != null && all_info_100cm != null) { info_text.setTextSize(10); info_text.setText(fromHtml(all_info_100cm)); } } } private float distanceCamera(Pose planePose, Pose cameraPose) { float dx = planePose.tx() - cameraPose.tx(); float dy = planePose.ty() - cameraPose.ty(); float dz = planePose.tz() - cameraPose.tz(); return (float) Math.sqrt(dx * dx + dy * dy + dz * dz); } }
NikosSpyropoulos/MEng-Thesis
FindItOCRARThesis/FindItOCRARThesis/app/src/main/java/com/example/findit_ocrarthesis/activities/MainActivity.java