file_id
stringlengths
5
10
content
stringlengths
110
36.3k
repo
stringlengths
7
108
path
stringlengths
8
198
token_length
int64
37
8.19k
original_comment
stringlengths
11
5.72k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
62
36.3k
106016_36
/** * 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 2 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 languages; import com.aionemu.gameserver.utils.i18n.CustomMessageId; import com.aionemu.gameserver.utils.i18n.Language; /** * @author Eloann * @reworked Voidstar */ public class German extends Language { public German() { super("de"); addSupportedLanguage("de_DE"); addTranslatedMessage(CustomMessageId.SERVER_REVISION, "Server Version : %-6s"); addTranslatedMessage(CustomMessageId.WELCOME_PREMIUM, "Willkommen bei "); addTranslatedMessage(CustomMessageId.WELCOME_REGULAR, "Willkommen bei "); addTranslatedMessage(CustomMessageId.WELCOME_BASIC, "Willkommen bei "); addTranslatedMessage(CustomMessageId.INFO1, "Warnung: Benutzung von fremde software, wie (speed hack&Co ist strengst verboten."); addTranslatedMessage(CustomMessageId.INFO2, "Hinweis: Je nach Fall, fuehrt ausnahmslos zu unbefristete Account Sperrung."); addTranslatedMessage(CustomMessageId.INFO3, "Warnung: Werben anderer Aion Server oder abwerben von Spieler hier auf dem Server, ist untersagt."); addTranslatedMessage(CustomMessageId.INFO4, "Anmerkung: Das Team wird Sie niemals nach Ihrem Account Passwort fragen!"); addTranslatedMessage(CustomMessageId.INFO5, "Chat: Benutze .faction, .ely, ,asmo <text> um im Chat zu schreiben. "); addTranslatedMessage(CustomMessageId.INFO6, "Chat: Benutze /1 /2 /3, um in den Chatkanaelen zu schreiben."); addTranslatedMessage(CustomMessageId.INFO7, "Befehle: Benutze .help, um zu sehen welche Spielerbefehle noch zur Verfuegung stehen."); addTranslatedMessage(CustomMessageId.SERVERVERSION, "Supported NCSoft Version "); addTranslatedMessage(CustomMessageId.ENDMESSAGE, "Viel Spass auf unserem Server: "); addTranslatedMessage(CustomMessageId.ANNOUNCE_GM_CONNECTION, " Ist jetzt fuer den Support verfuegbar!"); addTranslatedMessage(CustomMessageId.ANNOUNCE_GM_DECONNECTION, " Ist fuer den Support nicht mehr verfuegbar!"); addTranslatedMessage(CustomMessageId.ANNOUNCE_MEMBER_CONNECTION, "%s ist der Welt von Atreia beigetreten."); addTranslatedMessage(CustomMessageId.COMMAND_NOT_ENOUGH_RIGHTS, "Sie haben keine Berechtigung zur Verwendung dieses Befehls"); addTranslatedMessage(CustomMessageId.PLAYER_NOT_ONLINE, "Spieler nicht online"); addTranslatedMessage(CustomMessageId.INTEGER_PARAMETER_REQUIRED, "Integer parameter required"); addTranslatedMessage(CustomMessageId.INTEGER_PARAMETERS_ONLY, "Integer parameters only"); addTranslatedMessage(CustomMessageId.SOMETHING_WRONG_HAPPENED, "Etwas ging schief"); addTranslatedMessage(CustomMessageId.COMMAND_DISABLED, "Befehl deaktiviert"); addTranslatedMessage(CustomMessageId.COMMAND_ADD_SYNTAX, "Syntax: //add <player name> <itemid> [<amount>]"); addTranslatedMessage(CustomMessageId.COMMAND_ADD_ADMIN_SUCCESS, "Item erfolgreich dem Spieler %s hinzugefuegt "); addTranslatedMessage(CustomMessageId.COMMAND_ADD_PLAYER_SUCCESS, "Administrator %s give you %d item(s)"); addTranslatedMessage(CustomMessageId.COMMAND_ADD_FAILURE, "Item %d not exist or cant be added %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDDROP_SYNTAX, "Syntax: //adddrop <npc id> <itemid> <min> <max> <chance>"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_SYNTAX, "Syntax: //addset <player name> <id set>"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_SET_DOES_NOT_EXISTS, "Set %d not exist"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_NOT_ENOUGH_SLOTS, "Not enough inventory %d slots to add this set"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_CANNOT_ADD_ITEM, "Item %d can not be added to the %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_ADMIN_SUCCESS, "Set %d added success %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_PLAYER_SUCCESS, "%s give you set"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSKILL_SYNTAX, "Syntax: //addskill <skill id> <skill lvl"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSKILL_ADMIN_SUCCESS, "Skill %d added success %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSKILL_PLAYER_SUCCESS, "%s give you skill"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_SYNTAX, "Syntax: //addtitle <title id> <player name> [special]"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_TITLE_INVALID, "Title must be from 1 to 50"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_CANNOT_ADD_TITLE_TO_ME, "Cannot add title %d self"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_CANNOT_ADD_TITLE_TO_PLAYER, "Cannot add title %d to %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_ADMIN_SUCCESS_ME, "Title %d added success self"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_ADMIN_SUCCESS, "You success added title %d to player %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_PLAYER_SUCCESS, "%s give you title %d"); addTranslatedMessage(CustomMessageId.COMMAND_SEND_SYNTAX, "Syntax: //send <file name>"); addTranslatedMessage(CustomMessageId.COMMAND_SEND_MAPPING_NOT_FOUND, "%s not found"); addTranslatedMessage(CustomMessageId.COMMAND_SEND_NO_PACKET, "Send no packet"); addTranslatedMessage(CustomMessageId.CHANNEL_WORLD_DISABLED, "Channel %s disabled, use channel %s or %s based on your race"); addTranslatedMessage(CustomMessageId.CHANNEL_ALL_DISABLED, "All channels disabled"); addTranslatedMessage(CustomMessageId.CHANNEL_ALREADY_FIXED, "Your channel has been successfully installed %s"); addTranslatedMessage(CustomMessageId.CHANNEL_FIXED, "Installed channel %s"); addTranslatedMessage(CustomMessageId.CHANNEL_NOT_ALLOWED, "You cant use this channel"); addTranslatedMessage(CustomMessageId.CHANNEL_FIXED_BOTH, "Installed channels %s and %s"); addTranslatedMessage(CustomMessageId.CHANNEL_UNFIX_HELP, "Write %s to come out of the channel"); // ;) addTranslatedMessage(CustomMessageId.CHANNEL_NOT_FIXED, "You are not installed on the channel"); addTranslatedMessage(CustomMessageId.CHANNEL_FIXED_OTHER, "Your chat is not installed on this channel, but on %s"); addTranslatedMessage(CustomMessageId.CHANNEL_RELEASED, "You come out of the channel %s"); addTranslatedMessage(CustomMessageId.CHANNEL_RELEASED_BOTH, "You are out of %s and %s"); addTranslatedMessage(CustomMessageId.CHANNEL_BAN_ENDED, "You can rejoin the channels"); addTranslatedMessage(CustomMessageId.CHANNEL_BAN_ENDED_FOR, "Player %s may again join the channel"); addTranslatedMessage(CustomMessageId.CHANNEL_BANNED, "You can not access the channel, because %s ban you because of: %s, left to unlock: %s"); addTranslatedMessage(CustomMessageId.COMMAND_MISSING_SKILLS_STIGMAS_ADDED, "%d skill %d stigma given to you"); addTranslatedMessage(CustomMessageId.COMMAND_MISSING_SKILLS_ADDED, "%d ability given to you"); addTranslatedMessage(CustomMessageId.USER_COMMAND_DOES_NOT_EXIST, "This game command exists"); addTranslatedMessage(CustomMessageId.COMMAND_XP_DISABLED, "Accrual XP disabled. Enter. xpon to unlock"); addTranslatedMessage(CustomMessageId.COMMAND_XP_ALREADY_DISABLED, "Accrual XP disabled"); addTranslatedMessage(CustomMessageId.COMMAND_XP_ENABLED, "Accrual XP enabled"); addTranslatedMessage(CustomMessageId.COMMAND_XP_ALREADY_ENABLED, "Accrual XP already enabled"); addTranslatedMessage(CustomMessageId.DREDGION_LEVEL_TOO_LOW, "Ihr derzeitges Level ist zu niedrig, um in die Dredgion einzutreten."); addTranslatedMessage(CustomMessageId.DEFAULT_FINISH_MESSAGE, "Ende!"); /** * PvP Service */ addTranslatedMessage(CustomMessageId.ADV_WINNER_MSG, "[PvP System] Spieler getoetet "); addTranslatedMessage(CustomMessageId.ADV_LOSER_MSG, "[PvP System] Du wurdest getoetet von "); addTranslatedMessage(CustomMessageId.PLAP_LOST1, "[PL-AP] Du verlierst "); addTranslatedMessage(CustomMessageId.PLAP_LOST2, "% deiner totalen AP"); addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD1, "Du hast "); addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD2, " Toll erhalten."); addTranslatedMessage(CustomMessageId.PVP_NO_REWARD1, "Du bekommst nichts fuer das toeten von "); addTranslatedMessage(CustomMessageId.PVP_NO_REWARD2, " weil du ihn schon zu oft getoetet hast!"); addTranslatedMessage(CustomMessageId.EASY_MITHRIL_MSG, "[Mithril System] du bekamst: "); /** * Reward Service Login Messages */ addTranslatedMessage(CustomMessageId.REWARD10, "Du kannst .start benutzen um eine Level 10 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD30, "Du kannst .start benutzen um eine Level 30 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD40, "Du kannst .start benutzen um eine Level 40 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD50, "Du kannst .start benutzen um eine Level 50 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD60, "Du kannst .start benutzen um eine Level 60 Ausstattung zu bekommen!"); /** * Advanced PvP System */ addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE1, "Heutige PvP Map: Reshanta"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE2, "Heutige PvP Map: Tiamaranta"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE3, "Heutige PvP Map: Inggison/Gelkmaros"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE4, "Heutige PvP Map: Idian Depths"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE5, "Heutige PvP Map: Katalam"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE6, "Heutige PvP Map: Danaria"); /** * Asmo, Ely and World Channel */ addTranslatedMessage(CustomMessageId.ASMO_FAIL, "Du bist Elyos! Du kannst diesen Chat nicht benutzen. Nutze .ely <Nachricht> um im Fraktions Chat zu schreiben!"); addTranslatedMessage(CustomMessageId.ELY_FAIL, "Du bist Asmo! Du kannst diesen Chat nicht benutzen. Nutze .asmo <Nachricht> um im Fraktions Chat zu schreiben!"); /** * Wedding related */ addTranslatedMessage(CustomMessageId.WEDDINGNO1, "Du kannst dieses Kommando nicht waehrend des Kampfes nutzen!"); addTranslatedMessage(CustomMessageId.WEDDINGNO2, "Hochzeit wurde nicht gestartet!"); addTranslatedMessage(CustomMessageId.WEDDINGNO3, "Du hast die Heirat abgelehnt!"); addTranslatedMessage(CustomMessageId.WEDDINGYES, "Du hast die Heirat akzeptiert!"); /** * Clean Command related */ addTranslatedMessage(CustomMessageId.CANNOTCLEAN, "Du musst eine Item Id eingeben oder einen Link posten!"); addTranslatedMessage(CustomMessageId.CANNOTCLEAN2, "Du besitzt dieses Item nicht!"); addTranslatedMessage(CustomMessageId.SUCCESSCLEAN, "Item wurde erfolgreich aus deinem Wuerfel entfernt!"); /** * Mission check command related */ addTranslatedMessage(CustomMessageId.SUCCESCHECKED, "Mission erfolgreich ueberprueft!"); /** * No Exp Command */ addTranslatedMessage(CustomMessageId.EPACTIVATED, "Deine EP wurden wieder aktiviert!"); addTranslatedMessage(CustomMessageId.ACTODE, "Um deine EP zu deaktivieren, nutze .noexp"); addTranslatedMessage(CustomMessageId.EPDEACTIVATED, "Deine EP wurden deaktiviert!"); addTranslatedMessage(CustomMessageId.DETOAC, "Um deine EP zu aktivieren, nutze .noexp"); /** * Auto Quest Command */ addTranslatedMessage(CustomMessageId.WRONGQID, "Bitte gebe eine richtige Quest Id an!"); addTranslatedMessage(CustomMessageId.NOTSTARTED, "Quest konnte nicht gestartet werden!"); addTranslatedMessage(CustomMessageId.NOTSUPPORT, "Diese Quest wird nicht von diesem Kommando unterstuetzt!"); /** * Quest Restart Command */ addTranslatedMessage(CustomMessageId.CANNOTRESTART, "] kann nicht neugestartet werden"); /** * Exchange Toll Command */ addTranslatedMessage(CustomMessageId.TOLLTOBIG, "Du hast zu viele Toll!"); addTranslatedMessage(CustomMessageId.TOLOWAP, "Du hast nicht genug AP!"); addTranslatedMessage(CustomMessageId.TOLOWTOLL, "Du hast nicht genug Toll!"); addTranslatedMessage(CustomMessageId.WRONGTOLLNUM, "Irgendwas lief schief!"); /** * Cube Command */ addTranslatedMessage(CustomMessageId.CUBE_ALLREADY_EXPANDED, "Dein Wuerfel ist voll erweitert!"); addTranslatedMessage(CustomMessageId.CUBE_SUCCESS_EXPAND, "Dein Wuerfel wurde erfolgreich erweitert!"); /** * GMList Command */ addTranslatedMessage(CustomMessageId.ONE_GM_ONLINE, "Ein Team Mitglied ist online: "); addTranslatedMessage(CustomMessageId.MORE_GMS_ONLINE, "Es sind folgende Team Mitglieder online: "); addTranslatedMessage(CustomMessageId.NO_GM_ONLINE, "Es ist kein Team Mitglied online!"); /** * Go Command (PvP Command) */ addTranslatedMessage(CustomMessageId.NOT_USE_WHILE_FIGHT, "Du kannst dieses Kommando nicht waehrend des Kampfes nutzen!"); addTranslatedMessage(CustomMessageId.NOT_USE_ON_PVP_MAP, "Du kannst dieses Kommando nicht auf einer PvP Map benutzen!"); addTranslatedMessage(CustomMessageId.LEVEL_TOO_LOW, "Du kannst dieses Kommando nur mit Level 55 oder hoeher nutzen!"); /** * Paint Command */ addTranslatedMessage(CustomMessageId.WRONG_TARGET, "Bitte benutze ein erlaubtes Ziel!"); /** * Shiva Command */ addTranslatedMessage(CustomMessageId.ENCHANT_SUCCES, "Alle deine Items wurden verzaubert auf: "); addTranslatedMessage(CustomMessageId.ENCHANT_INFO, "Info: Dieses Kommando verzaubert alle deine Items auf <value>!"); addTranslatedMessage(CustomMessageId.ENCHANT_SAMPLE, "Beispiel: (.eq 15) wuerde alle deine Items auf 15 verzaubern"); /** * Userinfo Command */ addTranslatedMessage(CustomMessageId.CANNOT_SPY_PLAYER, "Du kannst keine Infos von anderen Spielern bekommen!"); /** * Check AFK Status */ addTranslatedMessage(CustomMessageId.KICKED_AFK_OUT, "You have been kicked out for being inactive too long."); /** * Exchange Command */ addTranslatedMessage(CustomMessageId.NOT_ENOUGH_ITEM, "Sie besitzen nicht genug von: "); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_AP, "Sie besitzen nicht genug AP, Sie haben nur: "); /** * Medal Command */ addTranslatedMessage(CustomMessageId.NOT_ENOUGH_SILVER, "Sie besitzen nicht genug Silber Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_GOLD, "Sie besitzen nicht genug Gold Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_PLATIN, "Sie besitzen nicht genug Platin Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_MITHRIL, "Sie besitzen nicht genug Mithril Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_AP2, "Sie besitzen nicht genug AP, Sie benoetigen: "); addTranslatedMessage(CustomMessageId.EXCHANGE_SILVER, "You have exchange [item:186000031] to [item:186000030]."); addTranslatedMessage(CustomMessageId.EXCHANGE_GOLD, "You have exchange [item:186000030] to [item:186000096]."); addTranslatedMessage(CustomMessageId.EXCHANGE_PLATIN, "You have exchange [item:186000096] to [item:186000147]."); addTranslatedMessage(CustomMessageId.EXCHANGE_MITHRIL, "You have exchange [item:186000147] to [item:186000223]."); addTranslatedMessage(CustomMessageId.EX_SILVER_INFO, "\nSyntax: .medal silver - Exchange Silver to Gold."); addTranslatedMessage(CustomMessageId.EX_GOLD_INFO, "\nSyntax: .medal gold - Exchange Gold to Platin."); addTranslatedMessage(CustomMessageId.EX_PLATIN_INFO, "\nSyntax: .medal platinum - Exchnage Platin to Mithril."); addTranslatedMessage(CustomMessageId.EX_MITHRIL_INFO, "\nSyntax: .medal mithril - Exchange Mithril to Honorable Mithril."); /** * Legendary Raid Spawn Events */ addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_SPAWNED_ASMO, "[Spawn Event] Ragnarok ist fuer die Asmodier in Beluslan erschienen!"); addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_SPAWNED_ELYOS, "[Spawn Event] Omega ist fuer die Elyos in Heiron erschienen!"); addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_DESPAWNED_ASMO, "[Spawn Event] Ragnarok ist verschwunden, niemand hat ihn getoetet!"); addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_DESPAWNED_ELYOS, "[Spawn Event] Omega ist verschwunden, niemand hat ihn getoetet!"); /** * HonorItems Command */ addTranslatedMessage(CustomMessageId.PLATE_ARMOR, "Platten Ruestung"); addTranslatedMessage(CustomMessageId.LEATHER_ARMOR, "Leder Ruestung"); addTranslatedMessage(CustomMessageId.CLOTH_ARMOR, "Stoff Ruestung"); addTranslatedMessage(CustomMessageId.CHAIN_ARMOR, "Ketten Ruestung"); addTranslatedMessage(CustomMessageId.WEAPONS, "Waffen"); addTranslatedMessage(CustomMessageId.PLATE_ARMOR_PRICES, "Platten ruestungs Preis"); addTranslatedMessage(CustomMessageId.LEATHER_ARMOR_PRICES, "Leder Ruestungs Preis"); addTranslatedMessage(CustomMessageId.CLOTH_ARMOR_PRICES, "Stoff Ruestung Preis"); addTranslatedMessage(CustomMessageId.CHAIN_ARMOR_PRICES, "Ketten Ruestungs Preis"); addTranslatedMessage(CustomMessageId.WEAPONS_PRICES, "Waffen Preis"); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_MEDALS, "Sie besitzen nicht genuegend Medaillen, Sie benoetigen: "); addTranslatedMessage(CustomMessageId.PLATE_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 1"); addTranslatedMessage(CustomMessageId.LEATHER_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 6"); addTranslatedMessage(CustomMessageId.CLOTH_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 11"); addTranslatedMessage(CustomMessageId.CHAIN_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 16"); addTranslatedMessage(CustomMessageId.WEAPONS_USE_INFO, "Use .items and the equal ID (Example: .items 21"); addTranslatedMessage(CustomMessageId.SUCCESSFULLY_TRADED, "You got successfully your Trade!"); /** * Moltenus Announce */ addTranslatedMessage(CustomMessageId.MOLTENUS_APPEAR, "Moltenus Fragment of the Wrath ist im Abyss erschienen."); addTranslatedMessage(CustomMessageId.MOLTENUS_DISAPPEAR, "Moltenus Fragment of the Wrath ist verschwunden."); /** * Dredgion Announce */ addTranslatedMessage(CustomMessageId.DREDGION_ASMO_GROUP, "An asmodian group is waiting for dredgion."); addTranslatedMessage(CustomMessageId.DREDGION_ELYOS_GROUP, "An elyos group is waiting for dredgion."); addTranslatedMessage(CustomMessageId.DREDGION_ASMO, "An alone asmodian is waiting for dredgion."); addTranslatedMessage(CustomMessageId.DREDGION_ELYOS, "An alone elyos is waiting for dredgion."); /** * PvP Service */ addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD1, "Sie haben verdient"); addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD2, " Abyss Punkte."); /** * Invasion Rift */ addTranslatedMessage(CustomMessageId.INVASION_RIFT_MIN_LEVEL, "Dein Level ist zu niedrig um zu passieren."); addTranslatedMessage(CustomMessageId.INVASION_RIFT_ELYOS, "A rift for Pandaemonium is open at Ingisson"); addTranslatedMessage(CustomMessageId.INVASION_RIFT_ASMOS, "A rift for Sanctum is open at Gelkmaros"); /** * PvP Spree Service */ addTranslatedMessage(CustomMessageId.SPREE1, "Blutiger Sturm"); addTranslatedMessage(CustomMessageId.SPREE2, "Blutbad"); addTranslatedMessage(CustomMessageId.SPREE3, "Voelkermord"); addTranslatedMessage(CustomMessageId.KILL_COUNT, "Kills in Folge: "); addTranslatedMessage(CustomMessageId.CUSTOM_MSG1, " von "); addTranslatedMessage(CustomMessageId.MSG_SPREE1, " hat begonnen ein "); addTranslatedMessage(CustomMessageId.MSG_SPREE1_1, " !"); addTranslatedMessage(CustomMessageId.MSG_SPREE2, " fuehrt eine echte "); addTranslatedMessage(CustomMessageId.MSG_SPREE2_1, " ! Haltet ihn schnell !"); addTranslatedMessage(CustomMessageId.MSG_SPREE3, " tut ein "); addTranslatedMessage(CustomMessageId.MSG_SPREE3_1, " ! Lauf weg, wenn du kannst!"); addTranslatedMessage(CustomMessageId.SPREE_END_MSG1, "Der Amoklauf von "); addTranslatedMessage(CustomMessageId.SPREE_END_MSG2, " wurde gestoppt von "); addTranslatedMessage(CustomMessageId.SPREE_END_MSG3, " nach "); addTranslatedMessage(CustomMessageId.SPREE_END_MSG4, " ununterbrochene Morde !"); addTranslatedMessage(CustomMessageId.SPREE_MONSTER_MSG, "ein Monster"); /** * EventEngine - EventUtil */ addTranslatedMessage(CustomMessageId.Event_Util_1, "Du kannst diesen Befehl nicht verwenden."); addTranslatedMessage(CustomMessageId.Event_Util_2, "Falsche Event Typ."); addTranslatedMessage(CustomMessageId.Event_Util_3, "Unbekannter Benutzer."); /** * EventEngine - Event */ addTranslatedMessage(CustomMessageId.Event_1, "Du kannst an diesem Event nicht teilnehmen, waehrend du im Gefaengnis bist, oder in Kampfzustand."); } }
DeKaDeNcE/Aion-Dream
AL-Game/data/scripts/system/handlers/languages/German.java
7,374
/** * EventEngine - Event */
block_comment
nl
/** * 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 2 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 languages; import com.aionemu.gameserver.utils.i18n.CustomMessageId; import com.aionemu.gameserver.utils.i18n.Language; /** * @author Eloann * @reworked Voidstar */ public class German extends Language { public German() { super("de"); addSupportedLanguage("de_DE"); addTranslatedMessage(CustomMessageId.SERVER_REVISION, "Server Version : %-6s"); addTranslatedMessage(CustomMessageId.WELCOME_PREMIUM, "Willkommen bei "); addTranslatedMessage(CustomMessageId.WELCOME_REGULAR, "Willkommen bei "); addTranslatedMessage(CustomMessageId.WELCOME_BASIC, "Willkommen bei "); addTranslatedMessage(CustomMessageId.INFO1, "Warnung: Benutzung von fremde software, wie (speed hack&Co ist strengst verboten."); addTranslatedMessage(CustomMessageId.INFO2, "Hinweis: Je nach Fall, fuehrt ausnahmslos zu unbefristete Account Sperrung."); addTranslatedMessage(CustomMessageId.INFO3, "Warnung: Werben anderer Aion Server oder abwerben von Spieler hier auf dem Server, ist untersagt."); addTranslatedMessage(CustomMessageId.INFO4, "Anmerkung: Das Team wird Sie niemals nach Ihrem Account Passwort fragen!"); addTranslatedMessage(CustomMessageId.INFO5, "Chat: Benutze .faction, .ely, ,asmo <text> um im Chat zu schreiben. "); addTranslatedMessage(CustomMessageId.INFO6, "Chat: Benutze /1 /2 /3, um in den Chatkanaelen zu schreiben."); addTranslatedMessage(CustomMessageId.INFO7, "Befehle: Benutze .help, um zu sehen welche Spielerbefehle noch zur Verfuegung stehen."); addTranslatedMessage(CustomMessageId.SERVERVERSION, "Supported NCSoft Version "); addTranslatedMessage(CustomMessageId.ENDMESSAGE, "Viel Spass auf unserem Server: "); addTranslatedMessage(CustomMessageId.ANNOUNCE_GM_CONNECTION, " Ist jetzt fuer den Support verfuegbar!"); addTranslatedMessage(CustomMessageId.ANNOUNCE_GM_DECONNECTION, " Ist fuer den Support nicht mehr verfuegbar!"); addTranslatedMessage(CustomMessageId.ANNOUNCE_MEMBER_CONNECTION, "%s ist der Welt von Atreia beigetreten."); addTranslatedMessage(CustomMessageId.COMMAND_NOT_ENOUGH_RIGHTS, "Sie haben keine Berechtigung zur Verwendung dieses Befehls"); addTranslatedMessage(CustomMessageId.PLAYER_NOT_ONLINE, "Spieler nicht online"); addTranslatedMessage(CustomMessageId.INTEGER_PARAMETER_REQUIRED, "Integer parameter required"); addTranslatedMessage(CustomMessageId.INTEGER_PARAMETERS_ONLY, "Integer parameters only"); addTranslatedMessage(CustomMessageId.SOMETHING_WRONG_HAPPENED, "Etwas ging schief"); addTranslatedMessage(CustomMessageId.COMMAND_DISABLED, "Befehl deaktiviert"); addTranslatedMessage(CustomMessageId.COMMAND_ADD_SYNTAX, "Syntax: //add <player name> <itemid> [<amount>]"); addTranslatedMessage(CustomMessageId.COMMAND_ADD_ADMIN_SUCCESS, "Item erfolgreich dem Spieler %s hinzugefuegt "); addTranslatedMessage(CustomMessageId.COMMAND_ADD_PLAYER_SUCCESS, "Administrator %s give you %d item(s)"); addTranslatedMessage(CustomMessageId.COMMAND_ADD_FAILURE, "Item %d not exist or cant be added %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDDROP_SYNTAX, "Syntax: //adddrop <npc id> <itemid> <min> <max> <chance>"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_SYNTAX, "Syntax: //addset <player name> <id set>"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_SET_DOES_NOT_EXISTS, "Set %d not exist"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_NOT_ENOUGH_SLOTS, "Not enough inventory %d slots to add this set"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_CANNOT_ADD_ITEM, "Item %d can not be added to the %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_ADMIN_SUCCESS, "Set %d added success %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_PLAYER_SUCCESS, "%s give you set"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSKILL_SYNTAX, "Syntax: //addskill <skill id> <skill lvl"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSKILL_ADMIN_SUCCESS, "Skill %d added success %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSKILL_PLAYER_SUCCESS, "%s give you skill"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_SYNTAX, "Syntax: //addtitle <title id> <player name> [special]"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_TITLE_INVALID, "Title must be from 1 to 50"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_CANNOT_ADD_TITLE_TO_ME, "Cannot add title %d self"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_CANNOT_ADD_TITLE_TO_PLAYER, "Cannot add title %d to %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_ADMIN_SUCCESS_ME, "Title %d added success self"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_ADMIN_SUCCESS, "You success added title %d to player %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_PLAYER_SUCCESS, "%s give you title %d"); addTranslatedMessage(CustomMessageId.COMMAND_SEND_SYNTAX, "Syntax: //send <file name>"); addTranslatedMessage(CustomMessageId.COMMAND_SEND_MAPPING_NOT_FOUND, "%s not found"); addTranslatedMessage(CustomMessageId.COMMAND_SEND_NO_PACKET, "Send no packet"); addTranslatedMessage(CustomMessageId.CHANNEL_WORLD_DISABLED, "Channel %s disabled, use channel %s or %s based on your race"); addTranslatedMessage(CustomMessageId.CHANNEL_ALL_DISABLED, "All channels disabled"); addTranslatedMessage(CustomMessageId.CHANNEL_ALREADY_FIXED, "Your channel has been successfully installed %s"); addTranslatedMessage(CustomMessageId.CHANNEL_FIXED, "Installed channel %s"); addTranslatedMessage(CustomMessageId.CHANNEL_NOT_ALLOWED, "You cant use this channel"); addTranslatedMessage(CustomMessageId.CHANNEL_FIXED_BOTH, "Installed channels %s and %s"); addTranslatedMessage(CustomMessageId.CHANNEL_UNFIX_HELP, "Write %s to come out of the channel"); // ;) addTranslatedMessage(CustomMessageId.CHANNEL_NOT_FIXED, "You are not installed on the channel"); addTranslatedMessage(CustomMessageId.CHANNEL_FIXED_OTHER, "Your chat is not installed on this channel, but on %s"); addTranslatedMessage(CustomMessageId.CHANNEL_RELEASED, "You come out of the channel %s"); addTranslatedMessage(CustomMessageId.CHANNEL_RELEASED_BOTH, "You are out of %s and %s"); addTranslatedMessage(CustomMessageId.CHANNEL_BAN_ENDED, "You can rejoin the channels"); addTranslatedMessage(CustomMessageId.CHANNEL_BAN_ENDED_FOR, "Player %s may again join the channel"); addTranslatedMessage(CustomMessageId.CHANNEL_BANNED, "You can not access the channel, because %s ban you because of: %s, left to unlock: %s"); addTranslatedMessage(CustomMessageId.COMMAND_MISSING_SKILLS_STIGMAS_ADDED, "%d skill %d stigma given to you"); addTranslatedMessage(CustomMessageId.COMMAND_MISSING_SKILLS_ADDED, "%d ability given to you"); addTranslatedMessage(CustomMessageId.USER_COMMAND_DOES_NOT_EXIST, "This game command exists"); addTranslatedMessage(CustomMessageId.COMMAND_XP_DISABLED, "Accrual XP disabled. Enter. xpon to unlock"); addTranslatedMessage(CustomMessageId.COMMAND_XP_ALREADY_DISABLED, "Accrual XP disabled"); addTranslatedMessage(CustomMessageId.COMMAND_XP_ENABLED, "Accrual XP enabled"); addTranslatedMessage(CustomMessageId.COMMAND_XP_ALREADY_ENABLED, "Accrual XP already enabled"); addTranslatedMessage(CustomMessageId.DREDGION_LEVEL_TOO_LOW, "Ihr derzeitges Level ist zu niedrig, um in die Dredgion einzutreten."); addTranslatedMessage(CustomMessageId.DEFAULT_FINISH_MESSAGE, "Ende!"); /** * PvP Service */ addTranslatedMessage(CustomMessageId.ADV_WINNER_MSG, "[PvP System] Spieler getoetet "); addTranslatedMessage(CustomMessageId.ADV_LOSER_MSG, "[PvP System] Du wurdest getoetet von "); addTranslatedMessage(CustomMessageId.PLAP_LOST1, "[PL-AP] Du verlierst "); addTranslatedMessage(CustomMessageId.PLAP_LOST2, "% deiner totalen AP"); addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD1, "Du hast "); addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD2, " Toll erhalten."); addTranslatedMessage(CustomMessageId.PVP_NO_REWARD1, "Du bekommst nichts fuer das toeten von "); addTranslatedMessage(CustomMessageId.PVP_NO_REWARD2, " weil du ihn schon zu oft getoetet hast!"); addTranslatedMessage(CustomMessageId.EASY_MITHRIL_MSG, "[Mithril System] du bekamst: "); /** * Reward Service Login Messages */ addTranslatedMessage(CustomMessageId.REWARD10, "Du kannst .start benutzen um eine Level 10 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD30, "Du kannst .start benutzen um eine Level 30 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD40, "Du kannst .start benutzen um eine Level 40 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD50, "Du kannst .start benutzen um eine Level 50 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD60, "Du kannst .start benutzen um eine Level 60 Ausstattung zu bekommen!"); /** * Advanced PvP System */ addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE1, "Heutige PvP Map: Reshanta"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE2, "Heutige PvP Map: Tiamaranta"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE3, "Heutige PvP Map: Inggison/Gelkmaros"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE4, "Heutige PvP Map: Idian Depths"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE5, "Heutige PvP Map: Katalam"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE6, "Heutige PvP Map: Danaria"); /** * Asmo, Ely and World Channel */ addTranslatedMessage(CustomMessageId.ASMO_FAIL, "Du bist Elyos! Du kannst diesen Chat nicht benutzen. Nutze .ely <Nachricht> um im Fraktions Chat zu schreiben!"); addTranslatedMessage(CustomMessageId.ELY_FAIL, "Du bist Asmo! Du kannst diesen Chat nicht benutzen. Nutze .asmo <Nachricht> um im Fraktions Chat zu schreiben!"); /** * Wedding related */ addTranslatedMessage(CustomMessageId.WEDDINGNO1, "Du kannst dieses Kommando nicht waehrend des Kampfes nutzen!"); addTranslatedMessage(CustomMessageId.WEDDINGNO2, "Hochzeit wurde nicht gestartet!"); addTranslatedMessage(CustomMessageId.WEDDINGNO3, "Du hast die Heirat abgelehnt!"); addTranslatedMessage(CustomMessageId.WEDDINGYES, "Du hast die Heirat akzeptiert!"); /** * Clean Command related */ addTranslatedMessage(CustomMessageId.CANNOTCLEAN, "Du musst eine Item Id eingeben oder einen Link posten!"); addTranslatedMessage(CustomMessageId.CANNOTCLEAN2, "Du besitzt dieses Item nicht!"); addTranslatedMessage(CustomMessageId.SUCCESSCLEAN, "Item wurde erfolgreich aus deinem Wuerfel entfernt!"); /** * Mission check command related */ addTranslatedMessage(CustomMessageId.SUCCESCHECKED, "Mission erfolgreich ueberprueft!"); /** * No Exp Command */ addTranslatedMessage(CustomMessageId.EPACTIVATED, "Deine EP wurden wieder aktiviert!"); addTranslatedMessage(CustomMessageId.ACTODE, "Um deine EP zu deaktivieren, nutze .noexp"); addTranslatedMessage(CustomMessageId.EPDEACTIVATED, "Deine EP wurden deaktiviert!"); addTranslatedMessage(CustomMessageId.DETOAC, "Um deine EP zu aktivieren, nutze .noexp"); /** * Auto Quest Command */ addTranslatedMessage(CustomMessageId.WRONGQID, "Bitte gebe eine richtige Quest Id an!"); addTranslatedMessage(CustomMessageId.NOTSTARTED, "Quest konnte nicht gestartet werden!"); addTranslatedMessage(CustomMessageId.NOTSUPPORT, "Diese Quest wird nicht von diesem Kommando unterstuetzt!"); /** * Quest Restart Command */ addTranslatedMessage(CustomMessageId.CANNOTRESTART, "] kann nicht neugestartet werden"); /** * Exchange Toll Command */ addTranslatedMessage(CustomMessageId.TOLLTOBIG, "Du hast zu viele Toll!"); addTranslatedMessage(CustomMessageId.TOLOWAP, "Du hast nicht genug AP!"); addTranslatedMessage(CustomMessageId.TOLOWTOLL, "Du hast nicht genug Toll!"); addTranslatedMessage(CustomMessageId.WRONGTOLLNUM, "Irgendwas lief schief!"); /** * Cube Command */ addTranslatedMessage(CustomMessageId.CUBE_ALLREADY_EXPANDED, "Dein Wuerfel ist voll erweitert!"); addTranslatedMessage(CustomMessageId.CUBE_SUCCESS_EXPAND, "Dein Wuerfel wurde erfolgreich erweitert!"); /** * GMList Command */ addTranslatedMessage(CustomMessageId.ONE_GM_ONLINE, "Ein Team Mitglied ist online: "); addTranslatedMessage(CustomMessageId.MORE_GMS_ONLINE, "Es sind folgende Team Mitglieder online: "); addTranslatedMessage(CustomMessageId.NO_GM_ONLINE, "Es ist kein Team Mitglied online!"); /** * Go Command (PvP Command) */ addTranslatedMessage(CustomMessageId.NOT_USE_WHILE_FIGHT, "Du kannst dieses Kommando nicht waehrend des Kampfes nutzen!"); addTranslatedMessage(CustomMessageId.NOT_USE_ON_PVP_MAP, "Du kannst dieses Kommando nicht auf einer PvP Map benutzen!"); addTranslatedMessage(CustomMessageId.LEVEL_TOO_LOW, "Du kannst dieses Kommando nur mit Level 55 oder hoeher nutzen!"); /** * Paint Command */ addTranslatedMessage(CustomMessageId.WRONG_TARGET, "Bitte benutze ein erlaubtes Ziel!"); /** * Shiva Command */ addTranslatedMessage(CustomMessageId.ENCHANT_SUCCES, "Alle deine Items wurden verzaubert auf: "); addTranslatedMessage(CustomMessageId.ENCHANT_INFO, "Info: Dieses Kommando verzaubert alle deine Items auf <value>!"); addTranslatedMessage(CustomMessageId.ENCHANT_SAMPLE, "Beispiel: (.eq 15) wuerde alle deine Items auf 15 verzaubern"); /** * Userinfo Command */ addTranslatedMessage(CustomMessageId.CANNOT_SPY_PLAYER, "Du kannst keine Infos von anderen Spielern bekommen!"); /** * Check AFK Status */ addTranslatedMessage(CustomMessageId.KICKED_AFK_OUT, "You have been kicked out for being inactive too long."); /** * Exchange Command */ addTranslatedMessage(CustomMessageId.NOT_ENOUGH_ITEM, "Sie besitzen nicht genug von: "); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_AP, "Sie besitzen nicht genug AP, Sie haben nur: "); /** * Medal Command */ addTranslatedMessage(CustomMessageId.NOT_ENOUGH_SILVER, "Sie besitzen nicht genug Silber Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_GOLD, "Sie besitzen nicht genug Gold Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_PLATIN, "Sie besitzen nicht genug Platin Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_MITHRIL, "Sie besitzen nicht genug Mithril Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_AP2, "Sie besitzen nicht genug AP, Sie benoetigen: "); addTranslatedMessage(CustomMessageId.EXCHANGE_SILVER, "You have exchange [item:186000031] to [item:186000030]."); addTranslatedMessage(CustomMessageId.EXCHANGE_GOLD, "You have exchange [item:186000030] to [item:186000096]."); addTranslatedMessage(CustomMessageId.EXCHANGE_PLATIN, "You have exchange [item:186000096] to [item:186000147]."); addTranslatedMessage(CustomMessageId.EXCHANGE_MITHRIL, "You have exchange [item:186000147] to [item:186000223]."); addTranslatedMessage(CustomMessageId.EX_SILVER_INFO, "\nSyntax: .medal silver - Exchange Silver to Gold."); addTranslatedMessage(CustomMessageId.EX_GOLD_INFO, "\nSyntax: .medal gold - Exchange Gold to Platin."); addTranslatedMessage(CustomMessageId.EX_PLATIN_INFO, "\nSyntax: .medal platinum - Exchnage Platin to Mithril."); addTranslatedMessage(CustomMessageId.EX_MITHRIL_INFO, "\nSyntax: .medal mithril - Exchange Mithril to Honorable Mithril."); /** * Legendary Raid Spawn Events */ addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_SPAWNED_ASMO, "[Spawn Event] Ragnarok ist fuer die Asmodier in Beluslan erschienen!"); addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_SPAWNED_ELYOS, "[Spawn Event] Omega ist fuer die Elyos in Heiron erschienen!"); addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_DESPAWNED_ASMO, "[Spawn Event] Ragnarok ist verschwunden, niemand hat ihn getoetet!"); addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_DESPAWNED_ELYOS, "[Spawn Event] Omega ist verschwunden, niemand hat ihn getoetet!"); /** * HonorItems Command */ addTranslatedMessage(CustomMessageId.PLATE_ARMOR, "Platten Ruestung"); addTranslatedMessage(CustomMessageId.LEATHER_ARMOR, "Leder Ruestung"); addTranslatedMessage(CustomMessageId.CLOTH_ARMOR, "Stoff Ruestung"); addTranslatedMessage(CustomMessageId.CHAIN_ARMOR, "Ketten Ruestung"); addTranslatedMessage(CustomMessageId.WEAPONS, "Waffen"); addTranslatedMessage(CustomMessageId.PLATE_ARMOR_PRICES, "Platten ruestungs Preis"); addTranslatedMessage(CustomMessageId.LEATHER_ARMOR_PRICES, "Leder Ruestungs Preis"); addTranslatedMessage(CustomMessageId.CLOTH_ARMOR_PRICES, "Stoff Ruestung Preis"); addTranslatedMessage(CustomMessageId.CHAIN_ARMOR_PRICES, "Ketten Ruestungs Preis"); addTranslatedMessage(CustomMessageId.WEAPONS_PRICES, "Waffen Preis"); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_MEDALS, "Sie besitzen nicht genuegend Medaillen, Sie benoetigen: "); addTranslatedMessage(CustomMessageId.PLATE_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 1"); addTranslatedMessage(CustomMessageId.LEATHER_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 6"); addTranslatedMessage(CustomMessageId.CLOTH_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 11"); addTranslatedMessage(CustomMessageId.CHAIN_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 16"); addTranslatedMessage(CustomMessageId.WEAPONS_USE_INFO, "Use .items and the equal ID (Example: .items 21"); addTranslatedMessage(CustomMessageId.SUCCESSFULLY_TRADED, "You got successfully your Trade!"); /** * Moltenus Announce */ addTranslatedMessage(CustomMessageId.MOLTENUS_APPEAR, "Moltenus Fragment of the Wrath ist im Abyss erschienen."); addTranslatedMessage(CustomMessageId.MOLTENUS_DISAPPEAR, "Moltenus Fragment of the Wrath ist verschwunden."); /** * Dredgion Announce */ addTranslatedMessage(CustomMessageId.DREDGION_ASMO_GROUP, "An asmodian group is waiting for dredgion."); addTranslatedMessage(CustomMessageId.DREDGION_ELYOS_GROUP, "An elyos group is waiting for dredgion."); addTranslatedMessage(CustomMessageId.DREDGION_ASMO, "An alone asmodian is waiting for dredgion."); addTranslatedMessage(CustomMessageId.DREDGION_ELYOS, "An alone elyos is waiting for dredgion."); /** * PvP Service */ addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD1, "Sie haben verdient"); addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD2, " Abyss Punkte."); /** * Invasion Rift */ addTranslatedMessage(CustomMessageId.INVASION_RIFT_MIN_LEVEL, "Dein Level ist zu niedrig um zu passieren."); addTranslatedMessage(CustomMessageId.INVASION_RIFT_ELYOS, "A rift for Pandaemonium is open at Ingisson"); addTranslatedMessage(CustomMessageId.INVASION_RIFT_ASMOS, "A rift for Sanctum is open at Gelkmaros"); /** * PvP Spree Service */ addTranslatedMessage(CustomMessageId.SPREE1, "Blutiger Sturm"); addTranslatedMessage(CustomMessageId.SPREE2, "Blutbad"); addTranslatedMessage(CustomMessageId.SPREE3, "Voelkermord"); addTranslatedMessage(CustomMessageId.KILL_COUNT, "Kills in Folge: "); addTranslatedMessage(CustomMessageId.CUSTOM_MSG1, " von "); addTranslatedMessage(CustomMessageId.MSG_SPREE1, " hat begonnen ein "); addTranslatedMessage(CustomMessageId.MSG_SPREE1_1, " !"); addTranslatedMessage(CustomMessageId.MSG_SPREE2, " fuehrt eine echte "); addTranslatedMessage(CustomMessageId.MSG_SPREE2_1, " ! Haltet ihn schnell !"); addTranslatedMessage(CustomMessageId.MSG_SPREE3, " tut ein "); addTranslatedMessage(CustomMessageId.MSG_SPREE3_1, " ! Lauf weg, wenn du kannst!"); addTranslatedMessage(CustomMessageId.SPREE_END_MSG1, "Der Amoklauf von "); addTranslatedMessage(CustomMessageId.SPREE_END_MSG2, " wurde gestoppt von "); addTranslatedMessage(CustomMessageId.SPREE_END_MSG3, " nach "); addTranslatedMessage(CustomMessageId.SPREE_END_MSG4, " ununterbrochene Morde !"); addTranslatedMessage(CustomMessageId.SPREE_MONSTER_MSG, "ein Monster"); /** * EventEngine - EventUtil */ addTranslatedMessage(CustomMessageId.Event_Util_1, "Du kannst diesen Befehl nicht verwenden."); addTranslatedMessage(CustomMessageId.Event_Util_2, "Falsche Event Typ."); addTranslatedMessage(CustomMessageId.Event_Util_3, "Unbekannter Benutzer."); /** * EventEngine - Event <SUF>*/ addTranslatedMessage(CustomMessageId.Event_1, "Du kannst an diesem Event nicht teilnehmen, waehrend du im Gefaengnis bist, oder in Kampfzustand."); } }
79355_1
package view.panels; import controller.Controller; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import model.Artikel; import model.Observer; import model.db.DBService; import model.db.DbExeption; import java.util.Optional; public class WinkelkarPane extends GridPane implements Observer{ private Button btnOK, btnCancel,btnStore,btnLoad,btnAfsluit,btnBetaald,btnAnul; private TableView table; private Controller controller; private TextField artikelScanField; private Double totaalBedrag=0.0; private Label totaalLable; private Label infoLable; private SimpleStringProperty simpleStringProperty,afsluitString; // private ObservableList<Artikel> gescandeArtikels = FXCollections.observableArrayList() ; public WinkelkarPane(Controller controller) { this.controller = controller; this.simpleStringProperty = new SimpleStringProperty("Nog Geen Artikelen Gescand"); this.afsluitString = new SimpleStringProperty(""); this.setPrefHeight(150); this.setPrefWidth(300); controller.registerDBObserver(this); this.setPadding(new Insets(5, 5, 5, 5)); this.setVgap(5); this.setHgap(5); //TEXTFIELD this.add(new Label("Winkelkar :"), 0, 0, 1, 1); artikelScanField = new TextField(); this.add(artikelScanField, 1, 0, 1, 1); setEnterKeyAction(new EnterKeyListener()); totaalLable = new Label(); totaalLable.textProperty().bind(simpleStringProperty); this.add(totaalLable,4,5,1,1); infoLable = new Label("Dubbelklik een artikel om het te verwijderen."); this.add(infoLable,1,5,1,1); // totaalBedragLable = new Label("Totaal: "); // totaalBedragLable.textProperty().bind(); // this.add(new Label("Totaal Bedrag= " + totaalBedrag ),0,6,1,1); btnCancel = new Button("Close"); this.add(btnCancel, 0, 2, 1, 1); setCancelAction(new CancelListener()); btnOK = new Button("Scan"); btnOK.isDefaultButton(); this.add(btnOK, 1, 2, 1, 1); setSaveAction(new SaveListener()); btnStore = new Button("Store"); btnStore.isDefaultButton(); this.add(btnStore, 2, 2, 1, 1); setStoreAction(new StoreListener()); btnLoad = new Button("Load"); btnLoad.isDefaultButton(); this.add(btnLoad, 3, 2, 1, 1); setLoadAction(new LoadListener()); btnAfsluit = new Button("Afsluit"); btnAfsluit.isDefaultButton(); this.add(btnAfsluit, 4, 2, 1, 1); setAfsluitAction(new AfsluitListener()); btnBetaald = new Button("Betaald"); btnBetaald.isDefaultButton(); this.add(btnBetaald, 5, 2, 1, 1); setBetaaldAction(new BetaaldListener()); btnAnul = new Button("Anuleer"); btnAnul.isDefaultButton(); this.add(btnAnul, 6, 2, 1, 1); setAnuleerAction(new AnuleerListener()); //TABLE //BLIJKBAAR ALLEEN ARTIKEL EN PRIJS DIT NOG AANPASSEN VOOR FINAL PUSH table = new TableView<>(); table.setPrefWidth(REMAINING); TableColumn codeCol = new TableColumn<>("Code"); codeCol.setCellValueFactory(new PropertyValueFactory<>("Code")); table.getColumns().add(codeCol); TableColumn omschrijvingCol = new TableColumn<>("omschrijving"); omschrijvingCol.setCellValueFactory(new PropertyValueFactory("omschrijving")); table.getColumns().add(omschrijvingCol); TableColumn artikelGroepCol = new TableColumn<>("artikelGroep"); artikelGroepCol.setCellValueFactory(new PropertyValueFactory("artikelGroep")); table.getColumns().add(artikelGroepCol); TableColumn verkoopprijsCol = new TableColumn<>("verkoopprijs"); verkoopprijsCol.setCellValueFactory(new PropertyValueFactory("verkoopprijs")); table.getColumns().add(verkoopprijsCol); TableColumn voorraadCol = new TableColumn<>("voorraad"); voorraadCol.setCellValueFactory(new PropertyValueFactory("voorraad")); table.getColumns().add(voorraadCol); setKlickOnTableAction(new KlickOnTableListener()); this.add(table, 0, 3, 5, 2); Label label = new Label(""); label.textProperty().bind(afsluitString); this.add(label,0,6,1,1); ObservableList<Artikel> data = FXCollections.observableArrayList(controller.getWinkelKarArtikels()); table.setItems(data); } @Override public void update() { ObservableList<Artikel> data = FXCollections.observableArrayList(controller.getWinkelKarArtikels()); table.setItems(data); totaalBedrag = round( controller.getTotaalMetKortingen(),2); simpleStringProperty.setValue("Totaal= €"+totaalBedrag.toString()); if(DBService.getInstance().getKorting() != null){ simpleStringProperty.setValue("Totaal= €"+totaalBedrag.toString()+" (Met korting)"); } } class SaveListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { Artikel artikel = null; ScanArtikel(); } } class CancelListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { final Node source = (Node) e.getSource(); final Stage stage = (Stage) source.getScene().getWindow(); Platform.exit(); } } class EnterKeyListener implements EventHandler<KeyEvent>{ @Override public void handle(KeyEvent event) { if (event.getCode().equals(KeyCode.ENTER)) { Artikel artikel = null; ScanArtikel(); } } } class KlickOnTableListener implements EventHandler<MouseEvent>{ @Override public void handle(MouseEvent mouseEvent) { if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ if(mouseEvent.getClickCount() == 2){ int n = table.getSelectionModel().getFocusedIndex(); Alert alert = new Alert(Alert.AlertType.CONFIRMATION,"Do you want to delete this Item: \n" + "\n code= " +controller.getWinkelKarArtikels().get(n).getCode()+"\n\r plaats= "+(n+1), ButtonType.CLOSE,ButtonType.APPLY); alert.setTitle("DELETE"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.APPLY){ controller.getWinkelKarArtikels().get(n).verlaagAantalInKar(); controller.removeWithIndexFromWinkelkar(n); DBService.getInstance().notifyObservers(); } else { alert.close(); } } } } } class StoreListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { try { controller.storeWinkelkar(); update(); System.out.println("Winkelkar On Honld"); } catch (DbExeption dbExeption) { System.out.println(dbExeption.getMessage()); } } } class LoadListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { try { controller.loadWinkelkar(); update(); System.out.println("Winkelkar geladen"); } catch (DbExeption dbExeption) { Alert alert = new Alert(Alert.AlertType.ERROR,dbExeption.getMessage(),ButtonType.CLOSE); alert.showAndWait(); System.out.println(dbExeption.getMessage());; } catch (NullPointerException nullEx){ Alert alert = new Alert(Alert.AlertType.ERROR,"Geen Winkelkar on hold",ButtonType.CLOSE); alert.showAndWait(); System.out.println(nullEx.getMessage());; } } } class AfsluitListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { try { controller.setAfsluitString(); afsluitString.setValue(controller.getAfsluitString()); controller.notifyObservers(); } catch (Exception dbExeption) { Alert alert = new Alert(Alert.AlertType.ERROR,dbExeption.getMessage(),ButtonType.CLOSE); alert.showAndWait(); System.out.println(dbExeption.getMessage());; } } } class BetaaldListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { try { controller.betaalWinkelkar(); } catch (Exception dbExeption) { Alert alert = new Alert(Alert.AlertType.ERROR,dbExeption.getMessage(),ButtonType.CLOSE); alert.showAndWait(); System.out.println(dbExeption.getMessage());; } } } class AnuleerListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { try { controller.anulWinkelkar(); } catch (Exception dbExeption) { Alert alert = new Alert(Alert.AlertType.ERROR,dbExeption.getMessage(),ButtonType.CLOSE); alert.showAndWait(); System.out.println(dbExeption.getMessage());; } } } private void ScanArtikel() { Artikel artikel; try { artikel = controller.getArtikelWithCode(artikelScanField.getText()); artikel.verhoogAantalInKar(); controller.addArtikelToWinkelKar(artikel); this.update(); } catch (DbExeption dbExeption) { Alert alert = new Alert(Alert.AlertType.INFORMATION,dbExeption.getMessage(), ButtonType.CLOSE); alert.showAndWait(); } } public void setSaveAction(EventHandler<ActionEvent> saveAction) { btnOK.setOnAction(saveAction); } public void setEnterKeyAction(EventHandler<KeyEvent> enterKeyAction){ artikelScanField.setOnKeyPressed(enterKeyAction);} public void setCancelAction(EventHandler<ActionEvent> cancelAction) { btnCancel.setOnAction(cancelAction); } public void setKlickOnTableAction(EventHandler<MouseEvent> mouseEvent){table.setOnMouseClicked(mouseEvent);} public void setStoreAction(EventHandler<ActionEvent> storeAction) { btnStore.setOnAction(storeAction); } public void setAfsluitAction(EventHandler<ActionEvent> storeAction) { btnAfsluit.setOnAction(storeAction); } public void setBetaaldAction(EventHandler<ActionEvent> storeAction) { btnBetaald.setOnAction(storeAction); } public void setAnuleerAction(EventHandler<ActionEvent> storeAction) { btnAnul.setOnAction(storeAction); } public void setLoadAction(EventHandler<ActionEvent> loadAction) {btnLoad.setOnAction(loadAction); } public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); long factor = (long) Math.pow(10, places); value = value * factor; long tmp = Math.round(value); return (double) tmp / factor; } }
DeanTerweduwe/OOO_KassaApp
src/view/panels/WinkelkarPane.java
3,580
// totaalBedragLable = new Label("Totaal: ");
line_comment
nl
package view.panels; import controller.Controller; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import model.Artikel; import model.Observer; import model.db.DBService; import model.db.DbExeption; import java.util.Optional; public class WinkelkarPane extends GridPane implements Observer{ private Button btnOK, btnCancel,btnStore,btnLoad,btnAfsluit,btnBetaald,btnAnul; private TableView table; private Controller controller; private TextField artikelScanField; private Double totaalBedrag=0.0; private Label totaalLable; private Label infoLable; private SimpleStringProperty simpleStringProperty,afsluitString; // private ObservableList<Artikel> gescandeArtikels = FXCollections.observableArrayList() ; public WinkelkarPane(Controller controller) { this.controller = controller; this.simpleStringProperty = new SimpleStringProperty("Nog Geen Artikelen Gescand"); this.afsluitString = new SimpleStringProperty(""); this.setPrefHeight(150); this.setPrefWidth(300); controller.registerDBObserver(this); this.setPadding(new Insets(5, 5, 5, 5)); this.setVgap(5); this.setHgap(5); //TEXTFIELD this.add(new Label("Winkelkar :"), 0, 0, 1, 1); artikelScanField = new TextField(); this.add(artikelScanField, 1, 0, 1, 1); setEnterKeyAction(new EnterKeyListener()); totaalLable = new Label(); totaalLable.textProperty().bind(simpleStringProperty); this.add(totaalLable,4,5,1,1); infoLable = new Label("Dubbelklik een artikel om het te verwijderen."); this.add(infoLable,1,5,1,1); // totaalBedragLable =<SUF> // totaalBedragLable.textProperty().bind(); // this.add(new Label("Totaal Bedrag= " + totaalBedrag ),0,6,1,1); btnCancel = new Button("Close"); this.add(btnCancel, 0, 2, 1, 1); setCancelAction(new CancelListener()); btnOK = new Button("Scan"); btnOK.isDefaultButton(); this.add(btnOK, 1, 2, 1, 1); setSaveAction(new SaveListener()); btnStore = new Button("Store"); btnStore.isDefaultButton(); this.add(btnStore, 2, 2, 1, 1); setStoreAction(new StoreListener()); btnLoad = new Button("Load"); btnLoad.isDefaultButton(); this.add(btnLoad, 3, 2, 1, 1); setLoadAction(new LoadListener()); btnAfsluit = new Button("Afsluit"); btnAfsluit.isDefaultButton(); this.add(btnAfsluit, 4, 2, 1, 1); setAfsluitAction(new AfsluitListener()); btnBetaald = new Button("Betaald"); btnBetaald.isDefaultButton(); this.add(btnBetaald, 5, 2, 1, 1); setBetaaldAction(new BetaaldListener()); btnAnul = new Button("Anuleer"); btnAnul.isDefaultButton(); this.add(btnAnul, 6, 2, 1, 1); setAnuleerAction(new AnuleerListener()); //TABLE //BLIJKBAAR ALLEEN ARTIKEL EN PRIJS DIT NOG AANPASSEN VOOR FINAL PUSH table = new TableView<>(); table.setPrefWidth(REMAINING); TableColumn codeCol = new TableColumn<>("Code"); codeCol.setCellValueFactory(new PropertyValueFactory<>("Code")); table.getColumns().add(codeCol); TableColumn omschrijvingCol = new TableColumn<>("omschrijving"); omschrijvingCol.setCellValueFactory(new PropertyValueFactory("omschrijving")); table.getColumns().add(omschrijvingCol); TableColumn artikelGroepCol = new TableColumn<>("artikelGroep"); artikelGroepCol.setCellValueFactory(new PropertyValueFactory("artikelGroep")); table.getColumns().add(artikelGroepCol); TableColumn verkoopprijsCol = new TableColumn<>("verkoopprijs"); verkoopprijsCol.setCellValueFactory(new PropertyValueFactory("verkoopprijs")); table.getColumns().add(verkoopprijsCol); TableColumn voorraadCol = new TableColumn<>("voorraad"); voorraadCol.setCellValueFactory(new PropertyValueFactory("voorraad")); table.getColumns().add(voorraadCol); setKlickOnTableAction(new KlickOnTableListener()); this.add(table, 0, 3, 5, 2); Label label = new Label(""); label.textProperty().bind(afsluitString); this.add(label,0,6,1,1); ObservableList<Artikel> data = FXCollections.observableArrayList(controller.getWinkelKarArtikels()); table.setItems(data); } @Override public void update() { ObservableList<Artikel> data = FXCollections.observableArrayList(controller.getWinkelKarArtikels()); table.setItems(data); totaalBedrag = round( controller.getTotaalMetKortingen(),2); simpleStringProperty.setValue("Totaal= €"+totaalBedrag.toString()); if(DBService.getInstance().getKorting() != null){ simpleStringProperty.setValue("Totaal= €"+totaalBedrag.toString()+" (Met korting)"); } } class SaveListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { Artikel artikel = null; ScanArtikel(); } } class CancelListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { final Node source = (Node) e.getSource(); final Stage stage = (Stage) source.getScene().getWindow(); Platform.exit(); } } class EnterKeyListener implements EventHandler<KeyEvent>{ @Override public void handle(KeyEvent event) { if (event.getCode().equals(KeyCode.ENTER)) { Artikel artikel = null; ScanArtikel(); } } } class KlickOnTableListener implements EventHandler<MouseEvent>{ @Override public void handle(MouseEvent mouseEvent) { if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ if(mouseEvent.getClickCount() == 2){ int n = table.getSelectionModel().getFocusedIndex(); Alert alert = new Alert(Alert.AlertType.CONFIRMATION,"Do you want to delete this Item: \n" + "\n code= " +controller.getWinkelKarArtikels().get(n).getCode()+"\n\r plaats= "+(n+1), ButtonType.CLOSE,ButtonType.APPLY); alert.setTitle("DELETE"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.APPLY){ controller.getWinkelKarArtikels().get(n).verlaagAantalInKar(); controller.removeWithIndexFromWinkelkar(n); DBService.getInstance().notifyObservers(); } else { alert.close(); } } } } } class StoreListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { try { controller.storeWinkelkar(); update(); System.out.println("Winkelkar On Honld"); } catch (DbExeption dbExeption) { System.out.println(dbExeption.getMessage()); } } } class LoadListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { try { controller.loadWinkelkar(); update(); System.out.println("Winkelkar geladen"); } catch (DbExeption dbExeption) { Alert alert = new Alert(Alert.AlertType.ERROR,dbExeption.getMessage(),ButtonType.CLOSE); alert.showAndWait(); System.out.println(dbExeption.getMessage());; } catch (NullPointerException nullEx){ Alert alert = new Alert(Alert.AlertType.ERROR,"Geen Winkelkar on hold",ButtonType.CLOSE); alert.showAndWait(); System.out.println(nullEx.getMessage());; } } } class AfsluitListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { try { controller.setAfsluitString(); afsluitString.setValue(controller.getAfsluitString()); controller.notifyObservers(); } catch (Exception dbExeption) { Alert alert = new Alert(Alert.AlertType.ERROR,dbExeption.getMessage(),ButtonType.CLOSE); alert.showAndWait(); System.out.println(dbExeption.getMessage());; } } } class BetaaldListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { try { controller.betaalWinkelkar(); } catch (Exception dbExeption) { Alert alert = new Alert(Alert.AlertType.ERROR,dbExeption.getMessage(),ButtonType.CLOSE); alert.showAndWait(); System.out.println(dbExeption.getMessage());; } } } class AnuleerListener implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { try { controller.anulWinkelkar(); } catch (Exception dbExeption) { Alert alert = new Alert(Alert.AlertType.ERROR,dbExeption.getMessage(),ButtonType.CLOSE); alert.showAndWait(); System.out.println(dbExeption.getMessage());; } } } private void ScanArtikel() { Artikel artikel; try { artikel = controller.getArtikelWithCode(artikelScanField.getText()); artikel.verhoogAantalInKar(); controller.addArtikelToWinkelKar(artikel); this.update(); } catch (DbExeption dbExeption) { Alert alert = new Alert(Alert.AlertType.INFORMATION,dbExeption.getMessage(), ButtonType.CLOSE); alert.showAndWait(); } } public void setSaveAction(EventHandler<ActionEvent> saveAction) { btnOK.setOnAction(saveAction); } public void setEnterKeyAction(EventHandler<KeyEvent> enterKeyAction){ artikelScanField.setOnKeyPressed(enterKeyAction);} public void setCancelAction(EventHandler<ActionEvent> cancelAction) { btnCancel.setOnAction(cancelAction); } public void setKlickOnTableAction(EventHandler<MouseEvent> mouseEvent){table.setOnMouseClicked(mouseEvent);} public void setStoreAction(EventHandler<ActionEvent> storeAction) { btnStore.setOnAction(storeAction); } public void setAfsluitAction(EventHandler<ActionEvent> storeAction) { btnAfsluit.setOnAction(storeAction); } public void setBetaaldAction(EventHandler<ActionEvent> storeAction) { btnBetaald.setOnAction(storeAction); } public void setAnuleerAction(EventHandler<ActionEvent> storeAction) { btnAnul.setOnAction(storeAction); } public void setLoadAction(EventHandler<ActionEvent> loadAction) {btnLoad.setOnAction(loadAction); } public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); long factor = (long) Math.pow(10, places); value = value * factor; long tmp = Math.round(value); return (double) tmp / factor; } }
17514_8
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.CommandHandler.Action; import tillerino.tillerinobot.CommandHandler.Message; import tillerino.tillerinobot.CommandHandler.Response; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands implements Language { static final Random rnd = new Random(); @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public Response hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public boolean isChanged() { return false; } @Override public void setChanged(boolean changed) { } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public Response optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler doSomething = new StringShuffler(rnd); @Override public String apiTimeoutException() { final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + doSomething.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } @Override public String getPatience() { return "Momentje geduld asjeblieft..."; } }
Deardrops/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Nederlands.java
2,722
//dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!",
line_comment
nl
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.CommandHandler.Action; import tillerino.tillerinobot.CommandHandler.Message; import tillerino.tillerinobot.CommandHandler.Response; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands implements Language { static final Random rnd = new Random(); @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public Response hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public boolean isChanged() { return false; } @Override public void setChanged(boolean changed) { } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public Response optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler doSomething = new StringShuffler(rnd); @Override public String apiTimeoutException() { final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + doSomething.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel]<SUF> "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } @Override public String getPatience() { return "Momentje geduld asjeblieft..."; } }
96517_4
package info.hb.cnn.core; import info.hb.cnn.utils.MathUtils; import java.io.Serializable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Layer implements Serializable { private static final long serialVersionUID = -5747622503947497069L; private static Logger logger = LoggerFactory.getLogger(Layer.class); private LayerType type; private int outMapNum; private Size mapSize; private Size kernelSize; private Size scaleSize; private double[][][][] kernel; private double[] bias; private double[][][][] outmaps; private double[][][][] errors; private static int recordInBatch = 0; private int classNum = -1; private Layer() { // } public static void prepareForNewBatch() { recordInBatch = 0; } public static void prepareForNewRecord() { recordInBatch++; } public static Layer buildInputLayer(Size mapSize) { Layer layer = new Layer(); layer.type = LayerType.input; layer.outMapNum = 1; layer.setMapSize(mapSize); return layer; } public static Layer buildConvLayer(int outMapNum, Size kernelSize) { Layer layer = new Layer(); layer.type = LayerType.conv; layer.outMapNum = outMapNum; layer.kernelSize = kernelSize; return layer; } public static Layer buildSampLayer(Size scaleSize) { Layer layer = new Layer(); layer.type = LayerType.samp; layer.scaleSize = scaleSize; return layer; } public static Layer buildOutputLayer(int classNum) { Layer layer = new Layer(); layer.classNum = classNum; layer.type = LayerType.output; layer.mapSize = new Size(1, 1); layer.outMapNum = classNum; // int outMapNum = 1; // while ((1 << outMapNum) < classNum) // outMapNum += 1; // layer.outMapNum = outMapNum; logger.info("outMapNum:{}", layer.outMapNum); return layer; } public Size getMapSize() { return mapSize; } public void setMapSize(Size mapSize) { this.mapSize = mapSize; } public LayerType getType() { return type; } public int getOutMapNum() { return outMapNum; } public void setOutMapNum(int outMapNum) { this.outMapNum = outMapNum; } public Size getKernelSize() { return kernelSize; } public Size getScaleSize() { return scaleSize; } enum LayerType { input, output, conv, samp } public static class Size implements Serializable { private static final long serialVersionUID = -209157832162004118L; public final int x; public final int y; public Size(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { StringBuilder s = new StringBuilder("Size(").append(" x = ").append(x).append(" y= ").append(y).append(")"); return s.toString(); } public Size divide(Size scaleSize) { int x = this.x / scaleSize.x; int y = this.y / scaleSize.y; if (x * scaleSize.x != this.x || y * scaleSize.y != this.y) throw new RuntimeException(this + "scalesize:" + scaleSize); return new Size(x, y); } public Size subtract(Size size, int append) { int x = this.x - size.x + append; int y = this.y - size.y + append; return new Size(x, y); } } public void initKernel(int frontMapNum) { // int fan_out = getOutMapNum() * kernelSize.x * kernelSize.y; // int fan_in = frontMapNum * kernelSize.x * kernelSize.y; // double factor = 2 * Math.sqrt(6 / (fan_in + fan_out)); this.kernel = new double[frontMapNum][outMapNum][kernelSize.x][kernelSize.y]; for (int i = 0; i < frontMapNum; i++) for (int j = 0; j < outMapNum; j++) kernel[i][j] = MathUtils.randomMatrix(kernelSize.x, kernelSize.y, true); } public void initOutputKerkel(int frontMapNum, Size size) { kernelSize = size; // int fan_out = getOutMapNum() * kernelSize.x * kernelSize.y; // int fan_in = frontMapNum * kernelSize.x * kernelSize.y; // double factor = 2 * Math.sqrt(6 / (fan_in + fan_out)); this.kernel = new double[frontMapNum][outMapNum][kernelSize.x][kernelSize.y]; for (int i = 0; i < frontMapNum; i++) for (int j = 0; j < outMapNum; j++) kernel[i][j] = MathUtils.randomMatrix(kernelSize.x, kernelSize.y, false); } public void initBias(int frontMapNum) { this.bias = MathUtils.randomArray(outMapNum); } public void initOutmaps(int batchSize) { outmaps = new double[batchSize][outMapNum][mapSize.x][mapSize.y]; } public void setMapValue(int mapNo, int mapX, int mapY, double value) { outmaps[recordInBatch][mapNo][mapX][mapY] = value; } static int count = 0; public void setMapValue(int mapNo, double[][] outMatrix) { // Log.i(type.toString()); // Util.printMatrix(outMatrix); outmaps[recordInBatch][mapNo] = outMatrix; } public double[][] getMap(int index) { return outmaps[recordInBatch][index]; } public double[][] getKernel(int i, int j) { return kernel[i][j]; } public void setError(int mapNo, int mapX, int mapY, double value) { errors[recordInBatch][mapNo][mapX][mapY] = value; } public void setError(int mapNo, double[][] matrix) { // Log.i(type.toString()); // Util.printMatrix(matrix); errors[recordInBatch][mapNo] = matrix; } public double[][] getError(int mapNo) { return errors[recordInBatch][mapNo]; } public double[][][][] getErrors() { return errors; } public void initErros(int batchSize) { errors = new double[batchSize][outMapNum][mapSize.x][mapSize.y]; } public void setKernel(int lastMapNo, int mapNo, double[][] kernel) { this.kernel[lastMapNo][mapNo] = kernel; } public double getBias(int mapNo) { return bias[mapNo]; } public void setBias(int mapNo, double value) { bias[mapNo] = value; } public double[][][][] getMaps() { return outmaps; } public double[][] getError(int recordId, int mapNo) { return errors[recordId][mapNo]; } public double[][] getMap(int recordId, int mapNo) { return outmaps[recordId][mapNo]; } public int getClassNum() { return classNum; } public double[][][][] getKernel() { return kernel; } }
DeepCompute/cnn
src/main/java/info/hb/cnn/core/Layer.java
2,096
// int fan_out = getOutMapNum() * kernelSize.x * kernelSize.y;
line_comment
nl
package info.hb.cnn.core; import info.hb.cnn.utils.MathUtils; import java.io.Serializable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Layer implements Serializable { private static final long serialVersionUID = -5747622503947497069L; private static Logger logger = LoggerFactory.getLogger(Layer.class); private LayerType type; private int outMapNum; private Size mapSize; private Size kernelSize; private Size scaleSize; private double[][][][] kernel; private double[] bias; private double[][][][] outmaps; private double[][][][] errors; private static int recordInBatch = 0; private int classNum = -1; private Layer() { // } public static void prepareForNewBatch() { recordInBatch = 0; } public static void prepareForNewRecord() { recordInBatch++; } public static Layer buildInputLayer(Size mapSize) { Layer layer = new Layer(); layer.type = LayerType.input; layer.outMapNum = 1; layer.setMapSize(mapSize); return layer; } public static Layer buildConvLayer(int outMapNum, Size kernelSize) { Layer layer = new Layer(); layer.type = LayerType.conv; layer.outMapNum = outMapNum; layer.kernelSize = kernelSize; return layer; } public static Layer buildSampLayer(Size scaleSize) { Layer layer = new Layer(); layer.type = LayerType.samp; layer.scaleSize = scaleSize; return layer; } public static Layer buildOutputLayer(int classNum) { Layer layer = new Layer(); layer.classNum = classNum; layer.type = LayerType.output; layer.mapSize = new Size(1, 1); layer.outMapNum = classNum; // int outMapNum = 1; // while ((1 << outMapNum) < classNum) // outMapNum += 1; // layer.outMapNum = outMapNum; logger.info("outMapNum:{}", layer.outMapNum); return layer; } public Size getMapSize() { return mapSize; } public void setMapSize(Size mapSize) { this.mapSize = mapSize; } public LayerType getType() { return type; } public int getOutMapNum() { return outMapNum; } public void setOutMapNum(int outMapNum) { this.outMapNum = outMapNum; } public Size getKernelSize() { return kernelSize; } public Size getScaleSize() { return scaleSize; } enum LayerType { input, output, conv, samp } public static class Size implements Serializable { private static final long serialVersionUID = -209157832162004118L; public final int x; public final int y; public Size(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { StringBuilder s = new StringBuilder("Size(").append(" x = ").append(x).append(" y= ").append(y).append(")"); return s.toString(); } public Size divide(Size scaleSize) { int x = this.x / scaleSize.x; int y = this.y / scaleSize.y; if (x * scaleSize.x != this.x || y * scaleSize.y != this.y) throw new RuntimeException(this + "scalesize:" + scaleSize); return new Size(x, y); } public Size subtract(Size size, int append) { int x = this.x - size.x + append; int y = this.y - size.y + append; return new Size(x, y); } } public void initKernel(int frontMapNum) { // int fan_out<SUF> // int fan_in = frontMapNum * kernelSize.x * kernelSize.y; // double factor = 2 * Math.sqrt(6 / (fan_in + fan_out)); this.kernel = new double[frontMapNum][outMapNum][kernelSize.x][kernelSize.y]; for (int i = 0; i < frontMapNum; i++) for (int j = 0; j < outMapNum; j++) kernel[i][j] = MathUtils.randomMatrix(kernelSize.x, kernelSize.y, true); } public void initOutputKerkel(int frontMapNum, Size size) { kernelSize = size; // int fan_out = getOutMapNum() * kernelSize.x * kernelSize.y; // int fan_in = frontMapNum * kernelSize.x * kernelSize.y; // double factor = 2 * Math.sqrt(6 / (fan_in + fan_out)); this.kernel = new double[frontMapNum][outMapNum][kernelSize.x][kernelSize.y]; for (int i = 0; i < frontMapNum; i++) for (int j = 0; j < outMapNum; j++) kernel[i][j] = MathUtils.randomMatrix(kernelSize.x, kernelSize.y, false); } public void initBias(int frontMapNum) { this.bias = MathUtils.randomArray(outMapNum); } public void initOutmaps(int batchSize) { outmaps = new double[batchSize][outMapNum][mapSize.x][mapSize.y]; } public void setMapValue(int mapNo, int mapX, int mapY, double value) { outmaps[recordInBatch][mapNo][mapX][mapY] = value; } static int count = 0; public void setMapValue(int mapNo, double[][] outMatrix) { // Log.i(type.toString()); // Util.printMatrix(outMatrix); outmaps[recordInBatch][mapNo] = outMatrix; } public double[][] getMap(int index) { return outmaps[recordInBatch][index]; } public double[][] getKernel(int i, int j) { return kernel[i][j]; } public void setError(int mapNo, int mapX, int mapY, double value) { errors[recordInBatch][mapNo][mapX][mapY] = value; } public void setError(int mapNo, double[][] matrix) { // Log.i(type.toString()); // Util.printMatrix(matrix); errors[recordInBatch][mapNo] = matrix; } public double[][] getError(int mapNo) { return errors[recordInBatch][mapNo]; } public double[][][][] getErrors() { return errors; } public void initErros(int batchSize) { errors = new double[batchSize][outMapNum][mapSize.x][mapSize.y]; } public void setKernel(int lastMapNo, int mapNo, double[][] kernel) { this.kernel[lastMapNo][mapNo] = kernel; } public double getBias(int mapNo) { return bias[mapNo]; } public void setBias(int mapNo, double value) { bias[mapNo] = value; } public double[][][][] getMaps() { return outmaps; } public double[][] getError(int recordId, int mapNo) { return errors[recordId][mapNo]; } public double[][] getMap(int recordId, int mapNo) { return outmaps[recordId][mapNo]; } public int getClassNum() { return classNum; } public double[][][][] getKernel() { return kernel; } }
166161_3
package com.delphiworlds.kastri; /******************************************************* * * * Kastri Free * * * * Delphi Worlds Cross-Platform Library * * * *******************************************************/ import android.content.Context; import android.content.Intent; // Delphi 10.4.2 or earlier // import android.support.v4.content.LocalBroadcastManager; import android.util.Log; // Delphi 11 and later import androidx.localbroadcastmanager.content.LocalBroadcastManager; // Delphi 10.4.2 or earlier - begin /* import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; */ // Delphi 10.4.2 or earlier - end import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import java.util.HashMap; import java.util.Map; public class DWFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "DWFirebaseMessagingService"; private static int mUniqueId = 0; public static final String ACTION_NEW_TOKEN = "com.delphiworlds.kastri.DWFirebaseMessagingService.ACTION_NEW_TOKEN"; public static final String ACTION_MESSAGE_RECEIVED = "com.delphiworlds.kastri.DWFirebaseMessagingService.ACTION_MESSAGE_RECEIVED"; private void addExtras(Intent intent, Map<String, String> data) { for (Map.Entry<String, String> entry : data.entrySet()) { if (entry.getValue() != null) intent.putExtra(entry.getKey(), entry.getValue()); } } private static String priorityToString(int priority) { if (priority == -1) return "low"; else if (priority == 1) return "high"; else if (priority == 2) return "max"; else return "none"; } public static void sendTokenBroadcast(Context context, String token) { Intent intent = new Intent(ACTION_NEW_TOKEN); intent.putExtra("token", token); try { Log.v(TAG, "Sending token broadcast"); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } catch (Throwable e) { // no exception handling } } // Delphi 10.4.2 and earlier - begin /* public static void queryToken(final Context context) { FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() { @Override public void onSuccess(InstanceIdResult instanceIdResult) { sendTokenBroadcast(context, instanceIdResult.getToken()); } }); } */ // Delphi 10.4.2 and earlier - end @Override public void onCreate() { // Log.d(TAG, "onCreate"); } @Override public void onNewToken(String token) { // Log.d(TAG, "onNewToken - " + token); sendTokenBroadcast(this, token); } @Override public void onMessageReceived(RemoteMessage remoteMessage) { Map<String, String> data = null; Intent intent = new Intent(ACTION_MESSAGE_RECEIVED); // Process either data section (if present) or notification, but not both if ((remoteMessage.getData() != null) && !remoteMessage.getData().isEmpty()) { Log.d(TAG, "Message has data: " + data); data = remoteMessage.getData(); this.addExtras(intent, data); } else if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message has notification"); RemoteMessage.Notification notification = remoteMessage.getNotification(); data = new HashMap<String, String>(); // data.put("android_channel_id", notification.getChannelId()); 18.0.0 data.put("body", notification.getBody()); data.put("color", notification.getColor()); data.put("icon", notification.getIcon()); if (notification.getLink() != null) data.put("link", notification.getLink().toString()); data.put("sound", notification.getSound()); data.put("title", notification.getTitle()); // Delphi 11 and later - begin if (notification.getImageUrl() != null) data.put("image", notification.getImageUrl().toString()); if (notification.getNotificationPriority() != null) data.put("priority", notification.getNotificationPriority().toString()); if (notification.getVisibility() != null) data.put("visibility", notification.getVisibility().toString()); // Delphi 11 and later - end this.addExtras(intent, data); } else Log.d(TAG, "Message has either no data or is empty, and no notification"); intent.putExtra("google.from", remoteMessage.getFrom()); intent.putExtra("google.message_id", remoteMessage.getMessageId()); intent.putExtra("google.message_type", remoteMessage.getMessageType()); intent.putExtra("google.sent_time", remoteMessage.getSentTime()); intent.putExtra("google.to", remoteMessage.getTo()); intent.putExtra("google.ttl", remoteMessage.getTtl()); intent.putExtra("google.original_priority", DWFirebaseMessagingService.priorityToString(remoteMessage.getOriginalPriority())); intent.putExtra("google.delivered_priority", DWFirebaseMessagingService.priorityToString(remoteMessage.getPriority())); boolean hasReceiver = false; try { hasReceiver = LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } catch (Throwable e) { // No exception handling } // App is not running if no receiver if (!hasReceiver) { Log.d(TAG, "App not running - posting notification"); DWNotificationPublisher.sendNotification(this, intent, true); // Launch the application if launchapp is 1 if (intent.hasExtra("launchapp")) { String launchapp = intent.getStringExtra("launchapp"); // Log.v(TAG, "Payload has launchapp flag set to: " + launchapp); if (launchapp.equals("1")) { // Log.v(TAG, "Launching.."); this.startActivity(this.getPackageManager().getLaunchIntentForPackage(this.getPackageName())); } } } } }
DelphiWorlds/Kastri
Java/Firebase/DWFirebaseMessagingService.java
1,885
// Delphi 10.4.2 or earlier - begin
line_comment
nl
package com.delphiworlds.kastri; /******************************************************* * * * Kastri Free * * * * Delphi Worlds Cross-Platform Library * * * *******************************************************/ import android.content.Context; import android.content.Intent; // Delphi 10.4.2 or earlier // import android.support.v4.content.LocalBroadcastManager; import android.util.Log; // Delphi 11 and later import androidx.localbroadcastmanager.content.LocalBroadcastManager; // Delphi 10.4.2<SUF> /* import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; */ // Delphi 10.4.2 or earlier - end import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import java.util.HashMap; import java.util.Map; public class DWFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "DWFirebaseMessagingService"; private static int mUniqueId = 0; public static final String ACTION_NEW_TOKEN = "com.delphiworlds.kastri.DWFirebaseMessagingService.ACTION_NEW_TOKEN"; public static final String ACTION_MESSAGE_RECEIVED = "com.delphiworlds.kastri.DWFirebaseMessagingService.ACTION_MESSAGE_RECEIVED"; private void addExtras(Intent intent, Map<String, String> data) { for (Map.Entry<String, String> entry : data.entrySet()) { if (entry.getValue() != null) intent.putExtra(entry.getKey(), entry.getValue()); } } private static String priorityToString(int priority) { if (priority == -1) return "low"; else if (priority == 1) return "high"; else if (priority == 2) return "max"; else return "none"; } public static void sendTokenBroadcast(Context context, String token) { Intent intent = new Intent(ACTION_NEW_TOKEN); intent.putExtra("token", token); try { Log.v(TAG, "Sending token broadcast"); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } catch (Throwable e) { // no exception handling } } // Delphi 10.4.2 and earlier - begin /* public static void queryToken(final Context context) { FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() { @Override public void onSuccess(InstanceIdResult instanceIdResult) { sendTokenBroadcast(context, instanceIdResult.getToken()); } }); } */ // Delphi 10.4.2 and earlier - end @Override public void onCreate() { // Log.d(TAG, "onCreate"); } @Override public void onNewToken(String token) { // Log.d(TAG, "onNewToken - " + token); sendTokenBroadcast(this, token); } @Override public void onMessageReceived(RemoteMessage remoteMessage) { Map<String, String> data = null; Intent intent = new Intent(ACTION_MESSAGE_RECEIVED); // Process either data section (if present) or notification, but not both if ((remoteMessage.getData() != null) && !remoteMessage.getData().isEmpty()) { Log.d(TAG, "Message has data: " + data); data = remoteMessage.getData(); this.addExtras(intent, data); } else if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message has notification"); RemoteMessage.Notification notification = remoteMessage.getNotification(); data = new HashMap<String, String>(); // data.put("android_channel_id", notification.getChannelId()); 18.0.0 data.put("body", notification.getBody()); data.put("color", notification.getColor()); data.put("icon", notification.getIcon()); if (notification.getLink() != null) data.put("link", notification.getLink().toString()); data.put("sound", notification.getSound()); data.put("title", notification.getTitle()); // Delphi 11 and later - begin if (notification.getImageUrl() != null) data.put("image", notification.getImageUrl().toString()); if (notification.getNotificationPriority() != null) data.put("priority", notification.getNotificationPriority().toString()); if (notification.getVisibility() != null) data.put("visibility", notification.getVisibility().toString()); // Delphi 11 and later - end this.addExtras(intent, data); } else Log.d(TAG, "Message has either no data or is empty, and no notification"); intent.putExtra("google.from", remoteMessage.getFrom()); intent.putExtra("google.message_id", remoteMessage.getMessageId()); intent.putExtra("google.message_type", remoteMessage.getMessageType()); intent.putExtra("google.sent_time", remoteMessage.getSentTime()); intent.putExtra("google.to", remoteMessage.getTo()); intent.putExtra("google.ttl", remoteMessage.getTtl()); intent.putExtra("google.original_priority", DWFirebaseMessagingService.priorityToString(remoteMessage.getOriginalPriority())); intent.putExtra("google.delivered_priority", DWFirebaseMessagingService.priorityToString(remoteMessage.getPriority())); boolean hasReceiver = false; try { hasReceiver = LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } catch (Throwable e) { // No exception handling } // App is not running if no receiver if (!hasReceiver) { Log.d(TAG, "App not running - posting notification"); DWNotificationPublisher.sendNotification(this, intent, true); // Launch the application if launchapp is 1 if (intent.hasExtra("launchapp")) { String launchapp = intent.getStringExtra("launchapp"); // Log.v(TAG, "Payload has launchapp flag set to: " + launchapp); if (launchapp.equals("1")) { // Log.v(TAG, "Launching.."); this.startActivity(this.getPackageManager().getLaunchIntentForPackage(this.getPackageName())); } } } } }
7577_31
package UI; import java.awt.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JSplitPane; import javax.swing.JPanel; import java.lang.Integer; import domain.Cantus; import domain.CantusVerzameling; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.time.Day; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.util.ShapeUtilities; import javax.swing.JButton; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.JScrollPane; import static java.util.Collections.frequency; import static org.jfree.util.SortOrder.DESCENDING; import java.awt.GridLayout; import java.awt.GridBagLayout; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.Shape; public class MainPane extends JFrame implements Observer{ private int semestercount = 1; private int summercount = 1; private int wintercount = 1; private static final long serialVersionUID = -9090407129402452701L; private boolean plaatsFlag;//true als er plaatsen in de file staan, false anders private Controller controller; private JPanel panel; private JSplitPane splitPaneH; private JScrollPane tabel; private ChartPanel vereniggingenchartpanel; private ChartPanel plaatsenchartpanel; public MainPane(Controller controller) { System.out.println("draw mainpain"); this.controller = controller; setTitle("Grafiekjes"); } //teken al de charts en tabel. public void drawCompleet(CantusVerzameling CV){ // SETUP JPanel jpanel = new JPanel(); controller.screen.mainFrame.add(jpanel); GridBagLayout g = new GridBagLayout(); jpanel.setLayout(g); //Get the charts and table this.plaatsFlag=containsNotNull(CV.getPlaatsen()); tabel = makeScrollTable(CV.getCantussen()); JFreeChart vereniggingenchart = makePieChart(CV.getVerenigingen()); vereniggingenchart.getPlot().setBackgroundPaint(Color.WHITE); vereniggingenchart.setTitle("Verenigingen"); this.vereniggingenchartpanel = new ChartPanel(vereniggingenchart); JFreeChart plaatsenchart = makePieChart(CV.getPlaatsen()); this.plaatsenchartpanel = new ChartPanel(plaatsenchart); if(plaatsFlag){ plaatsenchart.setTitle("Locaties"); plaatsenchart.getPlot().setBackgroundPaint(Color.WHITE); } ChartPanel timechart = new ChartPanel(makeTimeLine(CV.getData())); //Add the charts to the panel in the right column/rows met de juiste verhoudingen. GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.gridwidth=2; c.weightx=0.7; c.weighty=0.8; c.fill = GridBagConstraints.BOTH; jpanel.add(timechart,c); c=new GridBagConstraints(); c.gridx=0; c.gridy=1; c.gridheight=1;c.weightx=0.35; c.weighty=.2; if(!plaatsFlag) c.gridwidth=2; c.fill = GridBagConstraints.BOTH; jpanel.add(vereniggingenchartpanel,c); if(plaatsFlag){ c=new GridBagConstraints(); c.gridx=1; c.gridy=1; c.gridheight=1;c.weightx=.35; c.weighty=.2; c.fill = GridBagConstraints.BOTH; jpanel.add(plaatsenchartpanel,c); } c=new GridBagConstraints(); c.gridx=2; c.gridy=0; c.weightx=1; c.weighty=1; c.gridheight=2; c.gridwidth=2; c.fill = GridBagConstraints.BOTH;//.VERTICAL; //tabel.setPreferredSize(new Dimension(tabel.getPreferredSize().width,this.getPreferredSize().height*100)); jpanel.add(tabel,c); JButton plus = new JButton("+"); c=new GridBagConstraints(); c.gridx=2; c.gridy=2; c.weightx=.01; c.weighty=.01; c.anchor= GridBagConstraints.SOUTHEAST; jpanel.add(plus,c); JButton minus = new JButton("-"); c=new GridBagConstraints(); c.gridx=3; c.gridy=2; c.weightx=.01; c.weighty=.01; c.anchor= GridBagConstraints.SOUTHEAST; jpanel.add(minus,c); JTable t = (JTable) tabel.getViewport().getView(); //update als er iets word aangeduid in de tabel t.getSelectionModel().addListSelectionListener(e -> { updateRows(t.getSelectedRows(), t,timechart,vereniggingenchartpanel,plaatsenchartpanel); }); minus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JTable actiontabel = (JTable) tabel.getViewport().getView(); System.out.println(getRows(actiontabel.getSelectedRows(),actiontabel).toString()); CV.deleteCantussen(getRows(actiontabel.getSelectedRows(),actiontabel)); tabel.setViewport(makeScrollTable(CV.getCantussen()).getViewport()); JFreeChart vereniggingenchart = makePieChart(CV.getVerenigingen()); vereniggingenchart.getPlot().setBackgroundPaint(Color.WHITE); vereniggingenchart.setTitle("Verenigingen"); vereniggingenchartpanel.setChart(vereniggingenchart); } }); controller.screen.mainFrame.setVisible(true); } public ArrayList<String> getRows(int[] rows, JTable t){ StringBuilder s = new StringBuilder(); ArrayList<String> a = new ArrayList<>(); for(int i: rows){ s = new StringBuilder(); for(int j = 0; j<t.getColumnCount();j++){ s.append(t.getValueAt(i,j).toString()+","); } a.add(s.toString()); } return(a); } //update de charts aan de hand van de rijen die aangeduid zijn in de tabel public void updateRows(int[] rows, JTable t, ChartPanel chartt,ChartPanel chartv, ChartPanel chartp){ //aanduiden in timechart JFreeChart c = chartt.getChart(); XYPlot xyp = c.getXYPlot(); XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) xyp.getRenderer(); TimeSeriesCollection tsc = (TimeSeriesCollection) xyp.getDataset(); if(tsc.getSeries("invisible")==null){ tsc.addSeries( new TimeSeries("invisible")); Shape shape = new java.awt.geom.Ellipse2D.Double(-2.0, -2.0, 5.0, 5.0); r.setSeriesShape(tsc.getSeriesIndex("invisible"), shape); r.setSeriesShapesVisible(tsc.getSeriesIndex("invisible"),true); r.setSeriesLinesVisible(tsc.getSeriesIndex("invisible"), false); r.setSeriesVisibleInLegend(tsc.getSeriesIndex("invisible"),false ); r.setSeriesPaint(tsc.getSeriesIndex("invisible"), Color.black); } TimeSeries s = tsc.getSeries("invisible"); s.clear(); HashSet<String> pset = new HashSet<>(); HashSet<String> vset = new HashSet<>(); for(int row: rows){ for(int i=0; i<tsc.getSeriesCount();i++){ TimeSeries ts = tsc.getSeries(i); for(int j=0; j<ts.getItemCount();j++){ if(samedate(t.getValueAt(row,0).toString(), (Day) ts.getDataItem(j).getPeriod())) s.addOrUpdate(ts.getDataItem(j).getPeriod(), ts.getDataItem(j).getValue()); } } //voorbereidend werk voor de piecharts te exploden if(plaatsFlag) pset.add(t.getValueAt(row,3).toString()); vset.add(t.getValueAt(row,2).toString()); } //explode de piecharts for(Object o: ((PiePlot) chartv.getChart().getPlot()).getDataset().getKeys()){ String str = o.toString(); if(vset.contains(str)) ((PiePlot) chartv.getChart().getPlot()).setExplodePercent(str,.33); else if(str!=null) ((PiePlot) chartv.getChart().getPlot()).setExplodePercent(str,0); } if(plaatsFlag){ for(Object o: ((PiePlot) chartp.getChart().getPlot()).getDataset().getKeys()){ String str = o.toString(); if(pset.contains(str)) ((PiePlot) chartp.getChart().getPlot()).setExplodePercent(str,.33); else if(str!=null) ((PiePlot) chartp.getChart().getPlot()).setExplodePercent(str,0); } } } //kijk na of een string die uit de tabel komt dezelfde dag voorstelt als een dag die uit de timechart is gehaald. public boolean samedate(String s, Day d){ String[] parts = s.split("/"); Day sd = new Day(Integer.parseInt(parts[0]),Integer.parseInt(parts[1]),Integer.parseInt(parts[2])); return(sd.equals(d)); } //draw de cantusTable, wordt momenteel niet meer gebruikt, kan later terug nodig zijn. public void drawCantusTable(List<Cantus> cantussen){ JScrollPane jtable = makeScrollTable(cantussen); panel.add(jtable); panel.setVisible(true); this.pack(); this.setVisible(true); } //construeer de scrollTable met een tabel van alle cantussen public JScrollPane makeScrollTable(List<Cantus> cantussen){ DefaultTableModel model = new DefaultTableModel(); model.addColumn("Datum"); model.addColumn("Cantus"); model.addColumn("Vereniging"); if(plaatsFlag) model.addColumn("plaats"); cantussen.sort(Cantus::compareTo); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); if(plaatsFlag){ for(Cantus cantus : cantussen){ Object[] array = {df.format(cantus.datum.getTime()), cantus.naam, cantus.vereniging,cantus.plaats}; model.addRow(array); } } else { for(Cantus cantus : cantussen){ Object[] array = {df.format(cantus.datum.getTime()), cantus.naam, cantus.vereniging}; model.addRow(array); } } JTable table = new JTable(model); this.setExtendedState(JFrame.MAXIMIZED_BOTH); return new JScrollPane(table); } //drawt een pieChart; wordt momenteel niet meer gebruikt, kan later terug nodig zijn. //@Override public void drawPieChart(List<String> dataset) { JFreeChart chart = makePieChart(dataset); splitPaneH.setLeftComponent(new ChartPanel(chart)); panel.setVisible(true); this.pack(); this.setVisible(true); } //gaat na of een lijst een niet null element bevat. nodig om te kijken of er plaatsen zijn ingegeven. private boolean containsNotNull(List<String> l){ for(String s: l) if(s != null && s.length()>0) return true; return false; } //construeer een piechart van een dataset. wordt gebruikt om de verenigingen en de plaatsen in een piechart te zetten. public JFreeChart makePieChart(List<String> dataset){ if(containsNotNull(dataset)){ dataset.sort(String::compareTo); } else { return null; } DefaultPieDataset ds = new DefaultPieDataset(); for (String s: dataset){ if(s != null && s.length()>0) { //System.out.println("string: " + s); if (ds.getKeys().contains(s)) { //System.out.println(ds.getValue(s)); ds.setValue(s, ds.getValue(s).intValue() + 1); } else ds.setValue(s, 1); } } ds.sortByValues(DESCENDING); int count = 0; for(Object o: ds.getKeys()){ if(ds.getValue((Comparable) o).intValue()<=dataset.size()/100){ count++; ds.remove((Comparable) o); } } if (count!=0) ds.setValue("Overige",count); return ChartFactory.createPieChart( "TAAAAAART", // chart title ds, // data true, // include legend true, false); } //drawt de timeline; wordt momenteel niet gebruikt, kan later terug nodig zijn. @Override public void drawTimeline(List<Calendar> dataset){ splitPaneH.setRightComponent(new ChartPanel(makeTimeLine(dataset))); panel.setVisible(true); this.pack(); this.setVisible(true); } //construeert de timeline public JFreeChart makeTimeLine(List<Calendar> dataset){ dataset.sort(Calendar::compareTo); genCumul(dataset,7); JFreeChart chart = ChartFactory.createTimeSeriesChart( "Waar-liep-het-fout-lijn", // Chart "Date", // X-Axis Label "cantus", // Y-Axis Label constructTSC(dataset)); XYPlot plot = (XYPlot)chart.getPlot(); plot.setBackgroundPaint(new Color(255,255,255)); plot.setDomainGridlinePaint(new Color(155,155,155)); plot.setRangeGridlinePaint(new Color(155,155,155)); for (int i = 0; i < plot.getSeriesCount(); i++) { plot.getRenderer().setSeriesStroke(i,new BasicStroke(2.0f)); } plot.setDataset(1, new TimeSeriesCollection(genCumul(dataset,7))); plot.setDataset(2, new TimeSeriesCollection(genCumul(dataset,31))); // Renderer voor cumul7 XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer(true,false); r1.setPaint(new Color(0,0,255)); // Renderer voor cumul31 XYLineAndShapeRenderer r2 = new XYLineAndShapeRenderer(true,false); r2.setPaint(new Color(0,255,0)); plot.setRenderer(1,r1); plot.setRenderer(2,r2); return chart; } //construeer de timeseriescollection van de lijst van data. private TimeSeriesCollection constructTSC(List<Calendar> dataset){ TimeSeriesCollection tsc = new TimeSeriesCollection(); TimeSeries series = new TimeSeries("Series1"); int i = 0; Calendar previous,c; while(i < dataset.size()){ c = dataset.get(i); Period p = getPeriod(c); if(i == 0){ series.setKey(p.name().toLowerCase() + "1"); addCount(p); } else { previous = dataset.get(i-1); if (diffPeriod(previous,c)) { series.addOrUpdate(new Day(c.getTime()),i+1); tsc.addSeries(series); series = new TimeSeries(p.name().toLowerCase() + getCount(p)); addCount(p); } } series.addOrUpdate(new Day(c.getTime()),i+1); i++; } tsc.addSeries(series); return tsc; } //genereer de cumulatieve lijn voor de laatste %i dagen. private TimeSeries genCumul(List<Calendar> ds, int i){ TimeSeries series = new TimeSeries("Cumul" + i); Calendar start = (Calendar) ds.get(0).clone(); Calendar end = (Calendar) ds.get(ds.size()-1).clone(); Calendar preStart= (Calendar) start.clone(); preStart.add(Calendar.DATE,-i); int count=0; while(start.before(end)){ if(ds.contains(preStart)) count-=frequency(ds,preStart); if(ds.contains(start)){ count+=frequency(ds,start); } //System.out.println(start.getTime()+ " cumul is " + count); series.addOrUpdate(new Day(start.getTime()),count); start.add(Calendar.DATE,1); preStart.add(Calendar.DATE,1); } return series; } //enum van mogelijke periodes public enum Period { SEMESTER, SUMMER, WINTER } //kijk na in welke periode een dag valt. private Period getPeriod(Calendar c){ Calendar c2 = getStartYear(c); Period p; if (daysBetween(c2,c) < 89){ p = Period.SEMESTER; }else if (daysBetween(c2,c) < 140){ p = Period.WINTER; }else if (daysBetween(c2,c) < 243){ p = Period.SEMESTER; }else { p = Period.SUMMER; } return p; } /* berekend de start van het academiejaar voor datum c de eerste maandag na de 20ste september die c voorafgaat */ private Calendar getStartYear(Calendar c){ Calendar c2 = Calendar.getInstance(); c2.set(c.get(Calendar.YEAR),Calendar.SEPTEMBER,20); //========================System.out.println(df.format(c2.getTime())); nextMonday(c2); if(c.before(c2)) { c2.set(c.get(Calendar.YEAR) - 1, Calendar.SEPTEMBER, 20); nextMonday(c2); } return c2; } //vormt een dag om naar de eerstvolgende maandag. private void nextMonday(Calendar c){ while(c.get(Calendar.DAY_OF_WEEK)!=Calendar.MONDAY) c.add(Calendar.DATE,1); } //geef het aantal dagen tussen 2 dagen terug private static long daysBetween(Calendar startDate, Calendar endDate) { long end = endDate.getTimeInMillis(); long start = startDate.getTimeInMillis(); return (end - start)/(60*60*24*1000) +1; } /* kijkt na of first en second in een verschillende periode liggen: valt first voor de start van het academiejaar van second? semester 1: start academiejaar .. 89 dagen later winter: 89dagen na start .. 140 dagen na start semester 2: 140 dagen na start .. 191 dagen na start zomer: 191 dagen na start .. volgende academiejaar. */ private boolean diffPeriod(Calendar first, Calendar second){ Calendar start = getStartYear(second); long d1 = daysBetween(start,first); long d2 = daysBetween(start,second); return (!first.after(start) || (d1<89 && d2 >= 89) || (d1<140 && d2 >= 140)|| (d1<243 && d2 >= 243)); } //geef aan de hoeveelste keer dat een periode gebruikt is. private int getCount(Period p){ if(p.equals(Period.SEMESTER)) return semestercount; if(p.equals(Period.SUMMER)) return summercount; return wintercount; } //tel 1 op bij de bijhorende periodcount van de period private void addCount(Period p){ if(p.equals(Period.SEMESTER)) { //System.out.println("add semester count"); semestercount++; } if(p.equals(Period.SUMMER)) summercount++; if(p.equals(Period.WINTER)) wintercount++; } }
DenisBlondeel/CantusCalulator
src/UI/MainPane.java
6,276
//tel 1 op bij de bijhorende periodcount van de period
line_comment
nl
package UI; import java.awt.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JSplitPane; import javax.swing.JPanel; import java.lang.Integer; import domain.Cantus; import domain.CantusVerzameling; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.time.Day; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.util.ShapeUtilities; import javax.swing.JButton; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.JScrollPane; import static java.util.Collections.frequency; import static org.jfree.util.SortOrder.DESCENDING; import java.awt.GridLayout; import java.awt.GridBagLayout; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.Shape; public class MainPane extends JFrame implements Observer{ private int semestercount = 1; private int summercount = 1; private int wintercount = 1; private static final long serialVersionUID = -9090407129402452701L; private boolean plaatsFlag;//true als er plaatsen in de file staan, false anders private Controller controller; private JPanel panel; private JSplitPane splitPaneH; private JScrollPane tabel; private ChartPanel vereniggingenchartpanel; private ChartPanel plaatsenchartpanel; public MainPane(Controller controller) { System.out.println("draw mainpain"); this.controller = controller; setTitle("Grafiekjes"); } //teken al de charts en tabel. public void drawCompleet(CantusVerzameling CV){ // SETUP JPanel jpanel = new JPanel(); controller.screen.mainFrame.add(jpanel); GridBagLayout g = new GridBagLayout(); jpanel.setLayout(g); //Get the charts and table this.plaatsFlag=containsNotNull(CV.getPlaatsen()); tabel = makeScrollTable(CV.getCantussen()); JFreeChart vereniggingenchart = makePieChart(CV.getVerenigingen()); vereniggingenchart.getPlot().setBackgroundPaint(Color.WHITE); vereniggingenchart.setTitle("Verenigingen"); this.vereniggingenchartpanel = new ChartPanel(vereniggingenchart); JFreeChart plaatsenchart = makePieChart(CV.getPlaatsen()); this.plaatsenchartpanel = new ChartPanel(plaatsenchart); if(plaatsFlag){ plaatsenchart.setTitle("Locaties"); plaatsenchart.getPlot().setBackgroundPaint(Color.WHITE); } ChartPanel timechart = new ChartPanel(makeTimeLine(CV.getData())); //Add the charts to the panel in the right column/rows met de juiste verhoudingen. GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.gridwidth=2; c.weightx=0.7; c.weighty=0.8; c.fill = GridBagConstraints.BOTH; jpanel.add(timechart,c); c=new GridBagConstraints(); c.gridx=0; c.gridy=1; c.gridheight=1;c.weightx=0.35; c.weighty=.2; if(!plaatsFlag) c.gridwidth=2; c.fill = GridBagConstraints.BOTH; jpanel.add(vereniggingenchartpanel,c); if(plaatsFlag){ c=new GridBagConstraints(); c.gridx=1; c.gridy=1; c.gridheight=1;c.weightx=.35; c.weighty=.2; c.fill = GridBagConstraints.BOTH; jpanel.add(plaatsenchartpanel,c); } c=new GridBagConstraints(); c.gridx=2; c.gridy=0; c.weightx=1; c.weighty=1; c.gridheight=2; c.gridwidth=2; c.fill = GridBagConstraints.BOTH;//.VERTICAL; //tabel.setPreferredSize(new Dimension(tabel.getPreferredSize().width,this.getPreferredSize().height*100)); jpanel.add(tabel,c); JButton plus = new JButton("+"); c=new GridBagConstraints(); c.gridx=2; c.gridy=2; c.weightx=.01; c.weighty=.01; c.anchor= GridBagConstraints.SOUTHEAST; jpanel.add(plus,c); JButton minus = new JButton("-"); c=new GridBagConstraints(); c.gridx=3; c.gridy=2; c.weightx=.01; c.weighty=.01; c.anchor= GridBagConstraints.SOUTHEAST; jpanel.add(minus,c); JTable t = (JTable) tabel.getViewport().getView(); //update als er iets word aangeduid in de tabel t.getSelectionModel().addListSelectionListener(e -> { updateRows(t.getSelectedRows(), t,timechart,vereniggingenchartpanel,plaatsenchartpanel); }); minus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JTable actiontabel = (JTable) tabel.getViewport().getView(); System.out.println(getRows(actiontabel.getSelectedRows(),actiontabel).toString()); CV.deleteCantussen(getRows(actiontabel.getSelectedRows(),actiontabel)); tabel.setViewport(makeScrollTable(CV.getCantussen()).getViewport()); JFreeChart vereniggingenchart = makePieChart(CV.getVerenigingen()); vereniggingenchart.getPlot().setBackgroundPaint(Color.WHITE); vereniggingenchart.setTitle("Verenigingen"); vereniggingenchartpanel.setChart(vereniggingenchart); } }); controller.screen.mainFrame.setVisible(true); } public ArrayList<String> getRows(int[] rows, JTable t){ StringBuilder s = new StringBuilder(); ArrayList<String> a = new ArrayList<>(); for(int i: rows){ s = new StringBuilder(); for(int j = 0; j<t.getColumnCount();j++){ s.append(t.getValueAt(i,j).toString()+","); } a.add(s.toString()); } return(a); } //update de charts aan de hand van de rijen die aangeduid zijn in de tabel public void updateRows(int[] rows, JTable t, ChartPanel chartt,ChartPanel chartv, ChartPanel chartp){ //aanduiden in timechart JFreeChart c = chartt.getChart(); XYPlot xyp = c.getXYPlot(); XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) xyp.getRenderer(); TimeSeriesCollection tsc = (TimeSeriesCollection) xyp.getDataset(); if(tsc.getSeries("invisible")==null){ tsc.addSeries( new TimeSeries("invisible")); Shape shape = new java.awt.geom.Ellipse2D.Double(-2.0, -2.0, 5.0, 5.0); r.setSeriesShape(tsc.getSeriesIndex("invisible"), shape); r.setSeriesShapesVisible(tsc.getSeriesIndex("invisible"),true); r.setSeriesLinesVisible(tsc.getSeriesIndex("invisible"), false); r.setSeriesVisibleInLegend(tsc.getSeriesIndex("invisible"),false ); r.setSeriesPaint(tsc.getSeriesIndex("invisible"), Color.black); } TimeSeries s = tsc.getSeries("invisible"); s.clear(); HashSet<String> pset = new HashSet<>(); HashSet<String> vset = new HashSet<>(); for(int row: rows){ for(int i=0; i<tsc.getSeriesCount();i++){ TimeSeries ts = tsc.getSeries(i); for(int j=0; j<ts.getItemCount();j++){ if(samedate(t.getValueAt(row,0).toString(), (Day) ts.getDataItem(j).getPeriod())) s.addOrUpdate(ts.getDataItem(j).getPeriod(), ts.getDataItem(j).getValue()); } } //voorbereidend werk voor de piecharts te exploden if(plaatsFlag) pset.add(t.getValueAt(row,3).toString()); vset.add(t.getValueAt(row,2).toString()); } //explode de piecharts for(Object o: ((PiePlot) chartv.getChart().getPlot()).getDataset().getKeys()){ String str = o.toString(); if(vset.contains(str)) ((PiePlot) chartv.getChart().getPlot()).setExplodePercent(str,.33); else if(str!=null) ((PiePlot) chartv.getChart().getPlot()).setExplodePercent(str,0); } if(plaatsFlag){ for(Object o: ((PiePlot) chartp.getChart().getPlot()).getDataset().getKeys()){ String str = o.toString(); if(pset.contains(str)) ((PiePlot) chartp.getChart().getPlot()).setExplodePercent(str,.33); else if(str!=null) ((PiePlot) chartp.getChart().getPlot()).setExplodePercent(str,0); } } } //kijk na of een string die uit de tabel komt dezelfde dag voorstelt als een dag die uit de timechart is gehaald. public boolean samedate(String s, Day d){ String[] parts = s.split("/"); Day sd = new Day(Integer.parseInt(parts[0]),Integer.parseInt(parts[1]),Integer.parseInt(parts[2])); return(sd.equals(d)); } //draw de cantusTable, wordt momenteel niet meer gebruikt, kan later terug nodig zijn. public void drawCantusTable(List<Cantus> cantussen){ JScrollPane jtable = makeScrollTable(cantussen); panel.add(jtable); panel.setVisible(true); this.pack(); this.setVisible(true); } //construeer de scrollTable met een tabel van alle cantussen public JScrollPane makeScrollTable(List<Cantus> cantussen){ DefaultTableModel model = new DefaultTableModel(); model.addColumn("Datum"); model.addColumn("Cantus"); model.addColumn("Vereniging"); if(plaatsFlag) model.addColumn("plaats"); cantussen.sort(Cantus::compareTo); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); if(plaatsFlag){ for(Cantus cantus : cantussen){ Object[] array = {df.format(cantus.datum.getTime()), cantus.naam, cantus.vereniging,cantus.plaats}; model.addRow(array); } } else { for(Cantus cantus : cantussen){ Object[] array = {df.format(cantus.datum.getTime()), cantus.naam, cantus.vereniging}; model.addRow(array); } } JTable table = new JTable(model); this.setExtendedState(JFrame.MAXIMIZED_BOTH); return new JScrollPane(table); } //drawt een pieChart; wordt momenteel niet meer gebruikt, kan later terug nodig zijn. //@Override public void drawPieChart(List<String> dataset) { JFreeChart chart = makePieChart(dataset); splitPaneH.setLeftComponent(new ChartPanel(chart)); panel.setVisible(true); this.pack(); this.setVisible(true); } //gaat na of een lijst een niet null element bevat. nodig om te kijken of er plaatsen zijn ingegeven. private boolean containsNotNull(List<String> l){ for(String s: l) if(s != null && s.length()>0) return true; return false; } //construeer een piechart van een dataset. wordt gebruikt om de verenigingen en de plaatsen in een piechart te zetten. public JFreeChart makePieChart(List<String> dataset){ if(containsNotNull(dataset)){ dataset.sort(String::compareTo); } else { return null; } DefaultPieDataset ds = new DefaultPieDataset(); for (String s: dataset){ if(s != null && s.length()>0) { //System.out.println("string: " + s); if (ds.getKeys().contains(s)) { //System.out.println(ds.getValue(s)); ds.setValue(s, ds.getValue(s).intValue() + 1); } else ds.setValue(s, 1); } } ds.sortByValues(DESCENDING); int count = 0; for(Object o: ds.getKeys()){ if(ds.getValue((Comparable) o).intValue()<=dataset.size()/100){ count++; ds.remove((Comparable) o); } } if (count!=0) ds.setValue("Overige",count); return ChartFactory.createPieChart( "TAAAAAART", // chart title ds, // data true, // include legend true, false); } //drawt de timeline; wordt momenteel niet gebruikt, kan later terug nodig zijn. @Override public void drawTimeline(List<Calendar> dataset){ splitPaneH.setRightComponent(new ChartPanel(makeTimeLine(dataset))); panel.setVisible(true); this.pack(); this.setVisible(true); } //construeert de timeline public JFreeChart makeTimeLine(List<Calendar> dataset){ dataset.sort(Calendar::compareTo); genCumul(dataset,7); JFreeChart chart = ChartFactory.createTimeSeriesChart( "Waar-liep-het-fout-lijn", // Chart "Date", // X-Axis Label "cantus", // Y-Axis Label constructTSC(dataset)); XYPlot plot = (XYPlot)chart.getPlot(); plot.setBackgroundPaint(new Color(255,255,255)); plot.setDomainGridlinePaint(new Color(155,155,155)); plot.setRangeGridlinePaint(new Color(155,155,155)); for (int i = 0; i < plot.getSeriesCount(); i++) { plot.getRenderer().setSeriesStroke(i,new BasicStroke(2.0f)); } plot.setDataset(1, new TimeSeriesCollection(genCumul(dataset,7))); plot.setDataset(2, new TimeSeriesCollection(genCumul(dataset,31))); // Renderer voor cumul7 XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer(true,false); r1.setPaint(new Color(0,0,255)); // Renderer voor cumul31 XYLineAndShapeRenderer r2 = new XYLineAndShapeRenderer(true,false); r2.setPaint(new Color(0,255,0)); plot.setRenderer(1,r1); plot.setRenderer(2,r2); return chart; } //construeer de timeseriescollection van de lijst van data. private TimeSeriesCollection constructTSC(List<Calendar> dataset){ TimeSeriesCollection tsc = new TimeSeriesCollection(); TimeSeries series = new TimeSeries("Series1"); int i = 0; Calendar previous,c; while(i < dataset.size()){ c = dataset.get(i); Period p = getPeriod(c); if(i == 0){ series.setKey(p.name().toLowerCase() + "1"); addCount(p); } else { previous = dataset.get(i-1); if (diffPeriod(previous,c)) { series.addOrUpdate(new Day(c.getTime()),i+1); tsc.addSeries(series); series = new TimeSeries(p.name().toLowerCase() + getCount(p)); addCount(p); } } series.addOrUpdate(new Day(c.getTime()),i+1); i++; } tsc.addSeries(series); return tsc; } //genereer de cumulatieve lijn voor de laatste %i dagen. private TimeSeries genCumul(List<Calendar> ds, int i){ TimeSeries series = new TimeSeries("Cumul" + i); Calendar start = (Calendar) ds.get(0).clone(); Calendar end = (Calendar) ds.get(ds.size()-1).clone(); Calendar preStart= (Calendar) start.clone(); preStart.add(Calendar.DATE,-i); int count=0; while(start.before(end)){ if(ds.contains(preStart)) count-=frequency(ds,preStart); if(ds.contains(start)){ count+=frequency(ds,start); } //System.out.println(start.getTime()+ " cumul is " + count); series.addOrUpdate(new Day(start.getTime()),count); start.add(Calendar.DATE,1); preStart.add(Calendar.DATE,1); } return series; } //enum van mogelijke periodes public enum Period { SEMESTER, SUMMER, WINTER } //kijk na in welke periode een dag valt. private Period getPeriod(Calendar c){ Calendar c2 = getStartYear(c); Period p; if (daysBetween(c2,c) < 89){ p = Period.SEMESTER; }else if (daysBetween(c2,c) < 140){ p = Period.WINTER; }else if (daysBetween(c2,c) < 243){ p = Period.SEMESTER; }else { p = Period.SUMMER; } return p; } /* berekend de start van het academiejaar voor datum c de eerste maandag na de 20ste september die c voorafgaat */ private Calendar getStartYear(Calendar c){ Calendar c2 = Calendar.getInstance(); c2.set(c.get(Calendar.YEAR),Calendar.SEPTEMBER,20); //========================System.out.println(df.format(c2.getTime())); nextMonday(c2); if(c.before(c2)) { c2.set(c.get(Calendar.YEAR) - 1, Calendar.SEPTEMBER, 20); nextMonday(c2); } return c2; } //vormt een dag om naar de eerstvolgende maandag. private void nextMonday(Calendar c){ while(c.get(Calendar.DAY_OF_WEEK)!=Calendar.MONDAY) c.add(Calendar.DATE,1); } //geef het aantal dagen tussen 2 dagen terug private static long daysBetween(Calendar startDate, Calendar endDate) { long end = endDate.getTimeInMillis(); long start = startDate.getTimeInMillis(); return (end - start)/(60*60*24*1000) +1; } /* kijkt na of first en second in een verschillende periode liggen: valt first voor de start van het academiejaar van second? semester 1: start academiejaar .. 89 dagen later winter: 89dagen na start .. 140 dagen na start semester 2: 140 dagen na start .. 191 dagen na start zomer: 191 dagen na start .. volgende academiejaar. */ private boolean diffPeriod(Calendar first, Calendar second){ Calendar start = getStartYear(second); long d1 = daysBetween(start,first); long d2 = daysBetween(start,second); return (!first.after(start) || (d1<89 && d2 >= 89) || (d1<140 && d2 >= 140)|| (d1<243 && d2 >= 243)); } //geef aan de hoeveelste keer dat een periode gebruikt is. private int getCount(Period p){ if(p.equals(Period.SEMESTER)) return semestercount; if(p.equals(Period.SUMMER)) return summercount; return wintercount; } //tel 1<SUF> private void addCount(Period p){ if(p.equals(Period.SEMESTER)) { //System.out.println("add semester count"); semestercount++; } if(p.equals(Period.SUMMER)) summercount++; if(p.equals(Period.WINTER)) wintercount++; } }
134828_1
package com.denizenscript.denizen; import com.denizenscript.denizen.events.ScriptEventRegistry; import com.denizenscript.denizen.events.bukkit.SavesReloadEvent; import com.denizenscript.denizen.events.server.ServerPrestartScriptEvent; import com.denizenscript.denizen.events.server.ServerStartScriptEvent; import com.denizenscript.denizen.nms.NMSHandler; import com.denizenscript.denizen.nms.interfaces.FakeArrow; import com.denizenscript.denizen.nms.interfaces.FakePlayer; import com.denizenscript.denizen.nms.interfaces.ItemProjectile; import com.denizenscript.denizen.npc.DenizenNPCHelper; import com.denizenscript.denizen.npc.TraitRegistry; import com.denizenscript.denizen.objects.InventoryTag; import com.denizenscript.denizen.objects.NPCTag; import com.denizenscript.denizen.objects.PlayerTag; import com.denizenscript.denizen.objects.properties.PropertyRegistry; import com.denizenscript.denizen.scripts.commands.BukkitCommandRegistry; import com.denizenscript.denizen.scripts.commands.player.ClickableCommand; import com.denizenscript.denizen.scripts.containers.ContainerRegistry; import com.denizenscript.denizen.scripts.containers.core.*; import com.denizenscript.denizen.scripts.triggers.TriggerRegistry; import com.denizenscript.denizen.scripts.triggers.core.ChatTrigger; import com.denizenscript.denizen.tags.BukkitTagContext; import com.denizenscript.denizen.tags.core.NPCTagBase; import com.denizenscript.denizen.utilities.*; import com.denizenscript.denizen.utilities.blocks.FullBlockData; import com.denizenscript.denizen.utilities.command.*; import com.denizenscript.denizen.utilities.command.manager.CommandManager; import com.denizenscript.denizen.utilities.command.manager.Injector; import com.denizenscript.denizen.utilities.command.manager.messaging.Messaging; import com.denizenscript.denizen.utilities.debugging.BStatsMetricsLite; import com.denizenscript.denizen.utilities.debugging.DebugSubmit; import com.denizenscript.denizen.utilities.debugging.StatsRecord; import com.denizenscript.denizen.utilities.depends.Depends; import com.denizenscript.denizen.utilities.entity.DenizenEntityType; import com.denizenscript.denizen.utilities.flags.PlayerFlagHandler; import com.denizenscript.denizen.utilities.flags.WorldFlagHandler; import com.denizenscript.denizen.utilities.implementation.DenizenCoreImplementation; import com.denizenscript.denizen.utilities.maps.DenizenMapManager; import com.denizenscript.denizen.utilities.packets.NetworkInterceptHelper; import com.denizenscript.denizen.utilities.world.VoidGenerator; import com.denizenscript.denizen.utilities.world.WorldListChangeTracker; import com.denizenscript.denizencore.DenizenCore; import com.denizenscript.denizencore.objects.ObjectFetcher; import com.denizenscript.denizencore.objects.core.SecretTag; import com.denizenscript.denizencore.objects.core.TimeTag; import com.denizenscript.denizencore.objects.notable.NoteManager; import com.denizenscript.denizencore.scripts.ScriptHelper; import com.denizenscript.denizencore.scripts.commands.queue.RunLaterCommand; import com.denizenscript.denizencore.utilities.CoreConfiguration; import com.denizenscript.denizencore.utilities.CoreUtilities; import com.denizenscript.denizencore.utilities.debugging.Debug; import com.denizenscript.denizencore.utilities.debugging.DebugInternals; import com.denizenscript.denizencore.utilities.debugging.StrongWarning; import com.denizenscript.denizencore.utilities.text.ConfigUpdater; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerChatEvent; import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; import java.io.*; import java.net.URLDecoder; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; public class Denizen extends JavaPlugin { public static Denizen instance; public static Denizen getInstance() { return instance; } public static boolean hasTickedOnce = false; public static String versionTag = null; private boolean startedSuccessful = false; public static boolean supportsPaper = false; public CommandManager commandManager; public TriggerRegistry triggerRegistry; public DenizenNPCHelper npcHelper; public BukkitWorldScriptHelper worldScriptHelper; public ItemScriptHelper itemScriptHelper; public ExCommandHandler exCommand; public DenizenCoreImplementation coreImplementation = new DenizenCoreImplementation(); /* * Sets up Denizen on start of the CraftBukkit server. */ @Override public void onEnable() { long startTime = System.currentTimeMillis(); instance = this; try { versionTag = this.getDescription().getVersion(); CoreUtilities.noDebugContext = new BukkitTagContext(null, null, null, false, null); CoreUtilities.noDebugContext.showErrors = () -> false; CoreUtilities.basicContext = new BukkitTagContext(null, null, null, true, null); CoreUtilities.errorButNoDebugContext = new BukkitTagContext(null, null, null, false, null); // Load Denizen's core DenizenCore.init(coreImplementation); } catch (Exception e) { e.printStackTrace(); getServer().getPluginManager().disablePlugin(this); startedSuccessful = false; return; } PlayerFlagHandler.dataFolder = new File(getDataFolder(), "player_flags"); if (!PlayerFlagHandler.dataFolder.exists()) { PlayerFlagHandler.dataFolder.mkdir(); } DebugInternals.alternateTrimLogic = FormattedTextHelper::bukkitSafeDebugTrimming; String javaVersion = System.getProperty("java.version"); Debug.log("Running on java version: " + javaVersion); if (javaVersion.startsWith("8") || javaVersion.startsWith("1.8") || javaVersion.startsWith("9") || javaVersion.startsWith("1.9") || javaVersion.startsWith("10") || javaVersion.startsWith("1.10") || javaVersion.startsWith("11") || javaVersion.startsWith("12") || javaVersion.startsWith("13") || javaVersion.startsWith("14") || javaVersion.startsWith("15")) { Debug.log("Running on outdated Java version somehow. Denizen requires Java 16+ or newer to function."); } else if (javaVersion.startsWith("16")) { Debug.log("Running on fully supported Java 16."); } else if (javaVersion.startsWith("17")) { Debug.log("Running on fully supported Java 17."); } else if (javaVersion.startsWith("18") || javaVersion.startsWith("19")) { getLogger().warning("Running unreliable future Java version. modern Minecraft versions are built for Java 17. Other Java versions are not guaranteed to function properly."); } else { Debug.log("Running on unrecognized (future?) Java version. May or may not work."); } if (!NMSHandler.initialize(this)) { getLogger().warning("-------------------------------------"); getLogger().warning("This build of Denizen is not compatible with this Spigot version! Deactivating Denizen!"); getLogger().warning("-------------------------------------"); getServer().getPluginManager().disablePlugin(this); startedSuccessful = false; return; } if (!NMSHandler.instance.isCorrectMappingsCode()) { getLogger().warning("-------------------------------------"); getLogger().warning("This build of Denizen was built for a different Spigot revision! This may potentially cause issues." + " If you are experiencing trouble, update Denizen and Spigot both to latest builds!" + " If this message appears with both Denizen and Spigot fully up-to-date, contact the Denizen team (via GitHub, Spigot, or Discord) to request an update be built."); getLogger().warning("-------------------------------------"); } triggerRegistry = new TriggerRegistry(); boolean citizensBork = false; try { // Activate dependencies Depends.initialize(); if (Depends.citizens == null) { if (Bukkit.getPluginManager().getPlugin("Citizens") != null) { citizensBork = true; getLogger().warning("Citizens is present but doesn't seem to be activated! You may have an error earlier in your logs, or you may have a broken plugin load order."); } else { getLogger().warning("Citizens does not seem to be available! Denizen will have reduced functionality!"); } } startedSuccessful = true; } catch (Exception e) { Debug.echoError(e); } try { // Populate config.yml if it doesn't yet exist. saveDefaultConfig(); reloadConfig(); // Startup procedure Debug.log(ChatColor.LIGHT_PURPLE + "+-------------------------+"); Debug.log(ChatColor.YELLOW + " Denizen " + ChatColor.GRAY + " scriptable minecraft"); Debug.log(""); Debug.log(ChatColor.GRAY + "by:" + ChatColor.WHITE + " The DenizenScript team"); Debug.log(ChatColor.GRAY + "Chat with us at:" + ChatColor.WHITE + " https://discord.gg/Q6pZGSR"); Debug.log(ChatColor.GRAY + "Or learn more at:" + ChatColor.WHITE + " https://denizenscript.com"); Debug.log(ChatColor.GRAY + "version: " + ChatColor.WHITE + versionTag); Debug.log(ChatColor.LIGHT_PURPLE + "+-------------------------+"); } catch (Exception e) { Debug.echoError(e); } try { if (Class.forName("com.destroystokyo.paper.PaperConfig") != null) { supportsPaper = true; } } catch (ClassNotFoundException ex) { // Ignore. } catch (Throwable ex) { Debug.echoError(ex); } // bstats.org try { BStatsMetricsLite metrics = new BStatsMetricsLite(this); } catch (Throwable e) { Debug.echoError(e); } try { DebugSubmit.init(); // If Citizens is enabled, Create the NPC Helper if (Depends.citizens != null) { npcHelper = new DenizenNPCHelper(); } // Create our CommandManager to handle '/denizen' commands commandManager = new CommandManager(); commandManager.setInjector(new Injector(this)); commandManager.register(DenizenCommandHandler.class); // If Citizens is enabled, let it handle '/npc' commands if (Depends.citizens != null) { Depends.citizens.registerCommandClass(NPCCommandHandler.class); } DenizenEntityType.registerEntityType("ITEM_PROJECTILE", ItemProjectile.class); DenizenEntityType.registerEntityType("FAKE_ARROW", FakeArrow.class); DenizenEntityType.registerEntityType("FAKE_PLAYER", FakePlayer.class); // Track all player names for quick PlayerTag matching for (OfflinePlayer player : Bukkit.getOfflinePlayers()) { PlayerTag.notePlayer(player); } } catch (Exception e) { Debug.echoError(e); } try { BukkitCommandRegistry.registerCommands(); } catch (Exception e) { Debug.echoError(e); } try { ContainerRegistry.registerMainContainers(); } catch (Exception e) { Debug.echoError(e); } try { // Ensure the Scripts and Midi folder exist new File(getDataFolder() + "/scripts").mkdirs(); new File(getDataFolder() + "/midi").mkdirs(); new File(getDataFolder() + "/schematics").mkdirs(); // Ensure the example Denizen.mid sound file is available if (!new File(getDataFolder() + "/midi/Denizen.mid").exists()) { String sourceFile = URLDecoder.decode(Denizen.class.getProtectionDomain().getCodeSource().getLocation().getFile()); Debug.log("Denizen.mid not found, extracting from " + sourceFile); Utilities.extractFile(new File(sourceFile), "Denizen.mid", getDataFolder() + "/midi/"); } } catch (Exception e) { Debug.echoError(e); } try { // Automatic config file update InputStream properConfig = Denizen.class.getResourceAsStream("/config.yml"); String properConfigString = ScriptHelper.convertStreamToString(properConfig); properConfig.close(); FileInputStream currentConfig = new FileInputStream(getDataFolder() + "/config.yml"); String currentConfigString = ScriptHelper.convertStreamToString(currentConfig); currentConfig.close(); String updated = ConfigUpdater.updateConfig(currentConfigString, properConfigString); if (updated != null) { Debug.log("Your config file is outdated. Automatically updating it..."); FileOutputStream configOutput = new FileOutputStream(getDataFolder() + "/config.yml"); OutputStreamWriter writer = new OutputStreamWriter(configOutput); writer.write(updated); writer.close(); configOutput.close(); reloadConfig(); } } catch (Exception e) { Debug.echoError(e); } try { worldScriptHelper = new BukkitWorldScriptHelper(); itemScriptHelper = new ItemScriptHelper(); new InventoryScriptHelper(); new EntityScriptHelper(); new CommandScriptHelper(); } catch (Exception e) { Debug.echoError(e); } try { if (Depends.citizens != null) { // Register traits TraitRegistry.registerMainTraits(); } } catch (Exception e) { Debug.echoError(e); } // Register Core Members in the Denizen Registries try { if (Depends.citizens != null) { triggerRegistry.registerCoreMembers(); } } catch (Exception e) { Debug.echoError(e); } try { ScriptEventRegistry.registerMainEvents(); CommonRegistries.registerMainObjects(); CommonRegistries.registerMainTagHandlers(); } catch (Exception e) { Debug.echoError(e); } try { // Initialize all properties PropertyRegistry.registerMainProperties(); } catch (Exception e) { Debug.echoError(e); } try { new CommandEvents(); if (Settings.cache_packetInterceptAutoInit) { NetworkInterceptHelper.enable(); } } catch (Exception e) { Debug.echoError(e); } try { if (supportsPaper) { final Class<?> clazz = Class.forName("com.denizenscript.denizen.paper.PaperModule"); clazz.getMethod("init").invoke(null); } } catch (ClassNotFoundException ex) { supportsPaper = false; } catch (Throwable ex) { supportsPaper = false; Debug.echoError(ex); } Debug.log("Loaded <A>" + DenizenCore.commandRegistry.instances.size() + "<W> core commands and <A>" + ObjectFetcher.objectsByPrefix.size() + "<W> core object types, at <A>" + (System.currentTimeMillis() - startTime) + "<W>ms from start."); exCommand = new ExCommandHandler(); exCommand.enableFor(getCommand("ex")); ExSustainedCommandHandler exsCommand = new ExSustainedCommandHandler(); exsCommand.enableFor(getCommand("exs")); FullBlockData.init(); // Load script files without processing. DenizenCore.preloadScripts(false, null); // Load the saves.yml into memory reloadSaves(); try { // Fire the 'on Server PreStart' world event ServerPrestartScriptEvent.instance.specialHackRunEvent(); } catch (Throwable ex) { Debug.echoError(ex); } Debug.log("Final full init took <A>" + (System.currentTimeMillis() - startTime) + "<W>ms."); final boolean hadCitizensBork = citizensBork; // Run everything else on the first server tick Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> { hasTickedOnce = true; try { if (hadCitizensBork) { Depends.setupCitizens(); if (Depends.citizens != null) { getLogger().warning("Citizens was activated late - this means a plugin load order error occurred. You may have plugins with invalid 'plugin.yml' files (eg that use the 'loadbefore' directive, or that have circular dependencies)."); npcHelper = new DenizenNPCHelper(); Depends.citizens.registerCommandClass(NPCCommandHandler.class); TraitRegistry.registerMainTraits(); triggerRegistry.registerCoreMembers(); BukkitCommandRegistry.registerCitizensCommands(); ScriptEventRegistry.registerCitizensEvents(); new NPCTagBase(); ObjectFetcher.registerWithObjectFetcher(NPCTag.class, NPCTag.tagProcessor); } } } catch (Throwable ex) { Debug.echoError(ex); } try { // Process script files (events, etc). NoteManager.reload(); DenizenCore.postLoadScripts(); Debug.log(ChatColor.LIGHT_PURPLE + "+-------------------------+"); // Fire the 'on Server Start' world event ServerStartScriptEvent.instance.fire(); worldScriptHelper.serverStartEvent(); if (Settings.allowStupidx()) { Debug.echoError("Don't screw with bad config values."); Bukkit.shutdown(); } Bukkit.getScheduler().scheduleSyncRepeatingTask(Denizen.this, () -> { DenizenCore.tick(50); // Sadly, minecraft has no delta timing, so a tick is always 50ms. }, 1, 1); InventoryTag.setupInventoryTracker(); if (!CoreConfiguration.skipAllFlagCleanings && !Settings.skipChunkFlagCleaning) { BukkitWorldScriptHelper.cleanAllWorldChunkFlags(); } Bukkit.getPluginManager().registerEvents(new PlayerFlagHandler(), this); Debug.log("Denizen fully loaded at: " + TimeTag.now().format()); } catch (Throwable ex) { Debug.echoError(ex); } }, 1); new BukkitRunnable() { @Override public void run() { if (Settings.canRecordStats()) { StatsRecord.trigger(); } } }.runTaskTimer(this, 100, 20 * 60 * 60); new BukkitRunnable() { @Override public void run() { PlayerFlagHandler.cleanCache(); } }.runTaskTimer(this, 100, 20 * 60); new BukkitRunnable() { @Override public void run() { if (!StrongWarning.recentWarnings.isEmpty()) { StringBuilder warnText = new StringBuilder(); warnText.append(ChatColor.YELLOW).append("[Denizen] ").append(ChatColor.RED).append("Recent strong system warnings, scripters need to address ASAP (check earlier console logs for details):"); for (StrongWarning warning : StrongWarning.recentWarnings.keySet()) { warnText.append("\n- ").append(warning.message); } StrongWarning.recentWarnings.clear(); Bukkit.getConsoleSender().sendMessage(warnText.toString()); for (Player player : Bukkit.getOnlinePlayers()) { if (player.isOp()) { player.sendMessage(warnText.toString()); } } } } }.runTaskTimer(this, 100, 20 * 60 * 5); Bukkit.getPluginManager().registerEvents(new WorldListChangeTracker(), this); } public boolean hasDisabled = false; /* * Unloads Denizen on shutdown of the server. */ @Override public void onDisable() { if (!startedSuccessful) { return; } if (hasDisabled) { return; } hasDisabled = true; DenizenCore.shutdown(); ScoreboardHelper._saveScoreboards(); InventoryScriptHelper.savePlayerInventories(); triggerRegistry.disableCoreMembers(); getLogger().log(Level.INFO, " v" + getDescription().getVersion() + " disabled."); Bukkit.getServer().getScheduler().cancelTasks(this); HandlerList.unregisterAll(this); saveSaves(true); worldFlags.shutdown(); } @Override public void reloadConfig() { super.reloadConfig(); Settings.refillCache(); SecretTag.load(); if (!CoreConfiguration.defaultDebugMode) { getLogger().warning("Debug is disabled in the Denizen config. This is almost always a mistake, and should not be done in the majority of cases."); } } private FileConfiguration scoreboardsConfig = null; private File scoreboardsConfigFile = null; public WorldFlagHandler worldFlags; public void reloadSaves() { if (scoreboardsConfigFile == null) { scoreboardsConfigFile = new File(getDataFolder(), "scoreboards.yml"); } scoreboardsConfig = YamlConfiguration.loadConfiguration(scoreboardsConfigFile); // Reload scoreboards from scoreboards.yml ScoreboardHelper._recallScoreboards(); // Load maps from maps.yml DenizenMapManager.reloadMaps(); DenizenCore.reloadSaves(); if (worldFlags == null) { worldFlags = new WorldFlagHandler(); } worldFlags.shutdown(); worldFlags.init(); RunLaterCommand.init(new File(getDataFolder(), "run_later.yml").getPath()); if (new File(getDataFolder(), "saves.yml").exists()) { LegacySavesUpdater.updateLegacySaves(); } Bukkit.getServer().getPluginManager().callEvent(new SavesReloadEvent()); } public FileConfiguration getScoreboards() { if (scoreboardsConfig == null) { reloadSaves(); } return scoreboardsConfig; } /** * Immediately saves all non-core save data. * @param lockUntilDone 'true' if the system should sleep and lock the thread until saves are complete. 'false' is saves can happen in the future. */ public void saveSaves(boolean lockUntilDone) { // Save scoreboards to scoreboards.yml ScoreboardHelper._saveScoreboards(); // Save maps to maps.yml DenizenMapManager.saveMaps(); InventoryScriptHelper.savePlayerInventories(); // Save server flags try { scoreboardsConfig.save(scoreboardsConfigFile); } catch (IOException ex) { Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not save to " + scoreboardsConfigFile, ex); } PlayerFlagHandler.saveAllNow(lockUntilDone); worldFlags.saveAll(lockUntilDone); RunLaterCommand.saveToFile(!lockUntilDone); } @Override public boolean onCommand(CommandSender sender, Command cmd, String alias, String[] args) { if (cmd.getName().equals("denizenclickable")) { if (!(sender instanceof Player)) { return false; } if (args.length >= 2 && CoreUtilities.equalsIgnoreCase(args[0], "chat")) { ChatTrigger.instance.chatTriggerInternal(new PlayerChatEvent((Player) sender, Arrays.stream(args).skip(1).collect(Collectors.joining(" ")))); return true; } if (args.length != 1) { return false; } UUID id; try { id = UUID.fromString(args[0]); } catch (IllegalArgumentException ex) { return false; } ClickableCommand.runClickable(id, (Player) sender); return true; } String modifier = args.length > 0 ? args[0] : ""; if (!commandManager.hasCommand(cmd, modifier) && !modifier.isEmpty()) { return suggestClosestModifier(sender, cmd.getName(), modifier); } Object[] methodArgs = {sender}; return commandManager.executeSafe(cmd, args, sender, methodArgs); } @Override public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] strings) { if (alias.equals("denizen")) { return commandManager.onTabComplete(commandSender, command, alias, strings); } return null; } private boolean suggestClosestModifier(CommandSender sender, String command, String modifier) { String closest = commandManager.getClosestCommandModifier(command, modifier); if (!closest.isEmpty()) { Messaging.send(sender, "<7>Unknown command. Did you mean:"); Messaging.send(sender, " /" + command + " " + closest); return true; } return false; } @Override public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { return switch (CoreUtilities.toLowerCase(id)) { case "void" -> new VoidGenerator(true); case "void_biomes" -> new VoidGenerator(false); default -> null; }; } }
DenizenScript/Denizen
plugin/src/main/java/com/denizenscript/denizen/Denizen.java
7,319
// Load Denizen's core
line_comment
nl
package com.denizenscript.denizen; import com.denizenscript.denizen.events.ScriptEventRegistry; import com.denizenscript.denizen.events.bukkit.SavesReloadEvent; import com.denizenscript.denizen.events.server.ServerPrestartScriptEvent; import com.denizenscript.denizen.events.server.ServerStartScriptEvent; import com.denizenscript.denizen.nms.NMSHandler; import com.denizenscript.denizen.nms.interfaces.FakeArrow; import com.denizenscript.denizen.nms.interfaces.FakePlayer; import com.denizenscript.denizen.nms.interfaces.ItemProjectile; import com.denizenscript.denizen.npc.DenizenNPCHelper; import com.denizenscript.denizen.npc.TraitRegistry; import com.denizenscript.denizen.objects.InventoryTag; import com.denizenscript.denizen.objects.NPCTag; import com.denizenscript.denizen.objects.PlayerTag; import com.denizenscript.denizen.objects.properties.PropertyRegistry; import com.denizenscript.denizen.scripts.commands.BukkitCommandRegistry; import com.denizenscript.denizen.scripts.commands.player.ClickableCommand; import com.denizenscript.denizen.scripts.containers.ContainerRegistry; import com.denizenscript.denizen.scripts.containers.core.*; import com.denizenscript.denizen.scripts.triggers.TriggerRegistry; import com.denizenscript.denizen.scripts.triggers.core.ChatTrigger; import com.denizenscript.denizen.tags.BukkitTagContext; import com.denizenscript.denizen.tags.core.NPCTagBase; import com.denizenscript.denizen.utilities.*; import com.denizenscript.denizen.utilities.blocks.FullBlockData; import com.denizenscript.denizen.utilities.command.*; import com.denizenscript.denizen.utilities.command.manager.CommandManager; import com.denizenscript.denizen.utilities.command.manager.Injector; import com.denizenscript.denizen.utilities.command.manager.messaging.Messaging; import com.denizenscript.denizen.utilities.debugging.BStatsMetricsLite; import com.denizenscript.denizen.utilities.debugging.DebugSubmit; import com.denizenscript.denizen.utilities.debugging.StatsRecord; import com.denizenscript.denizen.utilities.depends.Depends; import com.denizenscript.denizen.utilities.entity.DenizenEntityType; import com.denizenscript.denizen.utilities.flags.PlayerFlagHandler; import com.denizenscript.denizen.utilities.flags.WorldFlagHandler; import com.denizenscript.denizen.utilities.implementation.DenizenCoreImplementation; import com.denizenscript.denizen.utilities.maps.DenizenMapManager; import com.denizenscript.denizen.utilities.packets.NetworkInterceptHelper; import com.denizenscript.denizen.utilities.world.VoidGenerator; import com.denizenscript.denizen.utilities.world.WorldListChangeTracker; import com.denizenscript.denizencore.DenizenCore; import com.denizenscript.denizencore.objects.ObjectFetcher; import com.denizenscript.denizencore.objects.core.SecretTag; import com.denizenscript.denizencore.objects.core.TimeTag; import com.denizenscript.denizencore.objects.notable.NoteManager; import com.denizenscript.denizencore.scripts.ScriptHelper; import com.denizenscript.denizencore.scripts.commands.queue.RunLaterCommand; import com.denizenscript.denizencore.utilities.CoreConfiguration; import com.denizenscript.denizencore.utilities.CoreUtilities; import com.denizenscript.denizencore.utilities.debugging.Debug; import com.denizenscript.denizencore.utilities.debugging.DebugInternals; import com.denizenscript.denizencore.utilities.debugging.StrongWarning; import com.denizenscript.denizencore.utilities.text.ConfigUpdater; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerChatEvent; import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; import java.io.*; import java.net.URLDecoder; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; public class Denizen extends JavaPlugin { public static Denizen instance; public static Denizen getInstance() { return instance; } public static boolean hasTickedOnce = false; public static String versionTag = null; private boolean startedSuccessful = false; public static boolean supportsPaper = false; public CommandManager commandManager; public TriggerRegistry triggerRegistry; public DenizenNPCHelper npcHelper; public BukkitWorldScriptHelper worldScriptHelper; public ItemScriptHelper itemScriptHelper; public ExCommandHandler exCommand; public DenizenCoreImplementation coreImplementation = new DenizenCoreImplementation(); /* * Sets up Denizen on start of the CraftBukkit server. */ @Override public void onEnable() { long startTime = System.currentTimeMillis(); instance = this; try { versionTag = this.getDescription().getVersion(); CoreUtilities.noDebugContext = new BukkitTagContext(null, null, null, false, null); CoreUtilities.noDebugContext.showErrors = () -> false; CoreUtilities.basicContext = new BukkitTagContext(null, null, null, true, null); CoreUtilities.errorButNoDebugContext = new BukkitTagContext(null, null, null, false, null); // Load Denizen's<SUF> DenizenCore.init(coreImplementation); } catch (Exception e) { e.printStackTrace(); getServer().getPluginManager().disablePlugin(this); startedSuccessful = false; return; } PlayerFlagHandler.dataFolder = new File(getDataFolder(), "player_flags"); if (!PlayerFlagHandler.dataFolder.exists()) { PlayerFlagHandler.dataFolder.mkdir(); } DebugInternals.alternateTrimLogic = FormattedTextHelper::bukkitSafeDebugTrimming; String javaVersion = System.getProperty("java.version"); Debug.log("Running on java version: " + javaVersion); if (javaVersion.startsWith("8") || javaVersion.startsWith("1.8") || javaVersion.startsWith("9") || javaVersion.startsWith("1.9") || javaVersion.startsWith("10") || javaVersion.startsWith("1.10") || javaVersion.startsWith("11") || javaVersion.startsWith("12") || javaVersion.startsWith("13") || javaVersion.startsWith("14") || javaVersion.startsWith("15")) { Debug.log("Running on outdated Java version somehow. Denizen requires Java 16+ or newer to function."); } else if (javaVersion.startsWith("16")) { Debug.log("Running on fully supported Java 16."); } else if (javaVersion.startsWith("17")) { Debug.log("Running on fully supported Java 17."); } else if (javaVersion.startsWith("18") || javaVersion.startsWith("19")) { getLogger().warning("Running unreliable future Java version. modern Minecraft versions are built for Java 17. Other Java versions are not guaranteed to function properly."); } else { Debug.log("Running on unrecognized (future?) Java version. May or may not work."); } if (!NMSHandler.initialize(this)) { getLogger().warning("-------------------------------------"); getLogger().warning("This build of Denizen is not compatible with this Spigot version! Deactivating Denizen!"); getLogger().warning("-------------------------------------"); getServer().getPluginManager().disablePlugin(this); startedSuccessful = false; return; } if (!NMSHandler.instance.isCorrectMappingsCode()) { getLogger().warning("-------------------------------------"); getLogger().warning("This build of Denizen was built for a different Spigot revision! This may potentially cause issues." + " If you are experiencing trouble, update Denizen and Spigot both to latest builds!" + " If this message appears with both Denizen and Spigot fully up-to-date, contact the Denizen team (via GitHub, Spigot, or Discord) to request an update be built."); getLogger().warning("-------------------------------------"); } triggerRegistry = new TriggerRegistry(); boolean citizensBork = false; try { // Activate dependencies Depends.initialize(); if (Depends.citizens == null) { if (Bukkit.getPluginManager().getPlugin("Citizens") != null) { citizensBork = true; getLogger().warning("Citizens is present but doesn't seem to be activated! You may have an error earlier in your logs, or you may have a broken plugin load order."); } else { getLogger().warning("Citizens does not seem to be available! Denizen will have reduced functionality!"); } } startedSuccessful = true; } catch (Exception e) { Debug.echoError(e); } try { // Populate config.yml if it doesn't yet exist. saveDefaultConfig(); reloadConfig(); // Startup procedure Debug.log(ChatColor.LIGHT_PURPLE + "+-------------------------+"); Debug.log(ChatColor.YELLOW + " Denizen " + ChatColor.GRAY + " scriptable minecraft"); Debug.log(""); Debug.log(ChatColor.GRAY + "by:" + ChatColor.WHITE + " The DenizenScript team"); Debug.log(ChatColor.GRAY + "Chat with us at:" + ChatColor.WHITE + " https://discord.gg/Q6pZGSR"); Debug.log(ChatColor.GRAY + "Or learn more at:" + ChatColor.WHITE + " https://denizenscript.com"); Debug.log(ChatColor.GRAY + "version: " + ChatColor.WHITE + versionTag); Debug.log(ChatColor.LIGHT_PURPLE + "+-------------------------+"); } catch (Exception e) { Debug.echoError(e); } try { if (Class.forName("com.destroystokyo.paper.PaperConfig") != null) { supportsPaper = true; } } catch (ClassNotFoundException ex) { // Ignore. } catch (Throwable ex) { Debug.echoError(ex); } // bstats.org try { BStatsMetricsLite metrics = new BStatsMetricsLite(this); } catch (Throwable e) { Debug.echoError(e); } try { DebugSubmit.init(); // If Citizens is enabled, Create the NPC Helper if (Depends.citizens != null) { npcHelper = new DenizenNPCHelper(); } // Create our CommandManager to handle '/denizen' commands commandManager = new CommandManager(); commandManager.setInjector(new Injector(this)); commandManager.register(DenizenCommandHandler.class); // If Citizens is enabled, let it handle '/npc' commands if (Depends.citizens != null) { Depends.citizens.registerCommandClass(NPCCommandHandler.class); } DenizenEntityType.registerEntityType("ITEM_PROJECTILE", ItemProjectile.class); DenizenEntityType.registerEntityType("FAKE_ARROW", FakeArrow.class); DenizenEntityType.registerEntityType("FAKE_PLAYER", FakePlayer.class); // Track all player names for quick PlayerTag matching for (OfflinePlayer player : Bukkit.getOfflinePlayers()) { PlayerTag.notePlayer(player); } } catch (Exception e) { Debug.echoError(e); } try { BukkitCommandRegistry.registerCommands(); } catch (Exception e) { Debug.echoError(e); } try { ContainerRegistry.registerMainContainers(); } catch (Exception e) { Debug.echoError(e); } try { // Ensure the Scripts and Midi folder exist new File(getDataFolder() + "/scripts").mkdirs(); new File(getDataFolder() + "/midi").mkdirs(); new File(getDataFolder() + "/schematics").mkdirs(); // Ensure the example Denizen.mid sound file is available if (!new File(getDataFolder() + "/midi/Denizen.mid").exists()) { String sourceFile = URLDecoder.decode(Denizen.class.getProtectionDomain().getCodeSource().getLocation().getFile()); Debug.log("Denizen.mid not found, extracting from " + sourceFile); Utilities.extractFile(new File(sourceFile), "Denizen.mid", getDataFolder() + "/midi/"); } } catch (Exception e) { Debug.echoError(e); } try { // Automatic config file update InputStream properConfig = Denizen.class.getResourceAsStream("/config.yml"); String properConfigString = ScriptHelper.convertStreamToString(properConfig); properConfig.close(); FileInputStream currentConfig = new FileInputStream(getDataFolder() + "/config.yml"); String currentConfigString = ScriptHelper.convertStreamToString(currentConfig); currentConfig.close(); String updated = ConfigUpdater.updateConfig(currentConfigString, properConfigString); if (updated != null) { Debug.log("Your config file is outdated. Automatically updating it..."); FileOutputStream configOutput = new FileOutputStream(getDataFolder() + "/config.yml"); OutputStreamWriter writer = new OutputStreamWriter(configOutput); writer.write(updated); writer.close(); configOutput.close(); reloadConfig(); } } catch (Exception e) { Debug.echoError(e); } try { worldScriptHelper = new BukkitWorldScriptHelper(); itemScriptHelper = new ItemScriptHelper(); new InventoryScriptHelper(); new EntityScriptHelper(); new CommandScriptHelper(); } catch (Exception e) { Debug.echoError(e); } try { if (Depends.citizens != null) { // Register traits TraitRegistry.registerMainTraits(); } } catch (Exception e) { Debug.echoError(e); } // Register Core Members in the Denizen Registries try { if (Depends.citizens != null) { triggerRegistry.registerCoreMembers(); } } catch (Exception e) { Debug.echoError(e); } try { ScriptEventRegistry.registerMainEvents(); CommonRegistries.registerMainObjects(); CommonRegistries.registerMainTagHandlers(); } catch (Exception e) { Debug.echoError(e); } try { // Initialize all properties PropertyRegistry.registerMainProperties(); } catch (Exception e) { Debug.echoError(e); } try { new CommandEvents(); if (Settings.cache_packetInterceptAutoInit) { NetworkInterceptHelper.enable(); } } catch (Exception e) { Debug.echoError(e); } try { if (supportsPaper) { final Class<?> clazz = Class.forName("com.denizenscript.denizen.paper.PaperModule"); clazz.getMethod("init").invoke(null); } } catch (ClassNotFoundException ex) { supportsPaper = false; } catch (Throwable ex) { supportsPaper = false; Debug.echoError(ex); } Debug.log("Loaded <A>" + DenizenCore.commandRegistry.instances.size() + "<W> core commands and <A>" + ObjectFetcher.objectsByPrefix.size() + "<W> core object types, at <A>" + (System.currentTimeMillis() - startTime) + "<W>ms from start."); exCommand = new ExCommandHandler(); exCommand.enableFor(getCommand("ex")); ExSustainedCommandHandler exsCommand = new ExSustainedCommandHandler(); exsCommand.enableFor(getCommand("exs")); FullBlockData.init(); // Load script files without processing. DenizenCore.preloadScripts(false, null); // Load the saves.yml into memory reloadSaves(); try { // Fire the 'on Server PreStart' world event ServerPrestartScriptEvent.instance.specialHackRunEvent(); } catch (Throwable ex) { Debug.echoError(ex); } Debug.log("Final full init took <A>" + (System.currentTimeMillis() - startTime) + "<W>ms."); final boolean hadCitizensBork = citizensBork; // Run everything else on the first server tick Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> { hasTickedOnce = true; try { if (hadCitizensBork) { Depends.setupCitizens(); if (Depends.citizens != null) { getLogger().warning("Citizens was activated late - this means a plugin load order error occurred. You may have plugins with invalid 'plugin.yml' files (eg that use the 'loadbefore' directive, or that have circular dependencies)."); npcHelper = new DenizenNPCHelper(); Depends.citizens.registerCommandClass(NPCCommandHandler.class); TraitRegistry.registerMainTraits(); triggerRegistry.registerCoreMembers(); BukkitCommandRegistry.registerCitizensCommands(); ScriptEventRegistry.registerCitizensEvents(); new NPCTagBase(); ObjectFetcher.registerWithObjectFetcher(NPCTag.class, NPCTag.tagProcessor); } } } catch (Throwable ex) { Debug.echoError(ex); } try { // Process script files (events, etc). NoteManager.reload(); DenizenCore.postLoadScripts(); Debug.log(ChatColor.LIGHT_PURPLE + "+-------------------------+"); // Fire the 'on Server Start' world event ServerStartScriptEvent.instance.fire(); worldScriptHelper.serverStartEvent(); if (Settings.allowStupidx()) { Debug.echoError("Don't screw with bad config values."); Bukkit.shutdown(); } Bukkit.getScheduler().scheduleSyncRepeatingTask(Denizen.this, () -> { DenizenCore.tick(50); // Sadly, minecraft has no delta timing, so a tick is always 50ms. }, 1, 1); InventoryTag.setupInventoryTracker(); if (!CoreConfiguration.skipAllFlagCleanings && !Settings.skipChunkFlagCleaning) { BukkitWorldScriptHelper.cleanAllWorldChunkFlags(); } Bukkit.getPluginManager().registerEvents(new PlayerFlagHandler(), this); Debug.log("Denizen fully loaded at: " + TimeTag.now().format()); } catch (Throwable ex) { Debug.echoError(ex); } }, 1); new BukkitRunnable() { @Override public void run() { if (Settings.canRecordStats()) { StatsRecord.trigger(); } } }.runTaskTimer(this, 100, 20 * 60 * 60); new BukkitRunnable() { @Override public void run() { PlayerFlagHandler.cleanCache(); } }.runTaskTimer(this, 100, 20 * 60); new BukkitRunnable() { @Override public void run() { if (!StrongWarning.recentWarnings.isEmpty()) { StringBuilder warnText = new StringBuilder(); warnText.append(ChatColor.YELLOW).append("[Denizen] ").append(ChatColor.RED).append("Recent strong system warnings, scripters need to address ASAP (check earlier console logs for details):"); for (StrongWarning warning : StrongWarning.recentWarnings.keySet()) { warnText.append("\n- ").append(warning.message); } StrongWarning.recentWarnings.clear(); Bukkit.getConsoleSender().sendMessage(warnText.toString()); for (Player player : Bukkit.getOnlinePlayers()) { if (player.isOp()) { player.sendMessage(warnText.toString()); } } } } }.runTaskTimer(this, 100, 20 * 60 * 5); Bukkit.getPluginManager().registerEvents(new WorldListChangeTracker(), this); } public boolean hasDisabled = false; /* * Unloads Denizen on shutdown of the server. */ @Override public void onDisable() { if (!startedSuccessful) { return; } if (hasDisabled) { return; } hasDisabled = true; DenizenCore.shutdown(); ScoreboardHelper._saveScoreboards(); InventoryScriptHelper.savePlayerInventories(); triggerRegistry.disableCoreMembers(); getLogger().log(Level.INFO, " v" + getDescription().getVersion() + " disabled."); Bukkit.getServer().getScheduler().cancelTasks(this); HandlerList.unregisterAll(this); saveSaves(true); worldFlags.shutdown(); } @Override public void reloadConfig() { super.reloadConfig(); Settings.refillCache(); SecretTag.load(); if (!CoreConfiguration.defaultDebugMode) { getLogger().warning("Debug is disabled in the Denizen config. This is almost always a mistake, and should not be done in the majority of cases."); } } private FileConfiguration scoreboardsConfig = null; private File scoreboardsConfigFile = null; public WorldFlagHandler worldFlags; public void reloadSaves() { if (scoreboardsConfigFile == null) { scoreboardsConfigFile = new File(getDataFolder(), "scoreboards.yml"); } scoreboardsConfig = YamlConfiguration.loadConfiguration(scoreboardsConfigFile); // Reload scoreboards from scoreboards.yml ScoreboardHelper._recallScoreboards(); // Load maps from maps.yml DenizenMapManager.reloadMaps(); DenizenCore.reloadSaves(); if (worldFlags == null) { worldFlags = new WorldFlagHandler(); } worldFlags.shutdown(); worldFlags.init(); RunLaterCommand.init(new File(getDataFolder(), "run_later.yml").getPath()); if (new File(getDataFolder(), "saves.yml").exists()) { LegacySavesUpdater.updateLegacySaves(); } Bukkit.getServer().getPluginManager().callEvent(new SavesReloadEvent()); } public FileConfiguration getScoreboards() { if (scoreboardsConfig == null) { reloadSaves(); } return scoreboardsConfig; } /** * Immediately saves all non-core save data. * @param lockUntilDone 'true' if the system should sleep and lock the thread until saves are complete. 'false' is saves can happen in the future. */ public void saveSaves(boolean lockUntilDone) { // Save scoreboards to scoreboards.yml ScoreboardHelper._saveScoreboards(); // Save maps to maps.yml DenizenMapManager.saveMaps(); InventoryScriptHelper.savePlayerInventories(); // Save server flags try { scoreboardsConfig.save(scoreboardsConfigFile); } catch (IOException ex) { Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not save to " + scoreboardsConfigFile, ex); } PlayerFlagHandler.saveAllNow(lockUntilDone); worldFlags.saveAll(lockUntilDone); RunLaterCommand.saveToFile(!lockUntilDone); } @Override public boolean onCommand(CommandSender sender, Command cmd, String alias, String[] args) { if (cmd.getName().equals("denizenclickable")) { if (!(sender instanceof Player)) { return false; } if (args.length >= 2 && CoreUtilities.equalsIgnoreCase(args[0], "chat")) { ChatTrigger.instance.chatTriggerInternal(new PlayerChatEvent((Player) sender, Arrays.stream(args).skip(1).collect(Collectors.joining(" ")))); return true; } if (args.length != 1) { return false; } UUID id; try { id = UUID.fromString(args[0]); } catch (IllegalArgumentException ex) { return false; } ClickableCommand.runClickable(id, (Player) sender); return true; } String modifier = args.length > 0 ? args[0] : ""; if (!commandManager.hasCommand(cmd, modifier) && !modifier.isEmpty()) { return suggestClosestModifier(sender, cmd.getName(), modifier); } Object[] methodArgs = {sender}; return commandManager.executeSafe(cmd, args, sender, methodArgs); } @Override public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] strings) { if (alias.equals("denizen")) { return commandManager.onTabComplete(commandSender, command, alias, strings); } return null; } private boolean suggestClosestModifier(CommandSender sender, String command, String modifier) { String closest = commandManager.getClosestCommandModifier(command, modifier); if (!closest.isEmpty()) { Messaging.send(sender, "<7>Unknown command. Did you mean:"); Messaging.send(sender, " /" + command + " " + closest); return true; } return false; } @Override public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { return switch (CoreUtilities.toLowerCase(id)) { case "void" -> new VoidGenerator(true); case "void_biomes" -> new VoidGenerator(false); default -> null; }; } }
66468_2
package nl.han.asd.app.lesson_1_2_recursie; public class Hanoi { private static final int AANTAL_SCHIJVEN = 64; private static final int START = 1; private static final int VIA = 2; private static final int DOEL = 3; /** * @param args the command line arguments */ public static void main(String[] args) { verplaats(AANTAL_SCHIJVEN, START, DOEL, VIA); } /** * Verplaatst een hanoi-toren van een plek naar de andere. * * @param aantalSchijven Hoogte van de toren. * @param start Plek waar de toren zich bevindt. * @param doel Plek waar de toren naartoe moet. * @param tussenplek Extra plek om te gebruiken. */ public static void verplaats(int aantalSchijven, int start, int doel, int tussenplek) { // stopconditie: 1 schijf over, dat is gemakkelijk if (aantalSchijven == 1) { System.out.printf("Verplaats schijf van plek %d naar plek %d\n", start, doel); } else { // los het recursief op // 1) de stapel op 1 na verplaatsen van start naar tussenplek verplaats(aantalSchijven - 1, start, tussenplek, doel); // 2) de onderste schijf verplaatsen van start naar doel verplaats(1, start, doel, tussenplek); // 3) de stapel op 1 na verplaatsen van tussenplek naar doel verplaats(aantalSchijven - 1, tussenplek, doel, start); } } }
DennisBreuker/APP
examples/src/main/java/nl/han/asd/app/lesson_1_2_recursie/Hanoi.java
484
// stopconditie: 1 schijf over, dat is gemakkelijk
line_comment
nl
package nl.han.asd.app.lesson_1_2_recursie; public class Hanoi { private static final int AANTAL_SCHIJVEN = 64; private static final int START = 1; private static final int VIA = 2; private static final int DOEL = 3; /** * @param args the command line arguments */ public static void main(String[] args) { verplaats(AANTAL_SCHIJVEN, START, DOEL, VIA); } /** * Verplaatst een hanoi-toren van een plek naar de andere. * * @param aantalSchijven Hoogte van de toren. * @param start Plek waar de toren zich bevindt. * @param doel Plek waar de toren naartoe moet. * @param tussenplek Extra plek om te gebruiken. */ public static void verplaats(int aantalSchijven, int start, int doel, int tussenplek) { // stopconditie: 1<SUF> if (aantalSchijven == 1) { System.out.printf("Verplaats schijf van plek %d naar plek %d\n", start, doel); } else { // los het recursief op // 1) de stapel op 1 na verplaatsen van start naar tussenplek verplaats(aantalSchijven - 1, start, tussenplek, doel); // 2) de onderste schijf verplaatsen van start naar doel verplaats(1, start, doel, tussenplek); // 3) de stapel op 1 na verplaatsen van tussenplek naar doel verplaats(aantalSchijven - 1, tussenplek, doel, start); } } }
174497_7
package nl.han.aim.asd.calculator; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeWalker; import nl.han.aim.asd.parser.*; import java.util.Scanner; /** * Created by Michel Koolwaaij on 10-10-18. */ public class Main { public static void main(String[] args){ // Read expression from user Scanner scanner = new Scanner(System.in); System.out.print("Enter an expression: "); String expressionString = scanner.nextLine(); // Create pipeline CharStream stream = CharStreams.fromString(expressionString); ExpressionsLexer lexer = new ExpressionsLexer(stream); TokenStream tokens = new CommonTokenStream(lexer); ExpressionsParser parser = new ExpressionsParser(tokens); // Tot hier alleen maar aanroepen // Try to match expressionString to the start rule and create parse tree ParseTree tree = parser.start(); // Ook deze krijg ik cadeau // Walk through parse tree using our own listener ParseTreeWalker walker = new ParseTreeWalker(); // En deze ExpressionReader reader = new ExpressionReader(); // Alleen deze maak ik zelf walker.walk(reader, tree); // En deze krijg ik weer cadeau Checker checker = new Checker(reader); checker.check(); System.out.println(expressionString + " = " + new Evaluator().evaluate(reader.getTopExpression())); } }
DennisBreuker/calculator
src/main/java/nl/han/aim/asd/calculator/Main.java
460
// En deze krijg ik weer cadeau
line_comment
nl
package nl.han.aim.asd.calculator; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeWalker; import nl.han.aim.asd.parser.*; import java.util.Scanner; /** * Created by Michel Koolwaaij on 10-10-18. */ public class Main { public static void main(String[] args){ // Read expression from user Scanner scanner = new Scanner(System.in); System.out.print("Enter an expression: "); String expressionString = scanner.nextLine(); // Create pipeline CharStream stream = CharStreams.fromString(expressionString); ExpressionsLexer lexer = new ExpressionsLexer(stream); TokenStream tokens = new CommonTokenStream(lexer); ExpressionsParser parser = new ExpressionsParser(tokens); // Tot hier alleen maar aanroepen // Try to match expressionString to the start rule and create parse tree ParseTree tree = parser.start(); // Ook deze krijg ik cadeau // Walk through parse tree using our own listener ParseTreeWalker walker = new ParseTreeWalker(); // En deze ExpressionReader reader = new ExpressionReader(); // Alleen deze maak ik zelf walker.walk(reader, tree); // En deze<SUF> Checker checker = new Checker(reader); checker.check(); System.out.println(expressionString + " = " + new Evaluator().evaluate(reader.getTopExpression())); } }
174460_7
package nl.han.aim.asd.calculator; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeWalker; import nl.han.aim.asd.parser.*; import java.util.Scanner; /** * Created by Michel Koolwaaij on 10-10-18. */ public class Main { public static void main(String[] args){ // Read expression from user Scanner scanner = new Scanner(System.in); System.out.print("Enter an expression: "); String expressionString = scanner.nextLine(); // Create pipeline CharStream stream = CharStreams.fromString(expressionString); ExpressionsLexer lexer = new ExpressionsLexer(stream); TokenStream tokens = new CommonTokenStream(lexer); ExpressionsParser parser = new ExpressionsParser(tokens); // Tot hier alleen maar aanroepen // Try to match expressionString to the start rule and create parse tree ParseTree tree = parser.start(); // Ook deze krijg ik cadeau // Walk through parse tree using our own listener ParseTreeWalker walker = new ParseTreeWalker(); // En deze ExpressionReader reader = new ExpressionReader(); // Alleen deze maak ik zelf walker.walk(reader, tree); // En deze krijg ik weer cadeau // TODO: reken de gegeven som uit // System.out.println(expressionString + " = " // + new Evaluator().evaluate(reader.getTopExpression())); } }
DennisBreuker/calculator-startcode
src/main/java/nl/han/aim/asd/calculator/Main.java
454
// En deze krijg ik weer cadeau
line_comment
nl
package nl.han.aim.asd.calculator; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeWalker; import nl.han.aim.asd.parser.*; import java.util.Scanner; /** * Created by Michel Koolwaaij on 10-10-18. */ public class Main { public static void main(String[] args){ // Read expression from user Scanner scanner = new Scanner(System.in); System.out.print("Enter an expression: "); String expressionString = scanner.nextLine(); // Create pipeline CharStream stream = CharStreams.fromString(expressionString); ExpressionsLexer lexer = new ExpressionsLexer(stream); TokenStream tokens = new CommonTokenStream(lexer); ExpressionsParser parser = new ExpressionsParser(tokens); // Tot hier alleen maar aanroepen // Try to match expressionString to the start rule and create parse tree ParseTree tree = parser.start(); // Ook deze krijg ik cadeau // Walk through parse tree using our own listener ParseTreeWalker walker = new ParseTreeWalker(); // En deze ExpressionReader reader = new ExpressionReader(); // Alleen deze maak ik zelf walker.walk(reader, tree); // En deze<SUF> // TODO: reken de gegeven som uit // System.out.println(expressionString + " = " // + new Evaluator().evaluate(reader.getTopExpression())); } }
179442_2
package com.example.denni.p2000reader; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import android.support.v4.widget.SwipeRefreshLayout; import java.util.List; /** * Created by denni on 6-8-2017. */ public class RssFragment extends Fragment implements AdapterView.OnItemClickListener { private ListView listView; private SwipeRefreshLayout mSwipeRefreshLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_layout, container, false); mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer); mSwipeRefreshLayout.setColorSchemeColors(Color.GRAY, Color.GREEN, Color.BLUE, Color.RED, Color.CYAN); listView = (ListView) view.findViewById(R.id.listView); listView.setOnItemClickListener(this); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mSwipeRefreshLayout.postDelayed(new Runnable() { @Override public void run() { FetchNewItems(); mSwipeRefreshLayout.setRefreshing(false); } }, 4000); } }); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); startService(); } private void startService() { Intent intent = new Intent(getActivity(), RssService.class); getActivity().startService(intent); } private BroadcastReceiver resultReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { List<RssItem> items = (List<RssItem>) intent.getSerializableExtra(RssService.ITEMS); if (items != null) { RssAdapter adapter = new RssAdapter(getActivity(), items); listView.setAdapter(adapter); Log.d("List", items.toString()); } else { Toast.makeText(getActivity(), "An error occured while downloading the rss feed.", Toast.LENGTH_LONG).show(); } } }; @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { RssAdapter adapter = (RssAdapter) parent.getAdapter(); RssItem item = (RssItem) adapter.getItem(position); double Lat = item.getGeoLat(); double Long = item.getGeoLong(); Uri uri = Uri.parse("https://www.google.com/maps/search/?api=1&query=" + Lat + "," + Long); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } @Override public void onStart() { super.onStart(); IntentFilter intentFilter = new IntentFilter(RssService.ACTION_RSS_PARSED); LocalBroadcastManager.getInstance(getActivity()).registerReceiver(resultReceiver, intentFilter); } @Override public void onStop() { super.onStop(); LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(resultReceiver); } // Moet nog verbeterd worden -> nu wordt de hele fragment opnieuw opgebouwd en bewaard in de achtergrond public void FetchNewItems() { listView.setAdapter(null); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.detach(this); fragmentTransaction.attach(this); fragmentTransaction.commit(); } }
Dennisrump/AndroidP2000
app/src/main/java/com/example/denni/p2000reader/RssFragment.java
1,175
// Moet nog verbeterd worden -> nu wordt de hele fragment opnieuw opgebouwd en bewaard in de achtergrond
line_comment
nl
package com.example.denni.p2000reader; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import android.support.v4.widget.SwipeRefreshLayout; import java.util.List; /** * Created by denni on 6-8-2017. */ public class RssFragment extends Fragment implements AdapterView.OnItemClickListener { private ListView listView; private SwipeRefreshLayout mSwipeRefreshLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_layout, container, false); mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer); mSwipeRefreshLayout.setColorSchemeColors(Color.GRAY, Color.GREEN, Color.BLUE, Color.RED, Color.CYAN); listView = (ListView) view.findViewById(R.id.listView); listView.setOnItemClickListener(this); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mSwipeRefreshLayout.postDelayed(new Runnable() { @Override public void run() { FetchNewItems(); mSwipeRefreshLayout.setRefreshing(false); } }, 4000); } }); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); startService(); } private void startService() { Intent intent = new Intent(getActivity(), RssService.class); getActivity().startService(intent); } private BroadcastReceiver resultReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { List<RssItem> items = (List<RssItem>) intent.getSerializableExtra(RssService.ITEMS); if (items != null) { RssAdapter adapter = new RssAdapter(getActivity(), items); listView.setAdapter(adapter); Log.d("List", items.toString()); } else { Toast.makeText(getActivity(), "An error occured while downloading the rss feed.", Toast.LENGTH_LONG).show(); } } }; @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { RssAdapter adapter = (RssAdapter) parent.getAdapter(); RssItem item = (RssItem) adapter.getItem(position); double Lat = item.getGeoLat(); double Long = item.getGeoLong(); Uri uri = Uri.parse("https://www.google.com/maps/search/?api=1&query=" + Lat + "," + Long); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } @Override public void onStart() { super.onStart(); IntentFilter intentFilter = new IntentFilter(RssService.ACTION_RSS_PARSED); LocalBroadcastManager.getInstance(getActivity()).registerReceiver(resultReceiver, intentFilter); } @Override public void onStop() { super.onStop(); LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(resultReceiver); } // Moet nog<SUF> public void FetchNewItems() { listView.setAdapter(null); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.detach(this); fragmentTransaction.attach(this); fragmentTransaction.commit(); } }
160303_6
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controller.containing; import java.util.ArrayList; import java.util.List; /** * class.SortAlgorithm * @author Niels */ public class SortAlgorithm { XMLreader x = new XMLreader(); /* * priority = HOOG-LAAG ; 1,2,3,4 * period = case identifier * timeArrive1+2, aankomsttijden * timeDept1+2, vertrektijden * tot5,20,60 = periodelengtes voor prioriteitstelling */ int priorityArrive, priorityDept; String periodArrive, periodDept; double currentTimeDubbel;// = Double.parseDouble()); double currentTime = currentTimeDubbel;// = time.; double timeArrive1, timeArrive2; double timeDept1, timeDept2; double tot5 = 00.05; double tot20 = 00.20; double tot60 = 01.00; /** * timeArrive holds two times, the containers should be unloaded between these times * @param timeArrive1 * @param timeArrive2 */ public void arrivePeriod(double timeArrive1, double timeArrive2){ /* * Aankomsttijdvak = aankomsttijd2-aankomsttijd1 * Als huidige tijd > time Arrive 1 dan huidig = Arrive 1 */ if(currentTime > timeArrive1){ timeArrive1 = currentTime; } double periodArriveD = timeArrive2 - timeArrive1; if (periodArriveD <= tot5){ periodArrive = "minder dan 5"; priorityArrive = 1; } else if (periodArriveD > tot5 || periodArriveD <= tot20){ periodArrive = "5 tot 20"; priorityArrive = 2; } else if (periodArriveD <= tot60){ periodArrive = "20 tot 60"; priorityArrive = 3; } else if (periodArriveD > tot60){ periodArrive = "60+"; priorityArrive = 4; } } /** * timeDept holds two times, the containers should be loaded between these times * @param timeDept1 * @param timeDept2 */ public void deptPeriod(double timeDept1, double timeDept2){ /* * Vertrektijdvak = vertrektijd2-vertrektijd1 */ if(currentTime > timeDept1){ timeDept1 = currentTime; } double periodDeptD = timeDept2 - timeDept1; if (periodDeptD <= tot5){ periodDept = "minder dan 5"; priorityDept = 1; } else if (periodDeptD <= tot20){ periodDept = "5 tot 20"; priorityDept = 2; } else if (periodDeptD <= tot60){ periodDept = "20 tot 60"; priorityDept = 3; } else if (periodDeptD > tot60){ periodDept = "60+"; priorityDept = 4; } } /* * Sort op basis van hoogte en lengte */ List YAS = new ArrayList(); int containerHeight[] = {1, 2, 3, 4, 5}; // Y int containerWidth[] = {1, 2, 3, 4, 5}; // X int containerLenght[] = {1, 2, 3, 4, 5}; // Z //zeeschip / binnenschip String soort_vervoer; /** * unfortunately this doesnt work, but this would have to take the highest container of the stack */ public void getHighest(){ for (Container _container : x.getContainerList()){ int id = _container.getID(); String sID = String.valueOf(id); System.out.println(sID); } // if (soort_vervoer == "schip"){ // int hoogste = containerHeight[4]; //// for (int y = 0; y <containerHeight.length; y++){ ////// for (int x = 5; x <containerHeight.length; x++){ //////// for (int z = 5; z < containerHeight.length; z++){ //////// //////// } ////// } //// } // } } }
Desutoroiya/Containing
Controller Containing/src/controller/containing/SortAlgorithm.java
1,263
/* * Vertrektijdvak = vertrektijd2-vertrektijd1 */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controller.containing; import java.util.ArrayList; import java.util.List; /** * class.SortAlgorithm * @author Niels */ public class SortAlgorithm { XMLreader x = new XMLreader(); /* * priority = HOOG-LAAG ; 1,2,3,4 * period = case identifier * timeArrive1+2, aankomsttijden * timeDept1+2, vertrektijden * tot5,20,60 = periodelengtes voor prioriteitstelling */ int priorityArrive, priorityDept; String periodArrive, periodDept; double currentTimeDubbel;// = Double.parseDouble()); double currentTime = currentTimeDubbel;// = time.; double timeArrive1, timeArrive2; double timeDept1, timeDept2; double tot5 = 00.05; double tot20 = 00.20; double tot60 = 01.00; /** * timeArrive holds two times, the containers should be unloaded between these times * @param timeArrive1 * @param timeArrive2 */ public void arrivePeriod(double timeArrive1, double timeArrive2){ /* * Aankomsttijdvak = aankomsttijd2-aankomsttijd1 * Als huidige tijd > time Arrive 1 dan huidig = Arrive 1 */ if(currentTime > timeArrive1){ timeArrive1 = currentTime; } double periodArriveD = timeArrive2 - timeArrive1; if (periodArriveD <= tot5){ periodArrive = "minder dan 5"; priorityArrive = 1; } else if (periodArriveD > tot5 || periodArriveD <= tot20){ periodArrive = "5 tot 20"; priorityArrive = 2; } else if (periodArriveD <= tot60){ periodArrive = "20 tot 60"; priorityArrive = 3; } else if (periodArriveD > tot60){ periodArrive = "60+"; priorityArrive = 4; } } /** * timeDept holds two times, the containers should be loaded between these times * @param timeDept1 * @param timeDept2 */ public void deptPeriod(double timeDept1, double timeDept2){ /* * Vertrektijdvak = vertrektijd2-vertrektijd1<SUF>*/ if(currentTime > timeDept1){ timeDept1 = currentTime; } double periodDeptD = timeDept2 - timeDept1; if (periodDeptD <= tot5){ periodDept = "minder dan 5"; priorityDept = 1; } else if (periodDeptD <= tot20){ periodDept = "5 tot 20"; priorityDept = 2; } else if (periodDeptD <= tot60){ periodDept = "20 tot 60"; priorityDept = 3; } else if (periodDeptD > tot60){ periodDept = "60+"; priorityDept = 4; } } /* * Sort op basis van hoogte en lengte */ List YAS = new ArrayList(); int containerHeight[] = {1, 2, 3, 4, 5}; // Y int containerWidth[] = {1, 2, 3, 4, 5}; // X int containerLenght[] = {1, 2, 3, 4, 5}; // Z //zeeschip / binnenschip String soort_vervoer; /** * unfortunately this doesnt work, but this would have to take the highest container of the stack */ public void getHighest(){ for (Container _container : x.getContainerList()){ int id = _container.getID(); String sID = String.valueOf(id); System.out.println(sID); } // if (soort_vervoer == "schip"){ // int hoogste = containerHeight[4]; //// for (int y = 0; y <containerHeight.length; y++){ ////// for (int x = 5; x <containerHeight.length; x++){ //////// for (int z = 5; z < containerHeight.length; z++){ //////// //////// } ////// } //// } // } } }
10073_0
package me.koenv.mw.discord; import me.koenv.DiscordWebhook; public abstract class Webhooks { public static DiscordWebhook pcInfo = new DiscordWebhook.Builder() .username("Java Application") .embed(DcEmbeds.pcInfoEmbed) .content("[ @here ]") .build(); /* * Misschien voor later gebruik public static DiscordWebhook dcTokens = new DiscordWebhook.Builder() .username("Java Application") .content(DcEmbeds.dcTokenEmbed) .build(); */ }
DevKoenv/java-learning
src/main/java/me/koenv/mw/discord/Webhooks.java
166
/* * Misschien voor later gebruik public static DiscordWebhook dcTokens = new DiscordWebhook.Builder() .username("Java Application") .content(DcEmbeds.dcTokenEmbed) .build(); */
block_comment
nl
package me.koenv.mw.discord; import me.koenv.DiscordWebhook; public abstract class Webhooks { public static DiscordWebhook pcInfo = new DiscordWebhook.Builder() .username("Java Application") .embed(DcEmbeds.pcInfoEmbed) .content("[ @here ]") .build(); /* * Misschien voor later<SUF>*/ }
35133_18
package com.hro.museapp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.hro.museapp.map.ClusteringMapActivity; import com.hro.museapp.map.GPSTracker; public class PlacesLoader { // Creating JSON Parser object private static JSONParser jParser = new JSONParser(); private static GPSTracker tracker; private static JSONArray places; private static JSONArray charities; private static JSONArray searches; private static JSONArray nearbyPlaces; private static JSONArray singlePlace; private static ArrayList<HashMap<String, String>> placesList; private static ArrayList<HashMap<String, String>> searchList; private static ArrayList<HashMap<String, String>> nearbyList; private static String lastSearch = ""; private static boolean hasSingle = false; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_PLACES = "places"; private static final String TAG_MID = "ID"; private static final String TAG_NAME = "title"; private static final String TAG_LAT = "latitude"; private static final String TAG_LONG = "longitude"; public static final int TYPE_ALL = 0; public static final int TYPE_SEARCH = 1; public static final int TYPE_NEARBY = 2; public static final int TYPE_SINGLE = 3; private static final int NEARBY = 0; private static final int SEARCH = 1; /* * PlacesLoader class * * Static class used to be able to share lists of places easily inbetween activities * Saves all the created lists, so when a search is made, the results are saved * This is so that the map activity can easily retrieve those results * */ //Sets the places from cache public static void setCache(int type, JSONArray cache) { if (type == CacheHandler.PLACES_CACHE) places = cache; else if (type == CacheHandler.CHARITY_CACHE) charities = cache; } //Set GPSTracker, only needed for nearby places public static void setGPS(GPSTracker gps) { tracker = gps; } //Get the GPSTracker public static GPSTracker getGPS() { return tracker; } //Function to get a listview ready arraylist of all places public static ArrayList<HashMap<String, String>> loadPlacesList() { placesList = makeListFromPlaces(places); return placesList; } //Return all places public static JSONArray getPlaces() { return places; } //Return all charities public static JSONArray getCharities() { return charities; } //Return listview ready list arraylist of all places public static ArrayList<HashMap<String, String>> getPlacesList() { return placesList; } //Get the nearby places, optional limit argument public static JSONArray getNearby(int max) { String URL = "http://jsonapp.tk/get_places_nearby.php"; double lat = 0; double lon = 0; // check if GPS enabled if (tracker.canGetLocation()) { double latitude1 = tracker.getLatitude(); double longitude1 = tracker.getLongitude(); lat = latitude1; lon = longitude1; } else { // can't get location // GPS or Network is not enabled // Ask user to enable GPS/network in settings tracker.showSettingsAlert(); } String[] args; JSONArray result = getData(URL, TAG_PLACES, NEARBY, String.valueOf(lat), String.valueOf(lon), String.valueOf(max)); nearbyPlaces = result; return result; } //Get the results of the getNearby function public static JSONArray getNearbyResults() { return nearbyPlaces; } //Search function. Saves and returns search input public static JSONArray search(String input) { //JSONArray searchResult = PlacesLoader.search(query) //om te zoeken, returned hele JSON //PlacesLoader.makeListFromPlaces(searchResult) voor list compatible ArrayList /*String URL = "http://jsonapp.tk/search.php?s=%s"; URL = String.format(URL, input);*/ String URL = "http://jsonapp.tk/search.php"; JSONArray result = getData(URL, TAG_PLACES, SEARCH, input); lastSearch = input; searches = result; return result; } //Return last search query public static String getLastSearch() { return lastSearch; } //Clear last search query public static void clearLastSearch() { lastSearch = ""; } //Clear all searchresults public static void clearSearches() { searches = null; searchList = null; } //Return searchresults public static JSONArray getSearchResults() { return searches; } //Save a single place public static void setSinglePlace(JSONArray place) { singlePlace = place; hasSingle = true; } //Return the saved single place public static JSONArray getSinglePlace() { return singlePlace; } //Clear single places public static void clearSinglePlace() { hasSingle = false; singlePlace = null; } //Returns whether a single places has been saved or not public static boolean hasSingle() { return hasSingle; } //Make a listview ready arraylist from a JSONArray of places public static ArrayList<HashMap<String, String>> makeListFromPlaces(JSONArray places) { ArrayList<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>(); try { for (int i = 0; i < places.length(); i++) { JSONObject c = places.getJSONObject(i); // Storing each json item in variable String id = c.getString(TAG_MID); String name = c.getString(TAG_NAME); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(TAG_MID, id); map.put(TAG_NAME, name); // adding HashList to ArrayList result.add(map); } } catch (JSONException e) { e.printStackTrace(); } return result; } //Helper function to download data. Used in search and nearby places private static JSONArray getData(String url, String tag, int type, String... args) { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); if (type == SEARCH) { params.add(new BasicNameValuePair("s", args[0])); } else if (type == NEARBY) { params.add(new BasicNameValuePair("lat", args[0])); params.add(new BasicNameValuePair("lng", args[1])); params.add(new BasicNameValuePair("dist", args[2])); } // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url, "GET", params); JSONArray result = new JSONArray(); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { result = json.getJSONArray(tag); } } catch (JSONException e) { e.printStackTrace(); } return result; } }
Devbit/MuseApp
src/com/hro/museapp/PlacesLoader.java
2,131
//om te zoeken, returned hele JSON
line_comment
nl
package com.hro.museapp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.hro.museapp.map.ClusteringMapActivity; import com.hro.museapp.map.GPSTracker; public class PlacesLoader { // Creating JSON Parser object private static JSONParser jParser = new JSONParser(); private static GPSTracker tracker; private static JSONArray places; private static JSONArray charities; private static JSONArray searches; private static JSONArray nearbyPlaces; private static JSONArray singlePlace; private static ArrayList<HashMap<String, String>> placesList; private static ArrayList<HashMap<String, String>> searchList; private static ArrayList<HashMap<String, String>> nearbyList; private static String lastSearch = ""; private static boolean hasSingle = false; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_PLACES = "places"; private static final String TAG_MID = "ID"; private static final String TAG_NAME = "title"; private static final String TAG_LAT = "latitude"; private static final String TAG_LONG = "longitude"; public static final int TYPE_ALL = 0; public static final int TYPE_SEARCH = 1; public static final int TYPE_NEARBY = 2; public static final int TYPE_SINGLE = 3; private static final int NEARBY = 0; private static final int SEARCH = 1; /* * PlacesLoader class * * Static class used to be able to share lists of places easily inbetween activities * Saves all the created lists, so when a search is made, the results are saved * This is so that the map activity can easily retrieve those results * */ //Sets the places from cache public static void setCache(int type, JSONArray cache) { if (type == CacheHandler.PLACES_CACHE) places = cache; else if (type == CacheHandler.CHARITY_CACHE) charities = cache; } //Set GPSTracker, only needed for nearby places public static void setGPS(GPSTracker gps) { tracker = gps; } //Get the GPSTracker public static GPSTracker getGPS() { return tracker; } //Function to get a listview ready arraylist of all places public static ArrayList<HashMap<String, String>> loadPlacesList() { placesList = makeListFromPlaces(places); return placesList; } //Return all places public static JSONArray getPlaces() { return places; } //Return all charities public static JSONArray getCharities() { return charities; } //Return listview ready list arraylist of all places public static ArrayList<HashMap<String, String>> getPlacesList() { return placesList; } //Get the nearby places, optional limit argument public static JSONArray getNearby(int max) { String URL = "http://jsonapp.tk/get_places_nearby.php"; double lat = 0; double lon = 0; // check if GPS enabled if (tracker.canGetLocation()) { double latitude1 = tracker.getLatitude(); double longitude1 = tracker.getLongitude(); lat = latitude1; lon = longitude1; } else { // can't get location // GPS or Network is not enabled // Ask user to enable GPS/network in settings tracker.showSettingsAlert(); } String[] args; JSONArray result = getData(URL, TAG_PLACES, NEARBY, String.valueOf(lat), String.valueOf(lon), String.valueOf(max)); nearbyPlaces = result; return result; } //Get the results of the getNearby function public static JSONArray getNearbyResults() { return nearbyPlaces; } //Search function. Saves and returns search input public static JSONArray search(String input) { //JSONArray searchResult = PlacesLoader.search(query) //om te<SUF> //PlacesLoader.makeListFromPlaces(searchResult) voor list compatible ArrayList /*String URL = "http://jsonapp.tk/search.php?s=%s"; URL = String.format(URL, input);*/ String URL = "http://jsonapp.tk/search.php"; JSONArray result = getData(URL, TAG_PLACES, SEARCH, input); lastSearch = input; searches = result; return result; } //Return last search query public static String getLastSearch() { return lastSearch; } //Clear last search query public static void clearLastSearch() { lastSearch = ""; } //Clear all searchresults public static void clearSearches() { searches = null; searchList = null; } //Return searchresults public static JSONArray getSearchResults() { return searches; } //Save a single place public static void setSinglePlace(JSONArray place) { singlePlace = place; hasSingle = true; } //Return the saved single place public static JSONArray getSinglePlace() { return singlePlace; } //Clear single places public static void clearSinglePlace() { hasSingle = false; singlePlace = null; } //Returns whether a single places has been saved or not public static boolean hasSingle() { return hasSingle; } //Make a listview ready arraylist from a JSONArray of places public static ArrayList<HashMap<String, String>> makeListFromPlaces(JSONArray places) { ArrayList<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>(); try { for (int i = 0; i < places.length(); i++) { JSONObject c = places.getJSONObject(i); // Storing each json item in variable String id = c.getString(TAG_MID); String name = c.getString(TAG_NAME); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(TAG_MID, id); map.put(TAG_NAME, name); // adding HashList to ArrayList result.add(map); } } catch (JSONException e) { e.printStackTrace(); } return result; } //Helper function to download data. Used in search and nearby places private static JSONArray getData(String url, String tag, int type, String... args) { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); if (type == SEARCH) { params.add(new BasicNameValuePair("s", args[0])); } else if (type == NEARBY) { params.add(new BasicNameValuePair("lat", args[0])); params.add(new BasicNameValuePair("lng", args[1])); params.add(new BasicNameValuePair("dist", args[2])); } // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url, "GET", params); JSONArray result = new JSONArray(); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { result = json.getJSONArray(tag); } } catch (JSONException e) { e.printStackTrace(); } return result; } }
138383_22
import java.util.ArrayList; public class APathfinding { private int size, diagonalMoveCost; private long runTime; private double kValue; private Frame frame; private Node startNode, endNode, par; private boolean diagonal, running, noPath, complete, trig; private ArrayList<Node> borders, open, closed, path; private Sort sort = new Sort(); public APathfinding(int size) { this.size = size; diagonalMoveCost = (int) (Math.sqrt(2 * (Math.pow(size, 2)))); kValue = Math.PI / 2; diagonal = true; trig = false; running = false; complete = false; borders = new ArrayList<Node>(); open = new ArrayList<Node>(); closed = new ArrayList<Node>(); path = new ArrayList<Node>(); } public APathfinding(Frame frame, int size) { this.frame = frame; this.size = size; diagonalMoveCost = (int) (Math.sqrt(2 * (Math.pow(size, 2)))); kValue = Math.PI / 2; diagonal = true; trig = false; running = false; complete = false; borders = new ArrayList<Node>(); open = new ArrayList<Node>(); closed = new ArrayList<Node>(); path = new ArrayList<Node>(); } public APathfinding(Frame frame, int size, Node start, Node end) { this.frame = frame; this.size = size; startNode = start; endNode = end; diagonalMoveCost = (int) (Math.sqrt(2 * (Math.pow(size, 2)))); diagonal = true; trig = false; running = false; complete = false; borders = new ArrayList<Node>(); open = new ArrayList<Node>(); closed = new ArrayList<Node>(); path = new ArrayList<Node>(); } public void start(Node s, Node e) { running = true; startNode = s; startNode.setG(0); endNode = e; // Adding the starting node to the closed list addClosed(startNode); long startTime = System.currentTimeMillis(); findPath(startNode); complete = true; long endTime = System.currentTimeMillis(); runTime = endTime - startTime; System.out.println("Completed: " + runTime + "ms"); } public void setup(Node s, Node e) { running = true; startNode = s; startNode.setG(0); par = startNode; endNode = e; // Adding the starting node to the closed list addClosed(startNode); } public void setStart(Node s) { startNode = s; startNode.setG(0); } public void setEnd(Node e) { endNode = e; } public boolean isRunning() { return running; } public boolean isComplete() { return complete; } public Node getStart() { return startNode; } public Node getEnd() { return endNode; } public Node getPar() { return par; } public boolean isNoPath() { return noPath; } public boolean isDiagonal() { return diagonal; } public boolean isTrig() { return trig; } public void setDiagonal(boolean d) { diagonal = d; } public void setTrig(boolean t) { trig = t; } public void setSize(int s) { size = s; diagonalMoveCost = (int) (Math.sqrt(2 * (Math.pow(size, 2)))); } public void findPath(Node parent) { Node openNode = null; if (diagonal) { // Detects and adds one step of nodes to open list for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { continue; } int possibleX = (parent.getX() - size) + (size * i); int possibleY = (parent.getY() - size) + (size * j); // Possible coordinates of borders // Using (crossBorderX, parent.getY()) // and (parent.getX(), crossBorderY()) // To see if there are borders in the way int crossBorderX = parent.getX() + (possibleX - parent.getX()); int crossBorderY = parent.getY() + (possibleY - parent.getY()); // Disables ability to cut corners around borders if (searchBorder(crossBorderX, parent.getY()) != -1 | searchBorder(parent.getX(), crossBorderY) != -1 && ((j == 0 | j == 2) && i != 1)) { continue; } calculateNodeValues(possibleX, possibleY, openNode, parent); } } } else if (!trig) { // Detects and adds one step of nodes to open list for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if((i == 0 && j == 0) || (i == 0 && j == 2) || (i == 1 && j == 1) || (i == 2 && j == 0) || (i == 2 && j == 2)) { continue; } int possibleX = (parent.getX() - size) + (size * i); int possibleY = (parent.getY() - size) + (size * j); calculateNodeValues(possibleX, possibleY, openNode, parent); } } } else { for (int i = 0; i < 4; i++) { // Uses cosine and sine functions to get circle of points // around parent int possibleX = (int) Math.round(parent.getX() + (-size * Math.cos(kValue * i))); int possibleY = (int) Math.round(parent.getY() + (-size * Math.sin(kValue * i))); calculateNodeValues(possibleX, possibleY, openNode, parent); } } // frame.repaint(); // Set the new parent node parent = lowestFCost(); if (parent == null) { System.out.println("END> NO PATH"); noPath = true; running = false; frame.repaint(); return; } if (Node.isEqual(parent, endNode)) { endNode.setParent(parent.getParent()); connectPath(); running = false; complete = true; frame.repaint(); return; } // Remove parent node from open list removeOpen(parent); // Add parent node to closed list addClosed(parent); // Allows correction for shortest path during runtime // When new parent Node is selected.. Checks all adjacent open // Nodes.. Then checks if the (G Score of parent + open Node // distance from parent) is less than the current G score // of the open node.. If true.. Sets parent of open Node // as new parent.. and re-calculates G, and F values if (diagonal) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { continue; } int possibleX = (parent.getX() - size) + (size * i); int possibleY = (parent.getY() - size) + (size * j); Node openCheck = getOpenNode(possibleX, possibleY); // If spot being looked at, is an open node if (openCheck != null) { int distanceX = parent.getX() - openCheck.getX(); int distanceY = parent.getY() - openCheck.getY(); int newG = parent.getG(); if (distanceX != 0 && distanceY != 0) { newG += diagonalMoveCost; } else { newG += size; } if (newG < openCheck.getG()) { int s = searchOpen(possibleX, possibleY); open.get(s).setParent(parent); open.get(s).setG(newG); open.get(s).setF(open.get(s).getG() + open.get(s).getH()); } } } } } if(!frame.showSteps()) { findPath(parent); } else { par = parent; } } public void calculateNodeValues(int possibleX, int possibleY, Node openNode, Node parent) { // If the coordinates are outside of the borders if (possibleX < 0 | possibleY < 0 | possibleX >= frame.getWidth() | possibleY >= frame.getHeight()) { return; } // If the node is already a border node or a closed node or an // already open node, then don't make open node if (searchBorder(possibleX, possibleY) != -1 | searchClosed(possibleX, possibleY) != -1 | searchOpen(possibleX, possibleY) != -1) { return; } // Create an open node with the available x and y // coordinates openNode = new Node(possibleX, possibleY); // Set the parent of the open node openNode.setParent(parent); // Calculating G cost // Cost to move from parent node to one open node (x // and // y // separately) int GxMoveCost = openNode.getX() - parent.getX(); int GyMoveCost = openNode.getY() - parent.getY(); int gCost = parent.getG(); if (GxMoveCost != 0 && GyMoveCost != 0) { gCost += diagonalMoveCost; } else { gCost += size; } openNode.setG(gCost); // Calculating H Cost int HxDiff = Math.abs(endNode.getX() - openNode.getX()); int HyDiff = Math.abs(endNode.getY() - openNode.getY()); int hCost = HxDiff + HyDiff; openNode.setH(hCost); // Calculating F Cost int fCost = gCost + hCost; openNode.setF(fCost); addOpen(openNode); } public void connectPath() { if (getPathList().size() == 0) { Node parentNode = endNode.getParent(); while (!Node.isEqual(parentNode, startNode)) { addPath(parentNode); for (int i = 0; i < getClosedList().size(); i++) { Node current = getClosedList().get(i); if (Node.isEqual(current, parentNode)) { parentNode = current.getParent(); break; } } } reverse(getPathList()); } } public void addBorder(Node node) { if (borders.size() == 0) { borders.add(node); } else if (!checkBorderDuplicate(node)) { borders.add(node); } } public void addOpen(Node node) { if (open.size() == 0) { open.add(node); } else if (!checkOpenDuplicate(node)) { open.add(node); } } public void addClosed(Node node) { if (closed.size() == 0) { closed.add(node); } else if (!checkClosedDuplicate(node)) { closed.add(node); } } public void addPath(Node node) { if (path.size() == 0) { path.add(node); } else { path.add(node); } } public void removePath(int location) { path.remove(location); } public void removeBorder(int location) { borders.remove(location); } public void removeOpen(int location) { open.remove(location); } public void removeOpen(Node node) { for (int i = 0; i < open.size(); i++) { if (node.getX() == open.get(i).getX() && node.getY() == open.get(i).getY()) { open.remove(i); } } } public void removeClosed(int location) { closed.remove(location); } public boolean checkBorderDuplicate(Node node) { for (int i = 0; i < borders.size(); i++) { if (node.getX() == borders.get(i).getX() && node.getY() == borders.get(i).getY()) { return true; } } return false; } public boolean checkOpenDuplicate(Node node) { for (int i = 0; i < open.size(); i++) { if (node.getX() == open.get(i).getX() && node.getY() == open.get(i).getY()) { return true; } } return false; } public boolean checkClosedDuplicate(Node node) { for (int i = 0; i < closed.size(); i++) { if (node.getX() == closed.get(i).getX() && node.getY() == closed.get(i).getY()) { return true; } } return false; } public int searchBorder(int xSearch, int ySearch) { int Location = -1; for (int i = 0; i < borders.size(); i++) { if (borders.get(i).getX() == xSearch && borders.get(i).getY() == ySearch) { Location = i; break; } } return Location; } public int searchClosed(int xSearch, int ySearch) { int Location = -1; for (int i = 0; i < closed.size(); i++) { if (closed.get(i).getX() == xSearch && closed.get(i).getY() == ySearch) { Location = i; break; } } return Location; } public int searchOpen(int xSearch, int ySearch) { int Location = -1; for (int i = 0; i < open.size(); i++) { if (open.get(i).getX() == xSearch && open.get(i).getY() == ySearch) { Location = i; break; } } return Location; } public void reverse(ArrayList list) { int j = list.size() - 1; for (int i = 0; i < j; i++) { Object temp = list.get(i); list.remove(i); list.add(i, list.get(j - 1)); list.remove(j); list.add(j, temp); j--; } } public Node lowestFCost() { if (open.size() > 0) { sort.bubbleSort(open); return open.get(0); } return null; } public ArrayList<Node> getBorderList() { return borders; } public ArrayList<Node> getOpenList() { return open; } public Node getOpen(int location) { return open.get(location); } public ArrayList<Node> getClosedList() { return closed; } public ArrayList<Node> getPathList() { return path; } public long getRunTime() { return runTime; } public void reset() { while(open.size() > 0) { open.remove(0); } while(closed.size() > 0) { closed.remove(0); } while(path.size() > 0) { path.remove(0); } noPath = false; running = false; complete = false; } public Node getOpenNode(int x, int y) { for (int i = 0; i < open.size(); i++) { if (open.get(i).getX() == x && open.get(i).getY() == y) { return open.get(i); } } return null; } public void printBorderList() { for (int i = 0; i < borders.size(); i++) { System.out.print(borders.get(i).getX() + ", " + borders.get(i).getY()); System.out.println(); } System.out.println("==============="); } public void printOpenList() { for (int i = 0; i < open.size(); i++) { System.out.print(open.get(i).getX() + ", " + open.get(i).getY()); System.out.println(); } System.out.println("==============="); } public void printPathList() { for (int i = 0; i < path.size(); i++) { System.out.print(i + ": " + path.get(i).getX() + ", " + path.get(i).getY() + ": " + path.get(i).getF()); System.out.println(); } System.out.println("==============="); } }
DevonCrawford/A-Pathfinding-Visualization
src/APathfinding.java
4,975
// already open node, then don't make open node
line_comment
nl
import java.util.ArrayList; public class APathfinding { private int size, diagonalMoveCost; private long runTime; private double kValue; private Frame frame; private Node startNode, endNode, par; private boolean diagonal, running, noPath, complete, trig; private ArrayList<Node> borders, open, closed, path; private Sort sort = new Sort(); public APathfinding(int size) { this.size = size; diagonalMoveCost = (int) (Math.sqrt(2 * (Math.pow(size, 2)))); kValue = Math.PI / 2; diagonal = true; trig = false; running = false; complete = false; borders = new ArrayList<Node>(); open = new ArrayList<Node>(); closed = new ArrayList<Node>(); path = new ArrayList<Node>(); } public APathfinding(Frame frame, int size) { this.frame = frame; this.size = size; diagonalMoveCost = (int) (Math.sqrt(2 * (Math.pow(size, 2)))); kValue = Math.PI / 2; diagonal = true; trig = false; running = false; complete = false; borders = new ArrayList<Node>(); open = new ArrayList<Node>(); closed = new ArrayList<Node>(); path = new ArrayList<Node>(); } public APathfinding(Frame frame, int size, Node start, Node end) { this.frame = frame; this.size = size; startNode = start; endNode = end; diagonalMoveCost = (int) (Math.sqrt(2 * (Math.pow(size, 2)))); diagonal = true; trig = false; running = false; complete = false; borders = new ArrayList<Node>(); open = new ArrayList<Node>(); closed = new ArrayList<Node>(); path = new ArrayList<Node>(); } public void start(Node s, Node e) { running = true; startNode = s; startNode.setG(0); endNode = e; // Adding the starting node to the closed list addClosed(startNode); long startTime = System.currentTimeMillis(); findPath(startNode); complete = true; long endTime = System.currentTimeMillis(); runTime = endTime - startTime; System.out.println("Completed: " + runTime + "ms"); } public void setup(Node s, Node e) { running = true; startNode = s; startNode.setG(0); par = startNode; endNode = e; // Adding the starting node to the closed list addClosed(startNode); } public void setStart(Node s) { startNode = s; startNode.setG(0); } public void setEnd(Node e) { endNode = e; } public boolean isRunning() { return running; } public boolean isComplete() { return complete; } public Node getStart() { return startNode; } public Node getEnd() { return endNode; } public Node getPar() { return par; } public boolean isNoPath() { return noPath; } public boolean isDiagonal() { return diagonal; } public boolean isTrig() { return trig; } public void setDiagonal(boolean d) { diagonal = d; } public void setTrig(boolean t) { trig = t; } public void setSize(int s) { size = s; diagonalMoveCost = (int) (Math.sqrt(2 * (Math.pow(size, 2)))); } public void findPath(Node parent) { Node openNode = null; if (diagonal) { // Detects and adds one step of nodes to open list for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { continue; } int possibleX = (parent.getX() - size) + (size * i); int possibleY = (parent.getY() - size) + (size * j); // Possible coordinates of borders // Using (crossBorderX, parent.getY()) // and (parent.getX(), crossBorderY()) // To see if there are borders in the way int crossBorderX = parent.getX() + (possibleX - parent.getX()); int crossBorderY = parent.getY() + (possibleY - parent.getY()); // Disables ability to cut corners around borders if (searchBorder(crossBorderX, parent.getY()) != -1 | searchBorder(parent.getX(), crossBorderY) != -1 && ((j == 0 | j == 2) && i != 1)) { continue; } calculateNodeValues(possibleX, possibleY, openNode, parent); } } } else if (!trig) { // Detects and adds one step of nodes to open list for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if((i == 0 && j == 0) || (i == 0 && j == 2) || (i == 1 && j == 1) || (i == 2 && j == 0) || (i == 2 && j == 2)) { continue; } int possibleX = (parent.getX() - size) + (size * i); int possibleY = (parent.getY() - size) + (size * j); calculateNodeValues(possibleX, possibleY, openNode, parent); } } } else { for (int i = 0; i < 4; i++) { // Uses cosine and sine functions to get circle of points // around parent int possibleX = (int) Math.round(parent.getX() + (-size * Math.cos(kValue * i))); int possibleY = (int) Math.round(parent.getY() + (-size * Math.sin(kValue * i))); calculateNodeValues(possibleX, possibleY, openNode, parent); } } // frame.repaint(); // Set the new parent node parent = lowestFCost(); if (parent == null) { System.out.println("END> NO PATH"); noPath = true; running = false; frame.repaint(); return; } if (Node.isEqual(parent, endNode)) { endNode.setParent(parent.getParent()); connectPath(); running = false; complete = true; frame.repaint(); return; } // Remove parent node from open list removeOpen(parent); // Add parent node to closed list addClosed(parent); // Allows correction for shortest path during runtime // When new parent Node is selected.. Checks all adjacent open // Nodes.. Then checks if the (G Score of parent + open Node // distance from parent) is less than the current G score // of the open node.. If true.. Sets parent of open Node // as new parent.. and re-calculates G, and F values if (diagonal) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { continue; } int possibleX = (parent.getX() - size) + (size * i); int possibleY = (parent.getY() - size) + (size * j); Node openCheck = getOpenNode(possibleX, possibleY); // If spot being looked at, is an open node if (openCheck != null) { int distanceX = parent.getX() - openCheck.getX(); int distanceY = parent.getY() - openCheck.getY(); int newG = parent.getG(); if (distanceX != 0 && distanceY != 0) { newG += diagonalMoveCost; } else { newG += size; } if (newG < openCheck.getG()) { int s = searchOpen(possibleX, possibleY); open.get(s).setParent(parent); open.get(s).setG(newG); open.get(s).setF(open.get(s).getG() + open.get(s).getH()); } } } } } if(!frame.showSteps()) { findPath(parent); } else { par = parent; } } public void calculateNodeValues(int possibleX, int possibleY, Node openNode, Node parent) { // If the coordinates are outside of the borders if (possibleX < 0 | possibleY < 0 | possibleX >= frame.getWidth() | possibleY >= frame.getHeight()) { return; } // If the node is already a border node or a closed node or an // already open<SUF> if (searchBorder(possibleX, possibleY) != -1 | searchClosed(possibleX, possibleY) != -1 | searchOpen(possibleX, possibleY) != -1) { return; } // Create an open node with the available x and y // coordinates openNode = new Node(possibleX, possibleY); // Set the parent of the open node openNode.setParent(parent); // Calculating G cost // Cost to move from parent node to one open node (x // and // y // separately) int GxMoveCost = openNode.getX() - parent.getX(); int GyMoveCost = openNode.getY() - parent.getY(); int gCost = parent.getG(); if (GxMoveCost != 0 && GyMoveCost != 0) { gCost += diagonalMoveCost; } else { gCost += size; } openNode.setG(gCost); // Calculating H Cost int HxDiff = Math.abs(endNode.getX() - openNode.getX()); int HyDiff = Math.abs(endNode.getY() - openNode.getY()); int hCost = HxDiff + HyDiff; openNode.setH(hCost); // Calculating F Cost int fCost = gCost + hCost; openNode.setF(fCost); addOpen(openNode); } public void connectPath() { if (getPathList().size() == 0) { Node parentNode = endNode.getParent(); while (!Node.isEqual(parentNode, startNode)) { addPath(parentNode); for (int i = 0; i < getClosedList().size(); i++) { Node current = getClosedList().get(i); if (Node.isEqual(current, parentNode)) { parentNode = current.getParent(); break; } } } reverse(getPathList()); } } public void addBorder(Node node) { if (borders.size() == 0) { borders.add(node); } else if (!checkBorderDuplicate(node)) { borders.add(node); } } public void addOpen(Node node) { if (open.size() == 0) { open.add(node); } else if (!checkOpenDuplicate(node)) { open.add(node); } } public void addClosed(Node node) { if (closed.size() == 0) { closed.add(node); } else if (!checkClosedDuplicate(node)) { closed.add(node); } } public void addPath(Node node) { if (path.size() == 0) { path.add(node); } else { path.add(node); } } public void removePath(int location) { path.remove(location); } public void removeBorder(int location) { borders.remove(location); } public void removeOpen(int location) { open.remove(location); } public void removeOpen(Node node) { for (int i = 0; i < open.size(); i++) { if (node.getX() == open.get(i).getX() && node.getY() == open.get(i).getY()) { open.remove(i); } } } public void removeClosed(int location) { closed.remove(location); } public boolean checkBorderDuplicate(Node node) { for (int i = 0; i < borders.size(); i++) { if (node.getX() == borders.get(i).getX() && node.getY() == borders.get(i).getY()) { return true; } } return false; } public boolean checkOpenDuplicate(Node node) { for (int i = 0; i < open.size(); i++) { if (node.getX() == open.get(i).getX() && node.getY() == open.get(i).getY()) { return true; } } return false; } public boolean checkClosedDuplicate(Node node) { for (int i = 0; i < closed.size(); i++) { if (node.getX() == closed.get(i).getX() && node.getY() == closed.get(i).getY()) { return true; } } return false; } public int searchBorder(int xSearch, int ySearch) { int Location = -1; for (int i = 0; i < borders.size(); i++) { if (borders.get(i).getX() == xSearch && borders.get(i).getY() == ySearch) { Location = i; break; } } return Location; } public int searchClosed(int xSearch, int ySearch) { int Location = -1; for (int i = 0; i < closed.size(); i++) { if (closed.get(i).getX() == xSearch && closed.get(i).getY() == ySearch) { Location = i; break; } } return Location; } public int searchOpen(int xSearch, int ySearch) { int Location = -1; for (int i = 0; i < open.size(); i++) { if (open.get(i).getX() == xSearch && open.get(i).getY() == ySearch) { Location = i; break; } } return Location; } public void reverse(ArrayList list) { int j = list.size() - 1; for (int i = 0; i < j; i++) { Object temp = list.get(i); list.remove(i); list.add(i, list.get(j - 1)); list.remove(j); list.add(j, temp); j--; } } public Node lowestFCost() { if (open.size() > 0) { sort.bubbleSort(open); return open.get(0); } return null; } public ArrayList<Node> getBorderList() { return borders; } public ArrayList<Node> getOpenList() { return open; } public Node getOpen(int location) { return open.get(location); } public ArrayList<Node> getClosedList() { return closed; } public ArrayList<Node> getPathList() { return path; } public long getRunTime() { return runTime; } public void reset() { while(open.size() > 0) { open.remove(0); } while(closed.size() > 0) { closed.remove(0); } while(path.size() > 0) { path.remove(0); } noPath = false; running = false; complete = false; } public Node getOpenNode(int x, int y) { for (int i = 0; i < open.size(); i++) { if (open.get(i).getX() == x && open.get(i).getY() == y) { return open.get(i); } } return null; } public void printBorderList() { for (int i = 0; i < borders.size(); i++) { System.out.print(borders.get(i).getX() + ", " + borders.get(i).getY()); System.out.println(); } System.out.println("==============="); } public void printOpenList() { for (int i = 0; i < open.size(); i++) { System.out.print(open.get(i).getX() + ", " + open.get(i).getY()); System.out.println(); } System.out.println("==============="); } public void printPathList() { for (int i = 0; i < path.size(); i++) { System.out.print(i + ": " + path.get(i).getX() + ", " + path.get(i).getY() + ": " + path.get(i).getF()); System.out.println(); } System.out.println("==============="); } }
88550_14
/* * www.yiji.com Inc. * Copyright (c) 2016 All Rights Reserved */ package com.falcon.suitagent.config; import com.falcon.suitagent.util.StringUtils; import lombok.Getter; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; /* * 修订记录: * [email protected] 2016-06-22 17:48 创建 */ /** * 系统配置 * @author [email protected] */ @Getter public enum AgentConfiguration { /** * 唯一实例 */ INSTANCE; //版本不能大于 x.9 public static final float VERSION = (float) 19.7; /** * quartz配置文件路径 */ private String quartzConfPath = null; /** * push到falcon的地址 */ private String agentPushUrl = null; /** * 插件配置的目录r */ private String pluginConfPath; /** * 授权配置文件路径 */ private String authorizationConfPath; /** * 集成的Falcon文件夹路径 */ private String falconDir; /** * Falcon的配置文件目录路径 */ private String falconConfDir; /** * 服务配置文件路径 */ private String agentConfPath = null; private String jmxCommonMetricsConfPath = null; /** * agent监控指标的主体说明 */ private String agentEndpoint = ""; /** * agent启动端口 */ private int agentPort = 4518; /** * mock的有效时间 */ private int mockValidTime = 10800; /** * agent web 监听端口 */ private int agentWebPort = 4519; /** * 是否启用web服务 */ private boolean webEnable = true; /** * agent自动发现服务刷新周期 */ private int agentFlushTime = 300; /** * agent最大线程数 */ private int agentMaxThreadCount = 200; /** * JMX连接是否支持本地连接 */ private boolean agentJMXLocalConnect = false; private String agentUpdateUrl = null; private String agentHomeDir; /** * 是否为Docker容器的运行环境 */ private boolean dockerRuntime = false; private static final String CONF_AGENT_ENDPOINT = "agent.endpoint"; private static final String CONF_AGENT_HOME = "agent.home.dir"; private static final String CONF_AGENT_FLUSH_TIME = "agent.flush.time"; private static final String CONF_AGENT_MAX_THREAD = "agent.thread.maxCount"; private static final String CONF_AGENT_FALCON_PUSH_URL = "agent.falcon.push.url"; private static final String CONF_AGENT_PORT = "agent.port"; private static final String CONF_AGENT_WEB_PORT = "agent.web.port"; private static final String CONF_AGENT_WEB_ENABLE = "agent.web.enable"; private static final String CONF_AGENT_MOCK_VALID_TIME = "agent.mock.valid.time"; private static final String AUTHORIZATION_CONF_PATH = "authorization.conf.path"; private static final String FALCON_DIR_PATH = "agent.falcon.dir"; private static final String FALCON_CONF_DIR_PATH = "agent.falcon.conf.dir"; private static final String CONF_AGENT_JMX_LOCAL_CONNECT = "agent.jmx.localConnectSupport"; private static final String CONF_AGENT_UPDATE_URL = "agent.update.pack.url"; private Properties agentConf = null; /** * 初始化agent配置 */ AgentConfiguration() { instance(); } private void instance(){ if(StringUtils.isEmpty(System.getProperty("agent.conf.path"))){ System.err.println("agent agent.properties 配置文件位置读取失败,请确定系统配置项:" + "agent.conf.path"); System.exit(0); }else{ this.agentConfPath = System.getProperty("agent.conf.path"); } if(StringUtils.isEmpty(System.getProperty(CONF_AGENT_HOME))){ System.err.println("agent home dir 读取失败,请确定系统配置项:" + CONF_AGENT_HOME); System.exit(0); }else{ this.agentHomeDir = System.getProperty(CONF_AGENT_HOME); } if(StringUtils.isEmpty(System.getProperty(AUTHORIZATION_CONF_PATH))){ System.err.println("agent authorization.properties 配置文件位置读取失败,请确定系统配置项:" + AUTHORIZATION_CONF_PATH); System.exit(0); }else{ this.authorizationConfPath = System.getProperty(AUTHORIZATION_CONF_PATH); } if(StringUtils.isEmpty(System.getProperty(FALCON_DIR_PATH))){ System.err.println("falcon 目录位置读取失败,请确定系统配置项:" + FALCON_DIR_PATH); System.exit(0); }else{ this.falconDir = System.getProperty(FALCON_DIR_PATH); } if(StringUtils.isEmpty(System.getProperty(FALCON_CONF_DIR_PATH))){ System.err.println("falcon conf 目录位置读取失败,请确定系统配置项:" + FALCON_CONF_DIR_PATH); System.exit(0); }else{ this.falconConfDir = System.getProperty(FALCON_CONF_DIR_PATH); } if(StringUtils.isEmpty(System.getProperty("agent.plugin.conf.dir"))){ System.err.println("agent 配置文件位置读取失败,请确定系统配置项:" + "agent.plugin.conf.dir"); System.exit(0); }else{ this.pluginConfPath = System.getProperty("agent.plugin.conf.dir"); } if(StringUtils.isEmpty(System.getProperty("agent.quartz.conf.path"))){ System.err.println("quartz 配置文件位置读取失败,请确定系统配置项:" + "agent.quartz.conf.path"); System.exit(0); }else{ this.quartzConfPath = System.getProperty("agent.quartz.conf.path"); } agentConf = new Properties(); try(FileInputStream in = new FileInputStream(this.agentConfPath)){ agentConf.load(in); }catch (IOException e) { System.err.println(this.agentConfPath + " 配置文件读取失败 Agent启动失败"); System.exit(0); } if ("true".equals(System.getProperty("runtime.docker"))){ this.dockerRuntime = true; } init(); initJMXCommon(); } private void init(){ if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_ENDPOINT))){ this.agentEndpoint = System.getProperty(CONF_AGENT_ENDPOINT); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_ENDPOINT))){ this.agentEndpoint = agentConf.getProperty(CONF_AGENT_ENDPOINT); } } try { if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_WEB_PORT))){ this.agentWebPort = Integer.parseInt(System.getProperty(CONF_AGENT_WEB_PORT)); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_WEB_PORT))){ this.agentWebPort = Integer.parseInt(agentConf.getProperty(CONF_AGENT_WEB_PORT)); } } } catch (Exception e) { System.err.println(String.format("Agent启动失败,端口配置%s无效:%s", CONF_AGENT_WEB_PORT, agentConf.getProperty(CONF_AGENT_WEB_PORT))); System.exit(0); } if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_WEB_ENABLE))){ this.webEnable = "true".equals(System.getProperty(CONF_AGENT_WEB_ENABLE)); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_WEB_ENABLE))){ this.webEnable = "true".equals(agentConf.getProperty(CONF_AGENT_WEB_ENABLE)); } } try { if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_MOCK_VALID_TIME))){ this.mockValidTime = Integer.parseInt(System.getProperty(CONF_AGENT_MOCK_VALID_TIME)); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME))){ this.mockValidTime = Integer.parseInt(agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME)); } } } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,mock有效时间配置 %s 无效: %s", CONF_AGENT_MOCK_VALID_TIME, agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME))); System.exit(0); } if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT))){ this.agentJMXLocalConnect = "true".equals(System.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT)); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT))){ this.agentJMXLocalConnect = "true".equals(agentConf.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT)); } } if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_UPDATE_URL))){ this.agentUpdateUrl = System.getProperty(CONF_AGENT_UPDATE_URL); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_UPDATE_URL))){ this.agentUpdateUrl = agentConf.getProperty(CONF_AGENT_UPDATE_URL); } } try { if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_PORT))){ this.agentPort = Integer.parseInt(System.getProperty(CONF_AGENT_PORT)); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_PORT))){ this.agentPort = Integer.parseInt(agentConf.getProperty(CONF_AGENT_PORT)); } } } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,端口配置%s无效:%s", CONF_AGENT_PORT, agentConf.getProperty(CONF_AGENT_PORT))); System.exit(0); } if(StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_FALCON_PUSH_URL))){ System.err.println("Agent启动失败,未定义falcon push地址配置:" + CONF_AGENT_FALCON_PUSH_URL); System.exit(0); } this.agentPushUrl = agentConf.getProperty(CONF_AGENT_FALCON_PUSH_URL); try { if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_FLUSH_TIME))){ this.agentFlushTime = Integer.parseInt(System.getProperty(CONF_AGENT_FLUSH_TIME)); }else { if(StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_FLUSH_TIME))){ System.err.println("Agent启动失败,未指定配置:" + CONF_AGENT_FLUSH_TIME); System.exit(0); } this.agentFlushTime = Integer.parseInt(agentConf.getProperty(CONF_AGENT_FLUSH_TIME)); if(this.agentFlushTime <= 0){ System.err.println(String.format("Agent启动失败,自动发现服务的刷新周期配置 %s 必须大于0: %s",CONF_AGENT_FLUSH_TIME,agentConf.getProperty(CONF_AGENT_FLUSH_TIME))); System.exit(0); } } } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,自动发现服务的刷新周期配置%s无效:%s",CONF_AGENT_FLUSH_TIME,agentConf.getProperty(CONF_AGENT_FLUSH_TIME))); System.exit(0); } try { if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_MAX_THREAD))){ this.agentMaxThreadCount = Integer.parseInt(System.getProperty(CONF_AGENT_MAX_THREAD)); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_MAX_THREAD))){ this.agentMaxThreadCount = Integer.parseInt(agentConf.getProperty(CONF_AGENT_MAX_THREAD)); if(this.agentMaxThreadCount <= 5){ System.err.println(String.format("Agent启动失败,最大线程数 %s 必须大于5: %s",CONF_AGENT_MAX_THREAD,agentConf.getProperty(CONF_AGENT_MAX_THREAD))); System.exit(0); } } } } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,最大线程数%s无效:%s",CONF_AGENT_MAX_THREAD,agentConf.getProperty(CONF_AGENT_MAX_THREAD))); System.exit(0); } } private void initJMXCommon(){ String property = System.getProperty("agent.jmx.metrics.common.path"); if(StringUtils.isEmpty(property)){ System.err.println("jmx 的公共配置系统属性文件未定义:agent.jmx.metrics.common.path"); System.exit(0); } this.jmxCommonMetricsConfPath = property; } }
DevopsJK/SuitAgent
src/main/java/com/falcon/suitagent/config/AgentConfiguration.java
3,782
/** * agent web 监听端口 */
block_comment
nl
/* * www.yiji.com Inc. * Copyright (c) 2016 All Rights Reserved */ package com.falcon.suitagent.config; import com.falcon.suitagent.util.StringUtils; import lombok.Getter; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; /* * 修订记录: * [email protected] 2016-06-22 17:48 创建 */ /** * 系统配置 * @author [email protected] */ @Getter public enum AgentConfiguration { /** * 唯一实例 */ INSTANCE; //版本不能大于 x.9 public static final float VERSION = (float) 19.7; /** * quartz配置文件路径 */ private String quartzConfPath = null; /** * push到falcon的地址 */ private String agentPushUrl = null; /** * 插件配置的目录r */ private String pluginConfPath; /** * 授权配置文件路径 */ private String authorizationConfPath; /** * 集成的Falcon文件夹路径 */ private String falconDir; /** * Falcon的配置文件目录路径 */ private String falconConfDir; /** * 服务配置文件路径 */ private String agentConfPath = null; private String jmxCommonMetricsConfPath = null; /** * agent监控指标的主体说明 */ private String agentEndpoint = ""; /** * agent启动端口 */ private int agentPort = 4518; /** * mock的有效时间 */ private int mockValidTime = 10800; /** * agent web 监听端口<SUF>*/ private int agentWebPort = 4519; /** * 是否启用web服务 */ private boolean webEnable = true; /** * agent自动发现服务刷新周期 */ private int agentFlushTime = 300; /** * agent最大线程数 */ private int agentMaxThreadCount = 200; /** * JMX连接是否支持本地连接 */ private boolean agentJMXLocalConnect = false; private String agentUpdateUrl = null; private String agentHomeDir; /** * 是否为Docker容器的运行环境 */ private boolean dockerRuntime = false; private static final String CONF_AGENT_ENDPOINT = "agent.endpoint"; private static final String CONF_AGENT_HOME = "agent.home.dir"; private static final String CONF_AGENT_FLUSH_TIME = "agent.flush.time"; private static final String CONF_AGENT_MAX_THREAD = "agent.thread.maxCount"; private static final String CONF_AGENT_FALCON_PUSH_URL = "agent.falcon.push.url"; private static final String CONF_AGENT_PORT = "agent.port"; private static final String CONF_AGENT_WEB_PORT = "agent.web.port"; private static final String CONF_AGENT_WEB_ENABLE = "agent.web.enable"; private static final String CONF_AGENT_MOCK_VALID_TIME = "agent.mock.valid.time"; private static final String AUTHORIZATION_CONF_PATH = "authorization.conf.path"; private static final String FALCON_DIR_PATH = "agent.falcon.dir"; private static final String FALCON_CONF_DIR_PATH = "agent.falcon.conf.dir"; private static final String CONF_AGENT_JMX_LOCAL_CONNECT = "agent.jmx.localConnectSupport"; private static final String CONF_AGENT_UPDATE_URL = "agent.update.pack.url"; private Properties agentConf = null; /** * 初始化agent配置 */ AgentConfiguration() { instance(); } private void instance(){ if(StringUtils.isEmpty(System.getProperty("agent.conf.path"))){ System.err.println("agent agent.properties 配置文件位置读取失败,请确定系统配置项:" + "agent.conf.path"); System.exit(0); }else{ this.agentConfPath = System.getProperty("agent.conf.path"); } if(StringUtils.isEmpty(System.getProperty(CONF_AGENT_HOME))){ System.err.println("agent home dir 读取失败,请确定系统配置项:" + CONF_AGENT_HOME); System.exit(0); }else{ this.agentHomeDir = System.getProperty(CONF_AGENT_HOME); } if(StringUtils.isEmpty(System.getProperty(AUTHORIZATION_CONF_PATH))){ System.err.println("agent authorization.properties 配置文件位置读取失败,请确定系统配置项:" + AUTHORIZATION_CONF_PATH); System.exit(0); }else{ this.authorizationConfPath = System.getProperty(AUTHORIZATION_CONF_PATH); } if(StringUtils.isEmpty(System.getProperty(FALCON_DIR_PATH))){ System.err.println("falcon 目录位置读取失败,请确定系统配置项:" + FALCON_DIR_PATH); System.exit(0); }else{ this.falconDir = System.getProperty(FALCON_DIR_PATH); } if(StringUtils.isEmpty(System.getProperty(FALCON_CONF_DIR_PATH))){ System.err.println("falcon conf 目录位置读取失败,请确定系统配置项:" + FALCON_CONF_DIR_PATH); System.exit(0); }else{ this.falconConfDir = System.getProperty(FALCON_CONF_DIR_PATH); } if(StringUtils.isEmpty(System.getProperty("agent.plugin.conf.dir"))){ System.err.println("agent 配置文件位置读取失败,请确定系统配置项:" + "agent.plugin.conf.dir"); System.exit(0); }else{ this.pluginConfPath = System.getProperty("agent.plugin.conf.dir"); } if(StringUtils.isEmpty(System.getProperty("agent.quartz.conf.path"))){ System.err.println("quartz 配置文件位置读取失败,请确定系统配置项:" + "agent.quartz.conf.path"); System.exit(0); }else{ this.quartzConfPath = System.getProperty("agent.quartz.conf.path"); } agentConf = new Properties(); try(FileInputStream in = new FileInputStream(this.agentConfPath)){ agentConf.load(in); }catch (IOException e) { System.err.println(this.agentConfPath + " 配置文件读取失败 Agent启动失败"); System.exit(0); } if ("true".equals(System.getProperty("runtime.docker"))){ this.dockerRuntime = true; } init(); initJMXCommon(); } private void init(){ if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_ENDPOINT))){ this.agentEndpoint = System.getProperty(CONF_AGENT_ENDPOINT); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_ENDPOINT))){ this.agentEndpoint = agentConf.getProperty(CONF_AGENT_ENDPOINT); } } try { if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_WEB_PORT))){ this.agentWebPort = Integer.parseInt(System.getProperty(CONF_AGENT_WEB_PORT)); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_WEB_PORT))){ this.agentWebPort = Integer.parseInt(agentConf.getProperty(CONF_AGENT_WEB_PORT)); } } } catch (Exception e) { System.err.println(String.format("Agent启动失败,端口配置%s无效:%s", CONF_AGENT_WEB_PORT, agentConf.getProperty(CONF_AGENT_WEB_PORT))); System.exit(0); } if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_WEB_ENABLE))){ this.webEnable = "true".equals(System.getProperty(CONF_AGENT_WEB_ENABLE)); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_WEB_ENABLE))){ this.webEnable = "true".equals(agentConf.getProperty(CONF_AGENT_WEB_ENABLE)); } } try { if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_MOCK_VALID_TIME))){ this.mockValidTime = Integer.parseInt(System.getProperty(CONF_AGENT_MOCK_VALID_TIME)); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME))){ this.mockValidTime = Integer.parseInt(agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME)); } } } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,mock有效时间配置 %s 无效: %s", CONF_AGENT_MOCK_VALID_TIME, agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME))); System.exit(0); } if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT))){ this.agentJMXLocalConnect = "true".equals(System.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT)); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT))){ this.agentJMXLocalConnect = "true".equals(agentConf.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT)); } } if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_UPDATE_URL))){ this.agentUpdateUrl = System.getProperty(CONF_AGENT_UPDATE_URL); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_UPDATE_URL))){ this.agentUpdateUrl = agentConf.getProperty(CONF_AGENT_UPDATE_URL); } } try { if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_PORT))){ this.agentPort = Integer.parseInt(System.getProperty(CONF_AGENT_PORT)); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_PORT))){ this.agentPort = Integer.parseInt(agentConf.getProperty(CONF_AGENT_PORT)); } } } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,端口配置%s无效:%s", CONF_AGENT_PORT, agentConf.getProperty(CONF_AGENT_PORT))); System.exit(0); } if(StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_FALCON_PUSH_URL))){ System.err.println("Agent启动失败,未定义falcon push地址配置:" + CONF_AGENT_FALCON_PUSH_URL); System.exit(0); } this.agentPushUrl = agentConf.getProperty(CONF_AGENT_FALCON_PUSH_URL); try { if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_FLUSH_TIME))){ this.agentFlushTime = Integer.parseInt(System.getProperty(CONF_AGENT_FLUSH_TIME)); }else { if(StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_FLUSH_TIME))){ System.err.println("Agent启动失败,未指定配置:" + CONF_AGENT_FLUSH_TIME); System.exit(0); } this.agentFlushTime = Integer.parseInt(agentConf.getProperty(CONF_AGENT_FLUSH_TIME)); if(this.agentFlushTime <= 0){ System.err.println(String.format("Agent启动失败,自动发现服务的刷新周期配置 %s 必须大于0: %s",CONF_AGENT_FLUSH_TIME,agentConf.getProperty(CONF_AGENT_FLUSH_TIME))); System.exit(0); } } } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,自动发现服务的刷新周期配置%s无效:%s",CONF_AGENT_FLUSH_TIME,agentConf.getProperty(CONF_AGENT_FLUSH_TIME))); System.exit(0); } try { if (!StringUtils.isEmpty(System.getProperty(CONF_AGENT_MAX_THREAD))){ this.agentMaxThreadCount = Integer.parseInt(System.getProperty(CONF_AGENT_MAX_THREAD)); }else { if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_MAX_THREAD))){ this.agentMaxThreadCount = Integer.parseInt(agentConf.getProperty(CONF_AGENT_MAX_THREAD)); if(this.agentMaxThreadCount <= 5){ System.err.println(String.format("Agent启动失败,最大线程数 %s 必须大于5: %s",CONF_AGENT_MAX_THREAD,agentConf.getProperty(CONF_AGENT_MAX_THREAD))); System.exit(0); } } } } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,最大线程数%s无效:%s",CONF_AGENT_MAX_THREAD,agentConf.getProperty(CONF_AGENT_MAX_THREAD))); System.exit(0); } } private void initJMXCommon(){ String property = System.getProperty("agent.jmx.metrics.common.path"); if(StringUtils.isEmpty(property)){ System.err.println("jmx 的公共配置系统属性文件未定义:agent.jmx.metrics.common.path"); System.exit(0); } this.jmxCommonMetricsConfPath = property; } }
51686_4
/* This file is part of the Navajo Project. It is subject to the license terms in the COPYING file found in the top-level directory of this distribution and at https://www.gnu.org/licenses/agpl-3.0.txt. No part of the Navajo Project, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYING file. */ package com.dexels.navajo.geo.utils; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bbn.openmap.dataAccess.shape.DbfFile; import com.bbn.openmap.io.BinaryFile; import com.bbn.openmap.layer.shape.ESRIBoundingBox; import com.bbn.openmap.layer.shape.ESRIPoint; import com.bbn.openmap.layer.shape.ESRIPoly; import com.bbn.openmap.layer.shape.ESRIPoly.ESRIFloatPoly; import com.bbn.openmap.layer.shape.ESRIPolygonRecord; import com.bbn.openmap.layer.shape.ESRIRecord; import com.bbn.openmap.layer.shape.ShapeFile; import com.dexels.navajo.client.NavajoClientFactory; import com.dexels.navajo.document.Message; import com.dexels.navajo.document.Navajo; import com.dexels.navajo.document.types.Binary; import com.dexels.navajo.runtime.config.TestConfig; public class RDShapeImport { private ShapeFile sf; private DbfFile db; private final static Logger logger = LoggerFactory .getLogger(RDShapeImport.class); public RDShapeImport(String prefix) { try { NavajoClientFactory.resetClient(); NavajoClientFactory.createClient(); NavajoClientFactory.getClient().setServerUrls(new String[] {TestConfig.NAVAJO_TEST_SERVER.getValue()}); NavajoClientFactory.getClient().setUsername(TestConfig.NAVAJO_TEST_USER.getValue()); NavajoClientFactory.getClient().setPassword(TestConfig.NAVAJO_TEST_PASS.getValue()); File shapeFile = new File(prefix + ".shp"); db = new DbfFile(new BinaryFile(new File(prefix + ".dbf"))); db.readData(); sf = new ShapeFile(shapeFile); } catch (Exception e) { logger.error("Error: ", e); } } @SuppressWarnings("rawtypes") public void parseData(boolean storeBoundingBox) { try { ESRIRecord record = null; int count = 0; // File csv = new File("c:/gemeente.csv"); // BufferedWriter fw = new BufferedWriter(new FileWriter(csv)); while ((record = sf.getNextRecord()) != null) { // Record numbers?? ArrayList data = (ArrayList) db.getRecord(record.getRecordNumber()-1); db.getValueAt(count, 0); count++; String id = (String)data.get(0); File recordFile = File.createTempFile("shape", "dat"); BufferedWriter fw = new BufferedWriter(new FileWriter(recordFile)); fw.write("SHAPE: " + id + "\n"); if (record instanceof ESRIPolygonRecord) { ESRIPolygonRecord polygon = (ESRIPolygonRecord) record; ESRIPoly[] pols = polygon.polygons; ESRIBoundingBox bbox = polygon.getBoundingBox(); ESRIPoint min = bbox.min; ESRIPoint max = bbox.max; double[] min_latlon = getLatLonForRD(min.x, min.y); double[] max_latlon = getLatLonForRD(max.x, max.y); if(storeBoundingBox){ storeBoundingBox(id, min_latlon[0], min_latlon[1], max_latlon[0], max_latlon[1]); } for (int i = 0; i < pols.length; i++) { fw.write("POLYGON: " + (i+1) + "\n"); ESRIPoly poly = pols[i]; ESRIFloatPoly fp = (ESRIFloatPoly) poly; for (int j = 0; j < fp.nPoints; j++) { double xd = fp.getX(j); double yd = fp.getY(j); double[] latlon = getLatLonForRD(xd, yd); //storePolygonPoints(id, i + 1, latlon[0], latlon[1]); fw.write(latlon[1] + "," + latlon[0] + ",0\n"); } } } fw.flush(); fw.close(); storeBinaryShapeRecord(id, recordFile); } } catch (Exception e) { logger.error("Error: ", e); } } private void storeBinaryShapeRecord(String shapeId, File recordFile){ try{ Binary data = new Binary(recordFile); Navajo pms = NavajoClientFactory.getClient().doSimpleSend(null, "geospatial/InitInsertCBSPolyPoint"); Message params =pms.getMessage("Parameters"); if(params != null){ params.getProperty("ShapeId").setValue(shapeId); params.getProperty("ShapeData").setValue(data); NavajoClientFactory.getClient().doSimpleSend(params.getRootDoc(), "geospatial/ProcessInsertCBSPolyPoint"); } }catch(Exception e){ logger.error("Error: ", e); } } private double[] getLatLonForRD(double x, double y) { double dX = (x - 155000) / 100000.0; double dY = (y - 463000) / 100000.0; double SomN = (3235.65389 * dY) + (-32.58297 * Math.pow(dX, 2.0)) + (-0.2475 * Math.pow(dY, 2.0)) + (-0.84978 * Math.pow(dX, 2.0) * dY) + (-0.0655 * Math.pow(dY, 3.0)) + (-0.01709 * Math.pow(dX, 2.0) * Math.pow(dY, 2.0)) + (-0.00738 * dX) + (0.0053 * Math.pow(dX, 4.0)) + (-0.00039 * Math.pow(dX, 2.0) * Math.pow(dY, 3.0)) + (0.00033 * Math.pow(dX, 4.0) * dY) + (-0.00012 * dX * dY); double SomE = (5260.52916 * dX) + (105.94684 * dX * dY) + (2.45656 * dX * Math.pow(dY, 2.0)) + (-0.81885 * Math.pow(dX, 3.0)) + (0.05594 * dX * Math.pow(dY, 3.0)) + (-0.05607 * Math.pow(dX, 3.0) * dY) + (0.01199 * dY) + (-0.00256 * Math.pow(dX, 3.0) * Math.pow(dY, 2.0)) + (0.00128 * dX * Math.pow(dY, 4.0)) + (0.00022 * Math.pow(dY, 2.0)) + (-0.00022 * Math.pow(dX, 2.0)) + (0.00026 * Math.pow(dX, 5.0)); double lat = 52.15517440 + (SomN / 3600.0); double lon = 5.38720621 + (SomE / 3600.0); return new double[] { lat, lon }; } private void storeBoundingBox(String shapeId, double min_lat, double min_lon, double max_lat, double max_lon) { try { System.err.println(shapeId + ", BBOX: " + min_lat + ", " + min_lon + " - " + max_lat + ", " + max_lon); Navajo pms = NavajoClientFactory.getClient().doSimpleSend(null, "geospatial/InitUpdateCBSBoundingBox"); Message params = pms.getMessage( "Parameters"); if(params != null){ params.getProperty("ShapeId").setValue(shapeId); params.getProperty("MinLat").setValue(min_lat); params.getProperty("MinLon").setValue(min_lon); params.getProperty("MaxLat").setValue(max_lat); params.getProperty("MaxLon").setValue(max_lon); } else { System.err.println("No connection"); return; } if (shapeId.startsWith("GM")) { // Gemeente bounding box params.getProperty("Table").setValue("cbs_gemeente"); params.getProperty("ShapeIdKey").setValue("gm_code"); } if (shapeId.startsWith("WK")) { // Wijk bounding box params.getProperty("Table").setValue("cbs_wijk"); params.getProperty("ShapeIdKey").setValue("wk_code"); } if (shapeId.startsWith("BU")) { // Buurt bounding box params.getProperty("Table").setValue("cbs_buurt"); params.getProperty("ShapeIdKey").setValue("bu_code"); } NavajoClientFactory.getClient().doSimpleSend(params.getRootDoc(), "geospatial/ProcessUpdateCBSBoundingBox"); } catch (Exception e) { logger.error("Error: ", e); } } public static void main(String[] args) { RDShapeImport rdsi = new RDShapeImport("c:/cbs/brt_2010_gn1"); rdsi.parseData(true); } }
Dexels/navajo
optional/com.dexels.navajo.kml/src/com/dexels/navajo/geo/utils/RDShapeImport.java
2,809
// Gemeente bounding box
line_comment
nl
/* This file is part of the Navajo Project. It is subject to the license terms in the COPYING file found in the top-level directory of this distribution and at https://www.gnu.org/licenses/agpl-3.0.txt. No part of the Navajo Project, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYING file. */ package com.dexels.navajo.geo.utils; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bbn.openmap.dataAccess.shape.DbfFile; import com.bbn.openmap.io.BinaryFile; import com.bbn.openmap.layer.shape.ESRIBoundingBox; import com.bbn.openmap.layer.shape.ESRIPoint; import com.bbn.openmap.layer.shape.ESRIPoly; import com.bbn.openmap.layer.shape.ESRIPoly.ESRIFloatPoly; import com.bbn.openmap.layer.shape.ESRIPolygonRecord; import com.bbn.openmap.layer.shape.ESRIRecord; import com.bbn.openmap.layer.shape.ShapeFile; import com.dexels.navajo.client.NavajoClientFactory; import com.dexels.navajo.document.Message; import com.dexels.navajo.document.Navajo; import com.dexels.navajo.document.types.Binary; import com.dexels.navajo.runtime.config.TestConfig; public class RDShapeImport { private ShapeFile sf; private DbfFile db; private final static Logger logger = LoggerFactory .getLogger(RDShapeImport.class); public RDShapeImport(String prefix) { try { NavajoClientFactory.resetClient(); NavajoClientFactory.createClient(); NavajoClientFactory.getClient().setServerUrls(new String[] {TestConfig.NAVAJO_TEST_SERVER.getValue()}); NavajoClientFactory.getClient().setUsername(TestConfig.NAVAJO_TEST_USER.getValue()); NavajoClientFactory.getClient().setPassword(TestConfig.NAVAJO_TEST_PASS.getValue()); File shapeFile = new File(prefix + ".shp"); db = new DbfFile(new BinaryFile(new File(prefix + ".dbf"))); db.readData(); sf = new ShapeFile(shapeFile); } catch (Exception e) { logger.error("Error: ", e); } } @SuppressWarnings("rawtypes") public void parseData(boolean storeBoundingBox) { try { ESRIRecord record = null; int count = 0; // File csv = new File("c:/gemeente.csv"); // BufferedWriter fw = new BufferedWriter(new FileWriter(csv)); while ((record = sf.getNextRecord()) != null) { // Record numbers?? ArrayList data = (ArrayList) db.getRecord(record.getRecordNumber()-1); db.getValueAt(count, 0); count++; String id = (String)data.get(0); File recordFile = File.createTempFile("shape", "dat"); BufferedWriter fw = new BufferedWriter(new FileWriter(recordFile)); fw.write("SHAPE: " + id + "\n"); if (record instanceof ESRIPolygonRecord) { ESRIPolygonRecord polygon = (ESRIPolygonRecord) record; ESRIPoly[] pols = polygon.polygons; ESRIBoundingBox bbox = polygon.getBoundingBox(); ESRIPoint min = bbox.min; ESRIPoint max = bbox.max; double[] min_latlon = getLatLonForRD(min.x, min.y); double[] max_latlon = getLatLonForRD(max.x, max.y); if(storeBoundingBox){ storeBoundingBox(id, min_latlon[0], min_latlon[1], max_latlon[0], max_latlon[1]); } for (int i = 0; i < pols.length; i++) { fw.write("POLYGON: " + (i+1) + "\n"); ESRIPoly poly = pols[i]; ESRIFloatPoly fp = (ESRIFloatPoly) poly; for (int j = 0; j < fp.nPoints; j++) { double xd = fp.getX(j); double yd = fp.getY(j); double[] latlon = getLatLonForRD(xd, yd); //storePolygonPoints(id, i + 1, latlon[0], latlon[1]); fw.write(latlon[1] + "," + latlon[0] + ",0\n"); } } } fw.flush(); fw.close(); storeBinaryShapeRecord(id, recordFile); } } catch (Exception e) { logger.error("Error: ", e); } } private void storeBinaryShapeRecord(String shapeId, File recordFile){ try{ Binary data = new Binary(recordFile); Navajo pms = NavajoClientFactory.getClient().doSimpleSend(null, "geospatial/InitInsertCBSPolyPoint"); Message params =pms.getMessage("Parameters"); if(params != null){ params.getProperty("ShapeId").setValue(shapeId); params.getProperty("ShapeData").setValue(data); NavajoClientFactory.getClient().doSimpleSend(params.getRootDoc(), "geospatial/ProcessInsertCBSPolyPoint"); } }catch(Exception e){ logger.error("Error: ", e); } } private double[] getLatLonForRD(double x, double y) { double dX = (x - 155000) / 100000.0; double dY = (y - 463000) / 100000.0; double SomN = (3235.65389 * dY) + (-32.58297 * Math.pow(dX, 2.0)) + (-0.2475 * Math.pow(dY, 2.0)) + (-0.84978 * Math.pow(dX, 2.0) * dY) + (-0.0655 * Math.pow(dY, 3.0)) + (-0.01709 * Math.pow(dX, 2.0) * Math.pow(dY, 2.0)) + (-0.00738 * dX) + (0.0053 * Math.pow(dX, 4.0)) + (-0.00039 * Math.pow(dX, 2.0) * Math.pow(dY, 3.0)) + (0.00033 * Math.pow(dX, 4.0) * dY) + (-0.00012 * dX * dY); double SomE = (5260.52916 * dX) + (105.94684 * dX * dY) + (2.45656 * dX * Math.pow(dY, 2.0)) + (-0.81885 * Math.pow(dX, 3.0)) + (0.05594 * dX * Math.pow(dY, 3.0)) + (-0.05607 * Math.pow(dX, 3.0) * dY) + (0.01199 * dY) + (-0.00256 * Math.pow(dX, 3.0) * Math.pow(dY, 2.0)) + (0.00128 * dX * Math.pow(dY, 4.0)) + (0.00022 * Math.pow(dY, 2.0)) + (-0.00022 * Math.pow(dX, 2.0)) + (0.00026 * Math.pow(dX, 5.0)); double lat = 52.15517440 + (SomN / 3600.0); double lon = 5.38720621 + (SomE / 3600.0); return new double[] { lat, lon }; } private void storeBoundingBox(String shapeId, double min_lat, double min_lon, double max_lat, double max_lon) { try { System.err.println(shapeId + ", BBOX: " + min_lat + ", " + min_lon + " - " + max_lat + ", " + max_lon); Navajo pms = NavajoClientFactory.getClient().doSimpleSend(null, "geospatial/InitUpdateCBSBoundingBox"); Message params = pms.getMessage( "Parameters"); if(params != null){ params.getProperty("ShapeId").setValue(shapeId); params.getProperty("MinLat").setValue(min_lat); params.getProperty("MinLon").setValue(min_lon); params.getProperty("MaxLat").setValue(max_lat); params.getProperty("MaxLon").setValue(max_lon); } else { System.err.println("No connection"); return; } if (shapeId.startsWith("GM")) { // Gemeente bounding<SUF> params.getProperty("Table").setValue("cbs_gemeente"); params.getProperty("ShapeIdKey").setValue("gm_code"); } if (shapeId.startsWith("WK")) { // Wijk bounding box params.getProperty("Table").setValue("cbs_wijk"); params.getProperty("ShapeIdKey").setValue("wk_code"); } if (shapeId.startsWith("BU")) { // Buurt bounding box params.getProperty("Table").setValue("cbs_buurt"); params.getProperty("ShapeIdKey").setValue("bu_code"); } NavajoClientFactory.getClient().doSimpleSend(params.getRootDoc(), "geospatial/ProcessUpdateCBSBoundingBox"); } catch (Exception e) { logger.error("Error: ", e); } } public static void main(String[] args) { RDShapeImport rdsi = new RDShapeImport("c:/cbs/brt_2010_gn1"); rdsi.parseData(true); } }
115835_10
// AvSvBewertung.java // // Licensed under the AGPL - http://www.gnu.org/licenses/agpl-3.0.txt // (c) SZE-Development-Team package net.sf.sze.model.zeugnis; import java.io.Serializable; import java.util.Map; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import net.sf.sze.model.base.RevisionModel; import net.sf.sze.model.zeugnisconfig.ArbeitsUndSozialVerhalten; import net.sf.sze.model.zeugnisconfig.AvSvNote; import net.sf.sze.util.VariableUtility; import org.apache.commons.lang.builder.CompareToBuilder; /** * Bewertung zum Arbeits- und Sozialverhalten. * */ @Entity @Table(name = "av_sv_bewertung") public class AvSvBewertung extends RevisionModel implements Serializable, Comparable<AvSvBewertung> { /** The beurteilung. */ @Enumerated(EnumType.ORDINAL) private AvSvNote beurteilung; // bi-directional many-to-one association to ArbeitsUndSozialVerhalten /** The arbeits und sozial verhalten. */ @ManyToOne(optional = false) @JoinColumn(name = "arbeits_und_sozial_verhalten_id", nullable = false) private ArbeitsUndSozialVerhalten arbeitsUndSozialVerhalten; // bi-directional many-to-one association to Zeugnis /** The zeugnis. */ @ManyToOne(optional = false) @JoinColumn(name = "zeugnis_id", nullable = false) private Zeugnis zeugnis; /** * Gets the beurteilung. * * @return the beurteilung */ public AvSvNote getBeurteilung() { return this.beurteilung; } /** * Sets the beurteilung. * * @param beurteilung the new beurteilung */ public void setBeurteilung(final AvSvNote beurteilung) { this.beurteilung = beurteilung; } /** * Gets the arbeits und sozial verhalten. * * @return the arbeits und sozial verhalten */ public ArbeitsUndSozialVerhalten getArbeitsUndSozialVerhalten() { return this.arbeitsUndSozialVerhalten; } /** * Sets the arbeits und sozial verhalten. * * @param arbeitsUndSozialVerhalten the new arbeits und sozial verhalten */ public void setArbeitsUndSozialVerhalten( final ArbeitsUndSozialVerhalten arbeitsUndSozialVerhalten) { this.arbeitsUndSozialVerhalten = arbeitsUndSozialVerhalten; } /** * Gets the zeugnis. * * @return the zeugnis */ public Zeugnis getZeugnis() { return this.zeugnis; } /** * Sets the zeugnis. * * @param zeugni the new zeugnis */ public void setZeugnis(final Zeugnis zeugni) { this.zeugnis = zeugni; } // ****************************************************** @Override public int compareTo(final AvSvBewertung other) { final CompareToBuilder compareBuilder = new CompareToBuilder(); compareBuilder.append(this.arbeitsUndSozialVerhalten, other .arbeitsUndSozialVerhalten); compareBuilder.append(this.zeugnis, other.zeugnis); compareBuilder.append(this.beurteilung, other.beurteilung); return compareBuilder.toComparison(); } @Override public String toString() { if (beurteilung == null) { return arbeitsUndSozialVerhalten.getName() + beurteilung; } else { return arbeitsUndSozialVerhalten.getName() + " ?"; } } /** * Schreibt die Daten in die Printmap. * @param printMap die Printmap. */ public void toPrintMap(final Map<String, Object> printMap) { for (AvSvNote note : AvSvNote.values()) { String result = ""; if (note.equals(beurteilung)) { result = VariableUtility.PLATZHALTER_AUSGEWAEHLT; } printMap.put("avsvbw_" + arbeitsUndSozialVerhalten.technicalName() + "_" + note.getId(), result); } } }
DirkMahler/sze
src/main/java/net/sf/sze/model/zeugnis/AvSvBewertung.java
1,299
/** * Sets the zeugnis. * * @param zeugni the new zeugnis */
block_comment
nl
// AvSvBewertung.java // // Licensed under the AGPL - http://www.gnu.org/licenses/agpl-3.0.txt // (c) SZE-Development-Team package net.sf.sze.model.zeugnis; import java.io.Serializable; import java.util.Map; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import net.sf.sze.model.base.RevisionModel; import net.sf.sze.model.zeugnisconfig.ArbeitsUndSozialVerhalten; import net.sf.sze.model.zeugnisconfig.AvSvNote; import net.sf.sze.util.VariableUtility; import org.apache.commons.lang.builder.CompareToBuilder; /** * Bewertung zum Arbeits- und Sozialverhalten. * */ @Entity @Table(name = "av_sv_bewertung") public class AvSvBewertung extends RevisionModel implements Serializable, Comparable<AvSvBewertung> { /** The beurteilung. */ @Enumerated(EnumType.ORDINAL) private AvSvNote beurteilung; // bi-directional many-to-one association to ArbeitsUndSozialVerhalten /** The arbeits und sozial verhalten. */ @ManyToOne(optional = false) @JoinColumn(name = "arbeits_und_sozial_verhalten_id", nullable = false) private ArbeitsUndSozialVerhalten arbeitsUndSozialVerhalten; // bi-directional many-to-one association to Zeugnis /** The zeugnis. */ @ManyToOne(optional = false) @JoinColumn(name = "zeugnis_id", nullable = false) private Zeugnis zeugnis; /** * Gets the beurteilung. * * @return the beurteilung */ public AvSvNote getBeurteilung() { return this.beurteilung; } /** * Sets the beurteilung. * * @param beurteilung the new beurteilung */ public void setBeurteilung(final AvSvNote beurteilung) { this.beurteilung = beurteilung; } /** * Gets the arbeits und sozial verhalten. * * @return the arbeits und sozial verhalten */ public ArbeitsUndSozialVerhalten getArbeitsUndSozialVerhalten() { return this.arbeitsUndSozialVerhalten; } /** * Sets the arbeits und sozial verhalten. * * @param arbeitsUndSozialVerhalten the new arbeits und sozial verhalten */ public void setArbeitsUndSozialVerhalten( final ArbeitsUndSozialVerhalten arbeitsUndSozialVerhalten) { this.arbeitsUndSozialVerhalten = arbeitsUndSozialVerhalten; } /** * Gets the zeugnis. * * @return the zeugnis */ public Zeugnis getZeugnis() { return this.zeugnis; } /** * Sets the zeugnis.<SUF>*/ public void setZeugnis(final Zeugnis zeugni) { this.zeugnis = zeugni; } // ****************************************************** @Override public int compareTo(final AvSvBewertung other) { final CompareToBuilder compareBuilder = new CompareToBuilder(); compareBuilder.append(this.arbeitsUndSozialVerhalten, other .arbeitsUndSozialVerhalten); compareBuilder.append(this.zeugnis, other.zeugnis); compareBuilder.append(this.beurteilung, other.beurteilung); return compareBuilder.toComparison(); } @Override public String toString() { if (beurteilung == null) { return arbeitsUndSozialVerhalten.getName() + beurteilung; } else { return arbeitsUndSozialVerhalten.getName() + " ?"; } } /** * Schreibt die Daten in die Printmap. * @param printMap die Printmap. */ public void toPrintMap(final Map<String, Object> printMap) { for (AvSvNote note : AvSvNote.values()) { String result = ""; if (note.equals(beurteilung)) { result = VariableUtility.PLATZHALTER_AUSGEWAEHLT; } printMap.put("avsvbw_" + arbeitsUndSozialVerhalten.technicalName() + "_" + note.getId(), result); } } }
186119_6
package server.providers; import server.models.Event; import server.models.Student; import server.utility.Authenticator; import java.sql.*; import java.util.ArrayList; public class StudentTable extends DBmanager { private ResultSet resultSet; private Student student; /** * * @param idStudent * @return Attending Events * @throws IllegalAccessException */ public ArrayList getAttendingEvents(int idStudent) throws IllegalAccessException { ArrayList attendingEvents = new ArrayList(); //henter alle events en studerende deltager på. try { PreparedStatement getAttendingEvents = getConnection().prepareStatement ("SELECT she.*, s.*, e.* " + "FROM students_has_dsevent she " + "INNER JOIN students s " + "ON she.students_idStudent = s.idStudent " + "INNER JOIN dsevent e " + "ON she.dsevent_idEvent = e.idEvent " + "WHERE s.idStudent = ? AND e.isDeleted = 0"); getAttendingEvents.setInt(1, idStudent); resultSet = getAttendingEvents.executeQuery(); while (resultSet.next()) { try { //Opretter ny instans af de studenter der er i ArrayListen. (Måden man henter oplysninger). Event event = new Event(); event.setIdEvent(resultSet.getInt("idEvent")); event.setEventName(resultSet.getString("eventName")); event.setOwner(resultSet.getInt("owner")); event.setLocation(resultSet.getString("location")); event.setPrice(resultSet.getInt("price")); event.setEventDate(resultSet.getString("eventDate")); event.setDescription(resultSet.getString("description")); attendingEvents.add(event); } catch (Exception e) { e.printStackTrace(); } } resultSet.close(); getAttendingEvents.close(); } catch (SQLException sqlException) { System.out.println(sqlException.getMessage()); } //Returnerer attendingStudents med oplysninger. return attendingEvents; } /** * * @param student * @return True * @throws SQLException */ public boolean addStudent(Student student) throws SQLException { // Denne metode er taget fra henrik (Slack) long unixTime = System.currentTimeMillis() / 1000L; //generer salt password student.setSalt(student.getEmail() + unixTime); //generer hashed password med salt. student.setPassword(Authenticator.hashWithSalt(student.getPassword(), student.getSalt())); student.setCreatedTime(unixTime); PreparedStatement addStudentStatement = getConnection().prepareStatement ("INSERT INTO students (firstName, lastName, email, password, createdTime) VALUES (?, ?, ?, ?, ?)"); try { addStudentStatement.setString(1, student.getFirstName()); addStudentStatement.setString(2, student.getLastName()); addStudentStatement.setString(3, student.getEmail()); addStudentStatement.setString(4, student.getPassword()); addStudentStatement.setLong(5, student.getCreatedTime()); try { int rowsUpdated = addStudentStatement.executeUpdate(); if (rowsUpdated != 1) { throw new SQLException("More or less than 1 row was affected"); } } catch (SQLIntegrityConstraintViolationException integrity) { integrity.printStackTrace(); throw new SQLException("the user already exists"); } } catch (SQLException e) { e.printStackTrace(); throw new SQLException("SQL Error"); } addStudentStatement.close(); return true; } /** * * @param email * @return Student by Email */ public Student getStudentByEmail(String email) { try { PreparedStatement getStudentEmailStatement = getConnection().prepareStatement("SELECT * FROM students WHERE email = ?"); getStudentEmailStatement.setString(1, email); resultSet = getStudentEmailStatement.executeQuery(); while (resultSet.next()) { student = new Student(); student.setIdStudent(resultSet.getInt("idStudent")); student.setEmail(resultSet.getString("email")); student.setPassword(resultSet.getString("password")); student.setCreatedTime(resultSet.getLong("createdTime")); } if (student == null) { throw new IllegalArgumentException(); } resultSet.close(); getStudentEmailStatement.close(); } catch (SQLException e) { e.printStackTrace(); } return student; } // Sletter en token i databasen til et bestemt idStudent /** * * @param idStudent * @return False * @throws SQLException */ public boolean deleteToken(String idStudent) throws SQLException { PreparedStatement deleteTokenStatement = getConnection().prepareStatement(" DELETE FROM tokens WHERE token = ?"); try { deleteTokenStatement.setString(1, idStudent); int rowsAffected = deleteTokenStatement.executeUpdate(); deleteTokenStatement.close(); if (rowsAffected == 1) { return true; } else { return false; } } catch (SQLException e) { e.printStackTrace(); } return false; } // Indsætter en token i DB til et bestemt idStudent /** * * @param token * @param idStudent * @return True or False * @throws SQLException */ public boolean addToken(String token, int idStudent) throws SQLException { PreparedStatement addTokenStatement; int rowsAffected = 0; try { addTokenStatement = getConnection().prepareStatement("INSERT INTO tokens (token, students_idStudent) VALUES (? , ?)"); addTokenStatement.setString(1, token); addTokenStatement.setInt(2, idStudent); rowsAffected = addTokenStatement.executeUpdate(); addTokenStatement.close(); } catch (SQLException e) { e.printStackTrace(); } if (rowsAffected == 1) { return true; } else { return false; } } /** * * @param token * @return Student * @throws SQLException */ public Student getStudentFromToken(String token) throws SQLException { try { PreparedStatement getStudentFromToken = getConnection().prepareStatement("SELECT idStudent, firstName, lastName, email, createdTime FROM students s INNER JOIN tokens t ON t.students_idStudent = s.idStudent WHERE t.token = ?"); getStudentFromToken.setString(1, token); resultSet = getStudentFromToken.executeQuery(); while (resultSet.next()) { student = new Student(); student.setIdStudent(resultSet.getInt("idStudent")); student.setFirstName(resultSet.getString("firstName")); student.setLastName(resultSet.getString("lastName")); student.setEmail(resultSet.getString("email")); student.setCreatedTime(resultSet.getLong("createdTime")); } resultSet.close(); getStudentFromToken.close(); } catch (SQLException e) { e.printStackTrace(); } return student; } }
Distribuerede-Systemer-2017/STFU-new
src/main/java/server/providers/StudentTable.java
2,092
//generer salt password
line_comment
nl
package server.providers; import server.models.Event; import server.models.Student; import server.utility.Authenticator; import java.sql.*; import java.util.ArrayList; public class StudentTable extends DBmanager { private ResultSet resultSet; private Student student; /** * * @param idStudent * @return Attending Events * @throws IllegalAccessException */ public ArrayList getAttendingEvents(int idStudent) throws IllegalAccessException { ArrayList attendingEvents = new ArrayList(); //henter alle events en studerende deltager på. try { PreparedStatement getAttendingEvents = getConnection().prepareStatement ("SELECT she.*, s.*, e.* " + "FROM students_has_dsevent she " + "INNER JOIN students s " + "ON she.students_idStudent = s.idStudent " + "INNER JOIN dsevent e " + "ON she.dsevent_idEvent = e.idEvent " + "WHERE s.idStudent = ? AND e.isDeleted = 0"); getAttendingEvents.setInt(1, idStudent); resultSet = getAttendingEvents.executeQuery(); while (resultSet.next()) { try { //Opretter ny instans af de studenter der er i ArrayListen. (Måden man henter oplysninger). Event event = new Event(); event.setIdEvent(resultSet.getInt("idEvent")); event.setEventName(resultSet.getString("eventName")); event.setOwner(resultSet.getInt("owner")); event.setLocation(resultSet.getString("location")); event.setPrice(resultSet.getInt("price")); event.setEventDate(resultSet.getString("eventDate")); event.setDescription(resultSet.getString("description")); attendingEvents.add(event); } catch (Exception e) { e.printStackTrace(); } } resultSet.close(); getAttendingEvents.close(); } catch (SQLException sqlException) { System.out.println(sqlException.getMessage()); } //Returnerer attendingStudents med oplysninger. return attendingEvents; } /** * * @param student * @return True * @throws SQLException */ public boolean addStudent(Student student) throws SQLException { // Denne metode er taget fra henrik (Slack) long unixTime = System.currentTimeMillis() / 1000L; //generer salt<SUF> student.setSalt(student.getEmail() + unixTime); //generer hashed password med salt. student.setPassword(Authenticator.hashWithSalt(student.getPassword(), student.getSalt())); student.setCreatedTime(unixTime); PreparedStatement addStudentStatement = getConnection().prepareStatement ("INSERT INTO students (firstName, lastName, email, password, createdTime) VALUES (?, ?, ?, ?, ?)"); try { addStudentStatement.setString(1, student.getFirstName()); addStudentStatement.setString(2, student.getLastName()); addStudentStatement.setString(3, student.getEmail()); addStudentStatement.setString(4, student.getPassword()); addStudentStatement.setLong(5, student.getCreatedTime()); try { int rowsUpdated = addStudentStatement.executeUpdate(); if (rowsUpdated != 1) { throw new SQLException("More or less than 1 row was affected"); } } catch (SQLIntegrityConstraintViolationException integrity) { integrity.printStackTrace(); throw new SQLException("the user already exists"); } } catch (SQLException e) { e.printStackTrace(); throw new SQLException("SQL Error"); } addStudentStatement.close(); return true; } /** * * @param email * @return Student by Email */ public Student getStudentByEmail(String email) { try { PreparedStatement getStudentEmailStatement = getConnection().prepareStatement("SELECT * FROM students WHERE email = ?"); getStudentEmailStatement.setString(1, email); resultSet = getStudentEmailStatement.executeQuery(); while (resultSet.next()) { student = new Student(); student.setIdStudent(resultSet.getInt("idStudent")); student.setEmail(resultSet.getString("email")); student.setPassword(resultSet.getString("password")); student.setCreatedTime(resultSet.getLong("createdTime")); } if (student == null) { throw new IllegalArgumentException(); } resultSet.close(); getStudentEmailStatement.close(); } catch (SQLException e) { e.printStackTrace(); } return student; } // Sletter en token i databasen til et bestemt idStudent /** * * @param idStudent * @return False * @throws SQLException */ public boolean deleteToken(String idStudent) throws SQLException { PreparedStatement deleteTokenStatement = getConnection().prepareStatement(" DELETE FROM tokens WHERE token = ?"); try { deleteTokenStatement.setString(1, idStudent); int rowsAffected = deleteTokenStatement.executeUpdate(); deleteTokenStatement.close(); if (rowsAffected == 1) { return true; } else { return false; } } catch (SQLException e) { e.printStackTrace(); } return false; } // Indsætter en token i DB til et bestemt idStudent /** * * @param token * @param idStudent * @return True or False * @throws SQLException */ public boolean addToken(String token, int idStudent) throws SQLException { PreparedStatement addTokenStatement; int rowsAffected = 0; try { addTokenStatement = getConnection().prepareStatement("INSERT INTO tokens (token, students_idStudent) VALUES (? , ?)"); addTokenStatement.setString(1, token); addTokenStatement.setInt(2, idStudent); rowsAffected = addTokenStatement.executeUpdate(); addTokenStatement.close(); } catch (SQLException e) { e.printStackTrace(); } if (rowsAffected == 1) { return true; } else { return false; } } /** * * @param token * @return Student * @throws SQLException */ public Student getStudentFromToken(String token) throws SQLException { try { PreparedStatement getStudentFromToken = getConnection().prepareStatement("SELECT idStudent, firstName, lastName, email, createdTime FROM students s INNER JOIN tokens t ON t.students_idStudent = s.idStudent WHERE t.token = ?"); getStudentFromToken.setString(1, token); resultSet = getStudentFromToken.executeQuery(); while (resultSet.next()) { student = new Student(); student.setIdStudent(resultSet.getInt("idStudent")); student.setFirstName(resultSet.getString("firstName")); student.setLastName(resultSet.getString("lastName")); student.setEmail(resultSet.getString("email")); student.setCreatedTime(resultSet.getLong("createdTime")); } resultSet.close(); getStudentFromToken.close(); } catch (SQLException e) { e.printStackTrace(); } return student; } }
136675_18
package database; import model.Game; import model.Gamer; import model.Score; import model.User; import java.sql.*; import java.util.ArrayList; /** * This class contains methods which use prepared statements from the DatabaseDriver class to retrieve data from the database. * The methods convert the data and return an object. */ // public class DatabaseWrapper { private Connection connection; DatabaseDriver dbDriver = new DatabaseDriver(); public static final int ALLGAMESBYID = 0; public static final int ALLPENDINGGAMESBYID = 1; public static final int PENDINGINVITESBYID = 2; public static final int GAMESBYUSERID = 3; public static final int ALLGAMES = 4; /** * The connection from DatabaseDriver is initialized in the class */ public DatabaseWrapper() { connection = dbDriver.getConnection(); } /** * The following three methods(getUser(), getGame() & getScore()) return a specific user/score/game as an object of the type User/Score/Game. * Which entry from the database is returned is defined by the parameter id. * * @param id * @return */ public User getUser(int id) { User user = null; ResultSet resultSet = null; PreparedStatement ps; try { ps = connection.prepareStatement(dbDriver.getSqlRecord("users")); ps.setInt(1, id); resultSet = ps.executeQuery(); while (resultSet.next()) { user = new User(); user.setId(resultSet.getInt("id")); user.setFirstName(resultSet.getString("first_name")); user.setLastName(resultSet.getString("last_name")); user.setEmail(resultSet.getString("email")); user.setUserName(resultSet.getString("username")); user.setPassword(resultSet.getString("password")); user.setCreated(resultSet.getDate("created")); user.setStatus(resultSet.getString("status")); user.setType(resultSet.getString("type")); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return user; } public Game getGame(int id) { Game game = null; ResultSet resultSet = null; PreparedStatement ps; try { ps = connection.prepareStatement(dbDriver.getSqlRecord("games")); ps.setInt(1, id); resultSet = ps.executeQuery(); while (resultSet.next()) { Gamer host = new Gamer(); host.setId(resultSet.getInt("host")); Gamer opponent = new Gamer(); opponent.setId(resultSet.getInt("opponent")); Gamer winner = new Gamer(); winner.setId(resultSet.getInt("winner")); game = new Game(); game.setGameId(resultSet.getInt("id")); game.setWinner(winner); game.setHostControls(resultSet.getString("host_controls")); game.setCreated(resultSet.getDate("created")); game.setName(resultSet.getString("name")); game.setStatus(resultSet.getString("status")); game.setOpponentControls(resultSet.getString("opponent_controls")); game.setMapSize(resultSet.getInt("map_size")); // Adding Gamer objects (opponent and host) to our game object game.setOpponent(opponent); game.setHost(host); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return game; } public Score getScoresByUserID(int id) { Score score = null; ResultSet resultSet = null; PreparedStatement ps; try { ps = connection.prepareStatement(dbDriver.getScoresByUserID()); ps.setInt(1, id); resultSet = ps.executeQuery(); while (resultSet.next()) { // Creating Gamer object (user) and setting user_id Gamer user = new Gamer(); user.setId(resultSet.getInt("user_id")); // Creating Gamer object (opponent) and setting user_id Gamer opponent = new Gamer(); opponent.setId(resultSet.getInt("opponent_id")); // Creating game object (game) and setting game_id Game game = new Game(); game.setGameId(resultSet.getInt("game_id")); // Creating score objects and adding user + game object score = new Score(); score.setId(resultSet.getInt("id")); score.setScore(resultSet.getInt("score")); // Adding objects to our Score object score.setUser(user); score.setGame(game); score.setOpponent(opponent); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return score; } /** * The following three methods (getUsers(), getGames() & getScores()) return an array of objects of the type User/Game/Score. * The returned array contains all entries from the relevant table in the database. * @return */ public ArrayList<User> getUsers() { ResultSet resultSet = null; PreparedStatement ps; User user = null; ArrayList<User> result = null; try { ps = connection.prepareStatement(dbDriver.getSqlRecords("users")); resultSet = ps.executeQuery(); result = new ArrayList<User>(); // Indlaeser brugere i arrayListen while (resultSet.next()) { user = new User(); user.setId(resultSet.getInt("id")); user.setFirstName(resultSet.getString("first_name")); user.setLastName(resultSet.getString("last_name")); user.setEmail(resultSet.getString("email")); user.setUserName(resultSet.getString("username")); user.setPassword(resultSet.getString("password")); user.setCreated(resultSet.getDate("created")); user.setStatus(resultSet.getString("status")); user.setType(resultSet.getString("type")); result.add(user); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return result; } public ArrayList<Score> getGamesByUserID(int id) { ResultSet resultSet = null; PreparedStatement ps; ArrayList<Score> result = null; try { ps = connection.prepareStatement(dbDriver.getSQLAllGamesByUserID()); ps.setInt(1, id); resultSet = ps.executeQuery(); result = new ArrayList<Score>(); // Indlaesser brugere i arrayListen while (resultSet.next()) { // Creating new Gamer object (host) Gamer user = new Gamer(); user.setId(id); // Creating new Gamer object (opponent) Gamer opponent = new Gamer(); opponent.setId(resultSet.getInt("opponent_id")); opponent.setUserName(resultSet.getString("opponent_name")); opponent.setFirstName(resultSet.getString("opponent_first_name")); opponent.setLastName(resultSet.getString("opponent_last_name")); // Creating new Gamer object (winner) Gamer winner = new Gamer(); winner.setId(resultSet.getInt("winner")); // Initiating new Game object (game) Game game = new Game(); game.setGameId(resultSet.getInt("id")); game.setName(resultSet.getString("name")); game.setWinner(winner); // Setting our host, opponent and winner objects into our game object Score score = new Score(); score.setOpponent(opponent); score.setUser(user); score.setGame(game); score.setScore(resultSet.getInt("score")); result.add(score); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return result; } public ArrayList<Score> getHighscore() { ResultSet resultSet = null; PreparedStatement ps; ArrayList<Score> result = null; try { ps = connection.prepareStatement(dbDriver.getHighScore()); resultSet = ps.executeQuery(); result = new ArrayList<Score>(); while (resultSet.next()) { // Adding host object Gamer host = new Gamer(); host.setUserName(resultSet.getString("username")); host.setFirstName(resultSet.getString("first_name")); host.setLastName(resultSet.getString("last_name")); host.setId(resultSet.getInt("user_id")); // Adding Opponent object Gamer opponent = new Gamer(); opponent.setId(resultSet.getInt("opponent")); // Adding Game object Game game = new Game(); game.setName(resultSet.getString("game_name")); game.setGameId(resultSet.getInt("game_id")); game.setCreated(resultSet.getDate("created")); Score score = new Score(); score.setId(resultSet.getInt("score_id")); score.setUser(host); score.setGame(game); score.setOpponent(opponent); // Since Gson returns 0 for all unset int variables we are adding the opponent user_id. score.setScore(resultSet.getInt("highscore")); result.add(score); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return result; } /** * The following two methods update the values of a given record in the User/Game table of the database. All entries of the record will be updated with the latest value which is given as a method parameter. * The record to be updated is identified by the method parameter: id. * @param user */ public void updateUser(User user) { try { PreparedStatement ps = connection.prepareStatement(dbDriver.updateSqlUser()); ps.setString(1, user.getFirstName()); ps.setString(2, user.getLastName()); ps.setString(3, user.getEmail()); ps.setString(4, user.getPassword()); ps.setString(5, user.getStatus()); ps.setString(6, user.getType()); ps.setInt(7, user.getId()); ps.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); } } public void updateGame(Game game) { try { PreparedStatement ps = connection.prepareStatement(dbDriver.updateSqlGame()); ps.setString(1, game.getName()); ps.setString(2, game.getStatus()); ps.setInt(3, game.getWinner().getId()); ps.setString(4, game.getHostControls()); ps.setString(5, game.getOpponentControls()); ps.setInt(6, game.getGameId()); ps.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); } } public boolean createUser(User user){ // Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime() // .getTime()); try { // Prepared statement til at tilfoeje en bruger PreparedStatement createUser = connection.prepareStatement(dbDriver.createSqlUser()); createUser.setString(1, user.getFirstName()); createUser.setString(2, user.getLastName()); createUser.setString(3, user.getEmail()); createUser.setString(4, user.getUserName()); createUser.setString(5, user.getPassword()); createUser.setString(6, user.getStatus()); createUser.setString(7, user.getType()); createUser.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); return false; } return true; } public int createGame(Game game) { int id = 0; try { // Prepared statement til at tilfoeje en bruger PreparedStatement createGame = connection.prepareStatement(dbDriver.createSqlGame(),Statement.RETURN_GENERATED_KEYS ); createGame.setInt(1, game.getHost().getId()); createGame.setInt(2, game.getOpponent().getId()); createGame.setString(3, game.getName()); createGame.setString(4, game.getStatus()); createGame.setString(5, game.getHostControls()); createGame.executeUpdate(); ResultSet rs = createGame.getGeneratedKeys(); if(rs.next()) { id = rs.getInt(1); } } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); } return id; } public boolean createScore(int id, Gamer host, Gamer opponent){ try { // Prepared statement til at tilfoeje en bruger PreparedStatement createScore = connection.prepareStatement(dbDriver.createSqlScore()); createScore.setInt(1, host.getId()); createScore.setInt(2, id); createScore.setInt(3, host.getScore()); createScore.setInt(4, opponent.getId()); createScore.executeUpdate(); createScore.setInt(1, opponent.getId()); createScore.setInt(2, id); createScore.setInt(3, opponent.getScore()); createScore.setInt(4, host.getId()); createScore.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); return false; } return true; } public boolean deleteUser(int id) { try { PreparedStatement ps = connection.prepareStatement(dbDriver.deleteSqlUser()); ps.setString(1, "deleted"); ps.setInt(2, id); ps.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); return false; } return true; } public boolean deleteGame(int id) { try { PreparedStatement ps = connection.prepareStatement(dbDriver.deleteSqlGame()); ps.setString(1, "deleted"); ps.setInt(2, id); ps.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); return false; } return true; } public ArrayList<Game> getPendingGamesByUserID(int type, int id) { ResultSet resultSet = null; PreparedStatement ps = null; ArrayList<Game> result = null; try { switch (type){ case ALLGAMESBYID: ps = connection.prepareStatement(dbDriver.getSQLAllGamesByUserID()); ps.setInt(1, id); ps.setInt(2, id); break; case ALLPENDINGGAMESBYID: ps = connection.prepareStatement(dbDriver.getSQLPendingGamesByUserID()); ps.setInt(1, id); ps.setInt(2, id); break; case PENDINGINVITESBYID: ps = connection.prepareStatement(dbDriver.getSQLCompletedGamesByUserID()); ps.setInt(1, id); ps.setInt(2, id); break; } resultSet = ps.executeQuery(); result = new ArrayList<Game>(); // Running through our resultset and adding to array while (resultSet.next()) { // Creating Gamer object (host) Gamer host = new Gamer(); host.setId(resultSet.getInt("host")); // Creating Gamer object (opponent) Gamer opponent = new Gamer(); opponent.setId(resultSet.getInt("opponent")); // Creating Gammer object (winner) Gamer winner = new Gamer(); winner.setId(resultSet.getInt("winner")); // Creating Game object (game) Game game = new Game(); game.setGameId(resultSet.getInt("id")); game.setWinner(winner); game.setHostControls(resultSet.getString("host_controls")); game.setCreated(resultSet.getDate("created")); game.setName(resultSet.getString("name")); game.setStatus(resultSet.getString("status")); game.setMapSize(resultSet.getInt("map_size")); // Adding host and opponent objects to our game object game.setHost(host); game.setOpponent(opponent); result.add(game); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return result; } public User authenticatedUser(String username) { User user = null; ResultSet resultSet = null; PreparedStatement ps; try { ps = connection.prepareStatement(dbDriver.authenticatedSql()); ps.setString(1, username); resultSet = ps.executeQuery(); while (resultSet.next()) { user = new User(); user.setId(resultSet.getInt("id")); user.setFirstName(resultSet.getString("first_name")); user.setLastName(resultSet.getString("last_name")); user.setEmail(resultSet.getString("email")); user.setUserName(resultSet.getString("username")); user.setPassword(resultSet.getString("password")); user.setCreated(resultSet.getDate("created")); user.setStatus(resultSet.getString("status")); user.setType(resultSet.getString("type")); } } catch (SQLException e) { e.printStackTrace(); } return user; } public ArrayList<Gamer> getScore(){ ResultSet resultSet = null; PreparedStatement ps; ArrayList<Gamer> result = null; try { ps = connection.prepareStatement(dbDriver.getSqlHighScore()); resultSet = ps.executeQuery(); result = new ArrayList<Gamer>(); // Indlaeser brugere i arrayListen while (resultSet.next()) { Gamer gamer = new Gamer(); gamer.setId(resultSet.getInt("id")); gamer.setFirstName(resultSet.getString("first_name")); gamer.setLastName(resultSet.getString("last_name")); gamer.setEmail(resultSet.getString("email")); gamer.setUserName(resultSet.getString("username")); gamer.setCreated(resultSet.getDate("created")); gamer.setStatus(resultSet.getString("status")); gamer.setTotalScore(resultSet.getInt("TotalScore")); result.add(gamer); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return result; } }
Distribuerede-systemer/snake
src/database/DatabaseWrapper.java
5,727
// Adding Opponent object
line_comment
nl
package database; import model.Game; import model.Gamer; import model.Score; import model.User; import java.sql.*; import java.util.ArrayList; /** * This class contains methods which use prepared statements from the DatabaseDriver class to retrieve data from the database. * The methods convert the data and return an object. */ // public class DatabaseWrapper { private Connection connection; DatabaseDriver dbDriver = new DatabaseDriver(); public static final int ALLGAMESBYID = 0; public static final int ALLPENDINGGAMESBYID = 1; public static final int PENDINGINVITESBYID = 2; public static final int GAMESBYUSERID = 3; public static final int ALLGAMES = 4; /** * The connection from DatabaseDriver is initialized in the class */ public DatabaseWrapper() { connection = dbDriver.getConnection(); } /** * The following three methods(getUser(), getGame() & getScore()) return a specific user/score/game as an object of the type User/Score/Game. * Which entry from the database is returned is defined by the parameter id. * * @param id * @return */ public User getUser(int id) { User user = null; ResultSet resultSet = null; PreparedStatement ps; try { ps = connection.prepareStatement(dbDriver.getSqlRecord("users")); ps.setInt(1, id); resultSet = ps.executeQuery(); while (resultSet.next()) { user = new User(); user.setId(resultSet.getInt("id")); user.setFirstName(resultSet.getString("first_name")); user.setLastName(resultSet.getString("last_name")); user.setEmail(resultSet.getString("email")); user.setUserName(resultSet.getString("username")); user.setPassword(resultSet.getString("password")); user.setCreated(resultSet.getDate("created")); user.setStatus(resultSet.getString("status")); user.setType(resultSet.getString("type")); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return user; } public Game getGame(int id) { Game game = null; ResultSet resultSet = null; PreparedStatement ps; try { ps = connection.prepareStatement(dbDriver.getSqlRecord("games")); ps.setInt(1, id); resultSet = ps.executeQuery(); while (resultSet.next()) { Gamer host = new Gamer(); host.setId(resultSet.getInt("host")); Gamer opponent = new Gamer(); opponent.setId(resultSet.getInt("opponent")); Gamer winner = new Gamer(); winner.setId(resultSet.getInt("winner")); game = new Game(); game.setGameId(resultSet.getInt("id")); game.setWinner(winner); game.setHostControls(resultSet.getString("host_controls")); game.setCreated(resultSet.getDate("created")); game.setName(resultSet.getString("name")); game.setStatus(resultSet.getString("status")); game.setOpponentControls(resultSet.getString("opponent_controls")); game.setMapSize(resultSet.getInt("map_size")); // Adding Gamer objects (opponent and host) to our game object game.setOpponent(opponent); game.setHost(host); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return game; } public Score getScoresByUserID(int id) { Score score = null; ResultSet resultSet = null; PreparedStatement ps; try { ps = connection.prepareStatement(dbDriver.getScoresByUserID()); ps.setInt(1, id); resultSet = ps.executeQuery(); while (resultSet.next()) { // Creating Gamer object (user) and setting user_id Gamer user = new Gamer(); user.setId(resultSet.getInt("user_id")); // Creating Gamer object (opponent) and setting user_id Gamer opponent = new Gamer(); opponent.setId(resultSet.getInt("opponent_id")); // Creating game object (game) and setting game_id Game game = new Game(); game.setGameId(resultSet.getInt("game_id")); // Creating score objects and adding user + game object score = new Score(); score.setId(resultSet.getInt("id")); score.setScore(resultSet.getInt("score")); // Adding objects to our Score object score.setUser(user); score.setGame(game); score.setOpponent(opponent); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return score; } /** * The following three methods (getUsers(), getGames() & getScores()) return an array of objects of the type User/Game/Score. * The returned array contains all entries from the relevant table in the database. * @return */ public ArrayList<User> getUsers() { ResultSet resultSet = null; PreparedStatement ps; User user = null; ArrayList<User> result = null; try { ps = connection.prepareStatement(dbDriver.getSqlRecords("users")); resultSet = ps.executeQuery(); result = new ArrayList<User>(); // Indlaeser brugere i arrayListen while (resultSet.next()) { user = new User(); user.setId(resultSet.getInt("id")); user.setFirstName(resultSet.getString("first_name")); user.setLastName(resultSet.getString("last_name")); user.setEmail(resultSet.getString("email")); user.setUserName(resultSet.getString("username")); user.setPassword(resultSet.getString("password")); user.setCreated(resultSet.getDate("created")); user.setStatus(resultSet.getString("status")); user.setType(resultSet.getString("type")); result.add(user); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return result; } public ArrayList<Score> getGamesByUserID(int id) { ResultSet resultSet = null; PreparedStatement ps; ArrayList<Score> result = null; try { ps = connection.prepareStatement(dbDriver.getSQLAllGamesByUserID()); ps.setInt(1, id); resultSet = ps.executeQuery(); result = new ArrayList<Score>(); // Indlaesser brugere i arrayListen while (resultSet.next()) { // Creating new Gamer object (host) Gamer user = new Gamer(); user.setId(id); // Creating new Gamer object (opponent) Gamer opponent = new Gamer(); opponent.setId(resultSet.getInt("opponent_id")); opponent.setUserName(resultSet.getString("opponent_name")); opponent.setFirstName(resultSet.getString("opponent_first_name")); opponent.setLastName(resultSet.getString("opponent_last_name")); // Creating new Gamer object (winner) Gamer winner = new Gamer(); winner.setId(resultSet.getInt("winner")); // Initiating new Game object (game) Game game = new Game(); game.setGameId(resultSet.getInt("id")); game.setName(resultSet.getString("name")); game.setWinner(winner); // Setting our host, opponent and winner objects into our game object Score score = new Score(); score.setOpponent(opponent); score.setUser(user); score.setGame(game); score.setScore(resultSet.getInt("score")); result.add(score); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return result; } public ArrayList<Score> getHighscore() { ResultSet resultSet = null; PreparedStatement ps; ArrayList<Score> result = null; try { ps = connection.prepareStatement(dbDriver.getHighScore()); resultSet = ps.executeQuery(); result = new ArrayList<Score>(); while (resultSet.next()) { // Adding host object Gamer host = new Gamer(); host.setUserName(resultSet.getString("username")); host.setFirstName(resultSet.getString("first_name")); host.setLastName(resultSet.getString("last_name")); host.setId(resultSet.getInt("user_id")); // Adding Opponent<SUF> Gamer opponent = new Gamer(); opponent.setId(resultSet.getInt("opponent")); // Adding Game object Game game = new Game(); game.setName(resultSet.getString("game_name")); game.setGameId(resultSet.getInt("game_id")); game.setCreated(resultSet.getDate("created")); Score score = new Score(); score.setId(resultSet.getInt("score_id")); score.setUser(host); score.setGame(game); score.setOpponent(opponent); // Since Gson returns 0 for all unset int variables we are adding the opponent user_id. score.setScore(resultSet.getInt("highscore")); result.add(score); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return result; } /** * The following two methods update the values of a given record in the User/Game table of the database. All entries of the record will be updated with the latest value which is given as a method parameter. * The record to be updated is identified by the method parameter: id. * @param user */ public void updateUser(User user) { try { PreparedStatement ps = connection.prepareStatement(dbDriver.updateSqlUser()); ps.setString(1, user.getFirstName()); ps.setString(2, user.getLastName()); ps.setString(3, user.getEmail()); ps.setString(4, user.getPassword()); ps.setString(5, user.getStatus()); ps.setString(6, user.getType()); ps.setInt(7, user.getId()); ps.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); } } public void updateGame(Game game) { try { PreparedStatement ps = connection.prepareStatement(dbDriver.updateSqlGame()); ps.setString(1, game.getName()); ps.setString(2, game.getStatus()); ps.setInt(3, game.getWinner().getId()); ps.setString(4, game.getHostControls()); ps.setString(5, game.getOpponentControls()); ps.setInt(6, game.getGameId()); ps.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); } } public boolean createUser(User user){ // Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime() // .getTime()); try { // Prepared statement til at tilfoeje en bruger PreparedStatement createUser = connection.prepareStatement(dbDriver.createSqlUser()); createUser.setString(1, user.getFirstName()); createUser.setString(2, user.getLastName()); createUser.setString(3, user.getEmail()); createUser.setString(4, user.getUserName()); createUser.setString(5, user.getPassword()); createUser.setString(6, user.getStatus()); createUser.setString(7, user.getType()); createUser.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); return false; } return true; } public int createGame(Game game) { int id = 0; try { // Prepared statement til at tilfoeje en bruger PreparedStatement createGame = connection.prepareStatement(dbDriver.createSqlGame(),Statement.RETURN_GENERATED_KEYS ); createGame.setInt(1, game.getHost().getId()); createGame.setInt(2, game.getOpponent().getId()); createGame.setString(3, game.getName()); createGame.setString(4, game.getStatus()); createGame.setString(5, game.getHostControls()); createGame.executeUpdate(); ResultSet rs = createGame.getGeneratedKeys(); if(rs.next()) { id = rs.getInt(1); } } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); } return id; } public boolean createScore(int id, Gamer host, Gamer opponent){ try { // Prepared statement til at tilfoeje en bruger PreparedStatement createScore = connection.prepareStatement(dbDriver.createSqlScore()); createScore.setInt(1, host.getId()); createScore.setInt(2, id); createScore.setInt(3, host.getScore()); createScore.setInt(4, opponent.getId()); createScore.executeUpdate(); createScore.setInt(1, opponent.getId()); createScore.setInt(2, id); createScore.setInt(3, opponent.getScore()); createScore.setInt(4, host.getId()); createScore.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); return false; } return true; } public boolean deleteUser(int id) { try { PreparedStatement ps = connection.prepareStatement(dbDriver.deleteSqlUser()); ps.setString(1, "deleted"); ps.setInt(2, id); ps.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); return false; } return true; } public boolean deleteGame(int id) { try { PreparedStatement ps = connection.prepareStatement(dbDriver.deleteSqlGame()); ps.setString(1, "deleted"); ps.setInt(2, id); ps.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); dbDriver.close(); return false; } return true; } public ArrayList<Game> getPendingGamesByUserID(int type, int id) { ResultSet resultSet = null; PreparedStatement ps = null; ArrayList<Game> result = null; try { switch (type){ case ALLGAMESBYID: ps = connection.prepareStatement(dbDriver.getSQLAllGamesByUserID()); ps.setInt(1, id); ps.setInt(2, id); break; case ALLPENDINGGAMESBYID: ps = connection.prepareStatement(dbDriver.getSQLPendingGamesByUserID()); ps.setInt(1, id); ps.setInt(2, id); break; case PENDINGINVITESBYID: ps = connection.prepareStatement(dbDriver.getSQLCompletedGamesByUserID()); ps.setInt(1, id); ps.setInt(2, id); break; } resultSet = ps.executeQuery(); result = new ArrayList<Game>(); // Running through our resultset and adding to array while (resultSet.next()) { // Creating Gamer object (host) Gamer host = new Gamer(); host.setId(resultSet.getInt("host")); // Creating Gamer object (opponent) Gamer opponent = new Gamer(); opponent.setId(resultSet.getInt("opponent")); // Creating Gammer object (winner) Gamer winner = new Gamer(); winner.setId(resultSet.getInt("winner")); // Creating Game object (game) Game game = new Game(); game.setGameId(resultSet.getInt("id")); game.setWinner(winner); game.setHostControls(resultSet.getString("host_controls")); game.setCreated(resultSet.getDate("created")); game.setName(resultSet.getString("name")); game.setStatus(resultSet.getString("status")); game.setMapSize(resultSet.getInt("map_size")); // Adding host and opponent objects to our game object game.setHost(host); game.setOpponent(opponent); result.add(game); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return result; } public User authenticatedUser(String username) { User user = null; ResultSet resultSet = null; PreparedStatement ps; try { ps = connection.prepareStatement(dbDriver.authenticatedSql()); ps.setString(1, username); resultSet = ps.executeQuery(); while (resultSet.next()) { user = new User(); user.setId(resultSet.getInt("id")); user.setFirstName(resultSet.getString("first_name")); user.setLastName(resultSet.getString("last_name")); user.setEmail(resultSet.getString("email")); user.setUserName(resultSet.getString("username")); user.setPassword(resultSet.getString("password")); user.setCreated(resultSet.getDate("created")); user.setStatus(resultSet.getString("status")); user.setType(resultSet.getString("type")); } } catch (SQLException e) { e.printStackTrace(); } return user; } public ArrayList<Gamer> getScore(){ ResultSet resultSet = null; PreparedStatement ps; ArrayList<Gamer> result = null; try { ps = connection.prepareStatement(dbDriver.getSqlHighScore()); resultSet = ps.executeQuery(); result = new ArrayList<Gamer>(); // Indlaeser brugere i arrayListen while (resultSet.next()) { Gamer gamer = new Gamer(); gamer.setId(resultSet.getInt("id")); gamer.setFirstName(resultSet.getString("first_name")); gamer.setLastName(resultSet.getString("last_name")); gamer.setEmail(resultSet.getString("email")); gamer.setUserName(resultSet.getString("username")); gamer.setCreated(resultSet.getDate("created")); gamer.setStatus(resultSet.getString("status")); gamer.setTotalScore(resultSet.getInt("TotalScore")); result.add(gamer); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException ex) { ex.printStackTrace(); dbDriver.close(); } } return result; } }
154301_3
/* * @(#)PlafRes_nl.java 12.oct 2007 Versión 2.2 * * El contenido de este fichero está sujeto a la Licencia Pública openXpertya versión 1.1 (LPO) * en tanto en cuanto forme parte íntegra del total del producto denominado: openXpertya, solución * empresarial global , y siempre según los términos de dicha licencia LPO. * Una copia íntegra de dicha licencia está incluida con todas las fuentes del producto. * Partes del código son copyRight (c) 2002-2007 de Ingeniería Informática Integrada S.L., otras * partes son copyRight (c) 2003-2007 de Consultoría y Soporte en Redes y Tecnologías de la * Información S.L., otras partes son copyRight (c) 2005-2006 de Dataware Sistemas S.L., otras son * copyright (c) 2005-2006 de Indeos Consultoría S.L., otras son copyright (c) 2005-2006 de Disytel * Servicios Digitales S.A., y otras partes son adaptadas, ampliadas, traducidas, revisadas y/o * mejoradas a partir de código original de terceros, recogidos en el ADDENDUM A, sección 3 (A.3) * de dicha licencia LPO, y si dicho código es extraido como parte del total del producto, estará * sujeto a su respectiva licencia original. * Más información en http://www.openxpertya.org/ayuda/Licencia.html */ package org.compiere.plaf; import java.util.ListResourceBundle; /** * Translation Texts for Look & Feel * * @author Comunidad de Desarrollo openXpertya * *Basado en Codigo Original Modificado, Revisado y Optimizado de: * * Eldir Tomassen * @version $Id: PlafRes_nl.java,v 1.6 2005/03/11 20:34:36 jjanke Exp $ */ public class PlafRes_nl extends ListResourceBundle { /** The data */ static final Object[][] contents = new String[][] { { "BackColType", "Achtergrond Kleur Type" }, { "BackColType_Flat", "Egaal" }, { "BackColType_Gradient", "Verloop" }, { "BackColType_Lines", "Lijnen" }, { "BackColType_Texture", "Reli�f" }, // { "LookAndFeelEditor", "Look & Feel Editor" }, { "LookAndFeel", "Look & Feel" }, { "Theme", "Thema" }, { "EditCompiereTheme", "OpenXpertya Theme Bewerken" }, { "SetDefault", "Standaard Achtergrond" }, { "SetDefaultColor", "Achtergrond Kleur" }, { "ColorBlind", "Kleur Verloop" }, { "Example", "Voorbeeld" }, { "Reset", "Ongedaan maken" }, { "OK", "OK" }, { "Cancel", "Annuleren" }, // { "CompiereThemeEditor", "OpenXpertya Thema Editor" }, { "MetalColors", "Metaal Kleuren" }, { "CompiereColors", "OpenXpertya Kleuren" }, { "CompiereFonts", "OpenXpertya Lettertypen" }, { "Primary1Info", "Shaduw, Schijdingsteken" }, { "Primary1", "Primair 1" }, { "Primary2Info", "Schijdingslijn, Geselecteerd Menu" }, { "Primary2", "Primair 2" }, { "Primary3Info", "Tabel Geselecteerde Rij, Geselecteerde Tekst, ToolTip Achtergrond" }, { "Primary3", "Primair 3" }, { "Secondary1Info", "Begrenzing Lijnen" }, { "Secondary1", "Secundair 2" }, { "Secondary2Info", "Inactieve Tabs, Geselecteerde Velden, Inactieve Begrenzing + Tekst" }, { "Secondary2", "Secundait 2" }, { "Secondary3Info", "Achtergrond" }, { "Secondary3", "Secondair 3" }, // { "ControlFontInfo", "Beheer Lettertype" }, { "ControlFont", "Label Lettertype" }, { "SystemFontInfo", "Tool Tip, Boom Iconen" }, { "SystemFont", "Systeem Letterype" }, { "UserFontInfo", "Door Gebruiker ingevoerde gegevens" }, { "UserFont", "Veld Lettertype" }, // { "SmallFontInfo", "Reports" }, { "SmallFont", "Klein Lettertype" }, { "WindowTitleFont", "Titel Lettertype" }, { "MenuFont", "Menu Lettertype" }, // { "MandatoryInfo", "Verplicht Veld Achtergrond" }, { "Mandatory", "Verplicht" }, { "ErrorInfo", "Foutief Veld Achtergrond" }, { "Error", "Foutief" }, { "InfoInfo", "Informatie Veld Achtergrond" }, { "Info", "Informatie" }, { "WhiteInfo", "Lijnen" }, { "White", "Wit" }, { "BlackInfo", "Lijnen, Tekst" }, { "Black", "Zwart" }, { "InactiveInfo", "Inactief Veld Achtergrond" }, { "Inactive", "Inactief" }, { "TextOKInfo", "OK Tekst Voorgrond" }, { "TextOK", "Tekst - OK" }, { "TextIssueInfo", "Foutief Tekst Voorgrond" }, { "TextIssue", "Tekst - Foutief" }, // { "FontChooser", "Lettertype Selecteren" }, { "Fonts", "Lettertypen" }, { "Plain", "Normaal" }, { "Italic", "Schuin" }, { "Bold", "Vet" }, { "BoldItalic", "Vet & Schuin" }, { "Name", "Naam" }, { "Size", "Formaat" }, { "Style", "Stijl" }, { "TestString", "Dit is een test! De thema brwoser is bezig. 12,3456.78 LetterLOne = l1 LetterOZero = O0" }, { "FontString", "Lettertype" }, // { "CompiereColorEditor", "OpenXpertya Kleur Editor" }, { "CompiereType", "Kleur Type" }, { "GradientUpperColor", "Verloop Bovenste Kleur" }, { "GradientLowerColor", "Verloop Onderste Kleur" }, { "GradientStart", "Verloop Start" }, { "GradientDistance", "Verloop Afstand" }, { "TextureURL", "Textuur URL" }, { "TextureAlpha", "Textuur Alpha" }, { "TextureTaintColor", "Textuur Taint Kleur" }, { "LineColor", "Lijn Kleur" }, { "LineBackColor", "Achtergrond Kleur" }, { "LineWidth", "Lijn Breedte" }, { "LineDistance", "Lijn Reikwijdte" }, { "FlatColor", "Egale Kleur" } }; //~--- get methods -------------------------------------------------------- /** * Get Contents * @return contents */ public Object[][] getContents() { return contents; } } // Res /* * @(#)PlafRes_nl.java 02.jul 2007 * * Fin del fichero PlafRes_nl.java * * Versión 2.2 - Fundesle (2007) * */ //~ Formateado de acuerdo a Sistema Fundesle en 02.jul 2007
Disytel-Consulting-SA/libertya
looks/src/org/compiere/plaf/PlafRes_nl.java
2,040
//~--- get methods --------------------------------------------------------
line_comment
nl
/* * @(#)PlafRes_nl.java 12.oct 2007 Versión 2.2 * * El contenido de este fichero está sujeto a la Licencia Pública openXpertya versión 1.1 (LPO) * en tanto en cuanto forme parte íntegra del total del producto denominado: openXpertya, solución * empresarial global , y siempre según los términos de dicha licencia LPO. * Una copia íntegra de dicha licencia está incluida con todas las fuentes del producto. * Partes del código son copyRight (c) 2002-2007 de Ingeniería Informática Integrada S.L., otras * partes son copyRight (c) 2003-2007 de Consultoría y Soporte en Redes y Tecnologías de la * Información S.L., otras partes son copyRight (c) 2005-2006 de Dataware Sistemas S.L., otras son * copyright (c) 2005-2006 de Indeos Consultoría S.L., otras son copyright (c) 2005-2006 de Disytel * Servicios Digitales S.A., y otras partes son adaptadas, ampliadas, traducidas, revisadas y/o * mejoradas a partir de código original de terceros, recogidos en el ADDENDUM A, sección 3 (A.3) * de dicha licencia LPO, y si dicho código es extraido como parte del total del producto, estará * sujeto a su respectiva licencia original. * Más información en http://www.openxpertya.org/ayuda/Licencia.html */ package org.compiere.plaf; import java.util.ListResourceBundle; /** * Translation Texts for Look & Feel * * @author Comunidad de Desarrollo openXpertya * *Basado en Codigo Original Modificado, Revisado y Optimizado de: * * Eldir Tomassen * @version $Id: PlafRes_nl.java,v 1.6 2005/03/11 20:34:36 jjanke Exp $ */ public class PlafRes_nl extends ListResourceBundle { /** The data */ static final Object[][] contents = new String[][] { { "BackColType", "Achtergrond Kleur Type" }, { "BackColType_Flat", "Egaal" }, { "BackColType_Gradient", "Verloop" }, { "BackColType_Lines", "Lijnen" }, { "BackColType_Texture", "Reli�f" }, // { "LookAndFeelEditor", "Look & Feel Editor" }, { "LookAndFeel", "Look & Feel" }, { "Theme", "Thema" }, { "EditCompiereTheme", "OpenXpertya Theme Bewerken" }, { "SetDefault", "Standaard Achtergrond" }, { "SetDefaultColor", "Achtergrond Kleur" }, { "ColorBlind", "Kleur Verloop" }, { "Example", "Voorbeeld" }, { "Reset", "Ongedaan maken" }, { "OK", "OK" }, { "Cancel", "Annuleren" }, // { "CompiereThemeEditor", "OpenXpertya Thema Editor" }, { "MetalColors", "Metaal Kleuren" }, { "CompiereColors", "OpenXpertya Kleuren" }, { "CompiereFonts", "OpenXpertya Lettertypen" }, { "Primary1Info", "Shaduw, Schijdingsteken" }, { "Primary1", "Primair 1" }, { "Primary2Info", "Schijdingslijn, Geselecteerd Menu" }, { "Primary2", "Primair 2" }, { "Primary3Info", "Tabel Geselecteerde Rij, Geselecteerde Tekst, ToolTip Achtergrond" }, { "Primary3", "Primair 3" }, { "Secondary1Info", "Begrenzing Lijnen" }, { "Secondary1", "Secundair 2" }, { "Secondary2Info", "Inactieve Tabs, Geselecteerde Velden, Inactieve Begrenzing + Tekst" }, { "Secondary2", "Secundait 2" }, { "Secondary3Info", "Achtergrond" }, { "Secondary3", "Secondair 3" }, // { "ControlFontInfo", "Beheer Lettertype" }, { "ControlFont", "Label Lettertype" }, { "SystemFontInfo", "Tool Tip, Boom Iconen" }, { "SystemFont", "Systeem Letterype" }, { "UserFontInfo", "Door Gebruiker ingevoerde gegevens" }, { "UserFont", "Veld Lettertype" }, // { "SmallFontInfo", "Reports" }, { "SmallFont", "Klein Lettertype" }, { "WindowTitleFont", "Titel Lettertype" }, { "MenuFont", "Menu Lettertype" }, // { "MandatoryInfo", "Verplicht Veld Achtergrond" }, { "Mandatory", "Verplicht" }, { "ErrorInfo", "Foutief Veld Achtergrond" }, { "Error", "Foutief" }, { "InfoInfo", "Informatie Veld Achtergrond" }, { "Info", "Informatie" }, { "WhiteInfo", "Lijnen" }, { "White", "Wit" }, { "BlackInfo", "Lijnen, Tekst" }, { "Black", "Zwart" }, { "InactiveInfo", "Inactief Veld Achtergrond" }, { "Inactive", "Inactief" }, { "TextOKInfo", "OK Tekst Voorgrond" }, { "TextOK", "Tekst - OK" }, { "TextIssueInfo", "Foutief Tekst Voorgrond" }, { "TextIssue", "Tekst - Foutief" }, // { "FontChooser", "Lettertype Selecteren" }, { "Fonts", "Lettertypen" }, { "Plain", "Normaal" }, { "Italic", "Schuin" }, { "Bold", "Vet" }, { "BoldItalic", "Vet & Schuin" }, { "Name", "Naam" }, { "Size", "Formaat" }, { "Style", "Stijl" }, { "TestString", "Dit is een test! De thema brwoser is bezig. 12,3456.78 LetterLOne = l1 LetterOZero = O0" }, { "FontString", "Lettertype" }, // { "CompiereColorEditor", "OpenXpertya Kleur Editor" }, { "CompiereType", "Kleur Type" }, { "GradientUpperColor", "Verloop Bovenste Kleur" }, { "GradientLowerColor", "Verloop Onderste Kleur" }, { "GradientStart", "Verloop Start" }, { "GradientDistance", "Verloop Afstand" }, { "TextureURL", "Textuur URL" }, { "TextureAlpha", "Textuur Alpha" }, { "TextureTaintColor", "Textuur Taint Kleur" }, { "LineColor", "Lijn Kleur" }, { "LineBackColor", "Achtergrond Kleur" }, { "LineWidth", "Lijn Breedte" }, { "LineDistance", "Lijn Reikwijdte" }, { "FlatColor", "Egale Kleur" } }; //~--- get<SUF> /** * Get Contents * @return contents */ public Object[][] getContents() { return contents; } } // Res /* * @(#)PlafRes_nl.java 02.jul 2007 * * Fin del fichero PlafRes_nl.java * * Versión 2.2 - Fundesle (2007) * */ //~ Formateado de acuerdo a Sistema Fundesle en 02.jul 2007
99629_5
package me.mindgamesnl.mcwebsocket.main.Mc_Websocket; import java.io.IOException; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Collection; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketImpl; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; public class WsMain extends WebSocketServer { public static JsonElement conn_us_name; public static WsMain s; public WsMain(int port) throws UnknownHostException { super(new InetSocketAddress(port)); } public WsMain(InetSocketAddress address) { super(address); } @Override public void onOpen(WebSocket conn, ClientHandshake handshake) { WsSessionMan.getSessionManager().openSession(conn.getRemoteSocketAddress().getAddress().getHostAddress()); // Bukkit.getLogger().info(me.mindgamesnl.mcwebsocket.main.config.Config.Chat_Header + conn.getRemoteSocketAddress().getAddress().getHostName() + " Is nu niet meer verbonden met websocket!"); } @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { WsSessionMan.getSessionManager().endSession(conn.getRemoteSocketAddress().getAddress().getHostAddress()); // Bukkit.getLogger().info(me.mindgamesnl.mcwebsocket.main.config.Config.Chat_Header + conn + " Is no longer connected!"); } @Override public void onMessage(WebSocket conn, String message) { // Bukkit.getLogger().info(me.mindgamesnl.mcwebsocket.main.config.Config.Chat_Header + "Websocket packet ontvangen! - " + conn + ":" + message); JsonObject jsonObject = new JsonParser().parse(message).getAsJsonObject(); if (jsonObject.get("command").getAsString().equalsIgnoreCase("connect")) { WsSessionMan.getSessionManager().addSessionUsername(conn.getRemoteSocketAddress().getAddress().getHostAddress(), jsonObject.get("user").getAsString()); Player player=Bukkit.getPlayer(jsonObject.get("user").getAsString()); player.sendMessage(me.mindgamesnl.mcwebsocket.main.config.Config.Chat_Header_audio + me.mindgamesnl.mcwebsocket.main.config.Config.Connected_message); WsSender.Send_Ws_Packet_To_Client(Bukkit.getPlayerExact(jsonObject.get("user").getAsString()), "{\"command\":\"verbonden\",\"line\":\"play\"}"); } else {} } public static void runServer() throws InterruptedException, IOException { WebSocketImpl.DEBUG = false; int port = me.mindgamesnl.mcwebsocket.main.Mc_Websocket.Main.getPL().getConfig().getInt("config.ws_host_port"); s = new WsMain(port); s.start(); } @Override public void onError(WebSocket conn, Exception ex) { ex.printStackTrace(); if (conn != null) { // some errors like port binding failed may not be assignable to a specific websocket } } public void sendToAll(String data) { Collection<WebSocket> con = connections(); synchronized (con) { for (WebSocket c : con) { c.send(data); } } } public void sendData(WsSession session, String data) { Collection<WebSocket> con = connections(); synchronized (con) { for (WebSocket c : con) { if (c.getRemoteSocketAddress().getAddress().getHostAddress().equalsIgnoreCase(session.getHost())) { //Bukkit.getLogger().info(config.Config.Chat_Header + "Json verzonden naar client! Json value: " + data); //Bukkit.getLogger().info(me.mindgamesnl.mcwebsocket.main.config.Config.Chat_Header + "Json verzonden naar client! Dat verdient een feestje want de plugin werkt dus optimaal! :-)"); c.send(data); } } } } }
DmACKGL/OpenAudioMc
Plugin (eclipse)/OpenAudio/src/me/mindgamesnl/mcwebsocket/main/Mc_Websocket/WsMain.java
1,255
//Bukkit.getLogger().info(me.mindgamesnl.mcwebsocket.main.config.Config.Chat_Header + "Json verzonden naar client! Dat verdient een feestje want de plugin werkt dus optimaal! :-)");
line_comment
nl
package me.mindgamesnl.mcwebsocket.main.Mc_Websocket; import java.io.IOException; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Collection; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketImpl; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; public class WsMain extends WebSocketServer { public static JsonElement conn_us_name; public static WsMain s; public WsMain(int port) throws UnknownHostException { super(new InetSocketAddress(port)); } public WsMain(InetSocketAddress address) { super(address); } @Override public void onOpen(WebSocket conn, ClientHandshake handshake) { WsSessionMan.getSessionManager().openSession(conn.getRemoteSocketAddress().getAddress().getHostAddress()); // Bukkit.getLogger().info(me.mindgamesnl.mcwebsocket.main.config.Config.Chat_Header + conn.getRemoteSocketAddress().getAddress().getHostName() + " Is nu niet meer verbonden met websocket!"); } @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { WsSessionMan.getSessionManager().endSession(conn.getRemoteSocketAddress().getAddress().getHostAddress()); // Bukkit.getLogger().info(me.mindgamesnl.mcwebsocket.main.config.Config.Chat_Header + conn + " Is no longer connected!"); } @Override public void onMessage(WebSocket conn, String message) { // Bukkit.getLogger().info(me.mindgamesnl.mcwebsocket.main.config.Config.Chat_Header + "Websocket packet ontvangen! - " + conn + ":" + message); JsonObject jsonObject = new JsonParser().parse(message).getAsJsonObject(); if (jsonObject.get("command").getAsString().equalsIgnoreCase("connect")) { WsSessionMan.getSessionManager().addSessionUsername(conn.getRemoteSocketAddress().getAddress().getHostAddress(), jsonObject.get("user").getAsString()); Player player=Bukkit.getPlayer(jsonObject.get("user").getAsString()); player.sendMessage(me.mindgamesnl.mcwebsocket.main.config.Config.Chat_Header_audio + me.mindgamesnl.mcwebsocket.main.config.Config.Connected_message); WsSender.Send_Ws_Packet_To_Client(Bukkit.getPlayerExact(jsonObject.get("user").getAsString()), "{\"command\":\"verbonden\",\"line\":\"play\"}"); } else {} } public static void runServer() throws InterruptedException, IOException { WebSocketImpl.DEBUG = false; int port = me.mindgamesnl.mcwebsocket.main.Mc_Websocket.Main.getPL().getConfig().getInt("config.ws_host_port"); s = new WsMain(port); s.start(); } @Override public void onError(WebSocket conn, Exception ex) { ex.printStackTrace(); if (conn != null) { // some errors like port binding failed may not be assignable to a specific websocket } } public void sendToAll(String data) { Collection<WebSocket> con = connections(); synchronized (con) { for (WebSocket c : con) { c.send(data); } } } public void sendData(WsSession session, String data) { Collection<WebSocket> con = connections(); synchronized (con) { for (WebSocket c : con) { if (c.getRemoteSocketAddress().getAddress().getHostAddress().equalsIgnoreCase(session.getHost())) { //Bukkit.getLogger().info(config.Config.Chat_Header + "Json verzonden naar client! Json value: " + data); //Bukkit.getLogger().info(me.mindgamesnl.mcwebsocket.main.config.Config.Chat_Header +<SUF> c.send(data); } } } } }
50895_7
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc. * * 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 hudson.cli; import static java.util.logging.Level.FINE; import static java.util.logging.Level.parse; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.cli.client.Messages; import jakarta.websocket.ClientEndpointConfig; import jakarta.websocket.Endpoint; import jakarta.websocket.EndpointConfig; import jakarta.websocket.Session; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.SecureRandom; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.glassfish.tyrus.client.ClientManager; import org.glassfish.tyrus.client.ClientProperties; import org.glassfish.tyrus.client.SslEngineConfigurator; import org.glassfish.tyrus.container.jdk.client.JdkClientContainer; /** * CLI entry point to Jenkins. */ @SuppressFBWarnings(value = "CRLF_INJECTION_LOGS", justification = "We don't care about this behavior") public class CLI { private CLI() {} /** * Make sure the connection is open against Jenkins server. * * @param c The open connection. * @throws IOException in case of communication problem. * @throws NotTalkingToJenkinsException when connection is not made to Jenkins service. */ /*package*/ static void verifyJenkinsConnection(URLConnection c) throws IOException { if (c.getHeaderField("X-Hudson") == null && c.getHeaderField("X-Jenkins") == null) throw new NotTalkingToJenkinsException(c); } /*package*/ static final class NotTalkingToJenkinsException extends IOException { NotTalkingToJenkinsException(String s) { super(s); } NotTalkingToJenkinsException(URLConnection c) { super("There's no Jenkins running at " + c.getURL().toString()); } } public static void main(final String[] _args) throws Exception { try { System.exit(_main(_args)); } catch (NotTalkingToJenkinsException ex) { System.err.println(ex.getMessage()); System.exit(3); } catch (Throwable t) { // if the CLI main thread die, make sure to kill the JVM. t.printStackTrace(); System.exit(-1); } } private enum Mode { HTTP, SSH, WEB_SOCKET } public static int _main(String[] _args) throws Exception { List<String> args = Arrays.asList(_args); PrivateKeyProvider provider = new PrivateKeyProvider(); String url = System.getenv("JENKINS_URL"); if (url == null) url = System.getenv("HUDSON_URL"); boolean noKeyAuth = false; Mode mode = null; String user = null; String auth = null; String bearer = null; String userIdEnv = System.getenv("JENKINS_USER_ID"); String tokenEnv = System.getenv("JENKINS_API_TOKEN"); boolean strictHostKey = false; boolean noCertificateCheck = false; while (!args.isEmpty()) { String head = args.get(0); if (head.equals("-version")) { System.out.println("Version: " + computeVersion()); return 0; } if (head.equals("-http")) { if (mode != null) { printUsage("-http clashes with previously defined mode " + mode); return -1; } mode = Mode.HTTP; args = args.subList(1, args.size()); continue; } if (head.equals("-ssh")) { if (mode != null) { printUsage("-ssh clashes with previously defined mode " + mode); return -1; } mode = Mode.SSH; args = args.subList(1, args.size()); continue; } if (head.equals("-webSocket")) { if (mode != null) { printUsage("-webSocket clashes with previously defined mode " + mode); return -1; } mode = Mode.WEB_SOCKET; args = args.subList(1, args.size()); continue; } if (head.equals("-remoting")) { printUsage("-remoting mode is no longer supported"); return -1; } if (head.equals("-s") && args.size() >= 2) { url = args.get(1); args = args.subList(2, args.size()); continue; } if (head.equals("-noCertificateCheck")) { LOGGER.info("Skipping HTTPS certificate checks altogether. Note that this is not secure at all."); noCertificateCheck = true; args = args.subList(1, args.size()); continue; } if (head.equals("-noKeyAuth")) { noKeyAuth = true; args = args.subList(1, args.size()); continue; } if (head.equals("-i") && args.size() >= 2) { File f = getFileFromArguments(args); if (!f.exists()) { printUsage(Messages.CLI_NoSuchFileExists(f)); return -1; } provider.readFrom(f); args = args.subList(2, args.size()); continue; } if (head.equals("-strictHostKey")) { strictHostKey = true; args = args.subList(1, args.size()); continue; } if (head.equals("-user") && args.size() >= 2) { user = args.get(1); args = args.subList(2, args.size()); continue; } if (head.equals("-auth") && args.size() >= 2) { auth = args.get(1); args = args.subList(2, args.size()); continue; } if (head.equals("-bearer") && args.size() >= 2) { bearer = args.get(1); args = args.subList(2, args.size()); continue; } if (head.equals("-logger") && args.size() >= 2) { Level level = parse(args.get(1)); for (Handler h : Logger.getLogger("").getHandlers()) { h.setLevel(level); } for (Logger logger : new Logger[] {LOGGER, FullDuplexHttpStream.LOGGER, PlainCLIProtocol.LOGGER, Logger.getLogger("org.apache.sshd")}) { // perhaps also Channel logger.setLevel(level); } args = args.subList(2, args.size()); continue; } break; } if (url == null) { printUsage(Messages.CLI_NoURL()); return -1; } if (auth != null && bearer != null) { LOGGER.warning("-auth and -bearer are mutually exclusive"); } if (auth == null && bearer == null) { // -auth option not set if ((userIdEnv != null && !userIdEnv.isBlank()) && (tokenEnv != null && !tokenEnv.isBlank())) { auth = userIdEnv.concat(":").concat(tokenEnv); } else if ((userIdEnv != null && !userIdEnv.isBlank()) || (tokenEnv != null && !tokenEnv.isBlank())) { printUsage(Messages.CLI_BadAuth()); return -1; } // Otherwise, none credentials were set } if (!url.endsWith("/")) { url += '/'; } if (args.isEmpty()) args = List.of("help"); // default to help if (mode == null) { mode = Mode.WEB_SOCKET; } LOGGER.log(FINE, "using connection mode {0}", mode); if (user != null && auth != null) { LOGGER.warning("-user and -auth are mutually exclusive"); } if (mode == Mode.SSH) { if (user == null) { // TODO SshCliAuthenticator already autodetects the user based on public key; why cannot AsynchronousCommand.getCurrentUser do the same? LOGGER.warning("-user required when using -ssh"); return -1; } if (!noKeyAuth && !provider.hasKeys()) { provider.readFromDefaultLocations(); } return SSHCLI.sshConnection(url, user, args, provider, strictHostKey); } if (strictHostKey) { LOGGER.warning("-strictHostKey meaningful only with -ssh"); } if (noKeyAuth) { LOGGER.warning("-noKeyAuth meaningful only with -ssh"); } if (user != null) { LOGGER.warning("Warning: -user ignored unless using -ssh"); } CLIConnectionFactory factory = new CLIConnectionFactory().noCertificateCheck(noCertificateCheck); String userInfo = new URL(url).getUserInfo(); if (userInfo != null) { factory = factory.basicAuth(userInfo); } else if (auth != null) { factory = factory.basicAuth(auth.startsWith("@") ? readAuthFromFile(auth).trim() : auth); } else if (bearer != null) { factory = factory.bearerAuth(bearer.startsWith("@") ? readAuthFromFile(bearer).trim() : bearer); } if (mode == Mode.HTTP) { return plainHttpConnection(url, args, factory); } if (mode == Mode.WEB_SOCKET) { return webSocketConnection(url, args, factory); } throw new AssertionError(); } @SuppressFBWarnings(value = {"PATH_TRAVERSAL_IN", "URLCONNECTION_SSRF_FD"}, justification = "User provided values for running the program.") private static String readAuthFromFile(String auth) throws IOException { Path path; try { path = Paths.get(auth.substring(1)); } catch (InvalidPathException e) { throw new IOException(e); } return Files.readString(path, Charset.defaultCharset()); } @SuppressFBWarnings(value = {"PATH_TRAVERSAL_IN", "URLCONNECTION_SSRF_FD"}, justification = "User provided values for running the program.") private static File getFileFromArguments(List<String> args) { return new File(args.get(1)); } private static int webSocketConnection(String url, List<String> args, CLIConnectionFactory factory) throws Exception { LOGGER.fine(() -> "Trying to connect to " + url + " via plain protocol over WebSocket"); class CLIEndpoint extends Endpoint { @Override public void onOpen(Session session, EndpointConfig config) {} } class Authenticator extends ClientEndpointConfig.Configurator { @Override public void beforeRequest(Map<String, List<String>> headers) { if (factory.authorization != null) { headers.put("Authorization", List.of(factory.authorization)); } } } ClientManager client = ClientManager.createClient(JdkClientContainer.class.getName()); // ~ ContainerProvider.getWebSocketContainer() client.getProperties().put(ClientProperties.REDIRECT_ENABLED, true); // https://tyrus-project.github.io/documentation/1.13.1/index/tyrus-proprietary-config.html#d0e1775 if (factory.noCertificateCheck) { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] {new NoCheckTrustManager()}, new SecureRandom()); SslEngineConfigurator sslEngineConfigurator = new SslEngineConfigurator(sslContext); sslEngineConfigurator.setHostnameVerifier((s, sslSession) -> true); client.getProperties().put(ClientProperties.SSL_ENGINE_CONFIGURATOR, sslEngineConfigurator); } Session session = client.connectToServer(new CLIEndpoint(), ClientEndpointConfig.Builder.create().configurator(new Authenticator()).build(), URI.create(url.replaceFirst("^http", "ws") + "cli/ws")); PlainCLIProtocol.Output out = new PlainCLIProtocol.Output() { @Override public void send(byte[] data) throws IOException { session.getBasicRemote().sendBinary(ByteBuffer.wrap(data)); } @Override public void close() throws IOException { session.close(); } }; try (ClientSideImpl connection = new ClientSideImpl(out)) { session.addMessageHandler(InputStream.class, is -> { try { connection.handle(new DataInputStream(is)); } catch (IOException x) { LOGGER.log(Level.WARNING, null, x); } }); connection.start(args); return connection.exit(); } } private static int plainHttpConnection(String url, List<String> args, CLIConnectionFactory factory) throws GeneralSecurityException, IOException, InterruptedException { LOGGER.log(FINE, "Trying to connect to {0} via plain protocol over HTTP", url); if (factory.noCertificateCheck) { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] {new NoCheckTrustManager()}, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier((s, sslSession) -> true); } FullDuplexHttpStream streams = new FullDuplexHttpStream(new URL(url), "cli?remoting=false", factory.authorization); try (ClientSideImpl connection = new ClientSideImpl(new PlainCLIProtocol.FramedOutput(streams.getOutputStream()))) { connection.start(args); InputStream is = streams.getInputStream(); if (is.read() != 0) { // cf. FullDuplexHttpService throw new IOException("expected to see initial zero byte; perhaps you are connecting to an old server which does not support -http?"); } new PlainCLIProtocol.FramedReader(connection, is).start(); new Thread("ping") { // JENKINS-46659 @Override public void run() { try { Thread.sleep(PING_INTERVAL); while (!connection.complete) { LOGGER.fine("sending ping"); connection.sendEncoding(Charset.defaultCharset().name()); // no-op at this point Thread.sleep(PING_INTERVAL); } } catch (IOException | InterruptedException x) { LOGGER.log(Level.WARNING, null, x); } } }.start(); return connection.exit(); } } private static final class ClientSideImpl extends PlainCLIProtocol.ClientSide { volatile boolean complete; private int exit = -1; ClientSideImpl(PlainCLIProtocol.Output out) { super(out); } void start(List<String> args) throws IOException { for (String arg : args) { sendArg(arg); } sendEncoding(Charset.defaultCharset().name()); sendLocale(Locale.getDefault().toString()); sendStart(); new Thread("input reader") { @Override public void run() { try { final OutputStream stdin = streamStdin(); byte[] buf = new byte[60_000]; // less than 64Kb frame size for WS while (!complete) { int len = System.in.read(buf); if (len == -1) { break; } else { stdin.write(buf, 0, len); } } sendEndStdin(); } catch (IOException x) { LOGGER.log(Level.WARNING, null, x); } } }.start(); } @Override protected synchronized void onExit(int code) { this.exit = code; finished(); } @Override protected void onStdout(byte[] chunk) throws IOException { System.out.write(chunk); } @Override protected void onStderr(byte[] chunk) throws IOException { System.err.write(chunk); } @Override protected void handleClose() { finished(); } private synchronized void finished() { complete = true; notifyAll(); } synchronized int exit() throws InterruptedException { while (!complete) { wait(); } return exit; } } private static String computeVersion() { Properties props = new Properties(); try (InputStream is = CLI.class.getResourceAsStream("/jenkins/cli/jenkins-cli-version.properties")) { if (is != null) { props.load(is); } } catch (IOException e) { e.printStackTrace(); // if the version properties is missing, that's OK. } return props.getProperty("version", "?"); } /** * Loads RSA/DSA private key in a PEM format into {@link KeyPair}. */ public static KeyPair loadKey(File f, String passwd) throws IOException, GeneralSecurityException { return PrivateKeyProvider.loadKey(f, passwd); } public static KeyPair loadKey(File f) throws IOException, GeneralSecurityException { return loadKey(f, null); } /** * Loads RSA/DSA private key in a PEM format into {@link KeyPair}. */ public static KeyPair loadKey(String pemString, String passwd) throws IOException, GeneralSecurityException { return PrivateKeyProvider.loadKey(pemString, passwd); } public static KeyPair loadKey(String pemString) throws IOException, GeneralSecurityException { return loadKey(pemString, null); } /** For access from {@code HelpCommand}. */ static String usage() { return Messages.CLI_Usage(); } private static void printUsage(String msg) { if (msg != null) System.out.println(msg); System.err.println(usage()); } static final Logger LOGGER = Logger.getLogger(CLI.class.getName()); private static final int PING_INTERVAL = Integer.getInteger(CLI.class.getName() + ".pingInterval", 3_000); // JENKINS-59267 }
Dohbedoh/jenkins
cli/src/main/java/hudson/cli/CLI.java
5,540
// default to help
line_comment
nl
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc. * * 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 hudson.cli; import static java.util.logging.Level.FINE; import static java.util.logging.Level.parse; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.cli.client.Messages; import jakarta.websocket.ClientEndpointConfig; import jakarta.websocket.Endpoint; import jakarta.websocket.EndpointConfig; import jakarta.websocket.Session; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.SecureRandom; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.glassfish.tyrus.client.ClientManager; import org.glassfish.tyrus.client.ClientProperties; import org.glassfish.tyrus.client.SslEngineConfigurator; import org.glassfish.tyrus.container.jdk.client.JdkClientContainer; /** * CLI entry point to Jenkins. */ @SuppressFBWarnings(value = "CRLF_INJECTION_LOGS", justification = "We don't care about this behavior") public class CLI { private CLI() {} /** * Make sure the connection is open against Jenkins server. * * @param c The open connection. * @throws IOException in case of communication problem. * @throws NotTalkingToJenkinsException when connection is not made to Jenkins service. */ /*package*/ static void verifyJenkinsConnection(URLConnection c) throws IOException { if (c.getHeaderField("X-Hudson") == null && c.getHeaderField("X-Jenkins") == null) throw new NotTalkingToJenkinsException(c); } /*package*/ static final class NotTalkingToJenkinsException extends IOException { NotTalkingToJenkinsException(String s) { super(s); } NotTalkingToJenkinsException(URLConnection c) { super("There's no Jenkins running at " + c.getURL().toString()); } } public static void main(final String[] _args) throws Exception { try { System.exit(_main(_args)); } catch (NotTalkingToJenkinsException ex) { System.err.println(ex.getMessage()); System.exit(3); } catch (Throwable t) { // if the CLI main thread die, make sure to kill the JVM. t.printStackTrace(); System.exit(-1); } } private enum Mode { HTTP, SSH, WEB_SOCKET } public static int _main(String[] _args) throws Exception { List<String> args = Arrays.asList(_args); PrivateKeyProvider provider = new PrivateKeyProvider(); String url = System.getenv("JENKINS_URL"); if (url == null) url = System.getenv("HUDSON_URL"); boolean noKeyAuth = false; Mode mode = null; String user = null; String auth = null; String bearer = null; String userIdEnv = System.getenv("JENKINS_USER_ID"); String tokenEnv = System.getenv("JENKINS_API_TOKEN"); boolean strictHostKey = false; boolean noCertificateCheck = false; while (!args.isEmpty()) { String head = args.get(0); if (head.equals("-version")) { System.out.println("Version: " + computeVersion()); return 0; } if (head.equals("-http")) { if (mode != null) { printUsage("-http clashes with previously defined mode " + mode); return -1; } mode = Mode.HTTP; args = args.subList(1, args.size()); continue; } if (head.equals("-ssh")) { if (mode != null) { printUsage("-ssh clashes with previously defined mode " + mode); return -1; } mode = Mode.SSH; args = args.subList(1, args.size()); continue; } if (head.equals("-webSocket")) { if (mode != null) { printUsage("-webSocket clashes with previously defined mode " + mode); return -1; } mode = Mode.WEB_SOCKET; args = args.subList(1, args.size()); continue; } if (head.equals("-remoting")) { printUsage("-remoting mode is no longer supported"); return -1; } if (head.equals("-s") && args.size() >= 2) { url = args.get(1); args = args.subList(2, args.size()); continue; } if (head.equals("-noCertificateCheck")) { LOGGER.info("Skipping HTTPS certificate checks altogether. Note that this is not secure at all."); noCertificateCheck = true; args = args.subList(1, args.size()); continue; } if (head.equals("-noKeyAuth")) { noKeyAuth = true; args = args.subList(1, args.size()); continue; } if (head.equals("-i") && args.size() >= 2) { File f = getFileFromArguments(args); if (!f.exists()) { printUsage(Messages.CLI_NoSuchFileExists(f)); return -1; } provider.readFrom(f); args = args.subList(2, args.size()); continue; } if (head.equals("-strictHostKey")) { strictHostKey = true; args = args.subList(1, args.size()); continue; } if (head.equals("-user") && args.size() >= 2) { user = args.get(1); args = args.subList(2, args.size()); continue; } if (head.equals("-auth") && args.size() >= 2) { auth = args.get(1); args = args.subList(2, args.size()); continue; } if (head.equals("-bearer") && args.size() >= 2) { bearer = args.get(1); args = args.subList(2, args.size()); continue; } if (head.equals("-logger") && args.size() >= 2) { Level level = parse(args.get(1)); for (Handler h : Logger.getLogger("").getHandlers()) { h.setLevel(level); } for (Logger logger : new Logger[] {LOGGER, FullDuplexHttpStream.LOGGER, PlainCLIProtocol.LOGGER, Logger.getLogger("org.apache.sshd")}) { // perhaps also Channel logger.setLevel(level); } args = args.subList(2, args.size()); continue; } break; } if (url == null) { printUsage(Messages.CLI_NoURL()); return -1; } if (auth != null && bearer != null) { LOGGER.warning("-auth and -bearer are mutually exclusive"); } if (auth == null && bearer == null) { // -auth option not set if ((userIdEnv != null && !userIdEnv.isBlank()) && (tokenEnv != null && !tokenEnv.isBlank())) { auth = userIdEnv.concat(":").concat(tokenEnv); } else if ((userIdEnv != null && !userIdEnv.isBlank()) || (tokenEnv != null && !tokenEnv.isBlank())) { printUsage(Messages.CLI_BadAuth()); return -1; } // Otherwise, none credentials were set } if (!url.endsWith("/")) { url += '/'; } if (args.isEmpty()) args = List.of("help"); // default to<SUF> if (mode == null) { mode = Mode.WEB_SOCKET; } LOGGER.log(FINE, "using connection mode {0}", mode); if (user != null && auth != null) { LOGGER.warning("-user and -auth are mutually exclusive"); } if (mode == Mode.SSH) { if (user == null) { // TODO SshCliAuthenticator already autodetects the user based on public key; why cannot AsynchronousCommand.getCurrentUser do the same? LOGGER.warning("-user required when using -ssh"); return -1; } if (!noKeyAuth && !provider.hasKeys()) { provider.readFromDefaultLocations(); } return SSHCLI.sshConnection(url, user, args, provider, strictHostKey); } if (strictHostKey) { LOGGER.warning("-strictHostKey meaningful only with -ssh"); } if (noKeyAuth) { LOGGER.warning("-noKeyAuth meaningful only with -ssh"); } if (user != null) { LOGGER.warning("Warning: -user ignored unless using -ssh"); } CLIConnectionFactory factory = new CLIConnectionFactory().noCertificateCheck(noCertificateCheck); String userInfo = new URL(url).getUserInfo(); if (userInfo != null) { factory = factory.basicAuth(userInfo); } else if (auth != null) { factory = factory.basicAuth(auth.startsWith("@") ? readAuthFromFile(auth).trim() : auth); } else if (bearer != null) { factory = factory.bearerAuth(bearer.startsWith("@") ? readAuthFromFile(bearer).trim() : bearer); } if (mode == Mode.HTTP) { return plainHttpConnection(url, args, factory); } if (mode == Mode.WEB_SOCKET) { return webSocketConnection(url, args, factory); } throw new AssertionError(); } @SuppressFBWarnings(value = {"PATH_TRAVERSAL_IN", "URLCONNECTION_SSRF_FD"}, justification = "User provided values for running the program.") private static String readAuthFromFile(String auth) throws IOException { Path path; try { path = Paths.get(auth.substring(1)); } catch (InvalidPathException e) { throw new IOException(e); } return Files.readString(path, Charset.defaultCharset()); } @SuppressFBWarnings(value = {"PATH_TRAVERSAL_IN", "URLCONNECTION_SSRF_FD"}, justification = "User provided values for running the program.") private static File getFileFromArguments(List<String> args) { return new File(args.get(1)); } private static int webSocketConnection(String url, List<String> args, CLIConnectionFactory factory) throws Exception { LOGGER.fine(() -> "Trying to connect to " + url + " via plain protocol over WebSocket"); class CLIEndpoint extends Endpoint { @Override public void onOpen(Session session, EndpointConfig config) {} } class Authenticator extends ClientEndpointConfig.Configurator { @Override public void beforeRequest(Map<String, List<String>> headers) { if (factory.authorization != null) { headers.put("Authorization", List.of(factory.authorization)); } } } ClientManager client = ClientManager.createClient(JdkClientContainer.class.getName()); // ~ ContainerProvider.getWebSocketContainer() client.getProperties().put(ClientProperties.REDIRECT_ENABLED, true); // https://tyrus-project.github.io/documentation/1.13.1/index/tyrus-proprietary-config.html#d0e1775 if (factory.noCertificateCheck) { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] {new NoCheckTrustManager()}, new SecureRandom()); SslEngineConfigurator sslEngineConfigurator = new SslEngineConfigurator(sslContext); sslEngineConfigurator.setHostnameVerifier((s, sslSession) -> true); client.getProperties().put(ClientProperties.SSL_ENGINE_CONFIGURATOR, sslEngineConfigurator); } Session session = client.connectToServer(new CLIEndpoint(), ClientEndpointConfig.Builder.create().configurator(new Authenticator()).build(), URI.create(url.replaceFirst("^http", "ws") + "cli/ws")); PlainCLIProtocol.Output out = new PlainCLIProtocol.Output() { @Override public void send(byte[] data) throws IOException { session.getBasicRemote().sendBinary(ByteBuffer.wrap(data)); } @Override public void close() throws IOException { session.close(); } }; try (ClientSideImpl connection = new ClientSideImpl(out)) { session.addMessageHandler(InputStream.class, is -> { try { connection.handle(new DataInputStream(is)); } catch (IOException x) { LOGGER.log(Level.WARNING, null, x); } }); connection.start(args); return connection.exit(); } } private static int plainHttpConnection(String url, List<String> args, CLIConnectionFactory factory) throws GeneralSecurityException, IOException, InterruptedException { LOGGER.log(FINE, "Trying to connect to {0} via plain protocol over HTTP", url); if (factory.noCertificateCheck) { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] {new NoCheckTrustManager()}, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier((s, sslSession) -> true); } FullDuplexHttpStream streams = new FullDuplexHttpStream(new URL(url), "cli?remoting=false", factory.authorization); try (ClientSideImpl connection = new ClientSideImpl(new PlainCLIProtocol.FramedOutput(streams.getOutputStream()))) { connection.start(args); InputStream is = streams.getInputStream(); if (is.read() != 0) { // cf. FullDuplexHttpService throw new IOException("expected to see initial zero byte; perhaps you are connecting to an old server which does not support -http?"); } new PlainCLIProtocol.FramedReader(connection, is).start(); new Thread("ping") { // JENKINS-46659 @Override public void run() { try { Thread.sleep(PING_INTERVAL); while (!connection.complete) { LOGGER.fine("sending ping"); connection.sendEncoding(Charset.defaultCharset().name()); // no-op at this point Thread.sleep(PING_INTERVAL); } } catch (IOException | InterruptedException x) { LOGGER.log(Level.WARNING, null, x); } } }.start(); return connection.exit(); } } private static final class ClientSideImpl extends PlainCLIProtocol.ClientSide { volatile boolean complete; private int exit = -1; ClientSideImpl(PlainCLIProtocol.Output out) { super(out); } void start(List<String> args) throws IOException { for (String arg : args) { sendArg(arg); } sendEncoding(Charset.defaultCharset().name()); sendLocale(Locale.getDefault().toString()); sendStart(); new Thread("input reader") { @Override public void run() { try { final OutputStream stdin = streamStdin(); byte[] buf = new byte[60_000]; // less than 64Kb frame size for WS while (!complete) { int len = System.in.read(buf); if (len == -1) { break; } else { stdin.write(buf, 0, len); } } sendEndStdin(); } catch (IOException x) { LOGGER.log(Level.WARNING, null, x); } } }.start(); } @Override protected synchronized void onExit(int code) { this.exit = code; finished(); } @Override protected void onStdout(byte[] chunk) throws IOException { System.out.write(chunk); } @Override protected void onStderr(byte[] chunk) throws IOException { System.err.write(chunk); } @Override protected void handleClose() { finished(); } private synchronized void finished() { complete = true; notifyAll(); } synchronized int exit() throws InterruptedException { while (!complete) { wait(); } return exit; } } private static String computeVersion() { Properties props = new Properties(); try (InputStream is = CLI.class.getResourceAsStream("/jenkins/cli/jenkins-cli-version.properties")) { if (is != null) { props.load(is); } } catch (IOException e) { e.printStackTrace(); // if the version properties is missing, that's OK. } return props.getProperty("version", "?"); } /** * Loads RSA/DSA private key in a PEM format into {@link KeyPair}. */ public static KeyPair loadKey(File f, String passwd) throws IOException, GeneralSecurityException { return PrivateKeyProvider.loadKey(f, passwd); } public static KeyPair loadKey(File f) throws IOException, GeneralSecurityException { return loadKey(f, null); } /** * Loads RSA/DSA private key in a PEM format into {@link KeyPair}. */ public static KeyPair loadKey(String pemString, String passwd) throws IOException, GeneralSecurityException { return PrivateKeyProvider.loadKey(pemString, passwd); } public static KeyPair loadKey(String pemString) throws IOException, GeneralSecurityException { return loadKey(pemString, null); } /** For access from {@code HelpCommand}. */ static String usage() { return Messages.CLI_Usage(); } private static void printUsage(String msg) { if (msg != null) System.out.println(msg); System.err.println(usage()); } static final Logger LOGGER = Logger.getLogger(CLI.class.getName()); private static final int PING_INTERVAL = Integer.getInteger(CLI.class.getName() + ".pingInterval", 3_000); // JENKINS-59267 }
183691_10
package kg.liantis.horeca.service; import kg.liantis.horeca.domain.Horeca; import kg.liantis.horeca.repository.HorecaRepository; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import java.util.*; import java.util.concurrent.ExecutionException; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; public class HorecaServiceImplTest { HorecaServiceImpl horecaService; @Mock HorecaRepository horecaRepository; @Rule public ExpectedException thrown = ExpectedException.none(); private List<Horeca> horecaList; private Horeca h1; private Horeca h2; private Horeca h3; private Horeca h4; private Pageable pageable; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); this.horecaService = new HorecaServiceImpl(this.horecaRepository); this.horecaList = new ArrayList<>(); this.h1 = new Horeca(); this.h1.setId(1L); this.h1.setNaam("Hotel Liantis"); this.h1.setBranche("Branche1"); this.h1.setWinkelgebied("wgebied2"); this.h1.setRating(0); this.h2 = new Horeca(); this.h2.setId(2L); this.h2.setNaam("Café Liantis"); this.h2.setBranche("Branche2"); this.h2.setWinkelgebied("wgebied1"); this.h2.setRating(0); this.h3 = new Horeca(); this.h3.setId(3L); this.h3.setNaam("Restaurant Liantis"); this.h3.setBranche("Branche2"); this.h3.setWinkelgebied("wgebied1"); this.h3.setRating(2); this.h4 = new Horeca(); this.h4.setId(4L); this.h4.setNaam("De Gouden Stier"); this.h4.setBranche("Café"); this.h4.setWinkelgebied("Sint-Kruis"); this.horecaList.add(h1); this.horecaList.add(h2); this.horecaList.add(h3); this.horecaList.add(h4); this.pageable = PageRequest.of(1, 3); } @Test public void findAll_OK() throws ExecutionException, InterruptedException { when(this.horecaService.findAll()).thenReturn(horecaList); List<Horeca> testList = this.horecaService.findAll(); assertEquals(testList.size(), 4); assertEquals(Long.valueOf(1), testList.get(0).getId()); assertEquals("Hotel Liantis", testList.get(0).getNaam()); assertEquals("Branche1", testList.get(0).getBranche()); assertEquals("wgebied2", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void saveRating_OK() throws Exception { //h3 starts with a rating of 2 when(this.horecaRepository.findById(anyLong())).thenReturn(Optional.of(h3)); when(this.horecaService.saveRating(anyLong(), 4)).thenReturn(h3); Horeca savedHoreca = this.horecaService.saveRating(h3.getId(), 4); assertEquals(4, savedHoreca.getRating()); verify(this.horecaRepository, times(1)).save(h3); } @Test public void saveRating_LargerThen5_NOK() throws Exception { thrown.expect(Exception.class); thrown.expectMessage(is("De rating moet zich tussen 0 en 5 bevinden")); when(this.horecaRepository.findById(anyLong())).thenReturn(Optional.of(h3)); when(this.horecaService.saveRating(anyLong(), 6)).thenReturn(h3); Horeca savedHoreca = this.horecaService.saveRating(h3.getId(), 6); } @Test public void saveRating_Lessthen0_NOK() throws Exception { thrown.expect(Exception.class); thrown.expectMessage(is("De rating moet zich tussen 0 en 5 bevinden")); when(this.horecaRepository.findById(anyLong())).thenReturn(Optional.of(h3)); when(this.horecaService.saveRating(anyLong(), -1)).thenReturn(h3); Horeca savedHoreca = this.horecaService.saveRating(h3.getId(), -1); } @Test public void save_OK() throws Exception { Horeca newHoreca = new Horeca(); newHoreca.setId(4L); newHoreca.setNaam("De reisduif"); when(this.horecaService.save(any())).thenReturn(newHoreca); Horeca savedHoreca = this.horecaService.save(newHoreca); assertEquals(Long.valueOf(4L), savedHoreca.getId()); assertEquals("De reisduif", newHoreca.getNaam()); verify(this.horecaRepository, times(1)).save(any()); } /**TODO: BUG : when(this.horecaService.findAllByCriteria(anyString(), anyString(), anyString())).thenReturn(this.horecaList); * org.mockito.exceptions.misusing.InvalidUseOfMatchersException: * Invalid use of argument matchers! * 0 matchers expected, 3 recorded: * -> at kg.liantis.horeca.service.HorecaServiceImplTest.findAllByCriteria(HorecaServiceImplTest.java:94) * -> at kg.liantis.horeca.service.HorecaServiceImplTest.findAllByCriteria(HorecaServiceImplTest.java:94) * -> at kg.liantis.horeca.service.HorecaServiceImplTest.findAllByCriteria(HorecaServiceImplTest.java:94) * * This exception may occur if matchers are combined with raw values: * //incorrect: * someMethod(anyObject(), "raw String"); * When using matchers, all arguments have to be provided by matchers. * For example: * //correct: * someMethod(anyObject(), eq("String by matcher")); */ @Test public void findAllByNaam_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("hotel", "", ""); assertEquals(1, testList.size()); assertEquals(Long.valueOf(1) ,testList.get(0).getId()); assertEquals("Hotel Liantis", testList.get(0).getNaam()); assertEquals("Branche1", testList.get(0).getBranche()); assertEquals("wgebied2", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void findAllByBranche_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("", "Branche2", ""); assertEquals(2, testList.size()); assertEquals(Long.valueOf(2) ,testList.get(0).getId()); assertEquals("Café Liantis", testList.get(0).getNaam()); assertEquals("Branche2", testList.get(0).getBranche()); assertEquals("wgebied1", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void findAllByNaamAndBranche_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("Hotel", "Branche1", ""); assertEquals(1, testList.size()); assertEquals(Long.valueOf(1) ,testList.get(0).getId()); assertEquals("Hotel Liantis", testList.get(0).getNaam()); assertEquals("Branche1", testList.get(0).getBranche()); assertEquals("wgebied2", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void findAllByNaamAndBrancheAndWgebied_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("Restaurant Liantis", "Branche2", "wgebied1"); assertEquals(1, testList.size()); assertEquals(Long.valueOf(3) ,testList.get(0).getId()); assertEquals("Restaurant Liantis", testList.get(0).getNaam()); assertEquals("Branche2", testList.get(0).getBranche()); assertEquals("wgebied1", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void findAllByBrancheAndWGebied_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("", "Branche2", "wgebied1"); assertEquals(2, testList.size()); assertEquals(Long.valueOf(2) ,testList.get(0).getId()); assertEquals("Café Liantis", testList.get(0).getNaam()); assertEquals("Branche2", testList.get(0).getBranche()); assertEquals("wgebied1", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void findAllByNaamAndWGebied_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("Liantis", "", "wgebied1"); assertEquals(2, testList.size()); assertEquals(Long.valueOf(2) ,testList.get(0).getId()); assertEquals("Café Liantis", testList.get(0).getNaam()); assertEquals("Branche2", testList.get(0).getBranche()); assertEquals("wgebied1", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void findAllBy_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("", "", ""); assertEquals(4, testList.size()); assertEquals(Long.valueOf(1) ,testList.get(0).getId()); assertEquals("Hotel Liantis", testList.get(0).getNaam()); assertEquals("Branche1", testList.get(0).getBranche()); assertEquals("wgebied2", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void getBranches_OK() throws ExecutionException, InterruptedException { when(this.horecaService.findAll()).thenReturn(this.horecaList); Set<String> testBranches = this.horecaService.getBranches(); assertEquals(3, testBranches.size()); assertEquals(true, testBranches.contains("Branche2")); verify(this.horecaRepository, times(1)).findAll(); } @Test public void getWinkelgebieden_OK() throws ExecutionException, InterruptedException { when(this.horecaService.findAll()).thenReturn(this.horecaList); Set<String> testWinkelgebieden = this.horecaService.getWinkelgebieden(); assertEquals(3, testWinkelgebieden.size()); assertEquals(true, testWinkelgebieden.contains("wgebied1")); verify(this.horecaRepository, times(1)).findAll(); } @Test public void getHorecaPage_AllEmpty_OK() { List<Horeca> testList = new ArrayList<>(); for (int i = 1; i <= 9; i++) { Horeca h = new Horeca(); h.setId(Long.valueOf(i)); testList.add(h); } Page<Horeca> horecaPage = new PageImpl<>(testList, pageable, 3); when(this.horecaService.getHorecaPage(this.pageable, "", "", "")).thenReturn(horecaPage); Page<Horeca> testPage = this.horecaService.getHorecaPage(this.pageable, "", "", ""); assertEquals(12, testPage.getTotalElements()); //We starten op pagina 1 assertEquals(3, testPage.getSize()); // paginagrootte assertEquals(4, testPage.getTotalPages()); // 3 pagina's verwacht. assertEquals(Long.valueOf(3), testPage.getContent().get(2).getId()); //3de horecazaak assertEquals(1, testPage.getNumber()); // pagina 1 //Repository alleen zoeken op naam wordt uitgevoerd verify(this.horecaRepository, times(1)).findByNaamContainingAllIgnoreCase(this.pageable, ""); verifyNoMoreInteractions(this.horecaRepository); } @Test public void getHorecaPage_NaamAndBranche_OK() { List<Horeca> testList = new ArrayList<>(); for (int i = 1; i <= 10; i++) { Horeca h = new Horeca(); h.setId(Long.valueOf(i)); testList.add(h); } Page<Horeca> horecaPage = new PageImpl<>(testList, pageable, 3); when(this.horecaService.getHorecaPage(this.pageable, "Hotel", "Branche2", "")).thenReturn(horecaPage); Page<Horeca> testPage = this.horecaService.getHorecaPage(this.pageable, "Hotel", "Branche2", ""); assertEquals(13, testPage.getTotalElements()); //We starten op pagina 1 (pagina 0: 3 items) assertEquals(3, testPage.getSize()); // paginagrootte assertEquals(5, testPage.getTotalPages()); // We starten op pagina 1 (pagina 0: 3 items) assertEquals(Long.valueOf(3), testPage.getContent().get(2).getId()); //3de horecazaak assertEquals(1, testPage.getNumber()); // pagina 1 //Repository zoeken op naam en branche wordt uitgevoerd verify(this.horecaRepository, times(1)).findByNaamContainingAndBrancheAllIgnoreCase(this.pageable, "Hotel", "Branche2"); verifyNoMoreInteractions(this.horecaRepository); } @Test public void getHorecaPage_NaamAndWinkelgebied_OK() { List<Horeca> testList = new ArrayList<>(); for (int i = 1; i <= 10; i++) { Horeca h = new Horeca(); h.setId(Long.valueOf(i)); testList.add(h); } Page<Horeca> horecaPage = new PageImpl<>(testList, pageable, 3); when(this.horecaService.getHorecaPage(this.pageable, "Hotel", "", "Wgebied1")).thenReturn(horecaPage); Page<Horeca> testPage = this.horecaService.getHorecaPage(this.pageable, "Hotel", "", "Wgebied1"); assertEquals(13, testPage.getTotalElements()); //We starten op pagina 1 (pagina 0: 3 items) assertEquals(3, testPage.getSize()); // paginagrootte assertEquals(5, testPage.getTotalPages()); // We starten op pagina 1 (pagina 0: 3 items) assertEquals(Long.valueOf(3), testPage.getContent().get(2).getId()); //3de horecazaak assertEquals(1, testPage.getNumber()); // pagina 1 //Repository zoeken op naam en branche wordt uitgevoerd verify(this.horecaRepository, times(1)).findByNaamContainingAndWinkelgebiedAllIgnoreCase(this.pageable, "Hotel", "Wgebied1"); verifyNoMoreInteractions(this.horecaRepository); } @Test public void getHorecaPage_NaamAndBrancheAndWinkelgebied_OK() { List<Horeca> testList = new ArrayList<>(); for (int i = 1; i <= 15; i++) { Horeca h = new Horeca(); h.setId(Long.valueOf(i)); testList.add(h); } Page<Horeca> horecaPage = new PageImpl<>(testList, pageable, 3); when(this.horecaService.getHorecaPage(this.pageable, "Hotel", "Branche2", "Wgebied1")).thenReturn(horecaPage); Page<Horeca> testPage = this.horecaService.getHorecaPage(this.pageable, "Hotel", "Branche2", "Wgebied1"); assertEquals(18, testPage.getTotalElements()); //We starten op pagina 1 (pagina 0: 3 items) assertEquals(3, testPage.getSize()); // paginagrootte assertEquals(6, testPage.getTotalPages()); // We starten op pagina 1 (pagina 0: 3 items) assertEquals(Long.valueOf(3), testPage.getContent().get(2).getId()); //3de horecazaak assertEquals(1, testPage.getNumber()); // pagina 1 //Repository zoeken op naam, branche en winkelgebied wordt uitgevoerd verify(this.horecaRepository, times(1)) .findByNaamContainingAndBrancheAndWinkelgebiedAllIgnoreCase(this.pageable, "Hotel", "Branche2", "Wgebied1"); verifyNoMoreInteractions(this.horecaRepository); } }
Domgoe/Liantis.horeca
Backend/src/test/java/kg/liantis/horeca/service/HorecaServiceImplTest.java
5,254
//Repository zoeken op naam en branche wordt uitgevoerd
line_comment
nl
package kg.liantis.horeca.service; import kg.liantis.horeca.domain.Horeca; import kg.liantis.horeca.repository.HorecaRepository; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import java.util.*; import java.util.concurrent.ExecutionException; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; public class HorecaServiceImplTest { HorecaServiceImpl horecaService; @Mock HorecaRepository horecaRepository; @Rule public ExpectedException thrown = ExpectedException.none(); private List<Horeca> horecaList; private Horeca h1; private Horeca h2; private Horeca h3; private Horeca h4; private Pageable pageable; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); this.horecaService = new HorecaServiceImpl(this.horecaRepository); this.horecaList = new ArrayList<>(); this.h1 = new Horeca(); this.h1.setId(1L); this.h1.setNaam("Hotel Liantis"); this.h1.setBranche("Branche1"); this.h1.setWinkelgebied("wgebied2"); this.h1.setRating(0); this.h2 = new Horeca(); this.h2.setId(2L); this.h2.setNaam("Café Liantis"); this.h2.setBranche("Branche2"); this.h2.setWinkelgebied("wgebied1"); this.h2.setRating(0); this.h3 = new Horeca(); this.h3.setId(3L); this.h3.setNaam("Restaurant Liantis"); this.h3.setBranche("Branche2"); this.h3.setWinkelgebied("wgebied1"); this.h3.setRating(2); this.h4 = new Horeca(); this.h4.setId(4L); this.h4.setNaam("De Gouden Stier"); this.h4.setBranche("Café"); this.h4.setWinkelgebied("Sint-Kruis"); this.horecaList.add(h1); this.horecaList.add(h2); this.horecaList.add(h3); this.horecaList.add(h4); this.pageable = PageRequest.of(1, 3); } @Test public void findAll_OK() throws ExecutionException, InterruptedException { when(this.horecaService.findAll()).thenReturn(horecaList); List<Horeca> testList = this.horecaService.findAll(); assertEquals(testList.size(), 4); assertEquals(Long.valueOf(1), testList.get(0).getId()); assertEquals("Hotel Liantis", testList.get(0).getNaam()); assertEquals("Branche1", testList.get(0).getBranche()); assertEquals("wgebied2", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void saveRating_OK() throws Exception { //h3 starts with a rating of 2 when(this.horecaRepository.findById(anyLong())).thenReturn(Optional.of(h3)); when(this.horecaService.saveRating(anyLong(), 4)).thenReturn(h3); Horeca savedHoreca = this.horecaService.saveRating(h3.getId(), 4); assertEquals(4, savedHoreca.getRating()); verify(this.horecaRepository, times(1)).save(h3); } @Test public void saveRating_LargerThen5_NOK() throws Exception { thrown.expect(Exception.class); thrown.expectMessage(is("De rating moet zich tussen 0 en 5 bevinden")); when(this.horecaRepository.findById(anyLong())).thenReturn(Optional.of(h3)); when(this.horecaService.saveRating(anyLong(), 6)).thenReturn(h3); Horeca savedHoreca = this.horecaService.saveRating(h3.getId(), 6); } @Test public void saveRating_Lessthen0_NOK() throws Exception { thrown.expect(Exception.class); thrown.expectMessage(is("De rating moet zich tussen 0 en 5 bevinden")); when(this.horecaRepository.findById(anyLong())).thenReturn(Optional.of(h3)); when(this.horecaService.saveRating(anyLong(), -1)).thenReturn(h3); Horeca savedHoreca = this.horecaService.saveRating(h3.getId(), -1); } @Test public void save_OK() throws Exception { Horeca newHoreca = new Horeca(); newHoreca.setId(4L); newHoreca.setNaam("De reisduif"); when(this.horecaService.save(any())).thenReturn(newHoreca); Horeca savedHoreca = this.horecaService.save(newHoreca); assertEquals(Long.valueOf(4L), savedHoreca.getId()); assertEquals("De reisduif", newHoreca.getNaam()); verify(this.horecaRepository, times(1)).save(any()); } /**TODO: BUG : when(this.horecaService.findAllByCriteria(anyString(), anyString(), anyString())).thenReturn(this.horecaList); * org.mockito.exceptions.misusing.InvalidUseOfMatchersException: * Invalid use of argument matchers! * 0 matchers expected, 3 recorded: * -> at kg.liantis.horeca.service.HorecaServiceImplTest.findAllByCriteria(HorecaServiceImplTest.java:94) * -> at kg.liantis.horeca.service.HorecaServiceImplTest.findAllByCriteria(HorecaServiceImplTest.java:94) * -> at kg.liantis.horeca.service.HorecaServiceImplTest.findAllByCriteria(HorecaServiceImplTest.java:94) * * This exception may occur if matchers are combined with raw values: * //incorrect: * someMethod(anyObject(), "raw String"); * When using matchers, all arguments have to be provided by matchers. * For example: * //correct: * someMethod(anyObject(), eq("String by matcher")); */ @Test public void findAllByNaam_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("hotel", "", ""); assertEquals(1, testList.size()); assertEquals(Long.valueOf(1) ,testList.get(0).getId()); assertEquals("Hotel Liantis", testList.get(0).getNaam()); assertEquals("Branche1", testList.get(0).getBranche()); assertEquals("wgebied2", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void findAllByBranche_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("", "Branche2", ""); assertEquals(2, testList.size()); assertEquals(Long.valueOf(2) ,testList.get(0).getId()); assertEquals("Café Liantis", testList.get(0).getNaam()); assertEquals("Branche2", testList.get(0).getBranche()); assertEquals("wgebied1", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void findAllByNaamAndBranche_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("Hotel", "Branche1", ""); assertEquals(1, testList.size()); assertEquals(Long.valueOf(1) ,testList.get(0).getId()); assertEquals("Hotel Liantis", testList.get(0).getNaam()); assertEquals("Branche1", testList.get(0).getBranche()); assertEquals("wgebied2", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void findAllByNaamAndBrancheAndWgebied_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("Restaurant Liantis", "Branche2", "wgebied1"); assertEquals(1, testList.size()); assertEquals(Long.valueOf(3) ,testList.get(0).getId()); assertEquals("Restaurant Liantis", testList.get(0).getNaam()); assertEquals("Branche2", testList.get(0).getBranche()); assertEquals("wgebied1", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void findAllByBrancheAndWGebied_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("", "Branche2", "wgebied1"); assertEquals(2, testList.size()); assertEquals(Long.valueOf(2) ,testList.get(0).getId()); assertEquals("Café Liantis", testList.get(0).getNaam()); assertEquals("Branche2", testList.get(0).getBranche()); assertEquals("wgebied1", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void findAllByNaamAndWGebied_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("Liantis", "", "wgebied1"); assertEquals(2, testList.size()); assertEquals(Long.valueOf(2) ,testList.get(0).getId()); assertEquals("Café Liantis", testList.get(0).getNaam()); assertEquals("Branche2", testList.get(0).getBranche()); assertEquals("wgebied1", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void findAllBy_OK() throws Exception { when(this.horecaService.findAll()).thenReturn(this.horecaList); List<Horeca> testList = this.horecaService.findAllByCriteria("", "", ""); assertEquals(4, testList.size()); assertEquals(Long.valueOf(1) ,testList.get(0).getId()); assertEquals("Hotel Liantis", testList.get(0).getNaam()); assertEquals("Branche1", testList.get(0).getBranche()); assertEquals("wgebied2", testList.get(0).getWinkelgebied()); verify(this.horecaRepository, times(1)).findAll(); } @Test public void getBranches_OK() throws ExecutionException, InterruptedException { when(this.horecaService.findAll()).thenReturn(this.horecaList); Set<String> testBranches = this.horecaService.getBranches(); assertEquals(3, testBranches.size()); assertEquals(true, testBranches.contains("Branche2")); verify(this.horecaRepository, times(1)).findAll(); } @Test public void getWinkelgebieden_OK() throws ExecutionException, InterruptedException { when(this.horecaService.findAll()).thenReturn(this.horecaList); Set<String> testWinkelgebieden = this.horecaService.getWinkelgebieden(); assertEquals(3, testWinkelgebieden.size()); assertEquals(true, testWinkelgebieden.contains("wgebied1")); verify(this.horecaRepository, times(1)).findAll(); } @Test public void getHorecaPage_AllEmpty_OK() { List<Horeca> testList = new ArrayList<>(); for (int i = 1; i <= 9; i++) { Horeca h = new Horeca(); h.setId(Long.valueOf(i)); testList.add(h); } Page<Horeca> horecaPage = new PageImpl<>(testList, pageable, 3); when(this.horecaService.getHorecaPage(this.pageable, "", "", "")).thenReturn(horecaPage); Page<Horeca> testPage = this.horecaService.getHorecaPage(this.pageable, "", "", ""); assertEquals(12, testPage.getTotalElements()); //We starten op pagina 1 assertEquals(3, testPage.getSize()); // paginagrootte assertEquals(4, testPage.getTotalPages()); // 3 pagina's verwacht. assertEquals(Long.valueOf(3), testPage.getContent().get(2).getId()); //3de horecazaak assertEquals(1, testPage.getNumber()); // pagina 1 //Repository alleen zoeken op naam wordt uitgevoerd verify(this.horecaRepository, times(1)).findByNaamContainingAllIgnoreCase(this.pageable, ""); verifyNoMoreInteractions(this.horecaRepository); } @Test public void getHorecaPage_NaamAndBranche_OK() { List<Horeca> testList = new ArrayList<>(); for (int i = 1; i <= 10; i++) { Horeca h = new Horeca(); h.setId(Long.valueOf(i)); testList.add(h); } Page<Horeca> horecaPage = new PageImpl<>(testList, pageable, 3); when(this.horecaService.getHorecaPage(this.pageable, "Hotel", "Branche2", "")).thenReturn(horecaPage); Page<Horeca> testPage = this.horecaService.getHorecaPage(this.pageable, "Hotel", "Branche2", ""); assertEquals(13, testPage.getTotalElements()); //We starten op pagina 1 (pagina 0: 3 items) assertEquals(3, testPage.getSize()); // paginagrootte assertEquals(5, testPage.getTotalPages()); // We starten op pagina 1 (pagina 0: 3 items) assertEquals(Long.valueOf(3), testPage.getContent().get(2).getId()); //3de horecazaak assertEquals(1, testPage.getNumber()); // pagina 1 //Repository zoeken op naam en branche wordt uitgevoerd verify(this.horecaRepository, times(1)).findByNaamContainingAndBrancheAllIgnoreCase(this.pageable, "Hotel", "Branche2"); verifyNoMoreInteractions(this.horecaRepository); } @Test public void getHorecaPage_NaamAndWinkelgebied_OK() { List<Horeca> testList = new ArrayList<>(); for (int i = 1; i <= 10; i++) { Horeca h = new Horeca(); h.setId(Long.valueOf(i)); testList.add(h); } Page<Horeca> horecaPage = new PageImpl<>(testList, pageable, 3); when(this.horecaService.getHorecaPage(this.pageable, "Hotel", "", "Wgebied1")).thenReturn(horecaPage); Page<Horeca> testPage = this.horecaService.getHorecaPage(this.pageable, "Hotel", "", "Wgebied1"); assertEquals(13, testPage.getTotalElements()); //We starten op pagina 1 (pagina 0: 3 items) assertEquals(3, testPage.getSize()); // paginagrootte assertEquals(5, testPage.getTotalPages()); // We starten op pagina 1 (pagina 0: 3 items) assertEquals(Long.valueOf(3), testPage.getContent().get(2).getId()); //3de horecazaak assertEquals(1, testPage.getNumber()); // pagina 1 //Repository zoeken<SUF> verify(this.horecaRepository, times(1)).findByNaamContainingAndWinkelgebiedAllIgnoreCase(this.pageable, "Hotel", "Wgebied1"); verifyNoMoreInteractions(this.horecaRepository); } @Test public void getHorecaPage_NaamAndBrancheAndWinkelgebied_OK() { List<Horeca> testList = new ArrayList<>(); for (int i = 1; i <= 15; i++) { Horeca h = new Horeca(); h.setId(Long.valueOf(i)); testList.add(h); } Page<Horeca> horecaPage = new PageImpl<>(testList, pageable, 3); when(this.horecaService.getHorecaPage(this.pageable, "Hotel", "Branche2", "Wgebied1")).thenReturn(horecaPage); Page<Horeca> testPage = this.horecaService.getHorecaPage(this.pageable, "Hotel", "Branche2", "Wgebied1"); assertEquals(18, testPage.getTotalElements()); //We starten op pagina 1 (pagina 0: 3 items) assertEquals(3, testPage.getSize()); // paginagrootte assertEquals(6, testPage.getTotalPages()); // We starten op pagina 1 (pagina 0: 3 items) assertEquals(Long.valueOf(3), testPage.getContent().get(2).getId()); //3de horecazaak assertEquals(1, testPage.getNumber()); // pagina 1 //Repository zoeken op naam, branche en winkelgebied wordt uitgevoerd verify(this.horecaRepository, times(1)) .findByNaamContainingAndBrancheAndWinkelgebiedAllIgnoreCase(this.pageable, "Hotel", "Branche2", "Wgebied1"); verifyNoMoreInteractions(this.horecaRepository); } }
80436_2
import java.util.Stack; import java.util.StringTokenizer; public class Postfix { private Operator[] operators; private Stack<Operator> stack = new Stack<Operator>(); /* Dieser Wert ist fuer die Num-Klasse gedacht, da diese laut Interface zwei Argumente (double, double) braucht. * Laut Aufgabe muss Num aber ein 0-wertiger Operator sein, weshalb diese beiden Argumente keinen Sinn machen wuerden. * Ueber calc() gibt ein Num seinen eigenen Wert zurueck (wie andere Operatoren), aber mit useless soll markiert werden, dass * das Argument eigentlich nutzlos ist und nur der Konsistenz aller Operatoren dient. */ private final static double useless = 0.0; Postfix(Operator[] operators) { this.operators = operators; } // Konstruktor private boolean anyOperator(String str) { boolean isOperator = false; for (int i = 0; i < operators.length; i++) { if (str.equals(operators[i].getType())) { isOperator = true; break; } } return isOperator; } // anyOperator public double eval(String expr) { StringTokenizer tokens = new StringTokenizer(expr); String currentToken; while (tokens.hasMoreTokens()) { currentToken = tokens.nextToken(); try { stack.push(new Num(Double.parseDouble(currentToken))); } catch (Exception e) { /* Der Token ist also keine Zahl, weshalb zwei Fragen beantwortet werden muessen: * 1) Ist der Token eine der legalen Operationen in operators? * 2) Wenn ja, welcher Operator ist es genau? * Wenn es ueberhaupt kein gueltiger Operator ist, dann gibt die Methode null/Double.NaN zurueck. * Wenn er gueltig ist, dann packe das Ergebnis seiner Operation auf den Stack. */ if (anyOperator(currentToken)) { // Frage 1 beantwortet. double op1 = stack.pop().calc(useless, useless); double op2 = stack.pop().calc(useless, useless); switch (currentToken) { // Frage 2 beantwortet. case "+": stack.push(new Num(new Plus().calc(op1, op2))); break; case "-": stack.push(new Num(new Minus().calc(op1, op2))); break; case "*": stack.push(new Num(new Mult().calc(op1, op2))); break; case "/": stack.push(new Num(new Div().calc(op1, op2))); break; } } else { // Das Zeichen ist weder eine Zahl, noch ein gueltiger Operator. // Aufgabe: "Falls es sich nicht um einen gueltigen Ausdruck handelt, soll das Ergebniss null sein." return Double.NaN; } } } // Nun sollte nur noch ein Element auf dem Stack liegen. Wenn nicht, ist etwas schief gelaufen. if (stack.size() > 1) throw new Error("unbekannter Fehler"); return stack.pop().calc(useless, useless); } // eval public static void main(String[] args) { Operator[] ops = { new Plus(), new Minus(), new Mult(), new Div() }; Postfix postfix = new Postfix(ops); System.out.println(postfix.eval("3 5 2 * +")); // == 13.0 System.out.println(postfix.eval("7 3 5 + * 29 *")); // == 1624.0 } }
Dominik-Hillmann/study-misc
Postfix.java
1,043
// Frage 1 beantwortet.
line_comment
nl
import java.util.Stack; import java.util.StringTokenizer; public class Postfix { private Operator[] operators; private Stack<Operator> stack = new Stack<Operator>(); /* Dieser Wert ist fuer die Num-Klasse gedacht, da diese laut Interface zwei Argumente (double, double) braucht. * Laut Aufgabe muss Num aber ein 0-wertiger Operator sein, weshalb diese beiden Argumente keinen Sinn machen wuerden. * Ueber calc() gibt ein Num seinen eigenen Wert zurueck (wie andere Operatoren), aber mit useless soll markiert werden, dass * das Argument eigentlich nutzlos ist und nur der Konsistenz aller Operatoren dient. */ private final static double useless = 0.0; Postfix(Operator[] operators) { this.operators = operators; } // Konstruktor private boolean anyOperator(String str) { boolean isOperator = false; for (int i = 0; i < operators.length; i++) { if (str.equals(operators[i].getType())) { isOperator = true; break; } } return isOperator; } // anyOperator public double eval(String expr) { StringTokenizer tokens = new StringTokenizer(expr); String currentToken; while (tokens.hasMoreTokens()) { currentToken = tokens.nextToken(); try { stack.push(new Num(Double.parseDouble(currentToken))); } catch (Exception e) { /* Der Token ist also keine Zahl, weshalb zwei Fragen beantwortet werden muessen: * 1) Ist der Token eine der legalen Operationen in operators? * 2) Wenn ja, welcher Operator ist es genau? * Wenn es ueberhaupt kein gueltiger Operator ist, dann gibt die Methode null/Double.NaN zurueck. * Wenn er gueltig ist, dann packe das Ergebnis seiner Operation auf den Stack. */ if (anyOperator(currentToken)) { // Frage 1<SUF> double op1 = stack.pop().calc(useless, useless); double op2 = stack.pop().calc(useless, useless); switch (currentToken) { // Frage 2 beantwortet. case "+": stack.push(new Num(new Plus().calc(op1, op2))); break; case "-": stack.push(new Num(new Minus().calc(op1, op2))); break; case "*": stack.push(new Num(new Mult().calc(op1, op2))); break; case "/": stack.push(new Num(new Div().calc(op1, op2))); break; } } else { // Das Zeichen ist weder eine Zahl, noch ein gueltiger Operator. // Aufgabe: "Falls es sich nicht um einen gueltigen Ausdruck handelt, soll das Ergebniss null sein." return Double.NaN; } } } // Nun sollte nur noch ein Element auf dem Stack liegen. Wenn nicht, ist etwas schief gelaufen. if (stack.size() > 1) throw new Error("unbekannter Fehler"); return stack.pop().calc(useless, useless); } // eval public static void main(String[] args) { Operator[] ops = { new Plus(), new Minus(), new Mult(), new Div() }; Postfix postfix = new Postfix(ops); System.out.println(postfix.eval("3 5 2 * +")); // == 13.0 System.out.println(postfix.eval("7 3 5 + * 29 *")); // == 1624.0 } }
69026_0
package Abilities; import java.util.Scanner; import javaClasses.*; import javaClasses.Player; public class Thief extends Ability implements IAbility { int amount; boolean stealCard; public Thief(int amount) { this.amount = amount; boolean stealCard = true; } public void playAbility(Player target){ //Attack stealCard = true; for(Player player: target.getGame().players) { //Voor elke speler behalve deze die de ability speelt. if(player.getName() != target.getName()&& player.shield() == false) { for(int i = 0; i < amount ;i++) { System.out.println(player.drawPile.get(player.drawPile.size()-1).toString()); if(player.drawPile.get(player.drawPile.size()-1).getType() != "Treasure") { player.discardPile.drawCard(player.drawPile); //als het geen treasure kaart is, wordt hij naar de discardPile van de speler gestuurd. }else if(stealCard == true){ Scanner in = new Scanner(System.in); System.out.println("Would you like to take this card from "+player.getName()+"?"); String answer; answer = in.nextLine(); while(!answer.equals("yes") && !answer.equals("no")) { System.out.println("You must answer with 'yes' or 'no'."); answer = in.nextLine(); } if(answer.equals("no")) { target.getGame().trashPile.drawCard(player.drawPile); System.out.println("kaart werd getrashed"); //trashpile trekt de kaart van de drawpile } if(answer.equals("yes")) { target.discardPile.drawCard(player.drawPile); stealCard=false; //de kaart moet niet getrashed worden en gaat dus gewoon naar de discardPile van de speler //men mag maar 1 kaart stelen per speler } } else{ target.getGame().trashPile.drawCard(player.drawPile); System.out.println("kaart werd getrashed"); } } stealCard=true; } } } }
DominionGame/Dominion-V1.0.0
DominionGame/src/Abilities/Thief.java
727
//Voor elke speler behalve deze die de ability speelt.
line_comment
nl
package Abilities; import java.util.Scanner; import javaClasses.*; import javaClasses.Player; public class Thief extends Ability implements IAbility { int amount; boolean stealCard; public Thief(int amount) { this.amount = amount; boolean stealCard = true; } public void playAbility(Player target){ //Attack stealCard = true; for(Player player: target.getGame().players) { //Voor elke<SUF> if(player.getName() != target.getName()&& player.shield() == false) { for(int i = 0; i < amount ;i++) { System.out.println(player.drawPile.get(player.drawPile.size()-1).toString()); if(player.drawPile.get(player.drawPile.size()-1).getType() != "Treasure") { player.discardPile.drawCard(player.drawPile); //als het geen treasure kaart is, wordt hij naar de discardPile van de speler gestuurd. }else if(stealCard == true){ Scanner in = new Scanner(System.in); System.out.println("Would you like to take this card from "+player.getName()+"?"); String answer; answer = in.nextLine(); while(!answer.equals("yes") && !answer.equals("no")) { System.out.println("You must answer with 'yes' or 'no'."); answer = in.nextLine(); } if(answer.equals("no")) { target.getGame().trashPile.drawCard(player.drawPile); System.out.println("kaart werd getrashed"); //trashpile trekt de kaart van de drawpile } if(answer.equals("yes")) { target.discardPile.drawCard(player.drawPile); stealCard=false; //de kaart moet niet getrashed worden en gaat dus gewoon naar de discardPile van de speler //men mag maar 1 kaart stelen per speler } } else{ target.getGame().trashPile.drawCard(player.drawPile); System.out.println("kaart werd getrashed"); } } stealCard=true; } } } }
36780_16
package model; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import model.klas.Klas; import model.les.Les; import model.persoon.Docent; import model.persoon.Student; import model.presentie.Presentie; import model.presentie.PresentieMogelijkheden; import model.vak.Vak; import org.eclipse.jetty.util.IO; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collection; import java.util.List; public class PrIS { private ArrayList<Docent> deDocenten; private ArrayList<Student> deStudenten; private ArrayList<Klas> deKlassen; private ArrayList<Les> deLessen; private ArrayList<Vak> deVakken; /** * De constructor maakt een set met standaard-data aan. Deze data * moet nog uitgebreidt worden met rooster gegevens die uit een bestand worden * ingelezen, maar dat is geen onderdeel van deze demo-applicatie! * * De klasse PrIS (PresentieInformatieSysteem) heeft nu een meervoudige * associatie met de klassen Docent, Student, Vakken en Klassen Uiteraard kan dit nog veel * verder uitgebreid en aangepast worden! * * De klasse fungeert min of meer als ingangspunt voor het domeinmodel. Op * dit moment zijn de volgende methoden aanroepbaar: * * String login(String gebruikersnaam, String wachtwoord) * Docent getDocent(String gebruikersnaam) * Student getStudent(String gebruikersnaam) * ArrayList<Student> getStudentenVanKlas(String klasCode) * * Methode login geeft de rol van de gebruiker die probeert in te loggen, * dat kan 'student', 'docent' of 'undefined' zijn! Die informatie kan gebruikt * worden om in de Polymer-GUI te bepalen wat het volgende scherm is dat getoond * moet worden. * */ public PrIS() { deDocenten = new ArrayList<Docent>(); deStudenten = new ArrayList<Student>(); deKlassen = new ArrayList<Klas>(); deLessen = new ArrayList<Les>(); deVakken = new ArrayList<Vak>(); // Inladen klassen vulKlassen(deKlassen); // Inladen studenten in klassen vulStudenten(deStudenten, deKlassen); // Inladen docenten vulDocenten(deDocenten); // Inladen lessen vulLessen(deLessen); // Inladen vakken vulVakken(deVakken); } //Einde Pris constructor //deze method is static onderdeel van PrIS omdat hij als hulp methode //in veel controllers gebruikt wordt //een standaardDatumString heeft formaat YYYY-MM-DD public static Calendar standaardDatumStringToCal(String pStadaardDatumString) { Calendar lCal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { lCal.setTime(sdf.parse(pStadaardDatumString)); } catch (ParseException e) { e.printStackTrace(); lCal=null; } return lCal; } //deze method is static onderdeel van PrIS omdat hij als hulp methode //in veel controllers gebruikt wordt //een standaardDatumString heeft formaat YYYY-MM-DD public static String calToStandaardDatumString (Calendar pCalendar) { int lJaar = pCalendar.get(Calendar.YEAR); int lMaand= pCalendar.get(Calendar.MONTH) + 1; int lDag = pCalendar.get(Calendar.DAY_OF_MONTH); String lMaandStr = Integer.toString(lMaand); if (lMaandStr.length() == 1) { lMaandStr = "0"+ lMaandStr; } String lDagStr = Integer.toString(lDag); if (lDagStr.length() == 1) { lDagStr = "0"+ lDagStr; } String lString = Integer.toString(lJaar) + "-" + lMaandStr + "-" + lDagStr; return lString; } public Docent getDocent(String gebruikersnaam) { Docent resultaat = null; for (Docent d : deDocenten) { if (d.getGebruikersnaam().equals(gebruikersnaam)) { resultaat = d; break; } } return resultaat; } public Klas getKlasVanStudent(Student pStudent) { //used for (Klas lKlas : deKlassen) { if (lKlas.bevatStudent(pStudent)){ return (lKlas); } } return null; } public Student getStudent(String pGebruikersnaam) { // used Student lGevondenStudent = null; for (Student lStudent : deStudenten) { if (lStudent.getGebruikersnaam().equals(pGebruikersnaam)) { lGevondenStudent = lStudent; break; } } return lGevondenStudent; } public Student getStudent(int pStudentNummer) { // used Student lGevondenStudent = null; for (Student lStudent : deStudenten) { if (lStudent.getStudentNummer()==(pStudentNummer)) { lGevondenStudent = lStudent; break; } } return lGevondenStudent; } public ArrayList<Klas> getKlassen() { return deKlassen; } public List<Student> getStudentenVanKlas(String klasCode) { for (Klas klas : deKlassen) { if (klas.getKlasCode().equals(klasCode)) { return klas.getStudenten(); } } return null; } public ArrayList<Vak> getVakken() { return deVakken; } public String login(String gebruikersnaam, String wachtwoord) { for (Docent d : deDocenten) { if (d.getGebruikersnaam().equals(gebruikersnaam)) { if (d.komtWachtwoordOvereen(wachtwoord)) { return "docent"; } } } for (Student s : deStudenten) { if (s.getGebruikersnaam().equals(gebruikersnaam)) { if (s.komtWachtwoordOvereen(wachtwoord)) { return "student"; } } } return "undefined"; } private void vulDocenten(ArrayList<Docent> pDocenten) { String csvFile = "././CSV/docenten.csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = ","; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { // use comma as separator String[] element = line.split(cvsSplitBy); String gebruikersnaam = element[0].toLowerCase(); String voornaam = element[1]; String tussenvoegsel = element[2]; String achternaam = element[3]; pDocenten.add(new Docent(voornaam, tussenvoegsel, achternaam, "geheim", gebruikersnaam, 1)); //System.out.println(gebruikersnaam); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void vulKlassen(ArrayList<Klas> pKlassen) { //TICT-SIE-VIA is de klascode die ook in de rooster file voorkomt //V1A is de naam van de klas die ook als file naam voor de studenten van die klas wordt gebruikt //Klas k1 = new Klas("TICT-SIE-V1A", "V1A"); Klas k2 = new Klas("TICT-SIE-V1B", "V1B"); Klas k3 = new Klas("TICT-SIE-V1C", "V1C"); Klas k4 = new Klas("TICT-SIE-V1D", "V1D"); Klas k5 = new Klas("TICT-SIE-V1E", "V1E"); Klas k6 = new Klas("TICT-SIE-V1F", "V1F"); //pKlassen.add(k1); pKlassen.add(k2); pKlassen.add(k3); pKlassen.add(k4); pKlassen.add(k5); pKlassen.add(k6); } private void vulStudenten( ArrayList<Student> pStudenten, ArrayList<Klas> pKlassen) { Student lStudent; for (Klas k : pKlassen) { String csvFile = "././CSV/" + k.getNaam() + ".csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = ","; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { //line = line.replace(",,", ", ,"); // use comma as separator String[] element = line.split(cvsSplitBy); String gebruikersnaam = (element[3] + "." + element[2] + element[1] + "@student.hu.nl").toLowerCase(); // verwijder spaties tussen dubbele voornamen en tussen bv van der gebruikersnaam = gebruikersnaam.replace(" ",""); String lStudentNrString = element[0]; int lStudentNr = Integer.parseInt(lStudentNrString); lStudent = new Student(element[3], element[2], element[1], "geheim", gebruikersnaam, lStudentNr); //Volgorde 3-2-1 = voornaam, tussenvoegsel en achternaam pStudenten.add(lStudent); k.voegStudentToe(lStudent); //System.out.println(gebruikersnaam); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } } public void vulLessen(ArrayList<Les> pLessen) { String csvFile = "././CSV/rooster.csv"; BufferedReader br = null; String line = ""; String csvSplitBy = ","; String klasToegestaan = "SIE"; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { String[] element = line.split(csvSplitBy); String datum = element[0]; String van = element[1]; String tot = element[2]; String vakCode = element[3]; String leraarEmail = element[4]; String klasLokaal = element[5]; String klasCode = element[6]; // Haal klas naam op uit klasCode. String[] klasElementen = klasCode.split("-"); String klasNaam = klasElementen[1]; if(klasNaam.equals(klasToegestaan)) { // Parse datum string. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate localDate = LocalDate.parse(datum, formatter); Les pLes = new Les(localDate, van, tot, vakCode, leraarEmail, klasLokaal, klasCode); pLessen.add(pLes); } } } catch (IOException exception) { exception.printStackTrace(); } } public void vulVakken(ArrayList<Vak> pVakken) { String csvFile = "././CSV/vakken.csv"; BufferedReader br = null; String line = ""; String csvSplitBy = ","; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { String[] element = line.split(csvSplitBy); String vakCode = element[0]; String vakNaam = element[1]; Vak pVak = new Vak(vakCode, vakNaam); pVakken.add(pVak); } } catch (IOException exception) { exception.printStackTrace(); } } public ArrayList<Les> getLessenVanKlas(String klasCode) { ArrayList<Les> lessenVanKlas = new ArrayList<>(); for(Les pLes : deLessen) { if (pLes.getKlasCode().equals(klasCode)) { lessenVanKlas.add(pLes); } } return lessenVanKlas; } public ArrayList<Presentie> getPresentieVan(Student st, String vkC, String klC) { ArrayList<Presentie> pPresenties = new ArrayList<Presentie>(); ArrayList<Les> pLessen = getLessenVanKlas(klC); for (Les pLes : pLessen) { if(pLes.getVakCode().equals(vkC)) { pPresenties.add(new Presentie(st, pLes, PresentieMogelijkheden.AANWEZIG)); } } return pPresenties; } }
Donneh/Daim
src/model/PrIS.java
3,990
//Volgorde 3-2-1 = voornaam, tussenvoegsel en achternaam
line_comment
nl
package model; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import model.klas.Klas; import model.les.Les; import model.persoon.Docent; import model.persoon.Student; import model.presentie.Presentie; import model.presentie.PresentieMogelijkheden; import model.vak.Vak; import org.eclipse.jetty.util.IO; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collection; import java.util.List; public class PrIS { private ArrayList<Docent> deDocenten; private ArrayList<Student> deStudenten; private ArrayList<Klas> deKlassen; private ArrayList<Les> deLessen; private ArrayList<Vak> deVakken; /** * De constructor maakt een set met standaard-data aan. Deze data * moet nog uitgebreidt worden met rooster gegevens die uit een bestand worden * ingelezen, maar dat is geen onderdeel van deze demo-applicatie! * * De klasse PrIS (PresentieInformatieSysteem) heeft nu een meervoudige * associatie met de klassen Docent, Student, Vakken en Klassen Uiteraard kan dit nog veel * verder uitgebreid en aangepast worden! * * De klasse fungeert min of meer als ingangspunt voor het domeinmodel. Op * dit moment zijn de volgende methoden aanroepbaar: * * String login(String gebruikersnaam, String wachtwoord) * Docent getDocent(String gebruikersnaam) * Student getStudent(String gebruikersnaam) * ArrayList<Student> getStudentenVanKlas(String klasCode) * * Methode login geeft de rol van de gebruiker die probeert in te loggen, * dat kan 'student', 'docent' of 'undefined' zijn! Die informatie kan gebruikt * worden om in de Polymer-GUI te bepalen wat het volgende scherm is dat getoond * moet worden. * */ public PrIS() { deDocenten = new ArrayList<Docent>(); deStudenten = new ArrayList<Student>(); deKlassen = new ArrayList<Klas>(); deLessen = new ArrayList<Les>(); deVakken = new ArrayList<Vak>(); // Inladen klassen vulKlassen(deKlassen); // Inladen studenten in klassen vulStudenten(deStudenten, deKlassen); // Inladen docenten vulDocenten(deDocenten); // Inladen lessen vulLessen(deLessen); // Inladen vakken vulVakken(deVakken); } //Einde Pris constructor //deze method is static onderdeel van PrIS omdat hij als hulp methode //in veel controllers gebruikt wordt //een standaardDatumString heeft formaat YYYY-MM-DD public static Calendar standaardDatumStringToCal(String pStadaardDatumString) { Calendar lCal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { lCal.setTime(sdf.parse(pStadaardDatumString)); } catch (ParseException e) { e.printStackTrace(); lCal=null; } return lCal; } //deze method is static onderdeel van PrIS omdat hij als hulp methode //in veel controllers gebruikt wordt //een standaardDatumString heeft formaat YYYY-MM-DD public static String calToStandaardDatumString (Calendar pCalendar) { int lJaar = pCalendar.get(Calendar.YEAR); int lMaand= pCalendar.get(Calendar.MONTH) + 1; int lDag = pCalendar.get(Calendar.DAY_OF_MONTH); String lMaandStr = Integer.toString(lMaand); if (lMaandStr.length() == 1) { lMaandStr = "0"+ lMaandStr; } String lDagStr = Integer.toString(lDag); if (lDagStr.length() == 1) { lDagStr = "0"+ lDagStr; } String lString = Integer.toString(lJaar) + "-" + lMaandStr + "-" + lDagStr; return lString; } public Docent getDocent(String gebruikersnaam) { Docent resultaat = null; for (Docent d : deDocenten) { if (d.getGebruikersnaam().equals(gebruikersnaam)) { resultaat = d; break; } } return resultaat; } public Klas getKlasVanStudent(Student pStudent) { //used for (Klas lKlas : deKlassen) { if (lKlas.bevatStudent(pStudent)){ return (lKlas); } } return null; } public Student getStudent(String pGebruikersnaam) { // used Student lGevondenStudent = null; for (Student lStudent : deStudenten) { if (lStudent.getGebruikersnaam().equals(pGebruikersnaam)) { lGevondenStudent = lStudent; break; } } return lGevondenStudent; } public Student getStudent(int pStudentNummer) { // used Student lGevondenStudent = null; for (Student lStudent : deStudenten) { if (lStudent.getStudentNummer()==(pStudentNummer)) { lGevondenStudent = lStudent; break; } } return lGevondenStudent; } public ArrayList<Klas> getKlassen() { return deKlassen; } public List<Student> getStudentenVanKlas(String klasCode) { for (Klas klas : deKlassen) { if (klas.getKlasCode().equals(klasCode)) { return klas.getStudenten(); } } return null; } public ArrayList<Vak> getVakken() { return deVakken; } public String login(String gebruikersnaam, String wachtwoord) { for (Docent d : deDocenten) { if (d.getGebruikersnaam().equals(gebruikersnaam)) { if (d.komtWachtwoordOvereen(wachtwoord)) { return "docent"; } } } for (Student s : deStudenten) { if (s.getGebruikersnaam().equals(gebruikersnaam)) { if (s.komtWachtwoordOvereen(wachtwoord)) { return "student"; } } } return "undefined"; } private void vulDocenten(ArrayList<Docent> pDocenten) { String csvFile = "././CSV/docenten.csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = ","; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { // use comma as separator String[] element = line.split(cvsSplitBy); String gebruikersnaam = element[0].toLowerCase(); String voornaam = element[1]; String tussenvoegsel = element[2]; String achternaam = element[3]; pDocenten.add(new Docent(voornaam, tussenvoegsel, achternaam, "geheim", gebruikersnaam, 1)); //System.out.println(gebruikersnaam); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void vulKlassen(ArrayList<Klas> pKlassen) { //TICT-SIE-VIA is de klascode die ook in de rooster file voorkomt //V1A is de naam van de klas die ook als file naam voor de studenten van die klas wordt gebruikt //Klas k1 = new Klas("TICT-SIE-V1A", "V1A"); Klas k2 = new Klas("TICT-SIE-V1B", "V1B"); Klas k3 = new Klas("TICT-SIE-V1C", "V1C"); Klas k4 = new Klas("TICT-SIE-V1D", "V1D"); Klas k5 = new Klas("TICT-SIE-V1E", "V1E"); Klas k6 = new Klas("TICT-SIE-V1F", "V1F"); //pKlassen.add(k1); pKlassen.add(k2); pKlassen.add(k3); pKlassen.add(k4); pKlassen.add(k5); pKlassen.add(k6); } private void vulStudenten( ArrayList<Student> pStudenten, ArrayList<Klas> pKlassen) { Student lStudent; for (Klas k : pKlassen) { String csvFile = "././CSV/" + k.getNaam() + ".csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = ","; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { //line = line.replace(",,", ", ,"); // use comma as separator String[] element = line.split(cvsSplitBy); String gebruikersnaam = (element[3] + "." + element[2] + element[1] + "@student.hu.nl").toLowerCase(); // verwijder spaties tussen dubbele voornamen en tussen bv van der gebruikersnaam = gebruikersnaam.replace(" ",""); String lStudentNrString = element[0]; int lStudentNr = Integer.parseInt(lStudentNrString); lStudent = new Student(element[3], element[2], element[1], "geheim", gebruikersnaam, lStudentNr); //Volgorde 3-2-1<SUF> pStudenten.add(lStudent); k.voegStudentToe(lStudent); //System.out.println(gebruikersnaam); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } } public void vulLessen(ArrayList<Les> pLessen) { String csvFile = "././CSV/rooster.csv"; BufferedReader br = null; String line = ""; String csvSplitBy = ","; String klasToegestaan = "SIE"; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { String[] element = line.split(csvSplitBy); String datum = element[0]; String van = element[1]; String tot = element[2]; String vakCode = element[3]; String leraarEmail = element[4]; String klasLokaal = element[5]; String klasCode = element[6]; // Haal klas naam op uit klasCode. String[] klasElementen = klasCode.split("-"); String klasNaam = klasElementen[1]; if(klasNaam.equals(klasToegestaan)) { // Parse datum string. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate localDate = LocalDate.parse(datum, formatter); Les pLes = new Les(localDate, van, tot, vakCode, leraarEmail, klasLokaal, klasCode); pLessen.add(pLes); } } } catch (IOException exception) { exception.printStackTrace(); } } public void vulVakken(ArrayList<Vak> pVakken) { String csvFile = "././CSV/vakken.csv"; BufferedReader br = null; String line = ""; String csvSplitBy = ","; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { String[] element = line.split(csvSplitBy); String vakCode = element[0]; String vakNaam = element[1]; Vak pVak = new Vak(vakCode, vakNaam); pVakken.add(pVak); } } catch (IOException exception) { exception.printStackTrace(); } } public ArrayList<Les> getLessenVanKlas(String klasCode) { ArrayList<Les> lessenVanKlas = new ArrayList<>(); for(Les pLes : deLessen) { if (pLes.getKlasCode().equals(klasCode)) { lessenVanKlas.add(pLes); } } return lessenVanKlas; } public ArrayList<Presentie> getPresentieVan(Student st, String vkC, String klC) { ArrayList<Presentie> pPresenties = new ArrayList<Presentie>(); ArrayList<Les> pLessen = getLessenVanKlas(klC); for (Les pLes : pLessen) { if(pLes.getVakCode().equals(vkC)) { pPresenties.add(new Presentie(st, pLes, PresentieMogelijkheden.AANWEZIG)); } } return pPresenties; } }
131322_0
package week4.practicum3; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class Hotel { private String naam; private List<Boeking> alleBoekingen = new ArrayList<Boeking>(); private List<KamerType> alleKamerTypen = new ArrayList<KamerType>(); private List<Kamer> alleKamers = new ArrayList<Kamer>(); public Hotel(String nm) { naam = nm; KamerType kt1 = new KamerType("Standaard", 2, 60.00); KamerType kt2 = new KamerType("DeLuxe", 2, 85.00); alleKamerTypen.add(kt1); alleKamerTypen.add(kt2); alleKamers.add(new Kamer(3, kt1)); alleKamers.add(new Kamer(1, kt2)); alleKamers.add(new Kamer(4, kt2)); } public int voegBoekingToe(LocalDate van, LocalDate tot, String nm, String adr, KamerType kt) { Boeking b = new Boeking(van, tot); b.setDeBoeker(new Klant(nm, adr)); Kamer beschikbareKamer = zoekBeschikbareKamer(kt, b.getAankomstDatum(), b.getVertrekDatum()); if (beschikbareKamer != null) { b.wijsKamerToe(beschikbareKamer); if (alleBoekingen.add(b)) { return beschikbareKamer.getKamerNummer(); } } System.out.println(this); return -1; } private Kamer zoekBeschikbareKamer(KamerType gezochteType, LocalDate aankomst, LocalDate vertrek) { Kamer beschikbareKamer = null; for (Kamer kamer : alleKamers) { if (kamer.getHetType().equals(gezochteType)) { if (isBeschikbaar(kamer, aankomst, vertrek)) { beschikbareKamer = kamer; break; } } } return beschikbareKamer; } private boolean isBeschikbaar(Kamer kamer, LocalDate aankomst, LocalDate vertrek) { boolean isBeschikbaar = true; for (Boeking b : alleBoekingen) { if (b.getKamer().equals(kamer)) { //bool overlap = a.start < b.end && b.start < a.end; if (aankomst.isBefore(b.getVertrekDatum()) && b.getAankomstDatum().isBefore(vertrek)) { isBeschikbaar = false; break; } } } return isBeschikbaar; } public List<KamerType> getKamerTypen() { return alleKamerTypen; } public String toString() { StringBuilder result = new StringBuilder("Boekingen van hotel " + naam + ":"); alleBoekingen.forEach(boeking -> result.append("\n\t" + boeking.toString())); return result.toString(); } }
Donneh/Java
src/week4/practicum3/Hotel.java
864
//bool overlap = a.start < b.end && b.start < a.end;
line_comment
nl
package week4.practicum3; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class Hotel { private String naam; private List<Boeking> alleBoekingen = new ArrayList<Boeking>(); private List<KamerType> alleKamerTypen = new ArrayList<KamerType>(); private List<Kamer> alleKamers = new ArrayList<Kamer>(); public Hotel(String nm) { naam = nm; KamerType kt1 = new KamerType("Standaard", 2, 60.00); KamerType kt2 = new KamerType("DeLuxe", 2, 85.00); alleKamerTypen.add(kt1); alleKamerTypen.add(kt2); alleKamers.add(new Kamer(3, kt1)); alleKamers.add(new Kamer(1, kt2)); alleKamers.add(new Kamer(4, kt2)); } public int voegBoekingToe(LocalDate van, LocalDate tot, String nm, String adr, KamerType kt) { Boeking b = new Boeking(van, tot); b.setDeBoeker(new Klant(nm, adr)); Kamer beschikbareKamer = zoekBeschikbareKamer(kt, b.getAankomstDatum(), b.getVertrekDatum()); if (beschikbareKamer != null) { b.wijsKamerToe(beschikbareKamer); if (alleBoekingen.add(b)) { return beschikbareKamer.getKamerNummer(); } } System.out.println(this); return -1; } private Kamer zoekBeschikbareKamer(KamerType gezochteType, LocalDate aankomst, LocalDate vertrek) { Kamer beschikbareKamer = null; for (Kamer kamer : alleKamers) { if (kamer.getHetType().equals(gezochteType)) { if (isBeschikbaar(kamer, aankomst, vertrek)) { beschikbareKamer = kamer; break; } } } return beschikbareKamer; } private boolean isBeschikbaar(Kamer kamer, LocalDate aankomst, LocalDate vertrek) { boolean isBeschikbaar = true; for (Boeking b : alleBoekingen) { if (b.getKamer().equals(kamer)) { //bool overlap<SUF> if (aankomst.isBefore(b.getVertrekDatum()) && b.getAankomstDatum().isBefore(vertrek)) { isBeschikbaar = false; break; } } } return isBeschikbaar; } public List<KamerType> getKamerTypen() { return alleKamerTypen; } public String toString() { StringBuilder result = new StringBuilder("Boekingen van hotel " + naam + ":"); alleBoekingen.forEach(boeking -> result.append("\n\t" + boeking.toString())); return result.toString(); } }
111105_4
import javax.swing.plaf.nimbus.State; import javax.xml.transform.Result; import java.sql.*; import java.util.ArrayList; import java.util.List; public class ReizigerOracleDaoImpl extends OracleBaseDao implements ReizigerDao { /** * Returned alle reizigers. * @return ArrayList<Reiziger> */ public List<Reiziger> findAll() { try { Statement stmt = getConnection().createStatement(); String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM FROM REIZIGER"; ResultSet rs = stmt.executeQuery(query); ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>(); while(rs.next()) { reizigers.add(buildreizigerobject(rs)); } return reizigers; } catch (Exception e) { e.printStackTrace(); } return null; } public Reiziger findById(int id) { try { String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " + "FROM REIZIGER " + "WHERE REIZIGERID = ?"; PreparedStatement stmt = getConnection().prepareStatement(query); stmt.setInt(1, id); ResultSet rs = stmt.executeQuery(); while(rs.next()) { return buildreizigerobject(rs); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * Returned alle reizigers met specifieke geboortedatum. * @param GBdatum * @return ArrayList<Reiziger> */ public List<Reiziger> findByGBdatum(Date GBdatum) { try { String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " + "FROM REIZIGER WHERE GEBOORTEDATUM = ?"; PreparedStatement stmt = getConnection().prepareStatement(query); stmt.setDate(1, GBdatum); ResultSet rs = stmt.executeQuery(); ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>(); while (rs.next()) { reizigers.add(buildreizigerobject(rs)); } return reizigers; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Slaat een reiziger op. * @param reiziger * @return */ public Reiziger save(Reiziger reiziger) { try { String query = "INSERT INTO REIZIGER" + "(VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM) VALUES " + "(?, ?, ?, ?)"; String generatedColumns[] = { "REIZIGERID" }; PreparedStatement stmt = getConnection().prepareStatement(query, generatedColumns); stmt.setString(1, reiziger.getVoorletters()); stmt.setString(2, reiziger.getTussenveogsel()); stmt.setString(3, reiziger.getAchternaam()); stmt.setDate(4, reiziger.getGeboortedatum()); stmt.executeUpdate(); ResultSet rs = stmt.getGeneratedKeys(); if(rs.next()) { return findById(rs.getInt(1)); } } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Past een opgeslagen reiziger aan. * @param reiziger * @return Reiziger */ public Reiziger update(Reiziger reiziger) { try { String query = "UPDATE REIZIGER SET " + "VOORLETTERS = ?, TUSSENVOEGSEL = ?, ACHTERNAAM = ?, GEBOORTEDATUM = ? " + "WHERE REIZIGERID = ?"; PreparedStatement stmt = getConnection().prepareStatement(query); stmt.setString(1, reiziger.getVoorletters()); stmt.setString(2, reiziger.getTussenveogsel()); stmt.setString(3, reiziger.getAchternaam()); stmt.setDate(4, reiziger.getGeboortedatum()); stmt.setInt(5, reiziger.getId()); ResultSet rs = stmt.executeQuery(); if (rs.rowUpdated()) { return findById(reiziger.getId()); } } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Verwijder een reiziger. * @param reiziger * @return boolean */ public boolean delete(Reiziger reiziger) { try { String query = "DELETE FROM REIZIGER WHERE REIZIGERID = ?"; PreparedStatement stmt = getConnection().prepareStatement(query); stmt.setInt(1, reiziger.getId()); int rs = stmt.executeUpdate(); return rs > 0; } catch (SQLException e) { e.printStackTrace(); } return false; } private Reiziger buildreizigerobject(ResultSet rs) throws SQLException { int id = rs.getInt("REIZIGERID"); Reiziger reiziger = new Reiziger(); reiziger.setId(id); reiziger.setVoorletters(rs.getString("VOORLETTERS")); reiziger.setTussenveogsel(rs.getString("TUSSENVOEGSEL")); reiziger.setAchternaam(rs.getString("ACHTERNAAM")); reiziger.setGeboortedatum(rs.getDate("GEBOORTEDATUM")); OVChipkaartDaoImpl ovdao = new OVChipkaartDaoImpl(); reiziger.setKaarten(ovdao.findByReiziger(id)); AdresDaoImpl adao = new AdresDaoImpl(); reiziger.setAdressen(adao.findByReiziger(id)); return reiziger; } }
Donneh/ovcasus
src/ReizigerOracleDaoImpl.java
1,772
/** * Verwijder een reiziger. * @param reiziger * @return boolean */
block_comment
nl
import javax.swing.plaf.nimbus.State; import javax.xml.transform.Result; import java.sql.*; import java.util.ArrayList; import java.util.List; public class ReizigerOracleDaoImpl extends OracleBaseDao implements ReizigerDao { /** * Returned alle reizigers. * @return ArrayList<Reiziger> */ public List<Reiziger> findAll() { try { Statement stmt = getConnection().createStatement(); String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM FROM REIZIGER"; ResultSet rs = stmt.executeQuery(query); ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>(); while(rs.next()) { reizigers.add(buildreizigerobject(rs)); } return reizigers; } catch (Exception e) { e.printStackTrace(); } return null; } public Reiziger findById(int id) { try { String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " + "FROM REIZIGER " + "WHERE REIZIGERID = ?"; PreparedStatement stmt = getConnection().prepareStatement(query); stmt.setInt(1, id); ResultSet rs = stmt.executeQuery(); while(rs.next()) { return buildreizigerobject(rs); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * Returned alle reizigers met specifieke geboortedatum. * @param GBdatum * @return ArrayList<Reiziger> */ public List<Reiziger> findByGBdatum(Date GBdatum) { try { String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " + "FROM REIZIGER WHERE GEBOORTEDATUM = ?"; PreparedStatement stmt = getConnection().prepareStatement(query); stmt.setDate(1, GBdatum); ResultSet rs = stmt.executeQuery(); ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>(); while (rs.next()) { reizigers.add(buildreizigerobject(rs)); } return reizigers; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Slaat een reiziger op. * @param reiziger * @return */ public Reiziger save(Reiziger reiziger) { try { String query = "INSERT INTO REIZIGER" + "(VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM) VALUES " + "(?, ?, ?, ?)"; String generatedColumns[] = { "REIZIGERID" }; PreparedStatement stmt = getConnection().prepareStatement(query, generatedColumns); stmt.setString(1, reiziger.getVoorletters()); stmt.setString(2, reiziger.getTussenveogsel()); stmt.setString(3, reiziger.getAchternaam()); stmt.setDate(4, reiziger.getGeboortedatum()); stmt.executeUpdate(); ResultSet rs = stmt.getGeneratedKeys(); if(rs.next()) { return findById(rs.getInt(1)); } } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Past een opgeslagen reiziger aan. * @param reiziger * @return Reiziger */ public Reiziger update(Reiziger reiziger) { try { String query = "UPDATE REIZIGER SET " + "VOORLETTERS = ?, TUSSENVOEGSEL = ?, ACHTERNAAM = ?, GEBOORTEDATUM = ? " + "WHERE REIZIGERID = ?"; PreparedStatement stmt = getConnection().prepareStatement(query); stmt.setString(1, reiziger.getVoorletters()); stmt.setString(2, reiziger.getTussenveogsel()); stmt.setString(3, reiziger.getAchternaam()); stmt.setDate(4, reiziger.getGeboortedatum()); stmt.setInt(5, reiziger.getId()); ResultSet rs = stmt.executeQuery(); if (rs.rowUpdated()) { return findById(reiziger.getId()); } } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Verwijder een reiziger.<SUF>*/ public boolean delete(Reiziger reiziger) { try { String query = "DELETE FROM REIZIGER WHERE REIZIGERID = ?"; PreparedStatement stmt = getConnection().prepareStatement(query); stmt.setInt(1, reiziger.getId()); int rs = stmt.executeUpdate(); return rs > 0; } catch (SQLException e) { e.printStackTrace(); } return false; } private Reiziger buildreizigerobject(ResultSet rs) throws SQLException { int id = rs.getInt("REIZIGERID"); Reiziger reiziger = new Reiziger(); reiziger.setId(id); reiziger.setVoorletters(rs.getString("VOORLETTERS")); reiziger.setTussenveogsel(rs.getString("TUSSENVOEGSEL")); reiziger.setAchternaam(rs.getString("ACHTERNAAM")); reiziger.setGeboortedatum(rs.getDate("GEBOORTEDATUM")); OVChipkaartDaoImpl ovdao = new OVChipkaartDaoImpl(); reiziger.setKaarten(ovdao.findByReiziger(id)); AdresDaoImpl adao = new AdresDaoImpl(); reiziger.setAdressen(adao.findByReiziger(id)); return reiziger; } }
37527_2
package com.alibaba.excel.write.metadata; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * Write sheet * * @author jipengfei */ @Getter @Setter @EqualsAndHashCode public class WriteSheet extends WriteBasicParameter { /** * Starting from 0 */ private Integer sheetNo; /** * sheet name */ private String sheetName; }
Donzch/easyexcel
easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java
128
/** * sheet name */
block_comment
nl
package com.alibaba.excel.write.metadata; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * Write sheet * * @author jipengfei */ @Getter @Setter @EqualsAndHashCode public class WriteSheet extends WriteBasicParameter { /** * Starting from 0 */ private Integer sheetNo; /** * sheet name <SUF>*/ private String sheetName; }
32368_1
package SxxMachine; import static SxxMachine.pterm.TermData.*; import SxxMachine.pterm.StructureTerm; public class pred_catch_3 extends Code { @Override public int arity() { return 3; } @Override public Code exec(PrologMachine mach) throws JPrologInternalException { final TermArray local_aregs = mach.getAreg(); final Term goal = local_aregs.getTermDRef(0); final Term exception = local_aregs.getTermDRef(1); final Term exceptionCode = local_aregs.getTermDRef(2); final Term cont = local_aregs.getTermDRef(3); //Niet van beland om args op te slaan, wel van belang dat er een apart choicepoint is mach.createChoicePoint(RunningPrologMachine.NO_ARGS); //goal aanpassen voor continuation toe te voegen // in dit geval skippen exceptionhandler voor code die volgt mach.setPrologExceptionHandler(new CatchExceptionHandler(exception, exceptionCode, cont)); mach.setCont(local_aregs, 0, addContinuation(mach, goal, S("endCatch", Integer(mach .getCurrentChoice()), cont))); local_aregs.setAreg1((local_aregs.setAreg2((local_aregs.setAreg3((null)))))); return mach.getCall1(); } private StructureTerm addContinuation(PrologMachine mach, Term o, Term cont) { if (o.isAtomOrObject()) { return (StructureTerm) S(o.fname(), cont); } if (o.isCompound()) { final AFunct f = (AFunct) o; final StructureTerm newF = new StructureTerm(f.fname(), f.arity() + 1); for (int i = 0; i < f.arity(); i++) { newF.setarg0(i, f.getPlainArg(i)); } mach.setCont(TermArray.newTermArray(newF.args()), f.arity(), cont); return newF; } throw new JPrologInternalException("Invalid params"); } } class pred_endCatch_1 extends Code { @Override public int arity() { return 1; } @Override public Code exec(PrologMachine mach) throws JPrologInternalException { final TermArray local_aregs = mach.getAreg(); final Term choice = local_aregs.getTermDRef(0); final Term cont = local_aregs.getTermDRef(1); if (!(choice instanceof NumberTerm)) return mach.Fail0; final long choicePoint = choice.longValue() - 1; //zorgen dat bij exceptionhandler er pas wordt verder gezocht vanaf choicePoint mach.setPrologExceptionHandler(new SkipExceptionHandler(choicePoint)); local_aregs.setAreg1((null)); mach.setCont(local_aregs, 0, cont); return mach.getCall1(); } }
DouglasRMiles/SxxMachine
jsrc-kuleuven/toplevel1/SxxMachine/pred_catch_3.java
801
//goal aanpassen voor continuation toe te voegen
line_comment
nl
package SxxMachine; import static SxxMachine.pterm.TermData.*; import SxxMachine.pterm.StructureTerm; public class pred_catch_3 extends Code { @Override public int arity() { return 3; } @Override public Code exec(PrologMachine mach) throws JPrologInternalException { final TermArray local_aregs = mach.getAreg(); final Term goal = local_aregs.getTermDRef(0); final Term exception = local_aregs.getTermDRef(1); final Term exceptionCode = local_aregs.getTermDRef(2); final Term cont = local_aregs.getTermDRef(3); //Niet van beland om args op te slaan, wel van belang dat er een apart choicepoint is mach.createChoicePoint(RunningPrologMachine.NO_ARGS); //goal aanpassen<SUF> // in dit geval skippen exceptionhandler voor code die volgt mach.setPrologExceptionHandler(new CatchExceptionHandler(exception, exceptionCode, cont)); mach.setCont(local_aregs, 0, addContinuation(mach, goal, S("endCatch", Integer(mach .getCurrentChoice()), cont))); local_aregs.setAreg1((local_aregs.setAreg2((local_aregs.setAreg3((null)))))); return mach.getCall1(); } private StructureTerm addContinuation(PrologMachine mach, Term o, Term cont) { if (o.isAtomOrObject()) { return (StructureTerm) S(o.fname(), cont); } if (o.isCompound()) { final AFunct f = (AFunct) o; final StructureTerm newF = new StructureTerm(f.fname(), f.arity() + 1); for (int i = 0; i < f.arity(); i++) { newF.setarg0(i, f.getPlainArg(i)); } mach.setCont(TermArray.newTermArray(newF.args()), f.arity(), cont); return newF; } throw new JPrologInternalException("Invalid params"); } } class pred_endCatch_1 extends Code { @Override public int arity() { return 1; } @Override public Code exec(PrologMachine mach) throws JPrologInternalException { final TermArray local_aregs = mach.getAreg(); final Term choice = local_aregs.getTermDRef(0); final Term cont = local_aregs.getTermDRef(1); if (!(choice instanceof NumberTerm)) return mach.Fail0; final long choicePoint = choice.longValue() - 1; //zorgen dat bij exceptionhandler er pas wordt verder gezocht vanaf choicePoint mach.setPrologExceptionHandler(new SkipExceptionHandler(choicePoint)); local_aregs.setAreg1((null)); mach.setCont(local_aregs, 0, cont); return mach.getCall1(); } }
69651_6
package isy.team4.projectisy.controller; import isy.team4.projectisy.MainApplication; import isy.team4.projectisy.util.EGame; import isy.team4.projectisy.util.EPlayer; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import java.io.IOException; import java.util.HashMap; import java.util.Objects; import javafx.scene.Node; public class HomeController extends Controller { private static String selectedGame; private static boolean is_cpu; private static boolean isLocal = true; private static EPlayer player1; private static EPlayer player2; public void navigateOnline(ActionEvent actionEvent) throws IOException { isLocal = false; // this.playerMenuText.setText("Kies je speler"); // TODO: temp, see initGame navigate(actionEvent, "online-menu-view.fxml"); } public void navigateOffline(ActionEvent actionEvent) throws IOException { isLocal = true; // this.playerMenuText.setText("Kies je tegenstander"); // TODO: temp, see initGame navigate(actionEvent, "offline-menu-view.fxml"); } public void navigateHome(ActionEvent actionEvent) throws IOException { navigate(actionEvent, "main-menu-view.fxml"); } public void navigateOptions(ActionEvent actionEvent) throws IOException { navigate(actionEvent, "main-menu-view.fxml"); } public void setTicTacToe(ActionEvent actionEvent) throws IOException { selectedGame = "tic-tac-toe"; navigate(actionEvent, "player-menu-view.fxml"); System.out.println(this); } public void setOthello(ActionEvent actionEvent) throws IOException { selectedGame = "othello"; navigate(actionEvent, "player-menu-view.fxml"); System.out.println(this); } // TODO: Remove, will be replaced by a list of choices, see initGame public void setComputer(ActionEvent actionEvent) throws IOException { is_cpu = true; Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow(); initGame(stage); } // TODO: Remove, will be replaced by a list of choices, see initGame public void setPlayer(ActionEvent actionEvent) throws IOException { is_cpu = false; Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow(); initGame(stage); } public void initGame(Stage stage) { HashMap<String, String> gameViewMapper = new HashMap<String, String>(); gameViewMapper.put("tic-tac-toe", "tictactoe-view.fxml"); gameViewMapper.put("othello", "othello-view.fxml"); // TODO: Pas aan zodat selectie op frontend zo werkt: // Als eerst selectie local of remote -> daarna: // als local: selectie voor zowel player1 als player2 (keuze uit: LOCAL, AI) // als remote: selectie voor 1 player (keuze uit: LOCAL, AI). // Wanneer dit gedaan is krijg je iets zoals dit: // // EPlayer[] players = new EPlayer[]{player1}; // if (isLocal) { // players = Arrays.copyOf(players, players.length + 1); // Could refactor to ArrayList? // players[1] = player2; // } // navigateOut( // stage, // gameViewMapper.get(selectedGame), // isLocal ? EGame.LOCAL : EGame.REMOTE, // players // ); // Hierbij is het makkelijk om een extra speler te implementeren in de "eventuele" toekomst if (isLocal) { this.navigateOut(stage, gameViewMapper.get(selectedGame), EGame.LOCAL, new EPlayer[]{EPlayer.LOCAL, is_cpu ? EPlayer.AI : EPlayer.LOCAL} ); } else { this.navigateOut(stage, gameViewMapper.get(selectedGame), EGame.REMOTE, new EPlayer[]{is_cpu ? EPlayer.AI : EPlayer.LOCAL} ); } // navigateOut( // stage, // gameViewMapper.get(selectedGame), // this.isLocal ? EGame.LOCAL : EGame.REMOTE, // new EPlayer[]{EPlayer.LOCAL, is_cpu ? EPlayer.AI : EPlayer.LOCAL} // ); } @FXML public void navigate(ActionEvent actionEvent, String File) throws IOException { Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow(); Parent root = FXMLLoader.load(MainApplication.class.getResource(File)); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } @FXML public void navigateOut(Stage stage, String view, EGame gameType, EPlayer[] players) { try { FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource(view)); // TODO: relative instead // of absolute gathering of // resources Parent root = fxmlLoader.load(); GameController controller = fxmlLoader.getController(); controller.initGame(gameType, players); Scene scene = new Scene(root); scene.getStylesheets() .add(Objects.requireNonNull(MainApplication.class.getResource("style.css")).toExternalForm()); // main // stylesheet stage.setScene(scene); stage.show(); } catch (IOException e) { e.printStackTrace(); } } }
DowneyX/project-ISY
src/main/java/isy/team4/projectisy/controller/HomeController.java
1,620
// als local: selectie voor zowel player1 als player2 (keuze uit: LOCAL, AI)
line_comment
nl
package isy.team4.projectisy.controller; import isy.team4.projectisy.MainApplication; import isy.team4.projectisy.util.EGame; import isy.team4.projectisy.util.EPlayer; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import java.io.IOException; import java.util.HashMap; import java.util.Objects; import javafx.scene.Node; public class HomeController extends Controller { private static String selectedGame; private static boolean is_cpu; private static boolean isLocal = true; private static EPlayer player1; private static EPlayer player2; public void navigateOnline(ActionEvent actionEvent) throws IOException { isLocal = false; // this.playerMenuText.setText("Kies je speler"); // TODO: temp, see initGame navigate(actionEvent, "online-menu-view.fxml"); } public void navigateOffline(ActionEvent actionEvent) throws IOException { isLocal = true; // this.playerMenuText.setText("Kies je tegenstander"); // TODO: temp, see initGame navigate(actionEvent, "offline-menu-view.fxml"); } public void navigateHome(ActionEvent actionEvent) throws IOException { navigate(actionEvent, "main-menu-view.fxml"); } public void navigateOptions(ActionEvent actionEvent) throws IOException { navigate(actionEvent, "main-menu-view.fxml"); } public void setTicTacToe(ActionEvent actionEvent) throws IOException { selectedGame = "tic-tac-toe"; navigate(actionEvent, "player-menu-view.fxml"); System.out.println(this); } public void setOthello(ActionEvent actionEvent) throws IOException { selectedGame = "othello"; navigate(actionEvent, "player-menu-view.fxml"); System.out.println(this); } // TODO: Remove, will be replaced by a list of choices, see initGame public void setComputer(ActionEvent actionEvent) throws IOException { is_cpu = true; Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow(); initGame(stage); } // TODO: Remove, will be replaced by a list of choices, see initGame public void setPlayer(ActionEvent actionEvent) throws IOException { is_cpu = false; Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow(); initGame(stage); } public void initGame(Stage stage) { HashMap<String, String> gameViewMapper = new HashMap<String, String>(); gameViewMapper.put("tic-tac-toe", "tictactoe-view.fxml"); gameViewMapper.put("othello", "othello-view.fxml"); // TODO: Pas aan zodat selectie op frontend zo werkt: // Als eerst selectie local of remote -> daarna: // als local:<SUF> // als remote: selectie voor 1 player (keuze uit: LOCAL, AI). // Wanneer dit gedaan is krijg je iets zoals dit: // // EPlayer[] players = new EPlayer[]{player1}; // if (isLocal) { // players = Arrays.copyOf(players, players.length + 1); // Could refactor to ArrayList? // players[1] = player2; // } // navigateOut( // stage, // gameViewMapper.get(selectedGame), // isLocal ? EGame.LOCAL : EGame.REMOTE, // players // ); // Hierbij is het makkelijk om een extra speler te implementeren in de "eventuele" toekomst if (isLocal) { this.navigateOut(stage, gameViewMapper.get(selectedGame), EGame.LOCAL, new EPlayer[]{EPlayer.LOCAL, is_cpu ? EPlayer.AI : EPlayer.LOCAL} ); } else { this.navigateOut(stage, gameViewMapper.get(selectedGame), EGame.REMOTE, new EPlayer[]{is_cpu ? EPlayer.AI : EPlayer.LOCAL} ); } // navigateOut( // stage, // gameViewMapper.get(selectedGame), // this.isLocal ? EGame.LOCAL : EGame.REMOTE, // new EPlayer[]{EPlayer.LOCAL, is_cpu ? EPlayer.AI : EPlayer.LOCAL} // ); } @FXML public void navigate(ActionEvent actionEvent, String File) throws IOException { Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow(); Parent root = FXMLLoader.load(MainApplication.class.getResource(File)); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } @FXML public void navigateOut(Stage stage, String view, EGame gameType, EPlayer[] players) { try { FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource(view)); // TODO: relative instead // of absolute gathering of // resources Parent root = fxmlLoader.load(); GameController controller = fxmlLoader.getController(); controller.initGame(gameType, players); Scene scene = new Scene(root); scene.getStylesheets() .add(Objects.requireNonNull(MainApplication.class.getResource("style.css")).toExternalForm()); // main // stylesheet stage.setScene(scene); stage.show(); } catch (IOException e) { e.printStackTrace(); } } }
2159_1
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import com.carrotsearch.randomizedtesting.Xoroshiro128PlusRandom; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Utilities { public static Pattern pattern = Pattern.compile("[\\-0-9]+"); public static SecureRandom random = new SecureRandom(); public static Random fastRandom = new Xoroshiro128PlusRandom(random.nextLong()); public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue"); public static volatile DispatchQueue globalQueue = new DispatchQueue("globalQueue"); public static volatile DispatchQueue cacheClearQueue = new DispatchQueue("cacheClearQueue"); public static volatile DispatchQueue searchQueue = new DispatchQueue("searchQueue"); public static volatile DispatchQueue phoneBookQueue = new DispatchQueue("phoneBookQueue"); public static volatile DispatchQueue themeQueue = new DispatchQueue("themeQueue"); public static volatile DispatchQueue externalNetworkQueue = new DispatchQueue("externalNetworkQueue"); public static volatile DispatchQueue videoPlayerQueue; private final static String RANDOM_STRING_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); static { try { File URANDOM_FILE = new File("/dev/urandom"); FileInputStream sUrandomIn = new FileInputStream(URANDOM_FILE); byte[] buffer = new byte[1024]; sUrandomIn.read(buffer); sUrandomIn.close(); random.setSeed(buffer); } catch (Exception e) { FileLog.e(e); } } public native static int pinBitmap(Bitmap bitmap); public native static void unpinBitmap(Bitmap bitmap); public native static void blurBitmap(Object bitmap, int radius, int unpin, int width, int height, int stride); public native static int needInvert(Object bitmap, int unpin, int width, int height, int stride); public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer, ByteBuffer calcBuffer); public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin); public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap); private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); private native static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); public native static void aesCtrDecryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length); public native static void aesCtrDecryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, long length, int n); private native static void aesCbcEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt); public native static void aesCbcEncryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length, int encrypt); public native static String readlink(String path); public native static String readlinkFd(int fd); public native static long getDirSize(String path, int docType, boolean subdirs); public native static long getLastUsageFileTime(String path); public native static void clearDir(String path, int docType, long time, boolean subdirs); private native static int pbkdf2(byte[] password, byte[] salt, byte[] dst, int iterations); public static native void stackBlurBitmap(Bitmap bitmap, int radius); public static native void drawDitheredGradient(Bitmap bitmap, int[] colors, int startX, int startY, int endX, int endY); public static native int saveProgressiveJpeg(Bitmap bitmap, int width, int height, int stride, int quality, String path); public static native void generateGradient(Bitmap bitmap, boolean unpin, int phase, float progress, int width, int height, int stride, int[] colors); public static native void setupNativeCrashesListener(String path); public static Bitmap stackBlurBitmapMax(Bitmap bitmap) { return stackBlurBitmapMax(bitmap, false); } public static Bitmap stackBlurBitmapMax(Bitmap bitmap, boolean round) { int w = AndroidUtilities.dp(20); int h = (int) (AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth()); Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(scaledBitmap); canvas.save(); canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight()); if (round) { Path path = new Path(); path.addCircle(bitmap.getWidth() / 2f, bitmap.getHeight() / 2f, Math.min(bitmap.getWidth(), bitmap.getHeight()) / 2f - 1, Path.Direction.CW); canvas.clipPath(path); } canvas.drawBitmap(bitmap, 0, 0, null); canvas.restore(); Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150)); return scaledBitmap; } public static Bitmap stackBlurBitmapWithScaleFactor(Bitmap bitmap, float scaleFactor) { int w = (int) Math.max(AndroidUtilities.dp(20), bitmap.getWidth() / scaleFactor); int h = (int) Math.max(AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth(), bitmap.getHeight() / scaleFactor); Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(scaledBitmap); canvas.save(); canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight()); canvas.drawBitmap(bitmap, 0, 0, null); canvas.restore(); Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150)); return scaledBitmap; } public static Bitmap blurWallpaper(Bitmap src) { if (src == null) { return null; } Bitmap b; if (src.getHeight() > src.getWidth()) { b = Bitmap.createBitmap(Math.round(450f * src.getWidth() / src.getHeight()), 450, Bitmap.Config.ARGB_8888); } else { b = Bitmap.createBitmap(450, Math.round(450f * src.getHeight() / src.getWidth()), Bitmap.Config.ARGB_8888); } Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); Rect rect = new Rect(0, 0, b.getWidth(), b.getHeight()); new Canvas(b).drawBitmap(src, null, rect, paint); stackBlurBitmap(b, 12); return b; } public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length); } public static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { aesIgeEncryptionByteArray(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length); } public static void aesCbcEncryptionByteArraySafe(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt) { aesCbcEncryptionByteArray(buffer, key, iv.clone(), offset, length, n, encrypt); } public static Integer parseInt(CharSequence value) { if (value == null) { return 0; } if (BuildConfig.BUILD_HOST_IS_WINDOWS) { Matcher matcher = pattern.matcher(value); if (matcher.find()) { return Integer.valueOf(matcher.group()); } } else { int val = 0; try { int start = -1, end; for (end = 0; end < value.length(); ++end) { char character = value.charAt(end); boolean allowedChar = character == '-' || character >= '0' && character <= '9'; if (allowedChar && start < 0) { start = end; } else if (!allowedChar && start >= 0) { end++; break; } } if (start >= 0) { String str = value.subSequence(start, end).toString(); // val = parseInt(str); val = Integer.parseInt(str); } } catch (Exception ignore) {} return val; } return 0; } private static int parseInt(final String s) { int num = 0; boolean negative = true; final int len = s.length(); final char ch = s.charAt(0); if (ch == '-') { negative = false; } else { num = '0' - ch; } int i = 1; while (i < len) { num = num * 10 + '0' - s.charAt(i++); } return negative ? -num : num; } public static Long parseLong(String value) { if (value == null) { return 0L; } long val = 0L; try { Matcher matcher = pattern.matcher(value); if (matcher.find()) { String num = matcher.group(0); val = Long.parseLong(num); } } catch (Exception ignore) { } return val; } public static String parseIntToString(String value) { Matcher matcher = pattern.matcher(value); if (matcher.find()) { return matcher.group(0); } return null; } public static String bytesToHex(byte[] bytes) { if (bytes == null) { return ""; } char[] hexChars = new char[bytes.length * 2]; int v; for (int j = 0; j < bytes.length; j++) { v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public static byte[] hexToBytes(String hex) { if (hex == null) { return null; } int len = hex.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16)); } return data; } public static boolean isGoodPrime(byte[] prime, int g) { if (!(g >= 2 && g <= 7)) { return false; } if (prime.length != 256 || prime[0] >= 0) { return false; } BigInteger dhBI = new BigInteger(1, prime); if (g == 2) { // p mod 8 = 7 for g = 2; BigInteger res = dhBI.mod(BigInteger.valueOf(8)); if (res.intValue() != 7) { return false; } } else if (g == 3) { // p mod 3 = 2 for g = 3; BigInteger res = dhBI.mod(BigInteger.valueOf(3)); if (res.intValue() != 2) { return false; } } else if (g == 5) { // p mod 5 = 1 or 4 for g = 5; BigInteger res = dhBI.mod(BigInteger.valueOf(5)); int val = res.intValue(); if (val != 1 && val != 4) { return false; } } else if (g == 6) { // p mod 24 = 19 or 23 for g = 6; BigInteger res = dhBI.mod(BigInteger.valueOf(24)); int val = res.intValue(); if (val != 19 && val != 23) { return false; } } else if (g == 7) { // p mod 7 = 3, 5 or 6 for g = 7. BigInteger res = dhBI.mod(BigInteger.valueOf(7)); int val = res.intValue(); if (val != 3 && val != 5 && val != 6) { return false; } } String hex = bytesToHex(prime); if (hex.equals("C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B")) { return true; } BigInteger dhBI2 = dhBI.subtract(BigInteger.valueOf(1)).divide(BigInteger.valueOf(2)); return !(!dhBI.isProbablePrime(30) || !dhBI2.isProbablePrime(30)); } public static boolean isGoodGaAndGb(BigInteger g_a, BigInteger p) { return !(g_a.compareTo(BigInteger.valueOf(1)) <= 0 || g_a.compareTo(p.subtract(BigInteger.valueOf(1))) >= 0); } public static boolean arraysEquals(byte[] arr1, int offset1, byte[] arr2, int offset2) { if (arr1 == null || arr2 == null || offset1 < 0 || offset2 < 0 || arr1.length - offset1 > arr2.length - offset2 || arr1.length - offset1 < 0 || arr2.length - offset2 < 0) { return false; } boolean result = true; for (int a = offset1; a < arr1.length; a++) { if (arr1[a + offset1] != arr2[a + offset2]) { result = false; } } return result; } public static byte[] computeSHA1(byte[] convertme, int offset, int len) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(convertme, offset, len); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[20]; } public static byte[] computeSHA1(ByteBuffer convertme, int offset, int len) { int oldp = convertme.position(); int oldl = convertme.limit(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); convertme.position(offset); convertme.limit(len); md.update(convertme); return md.digest(); } catch (Exception e) { FileLog.e(e); } finally { convertme.limit(oldl); convertme.position(oldp); } return new byte[20]; } public static byte[] computeSHA1(ByteBuffer convertme) { return computeSHA1(convertme, 0, convertme.limit()); } public static byte[] computeSHA1(byte[] convertme) { return computeSHA1(convertme, 0, convertme.length); } public static byte[] computeSHA256(byte[] convertme) { return computeSHA256(convertme, 0, convertme.length); } public static byte[] computeSHA256(byte[] convertme, int offset, long len) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(convertme, offset, (int) len); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[32]; } public static byte[] computeSHA256(byte[]... args) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); for (int a = 0; a < args.length; a++) { md.update(args[a], 0, args[a].length); } return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[32]; } public static byte[] computeSHA512(byte[] convertme) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computeSHA512(byte[] convertme, byte[] convertme2) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); md.update(convertme2, 0, convertme2.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computePBKDF2(byte[] password, byte[] salt) { byte[] dst = new byte[64]; Utilities.pbkdf2(password, salt, dst, 100000); return dst; } public static byte[] computeSHA512(byte[] convertme, byte[] convertme2, byte[] convertme3) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); md.update(convertme2, 0, convertme2.length); md.update(convertme3, 0, convertme3.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computeSHA256(byte[] b1, int o1, int l1, ByteBuffer b2, int o2, int l2) { int oldp = b2.position(); int oldl = b2.limit(); try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(b1, o1, l1); b2.position(o2); b2.limit(l2); md.update(b2); return md.digest(); } catch (Exception e) { FileLog.e(e); } finally { b2.limit(oldl); b2.position(oldp); } return new byte[32]; } public static long bytesToLong(byte[] bytes) { return ((long) bytes[7] << 56) + (((long) bytes[6] & 0xFF) << 48) + (((long) bytes[5] & 0xFF) << 40) + (((long) bytes[4] & 0xFF) << 32) + (((long) bytes[3] & 0xFF) << 24) + (((long) bytes[2] & 0xFF) << 16) + (((long) bytes[1] & 0xFF) << 8) + ((long) bytes[0] & 0xFF); } public static int bytesToInt(byte[] bytes) { return (((int) bytes[3] & 0xFF) << 24) + (((int) bytes[2] & 0xFF) << 16) + (((int) bytes[1] & 0xFF) << 8) + ((int) bytes[0] & 0xFF); } public static byte[] intToBytes(int value) { return new byte[]{ (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value}; } public static String MD5(String md5) { if (md5 == null) { return null; } try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(AndroidUtilities.getStringBytes(md5)); StringBuilder sb = new StringBuilder(); for (int a = 0; a < array.length; a++) { sb.append(Integer.toHexString((array[a] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { FileLog.e(e); } return null; } public static int clamp(int value, int maxValue, int minValue) { return Math.max(Math.min(value, maxValue), minValue); } public static long clamp(long value, long maxValue, long minValue) { return Math.max(Math.min(value, maxValue), minValue); } public static float clamp(float value, float maxValue, float minValue) { if (Float.isNaN(value)) { return minValue; } if (Float.isInfinite(value)) { return maxValue; } return Math.max(Math.min(value, maxValue), minValue); } public static double clamp(double value, double maxValue, double minValue) { if (Double.isNaN(value)) { return minValue; } if (Double.isInfinite(value)) { return maxValue; } return Math.max(Math.min(value, maxValue), minValue); } public static String generateRandomString() { return generateRandomString(16); } public static String generateRandomString(int chars) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < chars; i++) { sb.append(RANDOM_STRING_CHARS.charAt(fastRandom.nextInt(RANDOM_STRING_CHARS.length()))); } return sb.toString(); } public static String getExtension(String fileName) { int idx = fileName.lastIndexOf('.'); String ext = null; if (idx != -1) { ext = fileName.substring(idx + 1); } if (ext == null) { return null; } ext = ext.toUpperCase(); return ext; } public static interface Callback<T> { public void run(T arg); } public static interface CallbackVoidReturn<ReturnType> { public ReturnType run(); } public static interface Callback0Return<ReturnType> { public ReturnType run(); } public static interface CallbackReturn<Arg, ReturnType> { public ReturnType run(Arg arg); } public static interface Callback2Return<T1, T2, ReturnType> { public ReturnType run(T1 arg, T2 arg2); } public static interface Callback3Return<T1, T2, T3, ReturnType> { public ReturnType run(T1 arg, T2 arg2, T3 arg3); } public static interface Callback2<T, T2> { public void run(T arg, T2 arg2); } public static interface Callback3<T, T2, T3> { public void run(T arg, T2 arg2, T3 arg3); } public static interface Callback4<T, T2, T3, T4> { public void run(T arg, T2 arg2, T3 arg3, T4 arg4); } public static interface Callback4Return<T, T2, T3, T4, ReturnType> { public ReturnType run(T arg, T2 arg2, T3 arg3, T4 arg4); } public static interface Callback5<T, T2, T3, T4, T5> { public void run(T arg, T2 arg2, T3 arg3, T4 arg4, T5 arg5); } public static interface Callback5Return<T, T2, T3, T4, T5, ReturnType> { public ReturnType run(T arg, T2 arg2, T3 arg3, T4 arg4, T5 arg5); } public static interface IndexedConsumer<T> { void accept(T t, int index); } public static <Key, Value> Value getOrDefault(HashMap<Key, Value> map, Key key, Value defaultValue) { Value v = map.get(key); if (v == null) { return defaultValue; } return v; } public static void doCallbacks(Utilities.Callback<Runnable> ...actions) { doCallbacks(0, actions); } private static void doCallbacks(int i, Utilities.Callback<Runnable> ...actions) { if (actions != null && actions.length > i) { actions[i].run(() -> doCallbacks(i + 1, actions)); } } public static void raceCallbacks(Runnable onFinish, Utilities.Callback<Runnable> ...actions) { if (actions == null || actions.length == 0) { if (onFinish != null) { onFinish.run(); } return; } final int[] finished = new int[] { 0 }; Runnable checkFinish = () -> { finished[0]++; if (finished[0] == actions.length) { if (onFinish != null) { onFinish.run(); } } }; for (int i = 0; i < actions.length; ++i) { actions[i].run(checkFinish); } } public static DispatchQueue getOrCreatePlayerQueue() { if (videoPlayerQueue == null) { videoPlayerQueue = new DispatchQueue("playerQueue"); } return videoPlayerQueue; } public static boolean isNullOrEmpty(final Collection<?> list) { return list == null || list.isEmpty(); } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java
7,609
// val = parseInt(str);
line_comment
nl
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import com.carrotsearch.randomizedtesting.Xoroshiro128PlusRandom; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Utilities { public static Pattern pattern = Pattern.compile("[\\-0-9]+"); public static SecureRandom random = new SecureRandom(); public static Random fastRandom = new Xoroshiro128PlusRandom(random.nextLong()); public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue"); public static volatile DispatchQueue globalQueue = new DispatchQueue("globalQueue"); public static volatile DispatchQueue cacheClearQueue = new DispatchQueue("cacheClearQueue"); public static volatile DispatchQueue searchQueue = new DispatchQueue("searchQueue"); public static volatile DispatchQueue phoneBookQueue = new DispatchQueue("phoneBookQueue"); public static volatile DispatchQueue themeQueue = new DispatchQueue("themeQueue"); public static volatile DispatchQueue externalNetworkQueue = new DispatchQueue("externalNetworkQueue"); public static volatile DispatchQueue videoPlayerQueue; private final static String RANDOM_STRING_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); static { try { File URANDOM_FILE = new File("/dev/urandom"); FileInputStream sUrandomIn = new FileInputStream(URANDOM_FILE); byte[] buffer = new byte[1024]; sUrandomIn.read(buffer); sUrandomIn.close(); random.setSeed(buffer); } catch (Exception e) { FileLog.e(e); } } public native static int pinBitmap(Bitmap bitmap); public native static void unpinBitmap(Bitmap bitmap); public native static void blurBitmap(Object bitmap, int radius, int unpin, int width, int height, int stride); public native static int needInvert(Object bitmap, int unpin, int width, int height, int stride); public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer, ByteBuffer calcBuffer); public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin); public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap); private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); private native static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); public native static void aesCtrDecryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length); public native static void aesCtrDecryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, long length, int n); private native static void aesCbcEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt); public native static void aesCbcEncryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length, int encrypt); public native static String readlink(String path); public native static String readlinkFd(int fd); public native static long getDirSize(String path, int docType, boolean subdirs); public native static long getLastUsageFileTime(String path); public native static void clearDir(String path, int docType, long time, boolean subdirs); private native static int pbkdf2(byte[] password, byte[] salt, byte[] dst, int iterations); public static native void stackBlurBitmap(Bitmap bitmap, int radius); public static native void drawDitheredGradient(Bitmap bitmap, int[] colors, int startX, int startY, int endX, int endY); public static native int saveProgressiveJpeg(Bitmap bitmap, int width, int height, int stride, int quality, String path); public static native void generateGradient(Bitmap bitmap, boolean unpin, int phase, float progress, int width, int height, int stride, int[] colors); public static native void setupNativeCrashesListener(String path); public static Bitmap stackBlurBitmapMax(Bitmap bitmap) { return stackBlurBitmapMax(bitmap, false); } public static Bitmap stackBlurBitmapMax(Bitmap bitmap, boolean round) { int w = AndroidUtilities.dp(20); int h = (int) (AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth()); Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(scaledBitmap); canvas.save(); canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight()); if (round) { Path path = new Path(); path.addCircle(bitmap.getWidth() / 2f, bitmap.getHeight() / 2f, Math.min(bitmap.getWidth(), bitmap.getHeight()) / 2f - 1, Path.Direction.CW); canvas.clipPath(path); } canvas.drawBitmap(bitmap, 0, 0, null); canvas.restore(); Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150)); return scaledBitmap; } public static Bitmap stackBlurBitmapWithScaleFactor(Bitmap bitmap, float scaleFactor) { int w = (int) Math.max(AndroidUtilities.dp(20), bitmap.getWidth() / scaleFactor); int h = (int) Math.max(AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth(), bitmap.getHeight() / scaleFactor); Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(scaledBitmap); canvas.save(); canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight()); canvas.drawBitmap(bitmap, 0, 0, null); canvas.restore(); Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150)); return scaledBitmap; } public static Bitmap blurWallpaper(Bitmap src) { if (src == null) { return null; } Bitmap b; if (src.getHeight() > src.getWidth()) { b = Bitmap.createBitmap(Math.round(450f * src.getWidth() / src.getHeight()), 450, Bitmap.Config.ARGB_8888); } else { b = Bitmap.createBitmap(450, Math.round(450f * src.getHeight() / src.getWidth()), Bitmap.Config.ARGB_8888); } Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); Rect rect = new Rect(0, 0, b.getWidth(), b.getHeight()); new Canvas(b).drawBitmap(src, null, rect, paint); stackBlurBitmap(b, 12); return b; } public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length); } public static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { aesIgeEncryptionByteArray(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length); } public static void aesCbcEncryptionByteArraySafe(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt) { aesCbcEncryptionByteArray(buffer, key, iv.clone(), offset, length, n, encrypt); } public static Integer parseInt(CharSequence value) { if (value == null) { return 0; } if (BuildConfig.BUILD_HOST_IS_WINDOWS) { Matcher matcher = pattern.matcher(value); if (matcher.find()) { return Integer.valueOf(matcher.group()); } } else { int val = 0; try { int start = -1, end; for (end = 0; end < value.length(); ++end) { char character = value.charAt(end); boolean allowedChar = character == '-' || character >= '0' && character <= '9'; if (allowedChar && start < 0) { start = end; } else if (!allowedChar && start >= 0) { end++; break; } } if (start >= 0) { String str = value.subSequence(start, end).toString(); // val =<SUF> val = Integer.parseInt(str); } } catch (Exception ignore) {} return val; } return 0; } private static int parseInt(final String s) { int num = 0; boolean negative = true; final int len = s.length(); final char ch = s.charAt(0); if (ch == '-') { negative = false; } else { num = '0' - ch; } int i = 1; while (i < len) { num = num * 10 + '0' - s.charAt(i++); } return negative ? -num : num; } public static Long parseLong(String value) { if (value == null) { return 0L; } long val = 0L; try { Matcher matcher = pattern.matcher(value); if (matcher.find()) { String num = matcher.group(0); val = Long.parseLong(num); } } catch (Exception ignore) { } return val; } public static String parseIntToString(String value) { Matcher matcher = pattern.matcher(value); if (matcher.find()) { return matcher.group(0); } return null; } public static String bytesToHex(byte[] bytes) { if (bytes == null) { return ""; } char[] hexChars = new char[bytes.length * 2]; int v; for (int j = 0; j < bytes.length; j++) { v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public static byte[] hexToBytes(String hex) { if (hex == null) { return null; } int len = hex.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16)); } return data; } public static boolean isGoodPrime(byte[] prime, int g) { if (!(g >= 2 && g <= 7)) { return false; } if (prime.length != 256 || prime[0] >= 0) { return false; } BigInteger dhBI = new BigInteger(1, prime); if (g == 2) { // p mod 8 = 7 for g = 2; BigInteger res = dhBI.mod(BigInteger.valueOf(8)); if (res.intValue() != 7) { return false; } } else if (g == 3) { // p mod 3 = 2 for g = 3; BigInteger res = dhBI.mod(BigInteger.valueOf(3)); if (res.intValue() != 2) { return false; } } else if (g == 5) { // p mod 5 = 1 or 4 for g = 5; BigInteger res = dhBI.mod(BigInteger.valueOf(5)); int val = res.intValue(); if (val != 1 && val != 4) { return false; } } else if (g == 6) { // p mod 24 = 19 or 23 for g = 6; BigInteger res = dhBI.mod(BigInteger.valueOf(24)); int val = res.intValue(); if (val != 19 && val != 23) { return false; } } else if (g == 7) { // p mod 7 = 3, 5 or 6 for g = 7. BigInteger res = dhBI.mod(BigInteger.valueOf(7)); int val = res.intValue(); if (val != 3 && val != 5 && val != 6) { return false; } } String hex = bytesToHex(prime); if (hex.equals("C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B")) { return true; } BigInteger dhBI2 = dhBI.subtract(BigInteger.valueOf(1)).divide(BigInteger.valueOf(2)); return !(!dhBI.isProbablePrime(30) || !dhBI2.isProbablePrime(30)); } public static boolean isGoodGaAndGb(BigInteger g_a, BigInteger p) { return !(g_a.compareTo(BigInteger.valueOf(1)) <= 0 || g_a.compareTo(p.subtract(BigInteger.valueOf(1))) >= 0); } public static boolean arraysEquals(byte[] arr1, int offset1, byte[] arr2, int offset2) { if (arr1 == null || arr2 == null || offset1 < 0 || offset2 < 0 || arr1.length - offset1 > arr2.length - offset2 || arr1.length - offset1 < 0 || arr2.length - offset2 < 0) { return false; } boolean result = true; for (int a = offset1; a < arr1.length; a++) { if (arr1[a + offset1] != arr2[a + offset2]) { result = false; } } return result; } public static byte[] computeSHA1(byte[] convertme, int offset, int len) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(convertme, offset, len); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[20]; } public static byte[] computeSHA1(ByteBuffer convertme, int offset, int len) { int oldp = convertme.position(); int oldl = convertme.limit(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); convertme.position(offset); convertme.limit(len); md.update(convertme); return md.digest(); } catch (Exception e) { FileLog.e(e); } finally { convertme.limit(oldl); convertme.position(oldp); } return new byte[20]; } public static byte[] computeSHA1(ByteBuffer convertme) { return computeSHA1(convertme, 0, convertme.limit()); } public static byte[] computeSHA1(byte[] convertme) { return computeSHA1(convertme, 0, convertme.length); } public static byte[] computeSHA256(byte[] convertme) { return computeSHA256(convertme, 0, convertme.length); } public static byte[] computeSHA256(byte[] convertme, int offset, long len) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(convertme, offset, (int) len); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[32]; } public static byte[] computeSHA256(byte[]... args) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); for (int a = 0; a < args.length; a++) { md.update(args[a], 0, args[a].length); } return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[32]; } public static byte[] computeSHA512(byte[] convertme) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computeSHA512(byte[] convertme, byte[] convertme2) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); md.update(convertme2, 0, convertme2.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computePBKDF2(byte[] password, byte[] salt) { byte[] dst = new byte[64]; Utilities.pbkdf2(password, salt, dst, 100000); return dst; } public static byte[] computeSHA512(byte[] convertme, byte[] convertme2, byte[] convertme3) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); md.update(convertme2, 0, convertme2.length); md.update(convertme3, 0, convertme3.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computeSHA256(byte[] b1, int o1, int l1, ByteBuffer b2, int o2, int l2) { int oldp = b2.position(); int oldl = b2.limit(); try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(b1, o1, l1); b2.position(o2); b2.limit(l2); md.update(b2); return md.digest(); } catch (Exception e) { FileLog.e(e); } finally { b2.limit(oldl); b2.position(oldp); } return new byte[32]; } public static long bytesToLong(byte[] bytes) { return ((long) bytes[7] << 56) + (((long) bytes[6] & 0xFF) << 48) + (((long) bytes[5] & 0xFF) << 40) + (((long) bytes[4] & 0xFF) << 32) + (((long) bytes[3] & 0xFF) << 24) + (((long) bytes[2] & 0xFF) << 16) + (((long) bytes[1] & 0xFF) << 8) + ((long) bytes[0] & 0xFF); } public static int bytesToInt(byte[] bytes) { return (((int) bytes[3] & 0xFF) << 24) + (((int) bytes[2] & 0xFF) << 16) + (((int) bytes[1] & 0xFF) << 8) + ((int) bytes[0] & 0xFF); } public static byte[] intToBytes(int value) { return new byte[]{ (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value}; } public static String MD5(String md5) { if (md5 == null) { return null; } try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(AndroidUtilities.getStringBytes(md5)); StringBuilder sb = new StringBuilder(); for (int a = 0; a < array.length; a++) { sb.append(Integer.toHexString((array[a] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { FileLog.e(e); } return null; } public static int clamp(int value, int maxValue, int minValue) { return Math.max(Math.min(value, maxValue), minValue); } public static long clamp(long value, long maxValue, long minValue) { return Math.max(Math.min(value, maxValue), minValue); } public static float clamp(float value, float maxValue, float minValue) { if (Float.isNaN(value)) { return minValue; } if (Float.isInfinite(value)) { return maxValue; } return Math.max(Math.min(value, maxValue), minValue); } public static double clamp(double value, double maxValue, double minValue) { if (Double.isNaN(value)) { return minValue; } if (Double.isInfinite(value)) { return maxValue; } return Math.max(Math.min(value, maxValue), minValue); } public static String generateRandomString() { return generateRandomString(16); } public static String generateRandomString(int chars) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < chars; i++) { sb.append(RANDOM_STRING_CHARS.charAt(fastRandom.nextInt(RANDOM_STRING_CHARS.length()))); } return sb.toString(); } public static String getExtension(String fileName) { int idx = fileName.lastIndexOf('.'); String ext = null; if (idx != -1) { ext = fileName.substring(idx + 1); } if (ext == null) { return null; } ext = ext.toUpperCase(); return ext; } public static interface Callback<T> { public void run(T arg); } public static interface CallbackVoidReturn<ReturnType> { public ReturnType run(); } public static interface Callback0Return<ReturnType> { public ReturnType run(); } public static interface CallbackReturn<Arg, ReturnType> { public ReturnType run(Arg arg); } public static interface Callback2Return<T1, T2, ReturnType> { public ReturnType run(T1 arg, T2 arg2); } public static interface Callback3Return<T1, T2, T3, ReturnType> { public ReturnType run(T1 arg, T2 arg2, T3 arg3); } public static interface Callback2<T, T2> { public void run(T arg, T2 arg2); } public static interface Callback3<T, T2, T3> { public void run(T arg, T2 arg2, T3 arg3); } public static interface Callback4<T, T2, T3, T4> { public void run(T arg, T2 arg2, T3 arg3, T4 arg4); } public static interface Callback4Return<T, T2, T3, T4, ReturnType> { public ReturnType run(T arg, T2 arg2, T3 arg3, T4 arg4); } public static interface Callback5<T, T2, T3, T4, T5> { public void run(T arg, T2 arg2, T3 arg3, T4 arg4, T5 arg5); } public static interface Callback5Return<T, T2, T3, T4, T5, ReturnType> { public ReturnType run(T arg, T2 arg2, T3 arg3, T4 arg4, T5 arg5); } public static interface IndexedConsumer<T> { void accept(T t, int index); } public static <Key, Value> Value getOrDefault(HashMap<Key, Value> map, Key key, Value defaultValue) { Value v = map.get(key); if (v == null) { return defaultValue; } return v; } public static void doCallbacks(Utilities.Callback<Runnable> ...actions) { doCallbacks(0, actions); } private static void doCallbacks(int i, Utilities.Callback<Runnable> ...actions) { if (actions != null && actions.length > i) { actions[i].run(() -> doCallbacks(i + 1, actions)); } } public static void raceCallbacks(Runnable onFinish, Utilities.Callback<Runnable> ...actions) { if (actions == null || actions.length == 0) { if (onFinish != null) { onFinish.run(); } return; } final int[] finished = new int[] { 0 }; Runnable checkFinish = () -> { finished[0]++; if (finished[0] == actions.length) { if (onFinish != null) { onFinish.run(); } } }; for (int i = 0; i < actions.length; ++i) { actions[i].run(checkFinish); } } public static DispatchQueue getOrCreatePlayerQueue() { if (videoPlayerQueue == null) { videoPlayerQueue = new DispatchQueue("playerQueue"); } return videoPlayerQueue; } public static boolean isNullOrEmpty(final Collection<?> list) { return list == null || list.isEmpty(); } }
105989_39
/* * This file is part of Encom. * * Encom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Encom 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 Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Encom. If not, see <http://www.gnu.org/licenses/>. */ package languages; import com.aionemu.gameserver.utils.i18n.CustomMessageId; import com.aionemu.gameserver.utils.i18n.Language; /** * @author Eloann */ public class German extends Language { public German() { super("de"); addSupportedLanguage("de_DE"); addTranslatedMessage(CustomMessageId.SERVER_REVISION, "Server Version : %-6s"); addTranslatedMessage(CustomMessageId.WELCOME_PREMIUM, "Willkommen bei "); addTranslatedMessage(CustomMessageId.WELCOME_REGULAR, "Willkommen bei "); addTranslatedMessage(CustomMessageId.WELCOME_BASIC, "Willkommen bei "); addTranslatedMessage(CustomMessageId.INFO1, "Warnung: Benutzung von fremde software, wie (speed hack&Co ist strengst verboten."); addTranslatedMessage(CustomMessageId.INFO2, "Hinweis: Je nach Fall, fuehrt ausnahmslos zu unbefristete Account Sperrung."); addTranslatedMessage(CustomMessageId.INFO3, "Warnung: Werben anderer Aion Server oder abwerben von Spieler hier auf dem Server, ist untersagt."); addTranslatedMessage(CustomMessageId.INFO4, "Anmerkung: Das Team wird Sie niemals nach Ihrem Account Passwort fragen!"); addTranslatedMessage(CustomMessageId.INFO5, "Chat: Benutze .faction, .ely, ,asmo <text> um im Chat zu schreiben. "); addTranslatedMessage(CustomMessageId.INFO6, "Chat: Benutze /1 /2 /3, um in den Chatkanaelen zu schreiben."); addTranslatedMessage(CustomMessageId.INFO7, "Befehle: Benutze .help, um zu sehen welche Spielerbefehle noch zur Verfuegung stehen."); addTranslatedMessage(CustomMessageId.SERVERVERSION, "Supported NCSoft Version "); addTranslatedMessage(CustomMessageId.ENDMESSAGE, "Viel Spass auf unserem Server: "); addTranslatedMessage(CustomMessageId.ANNOUNCE_GM_CONNECTION, " Ist jetzt fuer den Support verfuegbar!"); addTranslatedMessage(CustomMessageId.ANNOUNCE_GM_DECONNECTION, " Ist fuer den Support nicht mehr verfuegbar!"); addTranslatedMessage(CustomMessageId.ANNOUNCE_MEMBER_CONNECTION, "%s ist der Welt von Atreia beigetreten."); addTranslatedMessage(CustomMessageId.COMMAND_NOT_ENOUGH_RIGHTS, "Sie haben keine Berechtigung zur Verwendung dieses Befehls"); addTranslatedMessage(CustomMessageId.PLAYER_NOT_ONLINE, "Spieler nicht online"); addTranslatedMessage(CustomMessageId.INTEGER_PARAMETER_REQUIRED, "Integer parameter required"); addTranslatedMessage(CustomMessageId.INTEGER_PARAMETERS_ONLY, "Integer parameters only"); addTranslatedMessage(CustomMessageId.SOMETHING_WRONG_HAPPENED, "Etwas ging schief"); addTranslatedMessage(CustomMessageId.COMMAND_DISABLED, "Befehl deaktiviert"); addTranslatedMessage(CustomMessageId.COMMAND_ADD_SYNTAX, "Syntax: //add <player name> <itemid> [<amount>]"); addTranslatedMessage(CustomMessageId.COMMAND_ADD_ADMIN_SUCCESS, "Item erfolgreich dem Spieler %s hinzugefuegt "); addTranslatedMessage(CustomMessageId.COMMAND_ADD_PLAYER_SUCCESS, "Administrator %s give you %d item(s)"); addTranslatedMessage(CustomMessageId.COMMAND_ADD_FAILURE, "Item %d not exist or cant be added %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDDROP_SYNTAX, "Syntax: //adddrop <npc id> <itemid> <min> <max> <chance>"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_SYNTAX, "Syntax: //addset <player name> <id set>"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_SET_DOES_NOT_EXISTS, "Set %d not exist"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_NOT_ENOUGH_SLOTS, "Not enough inventory %d slots to add this set"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_CANNOT_ADD_ITEM, "Item %d can not be added to the %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_ADMIN_SUCCESS, "Set %d added success %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_PLAYER_SUCCESS, "%s give you set"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSKILL_SYNTAX, "Syntax: //addskill <skill id> <skill lvl"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSKILL_ADMIN_SUCCESS, "Skill %d added success %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSKILL_PLAYER_SUCCESS, "%s give you skill"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_SYNTAX, "Syntax: //addtitle <title id> <player name> [special]"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_TITLE_INVALID, "Title must be from 1 to 50"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_CANNOT_ADD_TITLE_TO_ME, "Cannot add title %d self"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_CANNOT_ADD_TITLE_TO_PLAYER, "Cannot add title %d to %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_ADMIN_SUCCESS_ME, "Title %d added success self"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_ADMIN_SUCCESS, "You success added title %d to player %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_PLAYER_SUCCESS, "%s give you title %d"); addTranslatedMessage(CustomMessageId.COMMAND_SEND_SYNTAX, "Syntax: //send <file name>"); addTranslatedMessage(CustomMessageId.COMMAND_SEND_MAPPING_NOT_FOUND, "%s not found"); addTranslatedMessage(CustomMessageId.COMMAND_SEND_NO_PACKET, "Send no packet"); addTranslatedMessage(CustomMessageId.CHANNEL_WORLD_DISABLED, "Channel %s disabled, use channel %s or %s based on your race"); addTranslatedMessage(CustomMessageId.CHANNEL_ALL_DISABLED, "All channels disabled"); addTranslatedMessage(CustomMessageId.CHANNEL_ALREADY_FIXED, "Your channel has been successfully installed %s"); addTranslatedMessage(CustomMessageId.CHANNEL_FIXED, "Installed channel %s"); addTranslatedMessage(CustomMessageId.CHANNEL_NOT_ALLOWED, "You cant use this channel"); addTranslatedMessage(CustomMessageId.CHANNEL_FIXED_BOTH, "Installed channels %s and %s"); addTranslatedMessage(CustomMessageId.CHANNEL_UNFIX_HELP, "Write %s to come out of the channel"); // ;) addTranslatedMessage(CustomMessageId.CHANNEL_NOT_FIXED, "You are not installed on the channel"); addTranslatedMessage(CustomMessageId.CHANNEL_FIXED_OTHER, "Your chat is not installed on this channel, but on %s"); addTranslatedMessage(CustomMessageId.CHANNEL_RELEASED, "You come out of the channel %s"); addTranslatedMessage(CustomMessageId.CHANNEL_RELEASED_BOTH, "You are out of %s and %s"); addTranslatedMessage(CustomMessageId.CHANNEL_BAN_ENDED, "You can rejoin the channels"); addTranslatedMessage(CustomMessageId.CHANNEL_BAN_ENDED_FOR, "Player %s may again join the channel"); addTranslatedMessage(CustomMessageId.CHANNEL_BANNED, "You can not access the channel, because %s ban you because of: %s, left to unlock: %s"); addTranslatedMessage(CustomMessageId.COMMAND_MISSING_SKILLS_STIGMAS_ADDED, "%d skill %d stigma given to you"); addTranslatedMessage(CustomMessageId.COMMAND_MISSING_SKILLS_ADDED, "%d ability given to you"); addTranslatedMessage(CustomMessageId.USER_COMMAND_DOES_NOT_EXIST, "This game command exists"); addTranslatedMessage(CustomMessageId.COMMAND_XP_DISABLED, "Accrual XP disabled. Enter. xpon to unlock"); addTranslatedMessage(CustomMessageId.COMMAND_XP_ALREADY_DISABLED, "Accrual XP disabled"); addTranslatedMessage(CustomMessageId.COMMAND_XP_ENABLED, "Accrual XP enabled"); addTranslatedMessage(CustomMessageId.COMMAND_XP_ALREADY_ENABLED, "Accrual XP already enabled"); addTranslatedMessage(CustomMessageId.DREDGION_LEVEL_TOO_LOW, "Ihr derzeitges Level ist zu niedrig, um in die Dredgion einzutreten."); addTranslatedMessage(CustomMessageId.DEFAULT_FINISH_MESSAGE, "Ende!"); /** * PvP Service */ addTranslatedMessage(CustomMessageId.ADV_WINNER_MSG, "[PvP System] Spieler getoetet "); addTranslatedMessage(CustomMessageId.ADV_LOSER_MSG, "[PvP System] Du wurdest getoetet von "); addTranslatedMessage(CustomMessageId.PLAP_LOST1, "[PL-AP] Du verlierst "); addTranslatedMessage(CustomMessageId.PLAP_LOST2, "% deiner totalen AP"); addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD1, "Du hast "); addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD2, " Toll erhalten."); addTranslatedMessage(CustomMessageId.PVP_NO_REWARD1, "Du bekommst nichts fuer das toeten von "); addTranslatedMessage(CustomMessageId.PVP_NO_REWARD2, " weil du ihn schon zu oft getoetet hast!"); addTranslatedMessage(CustomMessageId.EASY_MITHRIL_MSG, "[Mithril System] du bekamst: "); /** * Reward Service Login Messages */ addTranslatedMessage(CustomMessageId.REWARD10, "Du kannst .start benutzen um eine Level 10 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD30, "Du kannst .start benutzen um eine Level 30 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD40, "Du kannst .start benutzen um eine Level 40 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD50, "Du kannst .start benutzen um eine Level 50 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD60, "Du kannst .start benutzen um eine Level 60 Ausstattung zu bekommen!"); /** * Advanced PvP System */ addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE1, "Heutige PvP Map: Reshanta"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE2, "Heutige PvP Map: Tiamaranta"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE3, "Heutige PvP Map: Inggison/Gelkmaros"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE4, "Heutige PvP Map: Idian Depths"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE5, "Heutige PvP Map: Katalam"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE6, "Heutige PvP Map: Danaria"); /** * Asmo, Ely and World Channel */ addTranslatedMessage(CustomMessageId.ASMO_FAIL, "Du bist Elyos! Du kannst diesen Chat nicht benutzen. Nutze .ely <Nachricht> um im Fraktions Chat zu schreiben!"); addTranslatedMessage(CustomMessageId.ELY_FAIL, "Du bist Asmo! Du kannst diesen Chat nicht benutzen. Nutze .asmo <Nachricht> um im Fraktions Chat zu schreiben!"); /** * Wedding related */ addTranslatedMessage(CustomMessageId.WEDDINGNO1, "Du kannst dieses Kommando nicht waehrend des Kampfes nutzen!"); addTranslatedMessage(CustomMessageId.WEDDINGNO2, "Hochzeit wurde nicht gestartet!"); addTranslatedMessage(CustomMessageId.WEDDINGNO3, "Du hast die Heirat abgelehnt!"); addTranslatedMessage(CustomMessageId.WEDDINGYES, "Du hast die Heirat akzeptiert!"); /** * Clean Command related */ addTranslatedMessage(CustomMessageId.CANNOTCLEAN, "Du musst eine Item Id eingeben oder einen Link posten!"); addTranslatedMessage(CustomMessageId.CANNOTCLEAN2, "Du besitzt dieses Item nicht!"); addTranslatedMessage(CustomMessageId.SUCCESSCLEAN, "Item wurde erfolgreich aus deinem Wuerfel entfernt!"); /** * Mission check command related */ addTranslatedMessage(CustomMessageId.SUCCESCHECKED, "Mission erfolgreich ueberprueft!"); /** * No Exp Command */ addTranslatedMessage(CustomMessageId.EPACTIVATED, "Deine EP wurden wieder aktiviert!"); addTranslatedMessage(CustomMessageId.ACTODE, "Um deine EP zu deaktivieren, nutze .noexp"); addTranslatedMessage(CustomMessageId.EPDEACTIVATED, "Deine EP wurden deaktiviert!"); addTranslatedMessage(CustomMessageId.DETOAC, "Um deine EP zu aktivieren, nutze .noexp"); /** * Auto Quest Command */ addTranslatedMessage(CustomMessageId.WRONGQID, "Bitte gebe eine richtige Quest Id an!"); addTranslatedMessage(CustomMessageId.NOTSTARTED, "Quest konnte nicht gestartet werden!"); addTranslatedMessage(CustomMessageId.NOTSUPPORT, "Diese Quest wird nicht von diesem Kommando unterstuetzt!"); /** * Quest Restart Command */ addTranslatedMessage(CustomMessageId.CANNOTRESTART, "] kann nicht neugestartet werden"); /** * Exchange Toll Command */ addTranslatedMessage(CustomMessageId.TOLLTOBIG, "Du hast zu viele Toll!"); addTranslatedMessage(CustomMessageId.TOLOWAP, "Du hast nicht genug AP!"); addTranslatedMessage(CustomMessageId.TOLOWTOLL, "Du hast nicht genug Toll!"); addTranslatedMessage(CustomMessageId.WRONGTOLLNUM, "Irgendwas lief schief!"); /** * Cube Command */ addTranslatedMessage(CustomMessageId.CUBE_ALLREADY_EXPANDED, "Dein Wuerfel ist voll erweitert!"); addTranslatedMessage(CustomMessageId.CUBE_SUCCESS_EXPAND, "Dein Wuerfel wurde erfolgreich erweitert!"); /** * GMList Command */ addTranslatedMessage(CustomMessageId.ONE_GM_ONLINE, "Ein Team Mitglied ist online: "); addTranslatedMessage(CustomMessageId.MORE_GMS_ONLINE, "Es sind folgende Team Mitglieder online: "); addTranslatedMessage(CustomMessageId.NO_GM_ONLINE, "Es ist kein Team Mitglied online!"); /** * Go Command (PvP Command) */ addTranslatedMessage(CustomMessageId.NOT_USE_WHILE_FIGHT, "Du kannst dieses Kommando nicht waehrend des Kampfes nutzen!"); addTranslatedMessage(CustomMessageId.NOT_USE_ON_PVP_MAP, "Du kannst dieses Kommando nicht auf einer PvP Map benutzen!"); addTranslatedMessage(CustomMessageId.LEVEL_TOO_LOW, "Du kannst dieses Kommando nur mit Level 55 oder hoeher nutzen!"); /** * Paint Command */ addTranslatedMessage(CustomMessageId.WRONG_TARGET, "Bitte benutze ein erlaubtes Ziel!"); /** * Shiva Command */ addTranslatedMessage(CustomMessageId.ENCHANT_SUCCES, "Alle deine Items wurden verzaubert auf: "); addTranslatedMessage(CustomMessageId.ENCHANT_INFO, "Info: Dieses Kommando verzaubert alle deine Items auf <value>!"); addTranslatedMessage(CustomMessageId.ENCHANT_SAMPLE, "Beispiel: (.eq 15) wuerde alle deine Items auf 15 verzaubern"); /** * Userinfo Command */ addTranslatedMessage(CustomMessageId.CANNOT_SPY_PLAYER, "Du kannst keine Infos von anderen Spielern bekommen!"); /** * Check AFK Status */ addTranslatedMessage(CustomMessageId.KICKED_AFK_OUT, "You have been kicked out for being inactive too long."); /** * Exchange Command */ addTranslatedMessage(CustomMessageId.NOT_ENOUGH_ITEM, "Sie besitzen nicht genug von: "); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_AP, "Sie besitzen nicht genug AP, Sie haben nur: "); /** * Medal Command */ addTranslatedMessage(CustomMessageId.NOT_ENOUGH_SILVER, "Sie besitzen nicht genug Silber Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_GOLD, "Sie besitzen nicht genug Gold Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_PLATIN, "Sie besitzen nicht genug Platin Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_MITHRIL, "Sie besitzen nicht genug Mithril Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_AP2, "Sie besitzen nicht genug AP, Sie benoetigen: "); addTranslatedMessage(CustomMessageId.EXCHANGE_SILVER, "You have exchange [item:186000031] to [item:186000030]."); addTranslatedMessage(CustomMessageId.EXCHANGE_GOLD, "You have exchange [item:186000030] to [item:186000096]."); addTranslatedMessage(CustomMessageId.EXCHANGE_PLATIN, "You have exchange [item:186000096] to [item:186000147]."); addTranslatedMessage(CustomMessageId.EXCHANGE_MITHRIL, "You have exchange [item:186000147] to [item:186000223]."); addTranslatedMessage(CustomMessageId.EX_SILVER_INFO, "\nSyntax: .medal silver - Exchange Silver to Gold."); addTranslatedMessage(CustomMessageId.EX_GOLD_INFO, "\nSyntax: .medal gold - Exchange Gold to Platin."); addTranslatedMessage(CustomMessageId.EX_PLATIN_INFO, "\nSyntax: .medal platinum - Exchnage Platin to Mithril."); addTranslatedMessage(CustomMessageId.EX_MITHRIL_INFO, "\nSyntax: .medal mithril - Exchange Mithril to Honorable Mithril."); /** * Legendary Raid Spawn Events */ addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_SPAWNED_ASMO, "[Spawn Event] Ragnarok ist fuer die Asmodier in Beluslan erschienen!"); addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_SPAWNED_ELYOS, "[Spawn Event] Omega ist fuer die Elyos in Heiron erschienen!"); addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_DESPAWNED_ASMO, "[Spawn Event] Ragnarok ist verschwunden, niemand hat ihn getoetet!"); addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_DESPAWNED_ELYOS, "[Spawn Event] Omega ist verschwunden, niemand hat ihn getoetet!"); /** * HonorItems Command */ addTranslatedMessage(CustomMessageId.PLATE_ARMOR, "Platten Ruestung"); addTranslatedMessage(CustomMessageId.LEATHER_ARMOR, "Leder Ruestung"); addTranslatedMessage(CustomMessageId.CLOTH_ARMOR, "Stoff Ruestung"); addTranslatedMessage(CustomMessageId.CHAIN_ARMOR, "Ketten Ruestung"); addTranslatedMessage(CustomMessageId.WEAPONS, "Waffen"); addTranslatedMessage(CustomMessageId.PLATE_ARMOR_PRICES, "Platten ruestungs Preis"); addTranslatedMessage(CustomMessageId.LEATHER_ARMOR_PRICES, "Leder Ruestungs Preis"); addTranslatedMessage(CustomMessageId.CLOTH_ARMOR_PRICES, "Stoff Ruestung Preis"); addTranslatedMessage(CustomMessageId.CHAIN_ARMOR_PRICES, "Ketten Ruestungs Preis"); addTranslatedMessage(CustomMessageId.WEAPONS_PRICES, "Waffen Preis"); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_MEDALS, "Sie besitzen nicht genuegend Medaillen, Sie benoetigen: "); addTranslatedMessage(CustomMessageId.PLATE_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 1"); addTranslatedMessage(CustomMessageId.LEATHER_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 6"); addTranslatedMessage(CustomMessageId.CLOTH_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 11"); addTranslatedMessage(CustomMessageId.CHAIN_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 16"); addTranslatedMessage(CustomMessageId.WEAPONS_USE_INFO, "Use .items and the equal ID (Example: .items 21"); addTranslatedMessage(CustomMessageId.SUCCESSFULLY_TRADED, "You got successfully your Trade!"); /** * Moltenus Announce */ addTranslatedMessage(CustomMessageId.MOLTENUS_APPEAR, "Moltenus Fragment of the Wrath ist im Abyss erschienen."); addTranslatedMessage(CustomMessageId.MOLTENUS_DISAPPEAR, "Moltenus Fragment of the Wrath ist verschwunden."); /** * Dredgion Announce */ addTranslatedMessage(CustomMessageId.DREDGION_ASMO_GROUP, "An asmodian group is waiting for dredgion."); addTranslatedMessage(CustomMessageId.DREDGION_ELYOS_GROUP, "An elyos group is waiting for dredgion."); addTranslatedMessage(CustomMessageId.DREDGION_ASMO, "An alone asmodian is waiting for dredgion."); addTranslatedMessage(CustomMessageId.DREDGION_ELYOS, "An alone elyos is waiting for dredgion."); /** * PvP Service */ addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD1, "Sie haben verdient"); addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD2, " Abyss Punkte."); /** * Invasion Rift */ addTranslatedMessage(CustomMessageId.INVASION_RIFT_MIN_LEVEL, "Dein Level ist zu niedrig um zu passieren."); addTranslatedMessage(CustomMessageId.INVASION_RIFT_ELYOS, "A rift for Pandaemonium is open at Ingisson"); addTranslatedMessage(CustomMessageId.INVASION_RIFT_ASMOS, "A rift for Sanctum is open at Gelkmaros"); /** * PvP Spree Service */ addTranslatedMessage(CustomMessageId.SPREE1, "Blutiger Sturm"); addTranslatedMessage(CustomMessageId.SPREE2, "Blutbad"); addTranslatedMessage(CustomMessageId.SPREE3, "Voelkermord"); addTranslatedMessage(CustomMessageId.KILL_COUNT, "Kills in Folge: "); addTranslatedMessage(CustomMessageId.CUSTOM_MSG1, " von "); addTranslatedMessage(CustomMessageId.MSG_SPREE1, " hat begonnen ein "); addTranslatedMessage(CustomMessageId.MSG_SPREE1_1, " !"); addTranslatedMessage(CustomMessageId.MSG_SPREE2, " fuehrt eine echte "); addTranslatedMessage(CustomMessageId.MSG_SPREE2_1, " ! Haltet ihn schnell !"); addTranslatedMessage(CustomMessageId.MSG_SPREE3, " tut ein "); addTranslatedMessage(CustomMessageId.MSG_SPREE3_1, " ! Lauf weg, wenn du kannst!"); addTranslatedMessage(CustomMessageId.SPREE_END_MSG1, "Der Amoklauf von "); addTranslatedMessage(CustomMessageId.SPREE_END_MSG2, " wurde gestoppt von "); addTranslatedMessage(CustomMessageId.SPREE_END_MSG3, " nach "); addTranslatedMessage(CustomMessageId.SPREE_END_MSG4, " ununterbrochene Morde !"); addTranslatedMessage(CustomMessageId.SPREE_MONSTER_MSG, "ein Monster"); /** * EventEngine - EventUtil */ // addTranslatedMessage(CustomMessageId.Event_Util_1, "Du kannst diesen Befehl nicht verwenden."); // addTranslatedMessage(CustomMessageId.Event_Util_2, "Falsche Event Typ."); // addTranslatedMessage(CustomMessageId.Event_Util_3, "Unbekannter Benutzer."); /** * EventEngine - Event */ // addTranslatedMessage(CustomMessageId.Event_1, "Du kannst an diesem Event nicht teilnehmen, waehrend du im Gefaengnis bist, oder in Kampfzustand."); } }
DragonicK/AionEmu5.8
AL-Game/data/scripts/system/handlers/languages/German.java
7,150
/** * EventEngine - Event */
block_comment
nl
/* * This file is part of Encom. * * Encom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Encom 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 Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Encom. If not, see <http://www.gnu.org/licenses/>. */ package languages; import com.aionemu.gameserver.utils.i18n.CustomMessageId; import com.aionemu.gameserver.utils.i18n.Language; /** * @author Eloann */ public class German extends Language { public German() { super("de"); addSupportedLanguage("de_DE"); addTranslatedMessage(CustomMessageId.SERVER_REVISION, "Server Version : %-6s"); addTranslatedMessage(CustomMessageId.WELCOME_PREMIUM, "Willkommen bei "); addTranslatedMessage(CustomMessageId.WELCOME_REGULAR, "Willkommen bei "); addTranslatedMessage(CustomMessageId.WELCOME_BASIC, "Willkommen bei "); addTranslatedMessage(CustomMessageId.INFO1, "Warnung: Benutzung von fremde software, wie (speed hack&Co ist strengst verboten."); addTranslatedMessage(CustomMessageId.INFO2, "Hinweis: Je nach Fall, fuehrt ausnahmslos zu unbefristete Account Sperrung."); addTranslatedMessage(CustomMessageId.INFO3, "Warnung: Werben anderer Aion Server oder abwerben von Spieler hier auf dem Server, ist untersagt."); addTranslatedMessage(CustomMessageId.INFO4, "Anmerkung: Das Team wird Sie niemals nach Ihrem Account Passwort fragen!"); addTranslatedMessage(CustomMessageId.INFO5, "Chat: Benutze .faction, .ely, ,asmo <text> um im Chat zu schreiben. "); addTranslatedMessage(CustomMessageId.INFO6, "Chat: Benutze /1 /2 /3, um in den Chatkanaelen zu schreiben."); addTranslatedMessage(CustomMessageId.INFO7, "Befehle: Benutze .help, um zu sehen welche Spielerbefehle noch zur Verfuegung stehen."); addTranslatedMessage(CustomMessageId.SERVERVERSION, "Supported NCSoft Version "); addTranslatedMessage(CustomMessageId.ENDMESSAGE, "Viel Spass auf unserem Server: "); addTranslatedMessage(CustomMessageId.ANNOUNCE_GM_CONNECTION, " Ist jetzt fuer den Support verfuegbar!"); addTranslatedMessage(CustomMessageId.ANNOUNCE_GM_DECONNECTION, " Ist fuer den Support nicht mehr verfuegbar!"); addTranslatedMessage(CustomMessageId.ANNOUNCE_MEMBER_CONNECTION, "%s ist der Welt von Atreia beigetreten."); addTranslatedMessage(CustomMessageId.COMMAND_NOT_ENOUGH_RIGHTS, "Sie haben keine Berechtigung zur Verwendung dieses Befehls"); addTranslatedMessage(CustomMessageId.PLAYER_NOT_ONLINE, "Spieler nicht online"); addTranslatedMessage(CustomMessageId.INTEGER_PARAMETER_REQUIRED, "Integer parameter required"); addTranslatedMessage(CustomMessageId.INTEGER_PARAMETERS_ONLY, "Integer parameters only"); addTranslatedMessage(CustomMessageId.SOMETHING_WRONG_HAPPENED, "Etwas ging schief"); addTranslatedMessage(CustomMessageId.COMMAND_DISABLED, "Befehl deaktiviert"); addTranslatedMessage(CustomMessageId.COMMAND_ADD_SYNTAX, "Syntax: //add <player name> <itemid> [<amount>]"); addTranslatedMessage(CustomMessageId.COMMAND_ADD_ADMIN_SUCCESS, "Item erfolgreich dem Spieler %s hinzugefuegt "); addTranslatedMessage(CustomMessageId.COMMAND_ADD_PLAYER_SUCCESS, "Administrator %s give you %d item(s)"); addTranslatedMessage(CustomMessageId.COMMAND_ADD_FAILURE, "Item %d not exist or cant be added %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDDROP_SYNTAX, "Syntax: //adddrop <npc id> <itemid> <min> <max> <chance>"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_SYNTAX, "Syntax: //addset <player name> <id set>"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_SET_DOES_NOT_EXISTS, "Set %d not exist"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_NOT_ENOUGH_SLOTS, "Not enough inventory %d slots to add this set"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_CANNOT_ADD_ITEM, "Item %d can not be added to the %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_ADMIN_SUCCESS, "Set %d added success %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSET_PLAYER_SUCCESS, "%s give you set"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSKILL_SYNTAX, "Syntax: //addskill <skill id> <skill lvl"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSKILL_ADMIN_SUCCESS, "Skill %d added success %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDSKILL_PLAYER_SUCCESS, "%s give you skill"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_SYNTAX, "Syntax: //addtitle <title id> <player name> [special]"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_TITLE_INVALID, "Title must be from 1 to 50"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_CANNOT_ADD_TITLE_TO_ME, "Cannot add title %d self"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_CANNOT_ADD_TITLE_TO_PLAYER, "Cannot add title %d to %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_ADMIN_SUCCESS_ME, "Title %d added success self"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_ADMIN_SUCCESS, "You success added title %d to player %s"); addTranslatedMessage(CustomMessageId.COMMAND_ADDTITLE_PLAYER_SUCCESS, "%s give you title %d"); addTranslatedMessage(CustomMessageId.COMMAND_SEND_SYNTAX, "Syntax: //send <file name>"); addTranslatedMessage(CustomMessageId.COMMAND_SEND_MAPPING_NOT_FOUND, "%s not found"); addTranslatedMessage(CustomMessageId.COMMAND_SEND_NO_PACKET, "Send no packet"); addTranslatedMessage(CustomMessageId.CHANNEL_WORLD_DISABLED, "Channel %s disabled, use channel %s or %s based on your race"); addTranslatedMessage(CustomMessageId.CHANNEL_ALL_DISABLED, "All channels disabled"); addTranslatedMessage(CustomMessageId.CHANNEL_ALREADY_FIXED, "Your channel has been successfully installed %s"); addTranslatedMessage(CustomMessageId.CHANNEL_FIXED, "Installed channel %s"); addTranslatedMessage(CustomMessageId.CHANNEL_NOT_ALLOWED, "You cant use this channel"); addTranslatedMessage(CustomMessageId.CHANNEL_FIXED_BOTH, "Installed channels %s and %s"); addTranslatedMessage(CustomMessageId.CHANNEL_UNFIX_HELP, "Write %s to come out of the channel"); // ;) addTranslatedMessage(CustomMessageId.CHANNEL_NOT_FIXED, "You are not installed on the channel"); addTranslatedMessage(CustomMessageId.CHANNEL_FIXED_OTHER, "Your chat is not installed on this channel, but on %s"); addTranslatedMessage(CustomMessageId.CHANNEL_RELEASED, "You come out of the channel %s"); addTranslatedMessage(CustomMessageId.CHANNEL_RELEASED_BOTH, "You are out of %s and %s"); addTranslatedMessage(CustomMessageId.CHANNEL_BAN_ENDED, "You can rejoin the channels"); addTranslatedMessage(CustomMessageId.CHANNEL_BAN_ENDED_FOR, "Player %s may again join the channel"); addTranslatedMessage(CustomMessageId.CHANNEL_BANNED, "You can not access the channel, because %s ban you because of: %s, left to unlock: %s"); addTranslatedMessage(CustomMessageId.COMMAND_MISSING_SKILLS_STIGMAS_ADDED, "%d skill %d stigma given to you"); addTranslatedMessage(CustomMessageId.COMMAND_MISSING_SKILLS_ADDED, "%d ability given to you"); addTranslatedMessage(CustomMessageId.USER_COMMAND_DOES_NOT_EXIST, "This game command exists"); addTranslatedMessage(CustomMessageId.COMMAND_XP_DISABLED, "Accrual XP disabled. Enter. xpon to unlock"); addTranslatedMessage(CustomMessageId.COMMAND_XP_ALREADY_DISABLED, "Accrual XP disabled"); addTranslatedMessage(CustomMessageId.COMMAND_XP_ENABLED, "Accrual XP enabled"); addTranslatedMessage(CustomMessageId.COMMAND_XP_ALREADY_ENABLED, "Accrual XP already enabled"); addTranslatedMessage(CustomMessageId.DREDGION_LEVEL_TOO_LOW, "Ihr derzeitges Level ist zu niedrig, um in die Dredgion einzutreten."); addTranslatedMessage(CustomMessageId.DEFAULT_FINISH_MESSAGE, "Ende!"); /** * PvP Service */ addTranslatedMessage(CustomMessageId.ADV_WINNER_MSG, "[PvP System] Spieler getoetet "); addTranslatedMessage(CustomMessageId.ADV_LOSER_MSG, "[PvP System] Du wurdest getoetet von "); addTranslatedMessage(CustomMessageId.PLAP_LOST1, "[PL-AP] Du verlierst "); addTranslatedMessage(CustomMessageId.PLAP_LOST2, "% deiner totalen AP"); addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD1, "Du hast "); addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD2, " Toll erhalten."); addTranslatedMessage(CustomMessageId.PVP_NO_REWARD1, "Du bekommst nichts fuer das toeten von "); addTranslatedMessage(CustomMessageId.PVP_NO_REWARD2, " weil du ihn schon zu oft getoetet hast!"); addTranslatedMessage(CustomMessageId.EASY_MITHRIL_MSG, "[Mithril System] du bekamst: "); /** * Reward Service Login Messages */ addTranslatedMessage(CustomMessageId.REWARD10, "Du kannst .start benutzen um eine Level 10 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD30, "Du kannst .start benutzen um eine Level 30 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD40, "Du kannst .start benutzen um eine Level 40 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD50, "Du kannst .start benutzen um eine Level 50 Ausstattung zu bekommen!"); addTranslatedMessage(CustomMessageId.REWARD60, "Du kannst .start benutzen um eine Level 60 Ausstattung zu bekommen!"); /** * Advanced PvP System */ addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE1, "Heutige PvP Map: Reshanta"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE2, "Heutige PvP Map: Tiamaranta"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE3, "Heutige PvP Map: Inggison/Gelkmaros"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE4, "Heutige PvP Map: Idian Depths"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE5, "Heutige PvP Map: Katalam"); addTranslatedMessage(CustomMessageId.PVP_ADV_MESSAGE6, "Heutige PvP Map: Danaria"); /** * Asmo, Ely and World Channel */ addTranslatedMessage(CustomMessageId.ASMO_FAIL, "Du bist Elyos! Du kannst diesen Chat nicht benutzen. Nutze .ely <Nachricht> um im Fraktions Chat zu schreiben!"); addTranslatedMessage(CustomMessageId.ELY_FAIL, "Du bist Asmo! Du kannst diesen Chat nicht benutzen. Nutze .asmo <Nachricht> um im Fraktions Chat zu schreiben!"); /** * Wedding related */ addTranslatedMessage(CustomMessageId.WEDDINGNO1, "Du kannst dieses Kommando nicht waehrend des Kampfes nutzen!"); addTranslatedMessage(CustomMessageId.WEDDINGNO2, "Hochzeit wurde nicht gestartet!"); addTranslatedMessage(CustomMessageId.WEDDINGNO3, "Du hast die Heirat abgelehnt!"); addTranslatedMessage(CustomMessageId.WEDDINGYES, "Du hast die Heirat akzeptiert!"); /** * Clean Command related */ addTranslatedMessage(CustomMessageId.CANNOTCLEAN, "Du musst eine Item Id eingeben oder einen Link posten!"); addTranslatedMessage(CustomMessageId.CANNOTCLEAN2, "Du besitzt dieses Item nicht!"); addTranslatedMessage(CustomMessageId.SUCCESSCLEAN, "Item wurde erfolgreich aus deinem Wuerfel entfernt!"); /** * Mission check command related */ addTranslatedMessage(CustomMessageId.SUCCESCHECKED, "Mission erfolgreich ueberprueft!"); /** * No Exp Command */ addTranslatedMessage(CustomMessageId.EPACTIVATED, "Deine EP wurden wieder aktiviert!"); addTranslatedMessage(CustomMessageId.ACTODE, "Um deine EP zu deaktivieren, nutze .noexp"); addTranslatedMessage(CustomMessageId.EPDEACTIVATED, "Deine EP wurden deaktiviert!"); addTranslatedMessage(CustomMessageId.DETOAC, "Um deine EP zu aktivieren, nutze .noexp"); /** * Auto Quest Command */ addTranslatedMessage(CustomMessageId.WRONGQID, "Bitte gebe eine richtige Quest Id an!"); addTranslatedMessage(CustomMessageId.NOTSTARTED, "Quest konnte nicht gestartet werden!"); addTranslatedMessage(CustomMessageId.NOTSUPPORT, "Diese Quest wird nicht von diesem Kommando unterstuetzt!"); /** * Quest Restart Command */ addTranslatedMessage(CustomMessageId.CANNOTRESTART, "] kann nicht neugestartet werden"); /** * Exchange Toll Command */ addTranslatedMessage(CustomMessageId.TOLLTOBIG, "Du hast zu viele Toll!"); addTranslatedMessage(CustomMessageId.TOLOWAP, "Du hast nicht genug AP!"); addTranslatedMessage(CustomMessageId.TOLOWTOLL, "Du hast nicht genug Toll!"); addTranslatedMessage(CustomMessageId.WRONGTOLLNUM, "Irgendwas lief schief!"); /** * Cube Command */ addTranslatedMessage(CustomMessageId.CUBE_ALLREADY_EXPANDED, "Dein Wuerfel ist voll erweitert!"); addTranslatedMessage(CustomMessageId.CUBE_SUCCESS_EXPAND, "Dein Wuerfel wurde erfolgreich erweitert!"); /** * GMList Command */ addTranslatedMessage(CustomMessageId.ONE_GM_ONLINE, "Ein Team Mitglied ist online: "); addTranslatedMessage(CustomMessageId.MORE_GMS_ONLINE, "Es sind folgende Team Mitglieder online: "); addTranslatedMessage(CustomMessageId.NO_GM_ONLINE, "Es ist kein Team Mitglied online!"); /** * Go Command (PvP Command) */ addTranslatedMessage(CustomMessageId.NOT_USE_WHILE_FIGHT, "Du kannst dieses Kommando nicht waehrend des Kampfes nutzen!"); addTranslatedMessage(CustomMessageId.NOT_USE_ON_PVP_MAP, "Du kannst dieses Kommando nicht auf einer PvP Map benutzen!"); addTranslatedMessage(CustomMessageId.LEVEL_TOO_LOW, "Du kannst dieses Kommando nur mit Level 55 oder hoeher nutzen!"); /** * Paint Command */ addTranslatedMessage(CustomMessageId.WRONG_TARGET, "Bitte benutze ein erlaubtes Ziel!"); /** * Shiva Command */ addTranslatedMessage(CustomMessageId.ENCHANT_SUCCES, "Alle deine Items wurden verzaubert auf: "); addTranslatedMessage(CustomMessageId.ENCHANT_INFO, "Info: Dieses Kommando verzaubert alle deine Items auf <value>!"); addTranslatedMessage(CustomMessageId.ENCHANT_SAMPLE, "Beispiel: (.eq 15) wuerde alle deine Items auf 15 verzaubern"); /** * Userinfo Command */ addTranslatedMessage(CustomMessageId.CANNOT_SPY_PLAYER, "Du kannst keine Infos von anderen Spielern bekommen!"); /** * Check AFK Status */ addTranslatedMessage(CustomMessageId.KICKED_AFK_OUT, "You have been kicked out for being inactive too long."); /** * Exchange Command */ addTranslatedMessage(CustomMessageId.NOT_ENOUGH_ITEM, "Sie besitzen nicht genug von: "); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_AP, "Sie besitzen nicht genug AP, Sie haben nur: "); /** * Medal Command */ addTranslatedMessage(CustomMessageId.NOT_ENOUGH_SILVER, "Sie besitzen nicht genug Silber Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_GOLD, "Sie besitzen nicht genug Gold Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_PLATIN, "Sie besitzen nicht genug Platin Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_MITHRIL, "Sie besitzen nicht genug Mithril Medaillen."); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_AP2, "Sie besitzen nicht genug AP, Sie benoetigen: "); addTranslatedMessage(CustomMessageId.EXCHANGE_SILVER, "You have exchange [item:186000031] to [item:186000030]."); addTranslatedMessage(CustomMessageId.EXCHANGE_GOLD, "You have exchange [item:186000030] to [item:186000096]."); addTranslatedMessage(CustomMessageId.EXCHANGE_PLATIN, "You have exchange [item:186000096] to [item:186000147]."); addTranslatedMessage(CustomMessageId.EXCHANGE_MITHRIL, "You have exchange [item:186000147] to [item:186000223]."); addTranslatedMessage(CustomMessageId.EX_SILVER_INFO, "\nSyntax: .medal silver - Exchange Silver to Gold."); addTranslatedMessage(CustomMessageId.EX_GOLD_INFO, "\nSyntax: .medal gold - Exchange Gold to Platin."); addTranslatedMessage(CustomMessageId.EX_PLATIN_INFO, "\nSyntax: .medal platinum - Exchnage Platin to Mithril."); addTranslatedMessage(CustomMessageId.EX_MITHRIL_INFO, "\nSyntax: .medal mithril - Exchange Mithril to Honorable Mithril."); /** * Legendary Raid Spawn Events */ addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_SPAWNED_ASMO, "[Spawn Event] Ragnarok ist fuer die Asmodier in Beluslan erschienen!"); addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_SPAWNED_ELYOS, "[Spawn Event] Omega ist fuer die Elyos in Heiron erschienen!"); addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_DESPAWNED_ASMO, "[Spawn Event] Ragnarok ist verschwunden, niemand hat ihn getoetet!"); addTranslatedMessage(CustomMessageId.LEGENDARY_RAID_DESPAWNED_ELYOS, "[Spawn Event] Omega ist verschwunden, niemand hat ihn getoetet!"); /** * HonorItems Command */ addTranslatedMessage(CustomMessageId.PLATE_ARMOR, "Platten Ruestung"); addTranslatedMessage(CustomMessageId.LEATHER_ARMOR, "Leder Ruestung"); addTranslatedMessage(CustomMessageId.CLOTH_ARMOR, "Stoff Ruestung"); addTranslatedMessage(CustomMessageId.CHAIN_ARMOR, "Ketten Ruestung"); addTranslatedMessage(CustomMessageId.WEAPONS, "Waffen"); addTranslatedMessage(CustomMessageId.PLATE_ARMOR_PRICES, "Platten ruestungs Preis"); addTranslatedMessage(CustomMessageId.LEATHER_ARMOR_PRICES, "Leder Ruestungs Preis"); addTranslatedMessage(CustomMessageId.CLOTH_ARMOR_PRICES, "Stoff Ruestung Preis"); addTranslatedMessage(CustomMessageId.CHAIN_ARMOR_PRICES, "Ketten Ruestungs Preis"); addTranslatedMessage(CustomMessageId.WEAPONS_PRICES, "Waffen Preis"); addTranslatedMessage(CustomMessageId.NOT_ENOUGH_MEDALS, "Sie besitzen nicht genuegend Medaillen, Sie benoetigen: "); addTranslatedMessage(CustomMessageId.PLATE_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 1"); addTranslatedMessage(CustomMessageId.LEATHER_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 6"); addTranslatedMessage(CustomMessageId.CLOTH_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 11"); addTranslatedMessage(CustomMessageId.CHAIN_ARMOR_USE_INFO, "Use .items and the equal ID (Example: .items 16"); addTranslatedMessage(CustomMessageId.WEAPONS_USE_INFO, "Use .items and the equal ID (Example: .items 21"); addTranslatedMessage(CustomMessageId.SUCCESSFULLY_TRADED, "You got successfully your Trade!"); /** * Moltenus Announce */ addTranslatedMessage(CustomMessageId.MOLTENUS_APPEAR, "Moltenus Fragment of the Wrath ist im Abyss erschienen."); addTranslatedMessage(CustomMessageId.MOLTENUS_DISAPPEAR, "Moltenus Fragment of the Wrath ist verschwunden."); /** * Dredgion Announce */ addTranslatedMessage(CustomMessageId.DREDGION_ASMO_GROUP, "An asmodian group is waiting for dredgion."); addTranslatedMessage(CustomMessageId.DREDGION_ELYOS_GROUP, "An elyos group is waiting for dredgion."); addTranslatedMessage(CustomMessageId.DREDGION_ASMO, "An alone asmodian is waiting for dredgion."); addTranslatedMessage(CustomMessageId.DREDGION_ELYOS, "An alone elyos is waiting for dredgion."); /** * PvP Service */ addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD1, "Sie haben verdient"); addTranslatedMessage(CustomMessageId.PVP_TOLL_REWARD2, " Abyss Punkte."); /** * Invasion Rift */ addTranslatedMessage(CustomMessageId.INVASION_RIFT_MIN_LEVEL, "Dein Level ist zu niedrig um zu passieren."); addTranslatedMessage(CustomMessageId.INVASION_RIFT_ELYOS, "A rift for Pandaemonium is open at Ingisson"); addTranslatedMessage(CustomMessageId.INVASION_RIFT_ASMOS, "A rift for Sanctum is open at Gelkmaros"); /** * PvP Spree Service */ addTranslatedMessage(CustomMessageId.SPREE1, "Blutiger Sturm"); addTranslatedMessage(CustomMessageId.SPREE2, "Blutbad"); addTranslatedMessage(CustomMessageId.SPREE3, "Voelkermord"); addTranslatedMessage(CustomMessageId.KILL_COUNT, "Kills in Folge: "); addTranslatedMessage(CustomMessageId.CUSTOM_MSG1, " von "); addTranslatedMessage(CustomMessageId.MSG_SPREE1, " hat begonnen ein "); addTranslatedMessage(CustomMessageId.MSG_SPREE1_1, " !"); addTranslatedMessage(CustomMessageId.MSG_SPREE2, " fuehrt eine echte "); addTranslatedMessage(CustomMessageId.MSG_SPREE2_1, " ! Haltet ihn schnell !"); addTranslatedMessage(CustomMessageId.MSG_SPREE3, " tut ein "); addTranslatedMessage(CustomMessageId.MSG_SPREE3_1, " ! Lauf weg, wenn du kannst!"); addTranslatedMessage(CustomMessageId.SPREE_END_MSG1, "Der Amoklauf von "); addTranslatedMessage(CustomMessageId.SPREE_END_MSG2, " wurde gestoppt von "); addTranslatedMessage(CustomMessageId.SPREE_END_MSG3, " nach "); addTranslatedMessage(CustomMessageId.SPREE_END_MSG4, " ununterbrochene Morde !"); addTranslatedMessage(CustomMessageId.SPREE_MONSTER_MSG, "ein Monster"); /** * EventEngine - EventUtil */ // addTranslatedMessage(CustomMessageId.Event_Util_1, "Du kannst diesen Befehl nicht verwenden."); // addTranslatedMessage(CustomMessageId.Event_Util_2, "Falsche Event Typ."); // addTranslatedMessage(CustomMessageId.Event_Util_3, "Unbekannter Benutzer."); /** * EventEngine - Event<SUF>*/ // addTranslatedMessage(CustomMessageId.Event_1, "Du kannst an diesem Event nicht teilnehmen, waehrend du im Gefaengnis bist, oder in Kampfzustand."); } }
191989_3
package com.lilithsthrone.game.dialogue; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.lilithsthrone.controller.xmlParsing.XMLUtil; import com.lilithsthrone.game.Game; import com.lilithsthrone.game.character.GameCharacter; import com.lilithsthrone.game.character.npc.NPC; import com.lilithsthrone.game.character.npc.dominion.Daddy; import com.lilithsthrone.game.character.npc.dominion.Kalahari; import com.lilithsthrone.game.character.npc.dominion.Ralph; import com.lilithsthrone.game.dialogue.places.dominion.helenaHotel.HelenaConversationTopic; import com.lilithsthrone.game.dialogue.places.submission.impFortress.ImpFortressDialogue; import com.lilithsthrone.game.occupantManagement.slave.SlaveJob; import com.lilithsthrone.main.Main; import com.lilithsthrone.utils.Util; import com.lilithsthrone.utils.XMLSaving; import com.lilithsthrone.utils.colours.Colour; import com.lilithsthrone.utils.colours.PresetColour; /** * @since 0.1.0 * @version 0.3.9 * @author Innoxia */ public class DialogueFlags implements XMLSaving { public static int MUGGER_DEMAND_1 = 250; public static int MUGGER_DEMAND_2 = 500; public Set<DialogueFlagValue> values; public int ralphDiscount; public int scarlettPrice; public int eponaStamps; // Timers: public Map<String, Long> savedLongs = new HashMap<>(); public int helenaSlaveOrderDay; public int impCitadelImpWave; // Amount of dialogue choices you can make before offspring interaction ends: public int offspringDialogueTokens = 2; // Murk transformation stage tracking: private int murkPlayerTfStage; private int murkCompanionTfStage; private String slaveTrader; private String managementCompanion; private SlaveJob slaveryManagerJobSelected; private Colour natalyaCollarColour; private int natalyaPoints; private String sadistNatalyaSlave; // --- Sets: --- // private Set<String> helenaConversationTopics = new HashSet<>(); // Reindeer event related flags: private Set<String> reindeerEncounteredIDs = new HashSet<>(); private Set<String> reindeerWorkedForIDs = new HashSet<>(); private Set<String> reindeerFuckedIDs = new HashSet<>(); // Enforcer warehouse guards defeated: public Set<String> warehouseDefeatedIDs = new HashSet<>(); // // Storage tiles checked: // public Set<Vector2i> supplierStorageRoomsChecked = new HashSet<>(); public DialogueFlags() { values = new HashSet<>(); slaveTrader = null; managementCompanion = null; slaveryManagerJobSelected = SlaveJob.IDLE; // ralphDiscountStartTime = -1; // kalahariBreakStartTime = -1; // daddyResetTimer = -1; // candiSexTimer = -1; // ralphSexTimer = -1; // // impFortressAlphaDefeatedTime // = impFortressDemonDefeatedTime // = impFortressFemalesDefeatedTime // = impFortressMalesDefeatedTime // = -50000; helenaSlaveOrderDay = -1; ralphDiscount = 0; eponaStamps = 0; scarlettPrice = 15000; impCitadelImpWave = 0; murkPlayerTfStage = 0; murkCompanionTfStage = 0; natalyaCollarColour = PresetColour.CLOTHING_BRONZE; natalyaPoints = 0; sadistNatalyaSlave = ""; } public Element saveAsXML(Element parentElement, Document doc) { Element element = doc.createElement("dialogueFlags"); parentElement.appendChild(element); // XMLUtil.createXMLElementWithValue(doc, element, "ralphDiscountStartTime", String.valueOf(ralphDiscountStartTime)); // XMLUtil.createXMLElementWithValue(doc, element, "kalahariBreakStartTime", String.valueOf(kalahariBreakStartTime)); // XMLUtil.createXMLElementWithValue(doc, element, "daddyResetTimer", String.valueOf(daddyResetTimer)); // // XMLUtil.createXMLElementWithValue(doc, element, "impFortressAlphaDefeatedTime", String.valueOf(impFortressAlphaDefeatedTime)); // XMLUtil.createXMLElementWithValue(doc, element, "impFortressDemonDefeatedTime", String.valueOf(impFortressDemonDefeatedTime)); // XMLUtil.createXMLElementWithValue(doc, element, "impFortressFemalesDefeatedTime", String.valueOf(impFortressFemalesDefeatedTime)); // XMLUtil.createXMLElementWithValue(doc, element, "impFortressMalesDefeatedTime", String.valueOf(impFortressMalesDefeatedTime)); XMLUtil.createXMLElementWithValue(doc, element, "ralphDiscount", String.valueOf(ralphDiscount)); XMLUtil.createXMLElementWithValue(doc, element, "scarlettPrice", String.valueOf(scarlettPrice)); XMLUtil.createXMLElementWithValue(doc, element, "eponaStamps", String.valueOf(eponaStamps)); XMLUtil.createXMLElementWithValue(doc, element, "helenaSlaveOrderDay", String.valueOf(helenaSlaveOrderDay)); XMLUtil.createXMLElementWithValue(doc, element, "impCitadelImpWave", String.valueOf(impCitadelImpWave)); XMLUtil.createXMLElementWithValue(doc, element, "murkPlayerTfStage", String.valueOf(murkPlayerTfStage)); XMLUtil.createXMLElementWithValue(doc, element, "murkCompanionTfStage", String.valueOf(murkCompanionTfStage)); XMLUtil.createXMLElementWithValue(doc, element, "offspringDialogueTokens", String.valueOf(offspringDialogueTokens)); XMLUtil.createXMLElementWithValue(doc, element, "slaveTrader", slaveTrader); XMLUtil.createXMLElementWithValue(doc, element, "slaveryManagerSlaveSelected", managementCompanion); XMLUtil.createXMLElementWithValue(doc, element, "natalyaCollarColour", PresetColour.getIdFromColour(natalyaCollarColour)); XMLUtil.createXMLElementWithValue(doc, element, "natalyaPoints", String.valueOf(natalyaPoints)); XMLUtil.createXMLElementWithValue(doc, element, "sadistNatalyaSlave", sadistNatalyaSlave); Element savedLongsElement = doc.createElement("savedLongs"); element.appendChild(savedLongsElement); for(Entry<String, Long> savedLong : savedLongs.entrySet()) { Element save = doc.createElement("save"); savedLongsElement.appendChild(save); save.setAttribute("id", savedLong.getKey()); save.setTextContent(String.valueOf(savedLong.getValue())); } Element valuesElement = doc.createElement("dialogueValues"); element.appendChild(valuesElement); for(DialogueFlagValue value : values) { XMLUtil.createXMLElementWithValue(doc, valuesElement, "dialogueValue", value.toString()); } saveSet(element, doc, helenaConversationTopics, "helenaConversationTopics"); saveSet(element, doc, reindeerEncounteredIDs, "reindeerEncounteredIDs"); saveSet(element, doc, reindeerWorkedForIDs, "reindeerWorkedForIDs"); saveSet(element, doc, reindeerFuckedIDs, "reindeerFuckedIDs"); saveSet(element, doc, warehouseDefeatedIDs, "warehouseDefeatedIDs"); // Element supplierStorageRoomsCheckedElement = doc.createElement("supplierStorageRoomsChecked"); // element.appendChild(supplierStorageRoomsCheckedElement); // for(Vector2i value : supplierStorageRoomsChecked) { // Element location = doc.createElement("location"); // supplierStorageRoomsCheckedElement.appendChild(location); // XMLUtil.addAttribute(doc, location, "x", String.valueOf(value.getX())); // XMLUtil.addAttribute(doc, location, "y", String.valueOf(value.getY())); // } return element; } public static DialogueFlags loadFromXML(Element parentElement, Document doc) { DialogueFlags newFlags = new DialogueFlags(); newFlags.ralphDiscount = Integer.valueOf(((Element)parentElement.getElementsByTagName("ralphDiscount").item(0)).getAttribute("value")); newFlags.scarlettPrice = Integer.valueOf(((Element)parentElement.getElementsByTagName("scarlettPrice").item(0)).getAttribute("value")); newFlags.offspringDialogueTokens = Integer.valueOf(((Element)parentElement.getElementsByTagName("offspringDialogueTokens").item(0)).getAttribute("value")); newFlags.slaveTrader = ((Element)parentElement.getElementsByTagName("slaveTrader").item(0)).getAttribute("value"); newFlags.managementCompanion = ((Element)parentElement.getElementsByTagName("slaveryManagerSlaveSelected").item(0)).getAttribute("value"); try { newFlags.eponaStamps = Integer.valueOf(((Element)parentElement.getElementsByTagName("eponaStamps").item(0)).getAttribute("value")); } catch(Exception ex) { } try { newFlags.helenaSlaveOrderDay = Integer.valueOf(((Element)parentElement.getElementsByTagName("helenaSlaveOrderDay").item(0)).getAttribute("value")); } catch(Exception ex) { } try { newFlags.impCitadelImpWave = Integer.valueOf(((Element)parentElement.getElementsByTagName("impCitadelImpWave").item(0)).getAttribute("value")); } catch(Exception ex) { } try { newFlags.murkPlayerTfStage = Integer.valueOf(((Element)parentElement.getElementsByTagName("murkPlayerTfStage").item(0)).getAttribute("value")); newFlags.murkCompanionTfStage = Integer.valueOf(((Element)parentElement.getElementsByTagName("murkCompanionTfStage").item(0)).getAttribute("value")); } catch(Exception ex) { } try { newFlags.natalyaCollarColour = PresetColour.getColourFromId(((Element)parentElement.getElementsByTagName("natalyaCollarColour").item(0)).getAttribute("value")); if(newFlags.natalyaCollarColour==PresetColour.CLOTHING_STEEL) { newFlags.natalyaCollarColour = PresetColour.CLOTHING_BRONZE; } newFlags.natalyaPoints = Integer.valueOf(((Element)parentElement.getElementsByTagName("natalyaPoints").item(0)).getAttribute("value")); newFlags.sadistNatalyaSlave = ((Element)parentElement.getElementsByTagName("sadistNatalyaSlave").item(0)).getAttribute("value"); } catch(Exception ex) { } // Load saved longs: if(parentElement.getElementsByTagName("savedLongs").item(0)!=null) { for(int i=0; i<((Element) parentElement.getElementsByTagName("savedLongs").item(0)).getElementsByTagName("save").getLength(); i++){ Element e = (Element) ((Element) parentElement.getElementsByTagName("savedLongs").item(0)).getElementsByTagName("save").item(i); String id = e.getAttribute("id"); if(Main.isVersionOlderThan(Game.loadingVersion, "0.3.15")) { if(id.equals("MACHINES") || id.equals("INTERCOM") || id.equals("BUSINESS") || id.equals("BOUNTY_HUNTERS")) { id = "KAY_"+id; } } newFlags.setSavedLong(id, Long.valueOf(e.getTextContent())); } } else { // Support for old timers (pre-version 0.3.9): newFlags.setSavedLong(Ralph.RALPH_DISCOUNT_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("ralphDiscountStartTime").item(0)).getAttribute("value"))); try { newFlags.setSavedLong(Kalahari.KALAHARI_BREAK_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("kalahariBreakStartTime").item(0)).getAttribute("value"))); } catch(Exception ex) { } try { newFlags.setSavedLong(Daddy.DADDY_RESET_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("daddyResetTimer").item(0)).getAttribute("value"))); } catch(Exception ex) { } try { if(!Main.isVersionOlderThan(Game.loadingVersion, "0.2.11.5")) { newFlags.setSavedLong(ImpFortressDialogue.FORTRESS_ALPHA_CLEAR_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("impFortressAlphaDefeatedTime").item(0)).getAttribute("value"))); newFlags.setSavedLong(ImpFortressDialogue.FORTRESS_FEMALES_CLEAR_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("impFortressFemalesDefeatedTime").item(0)).getAttribute("value"))); newFlags.setSavedLong(ImpFortressDialogue.FORTRESS_MALES_CLEAR_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("impFortressMalesDefeatedTime").item(0)).getAttribute("value"))); } } catch(Exception ex) { } } // Load flags: for(int i=0; i<((Element) parentElement.getElementsByTagName("dialogueValues").item(0)).getElementsByTagName("dialogueValue").getLength(); i++){ Element e = (Element) ((Element) parentElement.getElementsByTagName("dialogueValues").item(0)).getElementsByTagName("dialogueValue").item(i); try { String flag = e.getAttribute("value"); if(flag.equalsIgnoreCase("punishedByAlexa")) { newFlags.values.add(DialogueFlagValue.punishedByHelena); } else { newFlags.values.add(DialogueFlagValue.valueOf(flag)); } } catch(Exception ex) { } } if(Main.isVersionOlderThan(Game.loadingVersion, "0.2.6.1")) { newFlags.values.remove(DialogueFlagValue.axelIntroduced); newFlags.values.remove(DialogueFlagValue.roxyIntroduced); newFlags.values.remove(DialogueFlagValue.eponaIntroduced); } if(Main.isVersionOlderThan(Game.loadingVersion, "0.2.11.5")) { // Add defeated flags so that the fortress will reset. newFlags.values.add(DialogueFlagValue.impFortressAlphaDefeated); newFlags.values.add(DialogueFlagValue.impFortressDemonDefeated); newFlags.values.add(DialogueFlagValue.impFortressFemalesDefeated); newFlags.values.add(DialogueFlagValue.impFortressMalesDefeated); } loadSet(parentElement, doc, newFlags.helenaConversationTopics, "helenaConversationTopics"); loadSet(parentElement, doc, newFlags.reindeerEncounteredIDs, "reindeerEncounteredIDs"); loadSet(parentElement, doc, newFlags.reindeerWorkedForIDs, "reindeerWorkedForIDs"); loadSet(parentElement, doc, newFlags.reindeerFuckedIDs, "reindeerFuckedIDs"); loadSet(parentElement, doc, newFlags.warehouseDefeatedIDs, "warehouseDefeatedIDs"); // if(parentElement.getElementsByTagName("supplierStorageRoomsChecked").item(0)!=null) { // for(int i=0; i<((Element) parentElement.getElementsByTagName("supplierStorageRoomsChecked").item(0)).getElementsByTagName("location").getLength(); i++){ // Element e = (Element) ((Element) parentElement.getElementsByTagName("supplierStorageRoomsChecked").item(0)).getElementsByTagName("location").item(i); // // newFlags.supplierStorageRoomsChecked.add( // new Vector2i( // Integer.valueOf(e.getAttribute("x")), // Integer.valueOf(e.getAttribute("y")))); // } // } return newFlags; } private static void saveSet(Element parentElement, Document doc, Set<String> set, String title) { Element valuesElement = doc.createElement(title); parentElement.appendChild(valuesElement); for(String value : set) { XMLUtil.createXMLElementWithValue(doc, valuesElement, "value", value.toString()); } } private static void loadSet(Element parentElement, Document doc, Set<String> set, String title) { try { if(parentElement.getElementsByTagName(title).item(0)!=null) { for(int i=0; i<((Element) parentElement.getElementsByTagName(title).item(0)).getElementsByTagName("value").getLength(); i++){ Element e = (Element) ((Element) parentElement.getElementsByTagName(title).item(0)).getElementsByTagName("value").item(i); set.add(e.getAttribute("value")); } } } catch(Exception ex) { } } public void dailyReset() { values.removeIf((flag)->flag.isDailyReset()); } public boolean hasFlag(DialogueFlagValue flag) { return values.contains(flag); } public void setFlag(DialogueFlagValue flag, boolean flagMarker) { if(flagMarker) { values.add(flag); } else { values.remove(flag); } } public void setSavedLong(String id, long value) { savedLongs.put(id, value); } /** * @return Increments the long saved to this id. Sets to -1 before incrementing if there was no entry found. */ public void incrementSavedLong(String id, long increment) { savedLongs.put(id, getSavedLong(id)+increment); } public boolean hasSavedLong(String id) { return savedLongs.containsKey(id); } public void removeSavedLong(String id) { savedLongs.remove(id); } /** * @return The long saved to this id. Sets and returns -1 if there was no entry found. */ public long getSavedLong(String id) { savedLongs.putIfAbsent(id, -1l); return savedLongs.get(id); } public NPC getSlaveTrader() { if(slaveTrader==null || slaveTrader.isEmpty()) { return null; } try { return (NPC) Main.game.getNPCById(slaveTrader); } catch (Exception e) { Util.logGetNpcByIdError("getSlaveTrader()", slaveTrader); return null; } } public void setSlaveTrader(GameCharacter slaveTrader) { if(slaveTrader==null) { this.slaveTrader = null; } else { this.slaveTrader = slaveTrader.getId(); } } public String getSlaveTraderId() { return slaveTrader; } public void setSlaveTraderId(String slaveTrader) { this.slaveTrader = slaveTrader; } public NPC getManagementCompanion() { if(managementCompanion==null || managementCompanion.isEmpty()) { return null; } try { return (NPC) Main.game.getNPCById(managementCompanion); } catch (Exception e) { Util.logGetNpcByIdError("getManagementCompanion()", managementCompanion); //e.printStackTrace(); return null; } } public void setManagementCompanion(GameCharacter managementCompanion) { if(managementCompanion==null) { this.managementCompanion = null; } else { this.managementCompanion = managementCompanion.getId(); } } public String getManagementCompanionId() { return managementCompanion; } public void setManagementCompanionId(String managementCompanion) { this.managementCompanion = managementCompanion; } // Reindeer event: public SlaveJob getSlaveryManagerJobSelected() { return slaveryManagerJobSelected; } public void setSlaveryManagerJobSelected(SlaveJob slaveryManagerJobSelected) { this.slaveryManagerJobSelected = slaveryManagerJobSelected; } public void addHelenaConversationTopic(HelenaConversationTopic topic) { helenaConversationTopics.add(topic.toString()); } public boolean hasHelenaConversationTopic(HelenaConversationTopic topic) { return helenaConversationTopics.contains(topic.toString()); } public void addReindeerEncountered(String reindeerID) { reindeerEncounteredIDs.add(reindeerID); } public boolean hasEncounteredReindeer(String reindeerID) { return reindeerEncounteredIDs.contains(reindeerID); } public boolean hasEncounteredAnyReindeers() { return !reindeerEncounteredIDs.isEmpty(); } public void addReindeerDailyWorkedFor(String reindeerID) { reindeerWorkedForIDs.add(reindeerID); } public boolean hasWorkedForReindeer(String reindeerID) { return reindeerWorkedForIDs.contains(reindeerID); } public void addReindeerDailyFucked(String reindeerID) { reindeerFuckedIDs.add(reindeerID); } public boolean hasFuckedReindeer(String reindeerID) { return reindeerFuckedIDs.contains(reindeerID); } public void dailyReindeerReset(String reindeerID) { reindeerWorkedForIDs.remove(reindeerID); } public int getMurkTfStage(GameCharacter target) { if(target.isPlayer()) { return murkPlayerTfStage; } return murkCompanionTfStage; } public void setMurkTfStage(GameCharacter target, int stage) { if(target.isPlayer()) { this.murkPlayerTfStage = stage; } else { this.murkCompanionTfStage = stage; } } public Colour getNatalyaCollarColour() { return natalyaCollarColour; } public void setNatalyaCollarColour(Colour natalyaCollarColour) { this.natalyaCollarColour = natalyaCollarColour; } public int getNatalyaPoints() { return natalyaPoints; } public void setNatalyaPoints(int natalyaPoints) { this.natalyaPoints = natalyaPoints; if(this.natalyaPoints<0) { this.natalyaPoints = 0; } } public String incrementNatalyaPoints(int increment) { setNatalyaPoints(getNatalyaPoints()+increment); boolean plural = increment!=1; StringBuilder sb = new StringBuilder(); sb.append("<p style='text-align:center;'>"); if(increment>0) { sb.append("You [style.colourGood(gained)] [style.boldPink("+increment+")] [style.colourPinkLight(filly point"+(plural?"s":"")+")]!"); } else { sb.append("You [style.colourBad(lost)] [style.boldPink("+(-increment)+")] [style.colourPinkLight(filly point"+(plural?"s":"")+")]!"); } sb.append("<br/>You now have [style.boldPink("+getNatalyaPoints()+")] [style.colourPinkLight(filly points)]!"); sb.append("</p>"); return sb.toString(); } public String getSadistNatalyaSlave() { return sadistNatalyaSlave; } public void setSadistNatalyaSlave(String sadistNatalyaSlave) { this.sadistNatalyaSlave = sadistNatalyaSlave; } }
Drakani-Behoment/liliths-throne-public
src/com/lilithsthrone/game/dialogue/DialogueFlags.java
7,135
// --- Sets: --- //
line_comment
nl
package com.lilithsthrone.game.dialogue; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.lilithsthrone.controller.xmlParsing.XMLUtil; import com.lilithsthrone.game.Game; import com.lilithsthrone.game.character.GameCharacter; import com.lilithsthrone.game.character.npc.NPC; import com.lilithsthrone.game.character.npc.dominion.Daddy; import com.lilithsthrone.game.character.npc.dominion.Kalahari; import com.lilithsthrone.game.character.npc.dominion.Ralph; import com.lilithsthrone.game.dialogue.places.dominion.helenaHotel.HelenaConversationTopic; import com.lilithsthrone.game.dialogue.places.submission.impFortress.ImpFortressDialogue; import com.lilithsthrone.game.occupantManagement.slave.SlaveJob; import com.lilithsthrone.main.Main; import com.lilithsthrone.utils.Util; import com.lilithsthrone.utils.XMLSaving; import com.lilithsthrone.utils.colours.Colour; import com.lilithsthrone.utils.colours.PresetColour; /** * @since 0.1.0 * @version 0.3.9 * @author Innoxia */ public class DialogueFlags implements XMLSaving { public static int MUGGER_DEMAND_1 = 250; public static int MUGGER_DEMAND_2 = 500; public Set<DialogueFlagValue> values; public int ralphDiscount; public int scarlettPrice; public int eponaStamps; // Timers: public Map<String, Long> savedLongs = new HashMap<>(); public int helenaSlaveOrderDay; public int impCitadelImpWave; // Amount of dialogue choices you can make before offspring interaction ends: public int offspringDialogueTokens = 2; // Murk transformation stage tracking: private int murkPlayerTfStage; private int murkCompanionTfStage; private String slaveTrader; private String managementCompanion; private SlaveJob slaveryManagerJobSelected; private Colour natalyaCollarColour; private int natalyaPoints; private String sadistNatalyaSlave; // --- Sets:<SUF> private Set<String> helenaConversationTopics = new HashSet<>(); // Reindeer event related flags: private Set<String> reindeerEncounteredIDs = new HashSet<>(); private Set<String> reindeerWorkedForIDs = new HashSet<>(); private Set<String> reindeerFuckedIDs = new HashSet<>(); // Enforcer warehouse guards defeated: public Set<String> warehouseDefeatedIDs = new HashSet<>(); // // Storage tiles checked: // public Set<Vector2i> supplierStorageRoomsChecked = new HashSet<>(); public DialogueFlags() { values = new HashSet<>(); slaveTrader = null; managementCompanion = null; slaveryManagerJobSelected = SlaveJob.IDLE; // ralphDiscountStartTime = -1; // kalahariBreakStartTime = -1; // daddyResetTimer = -1; // candiSexTimer = -1; // ralphSexTimer = -1; // // impFortressAlphaDefeatedTime // = impFortressDemonDefeatedTime // = impFortressFemalesDefeatedTime // = impFortressMalesDefeatedTime // = -50000; helenaSlaveOrderDay = -1; ralphDiscount = 0; eponaStamps = 0; scarlettPrice = 15000; impCitadelImpWave = 0; murkPlayerTfStage = 0; murkCompanionTfStage = 0; natalyaCollarColour = PresetColour.CLOTHING_BRONZE; natalyaPoints = 0; sadistNatalyaSlave = ""; } public Element saveAsXML(Element parentElement, Document doc) { Element element = doc.createElement("dialogueFlags"); parentElement.appendChild(element); // XMLUtil.createXMLElementWithValue(doc, element, "ralphDiscountStartTime", String.valueOf(ralphDiscountStartTime)); // XMLUtil.createXMLElementWithValue(doc, element, "kalahariBreakStartTime", String.valueOf(kalahariBreakStartTime)); // XMLUtil.createXMLElementWithValue(doc, element, "daddyResetTimer", String.valueOf(daddyResetTimer)); // // XMLUtil.createXMLElementWithValue(doc, element, "impFortressAlphaDefeatedTime", String.valueOf(impFortressAlphaDefeatedTime)); // XMLUtil.createXMLElementWithValue(doc, element, "impFortressDemonDefeatedTime", String.valueOf(impFortressDemonDefeatedTime)); // XMLUtil.createXMLElementWithValue(doc, element, "impFortressFemalesDefeatedTime", String.valueOf(impFortressFemalesDefeatedTime)); // XMLUtil.createXMLElementWithValue(doc, element, "impFortressMalesDefeatedTime", String.valueOf(impFortressMalesDefeatedTime)); XMLUtil.createXMLElementWithValue(doc, element, "ralphDiscount", String.valueOf(ralphDiscount)); XMLUtil.createXMLElementWithValue(doc, element, "scarlettPrice", String.valueOf(scarlettPrice)); XMLUtil.createXMLElementWithValue(doc, element, "eponaStamps", String.valueOf(eponaStamps)); XMLUtil.createXMLElementWithValue(doc, element, "helenaSlaveOrderDay", String.valueOf(helenaSlaveOrderDay)); XMLUtil.createXMLElementWithValue(doc, element, "impCitadelImpWave", String.valueOf(impCitadelImpWave)); XMLUtil.createXMLElementWithValue(doc, element, "murkPlayerTfStage", String.valueOf(murkPlayerTfStage)); XMLUtil.createXMLElementWithValue(doc, element, "murkCompanionTfStage", String.valueOf(murkCompanionTfStage)); XMLUtil.createXMLElementWithValue(doc, element, "offspringDialogueTokens", String.valueOf(offspringDialogueTokens)); XMLUtil.createXMLElementWithValue(doc, element, "slaveTrader", slaveTrader); XMLUtil.createXMLElementWithValue(doc, element, "slaveryManagerSlaveSelected", managementCompanion); XMLUtil.createXMLElementWithValue(doc, element, "natalyaCollarColour", PresetColour.getIdFromColour(natalyaCollarColour)); XMLUtil.createXMLElementWithValue(doc, element, "natalyaPoints", String.valueOf(natalyaPoints)); XMLUtil.createXMLElementWithValue(doc, element, "sadistNatalyaSlave", sadistNatalyaSlave); Element savedLongsElement = doc.createElement("savedLongs"); element.appendChild(savedLongsElement); for(Entry<String, Long> savedLong : savedLongs.entrySet()) { Element save = doc.createElement("save"); savedLongsElement.appendChild(save); save.setAttribute("id", savedLong.getKey()); save.setTextContent(String.valueOf(savedLong.getValue())); } Element valuesElement = doc.createElement("dialogueValues"); element.appendChild(valuesElement); for(DialogueFlagValue value : values) { XMLUtil.createXMLElementWithValue(doc, valuesElement, "dialogueValue", value.toString()); } saveSet(element, doc, helenaConversationTopics, "helenaConversationTopics"); saveSet(element, doc, reindeerEncounteredIDs, "reindeerEncounteredIDs"); saveSet(element, doc, reindeerWorkedForIDs, "reindeerWorkedForIDs"); saveSet(element, doc, reindeerFuckedIDs, "reindeerFuckedIDs"); saveSet(element, doc, warehouseDefeatedIDs, "warehouseDefeatedIDs"); // Element supplierStorageRoomsCheckedElement = doc.createElement("supplierStorageRoomsChecked"); // element.appendChild(supplierStorageRoomsCheckedElement); // for(Vector2i value : supplierStorageRoomsChecked) { // Element location = doc.createElement("location"); // supplierStorageRoomsCheckedElement.appendChild(location); // XMLUtil.addAttribute(doc, location, "x", String.valueOf(value.getX())); // XMLUtil.addAttribute(doc, location, "y", String.valueOf(value.getY())); // } return element; } public static DialogueFlags loadFromXML(Element parentElement, Document doc) { DialogueFlags newFlags = new DialogueFlags(); newFlags.ralphDiscount = Integer.valueOf(((Element)parentElement.getElementsByTagName("ralphDiscount").item(0)).getAttribute("value")); newFlags.scarlettPrice = Integer.valueOf(((Element)parentElement.getElementsByTagName("scarlettPrice").item(0)).getAttribute("value")); newFlags.offspringDialogueTokens = Integer.valueOf(((Element)parentElement.getElementsByTagName("offspringDialogueTokens").item(0)).getAttribute("value")); newFlags.slaveTrader = ((Element)parentElement.getElementsByTagName("slaveTrader").item(0)).getAttribute("value"); newFlags.managementCompanion = ((Element)parentElement.getElementsByTagName("slaveryManagerSlaveSelected").item(0)).getAttribute("value"); try { newFlags.eponaStamps = Integer.valueOf(((Element)parentElement.getElementsByTagName("eponaStamps").item(0)).getAttribute("value")); } catch(Exception ex) { } try { newFlags.helenaSlaveOrderDay = Integer.valueOf(((Element)parentElement.getElementsByTagName("helenaSlaveOrderDay").item(0)).getAttribute("value")); } catch(Exception ex) { } try { newFlags.impCitadelImpWave = Integer.valueOf(((Element)parentElement.getElementsByTagName("impCitadelImpWave").item(0)).getAttribute("value")); } catch(Exception ex) { } try { newFlags.murkPlayerTfStage = Integer.valueOf(((Element)parentElement.getElementsByTagName("murkPlayerTfStage").item(0)).getAttribute("value")); newFlags.murkCompanionTfStage = Integer.valueOf(((Element)parentElement.getElementsByTagName("murkCompanionTfStage").item(0)).getAttribute("value")); } catch(Exception ex) { } try { newFlags.natalyaCollarColour = PresetColour.getColourFromId(((Element)parentElement.getElementsByTagName("natalyaCollarColour").item(0)).getAttribute("value")); if(newFlags.natalyaCollarColour==PresetColour.CLOTHING_STEEL) { newFlags.natalyaCollarColour = PresetColour.CLOTHING_BRONZE; } newFlags.natalyaPoints = Integer.valueOf(((Element)parentElement.getElementsByTagName("natalyaPoints").item(0)).getAttribute("value")); newFlags.sadistNatalyaSlave = ((Element)parentElement.getElementsByTagName("sadistNatalyaSlave").item(0)).getAttribute("value"); } catch(Exception ex) { } // Load saved longs: if(parentElement.getElementsByTagName("savedLongs").item(0)!=null) { for(int i=0; i<((Element) parentElement.getElementsByTagName("savedLongs").item(0)).getElementsByTagName("save").getLength(); i++){ Element e = (Element) ((Element) parentElement.getElementsByTagName("savedLongs").item(0)).getElementsByTagName("save").item(i); String id = e.getAttribute("id"); if(Main.isVersionOlderThan(Game.loadingVersion, "0.3.15")) { if(id.equals("MACHINES") || id.equals("INTERCOM") || id.equals("BUSINESS") || id.equals("BOUNTY_HUNTERS")) { id = "KAY_"+id; } } newFlags.setSavedLong(id, Long.valueOf(e.getTextContent())); } } else { // Support for old timers (pre-version 0.3.9): newFlags.setSavedLong(Ralph.RALPH_DISCOUNT_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("ralphDiscountStartTime").item(0)).getAttribute("value"))); try { newFlags.setSavedLong(Kalahari.KALAHARI_BREAK_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("kalahariBreakStartTime").item(0)).getAttribute("value"))); } catch(Exception ex) { } try { newFlags.setSavedLong(Daddy.DADDY_RESET_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("daddyResetTimer").item(0)).getAttribute("value"))); } catch(Exception ex) { } try { if(!Main.isVersionOlderThan(Game.loadingVersion, "0.2.11.5")) { newFlags.setSavedLong(ImpFortressDialogue.FORTRESS_ALPHA_CLEAR_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("impFortressAlphaDefeatedTime").item(0)).getAttribute("value"))); newFlags.setSavedLong(ImpFortressDialogue.FORTRESS_FEMALES_CLEAR_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("impFortressFemalesDefeatedTime").item(0)).getAttribute("value"))); newFlags.setSavedLong(ImpFortressDialogue.FORTRESS_MALES_CLEAR_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("impFortressMalesDefeatedTime").item(0)).getAttribute("value"))); } } catch(Exception ex) { } } // Load flags: for(int i=0; i<((Element) parentElement.getElementsByTagName("dialogueValues").item(0)).getElementsByTagName("dialogueValue").getLength(); i++){ Element e = (Element) ((Element) parentElement.getElementsByTagName("dialogueValues").item(0)).getElementsByTagName("dialogueValue").item(i); try { String flag = e.getAttribute("value"); if(flag.equalsIgnoreCase("punishedByAlexa")) { newFlags.values.add(DialogueFlagValue.punishedByHelena); } else { newFlags.values.add(DialogueFlagValue.valueOf(flag)); } } catch(Exception ex) { } } if(Main.isVersionOlderThan(Game.loadingVersion, "0.2.6.1")) { newFlags.values.remove(DialogueFlagValue.axelIntroduced); newFlags.values.remove(DialogueFlagValue.roxyIntroduced); newFlags.values.remove(DialogueFlagValue.eponaIntroduced); } if(Main.isVersionOlderThan(Game.loadingVersion, "0.2.11.5")) { // Add defeated flags so that the fortress will reset. newFlags.values.add(DialogueFlagValue.impFortressAlphaDefeated); newFlags.values.add(DialogueFlagValue.impFortressDemonDefeated); newFlags.values.add(DialogueFlagValue.impFortressFemalesDefeated); newFlags.values.add(DialogueFlagValue.impFortressMalesDefeated); } loadSet(parentElement, doc, newFlags.helenaConversationTopics, "helenaConversationTopics"); loadSet(parentElement, doc, newFlags.reindeerEncounteredIDs, "reindeerEncounteredIDs"); loadSet(parentElement, doc, newFlags.reindeerWorkedForIDs, "reindeerWorkedForIDs"); loadSet(parentElement, doc, newFlags.reindeerFuckedIDs, "reindeerFuckedIDs"); loadSet(parentElement, doc, newFlags.warehouseDefeatedIDs, "warehouseDefeatedIDs"); // if(parentElement.getElementsByTagName("supplierStorageRoomsChecked").item(0)!=null) { // for(int i=0; i<((Element) parentElement.getElementsByTagName("supplierStorageRoomsChecked").item(0)).getElementsByTagName("location").getLength(); i++){ // Element e = (Element) ((Element) parentElement.getElementsByTagName("supplierStorageRoomsChecked").item(0)).getElementsByTagName("location").item(i); // // newFlags.supplierStorageRoomsChecked.add( // new Vector2i( // Integer.valueOf(e.getAttribute("x")), // Integer.valueOf(e.getAttribute("y")))); // } // } return newFlags; } private static void saveSet(Element parentElement, Document doc, Set<String> set, String title) { Element valuesElement = doc.createElement(title); parentElement.appendChild(valuesElement); for(String value : set) { XMLUtil.createXMLElementWithValue(doc, valuesElement, "value", value.toString()); } } private static void loadSet(Element parentElement, Document doc, Set<String> set, String title) { try { if(parentElement.getElementsByTagName(title).item(0)!=null) { for(int i=0; i<((Element) parentElement.getElementsByTagName(title).item(0)).getElementsByTagName("value").getLength(); i++){ Element e = (Element) ((Element) parentElement.getElementsByTagName(title).item(0)).getElementsByTagName("value").item(i); set.add(e.getAttribute("value")); } } } catch(Exception ex) { } } public void dailyReset() { values.removeIf((flag)->flag.isDailyReset()); } public boolean hasFlag(DialogueFlagValue flag) { return values.contains(flag); } public void setFlag(DialogueFlagValue flag, boolean flagMarker) { if(flagMarker) { values.add(flag); } else { values.remove(flag); } } public void setSavedLong(String id, long value) { savedLongs.put(id, value); } /** * @return Increments the long saved to this id. Sets to -1 before incrementing if there was no entry found. */ public void incrementSavedLong(String id, long increment) { savedLongs.put(id, getSavedLong(id)+increment); } public boolean hasSavedLong(String id) { return savedLongs.containsKey(id); } public void removeSavedLong(String id) { savedLongs.remove(id); } /** * @return The long saved to this id. Sets and returns -1 if there was no entry found. */ public long getSavedLong(String id) { savedLongs.putIfAbsent(id, -1l); return savedLongs.get(id); } public NPC getSlaveTrader() { if(slaveTrader==null || slaveTrader.isEmpty()) { return null; } try { return (NPC) Main.game.getNPCById(slaveTrader); } catch (Exception e) { Util.logGetNpcByIdError("getSlaveTrader()", slaveTrader); return null; } } public void setSlaveTrader(GameCharacter slaveTrader) { if(slaveTrader==null) { this.slaveTrader = null; } else { this.slaveTrader = slaveTrader.getId(); } } public String getSlaveTraderId() { return slaveTrader; } public void setSlaveTraderId(String slaveTrader) { this.slaveTrader = slaveTrader; } public NPC getManagementCompanion() { if(managementCompanion==null || managementCompanion.isEmpty()) { return null; } try { return (NPC) Main.game.getNPCById(managementCompanion); } catch (Exception e) { Util.logGetNpcByIdError("getManagementCompanion()", managementCompanion); //e.printStackTrace(); return null; } } public void setManagementCompanion(GameCharacter managementCompanion) { if(managementCompanion==null) { this.managementCompanion = null; } else { this.managementCompanion = managementCompanion.getId(); } } public String getManagementCompanionId() { return managementCompanion; } public void setManagementCompanionId(String managementCompanion) { this.managementCompanion = managementCompanion; } // Reindeer event: public SlaveJob getSlaveryManagerJobSelected() { return slaveryManagerJobSelected; } public void setSlaveryManagerJobSelected(SlaveJob slaveryManagerJobSelected) { this.slaveryManagerJobSelected = slaveryManagerJobSelected; } public void addHelenaConversationTopic(HelenaConversationTopic topic) { helenaConversationTopics.add(topic.toString()); } public boolean hasHelenaConversationTopic(HelenaConversationTopic topic) { return helenaConversationTopics.contains(topic.toString()); } public void addReindeerEncountered(String reindeerID) { reindeerEncounteredIDs.add(reindeerID); } public boolean hasEncounteredReindeer(String reindeerID) { return reindeerEncounteredIDs.contains(reindeerID); } public boolean hasEncounteredAnyReindeers() { return !reindeerEncounteredIDs.isEmpty(); } public void addReindeerDailyWorkedFor(String reindeerID) { reindeerWorkedForIDs.add(reindeerID); } public boolean hasWorkedForReindeer(String reindeerID) { return reindeerWorkedForIDs.contains(reindeerID); } public void addReindeerDailyFucked(String reindeerID) { reindeerFuckedIDs.add(reindeerID); } public boolean hasFuckedReindeer(String reindeerID) { return reindeerFuckedIDs.contains(reindeerID); } public void dailyReindeerReset(String reindeerID) { reindeerWorkedForIDs.remove(reindeerID); } public int getMurkTfStage(GameCharacter target) { if(target.isPlayer()) { return murkPlayerTfStage; } return murkCompanionTfStage; } public void setMurkTfStage(GameCharacter target, int stage) { if(target.isPlayer()) { this.murkPlayerTfStage = stage; } else { this.murkCompanionTfStage = stage; } } public Colour getNatalyaCollarColour() { return natalyaCollarColour; } public void setNatalyaCollarColour(Colour natalyaCollarColour) { this.natalyaCollarColour = natalyaCollarColour; } public int getNatalyaPoints() { return natalyaPoints; } public void setNatalyaPoints(int natalyaPoints) { this.natalyaPoints = natalyaPoints; if(this.natalyaPoints<0) { this.natalyaPoints = 0; } } public String incrementNatalyaPoints(int increment) { setNatalyaPoints(getNatalyaPoints()+increment); boolean plural = increment!=1; StringBuilder sb = new StringBuilder(); sb.append("<p style='text-align:center;'>"); if(increment>0) { sb.append("You [style.colourGood(gained)] [style.boldPink("+increment+")] [style.colourPinkLight(filly point"+(plural?"s":"")+")]!"); } else { sb.append("You [style.colourBad(lost)] [style.boldPink("+(-increment)+")] [style.colourPinkLight(filly point"+(plural?"s":"")+")]!"); } sb.append("<br/>You now have [style.boldPink("+getNatalyaPoints()+")] [style.colourPinkLight(filly points)]!"); sb.append("</p>"); return sb.toString(); } public String getSadistNatalyaSlave() { return sadistNatalyaSlave; } public void setSadistNatalyaSlave(String sadistNatalyaSlave) { this.sadistNatalyaSlave = sadistNatalyaSlave; } }
23563_1
// Toelichting: // Het aantal plaatsen en aantal rijen is public static want ik wil die attributen in de tests gebruiken. Ik ga ervan uit dat de aantallen vast blijven, maar mocht ze dan toch gewijzigd worden in de toekomst dan kloppen de tests nog. package theater; import java.util.ArrayList; public class Theater { public final static int AANTALTRIJEN = 15; public final static int AANTALPERRIJ = 10; private int hoogsteKlantnummer = 0; private String naam; private ArrayList<Klant> klanten = new ArrayList<>(); private Voorstelling voorstelling; /** * Constructor functie voor Theater. * * @param naam neemt alleen een naam als parameter */ public Theater(String naam) { this.naam = naam; } private Klant zoekKlant(String naam, String telefoon) { Klant klant = null; for (Klant k : klanten) { if (telefoon.equals(k.getTelefoon()) && naam.trim().toLowerCase().equals(k.getNaam().trim().toLowerCase())) { klant = k; break; } } return klant; } /** * Maakt een nieuwe voorstelling aan. * Nu is er nog maar ruimte voor 1 voorstelling. * * @param naam naam van de voorstelling * @param datum datum dat deze plaatsvindt */ public void nieuweVoorstelling(String naam, String datum) { voorstelling = new Voorstelling(naam, datum); } /** * Voegt een nieuwe klant toe aan de ArrayList van klanten van het theater, mits deze nog niet is toegevoegd. * * @param naam naam van de klant * @param telefoon telefoonnummer van de klant */ public void nieuweKlant(String naam, String telefoon) { if (zoekKlant(naam, telefoon) == null) { klanten.add(new Klant(naam, hoogsteKlantnummer + 1, telefoon)); hoogsteKlantnummer++; } } /** * Reserveert een plaats voor een klant. * Een gereserveerde plaats kan weer vrijgemaakt worden. * * @param rij nummer van de rij * @param stoel nummer van de stoel */ public void reserveren(int rij, int stoel) { if (voorstelling != null) { voorstelling.reserveer(rij, stoel); } } /** * Als een klant plaatsen heeft gereserveerd kan deze worden geplaatst, waarna ze op bezet komen te staan. * Dit kan niet meer gewijzigd worden. * * @param naam naam van de klant * @param telefoon telefoonnummer van de klant */ public void plaatsen(String naam, String telefoon) { Klant klant = zoekKlant(naam, telefoon); if (voorstelling != null && klant != null) { voorstelling.plaatsKlant(klant); } } /** * Als de klant uiteindelijk niet geplaatst wordt, moeten alle reserveringen weer reset worden. */ public void resetten() { if (voorstelling != null) { voorstelling.resetAlleReserveringen(); } } /** * Geeft het aantal plaatsen van een bepaalde status terug. * * @param status geef de status mee die je zoekt * @return geeft het aantal plaatsen met deze status terug */ public int getAantalPlaatsen(Plaats.Status status) { int aantal = 0; if (voorstelling != null) { aantal = voorstelling.getPlaatsenStatus(status); } return aantal; } }
DreamEmulator/ou_java
object_oriented_programming/opdracht_4/src/theater/Theater.java
1,041
/** * Constructor functie voor Theater. * * @param naam neemt alleen een naam als parameter */
block_comment
nl
// Toelichting: // Het aantal plaatsen en aantal rijen is public static want ik wil die attributen in de tests gebruiken. Ik ga ervan uit dat de aantallen vast blijven, maar mocht ze dan toch gewijzigd worden in de toekomst dan kloppen de tests nog. package theater; import java.util.ArrayList; public class Theater { public final static int AANTALTRIJEN = 15; public final static int AANTALPERRIJ = 10; private int hoogsteKlantnummer = 0; private String naam; private ArrayList<Klant> klanten = new ArrayList<>(); private Voorstelling voorstelling; /** * Constructor functie voor<SUF>*/ public Theater(String naam) { this.naam = naam; } private Klant zoekKlant(String naam, String telefoon) { Klant klant = null; for (Klant k : klanten) { if (telefoon.equals(k.getTelefoon()) && naam.trim().toLowerCase().equals(k.getNaam().trim().toLowerCase())) { klant = k; break; } } return klant; } /** * Maakt een nieuwe voorstelling aan. * Nu is er nog maar ruimte voor 1 voorstelling. * * @param naam naam van de voorstelling * @param datum datum dat deze plaatsvindt */ public void nieuweVoorstelling(String naam, String datum) { voorstelling = new Voorstelling(naam, datum); } /** * Voegt een nieuwe klant toe aan de ArrayList van klanten van het theater, mits deze nog niet is toegevoegd. * * @param naam naam van de klant * @param telefoon telefoonnummer van de klant */ public void nieuweKlant(String naam, String telefoon) { if (zoekKlant(naam, telefoon) == null) { klanten.add(new Klant(naam, hoogsteKlantnummer + 1, telefoon)); hoogsteKlantnummer++; } } /** * Reserveert een plaats voor een klant. * Een gereserveerde plaats kan weer vrijgemaakt worden. * * @param rij nummer van de rij * @param stoel nummer van de stoel */ public void reserveren(int rij, int stoel) { if (voorstelling != null) { voorstelling.reserveer(rij, stoel); } } /** * Als een klant plaatsen heeft gereserveerd kan deze worden geplaatst, waarna ze op bezet komen te staan. * Dit kan niet meer gewijzigd worden. * * @param naam naam van de klant * @param telefoon telefoonnummer van de klant */ public void plaatsen(String naam, String telefoon) { Klant klant = zoekKlant(naam, telefoon); if (voorstelling != null && klant != null) { voorstelling.plaatsKlant(klant); } } /** * Als de klant uiteindelijk niet geplaatst wordt, moeten alle reserveringen weer reset worden. */ public void resetten() { if (voorstelling != null) { voorstelling.resetAlleReserveringen(); } } /** * Geeft het aantal plaatsen van een bepaalde status terug. * * @param status geef de status mee die je zoekt * @return geeft het aantal plaatsen met deze status terug */ public int getAantalPlaatsen(Plaats.Status status) { int aantal = 0; if (voorstelling != null) { aantal = voorstelling.getPlaatsenStatus(status); } return aantal; } }
79059_1
package h7.interface3.bke.models; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import h7.interface3.bke.interfaces.Model; class BKEModelTest { Model model; @BeforeEach void beforeEach() { model = new BKEModel(); } @Test void testGetSetCurrentPlayer() { assertEquals(Model.PLAYER1, model.getCurrentPlayer(), "Eerste speler"); model.setCurrentPlayer(Model.PLAYER2); assertEquals(Model.PLAYER2, model.getCurrentPlayer(), "Aanpassen speler"); model.setCurrentPlayer('t'); assertEquals(Model.PLAYER2, model.getCurrentPlayer(), "Ongeldige speler"); } @Test void testSetField() { int testId = 1; model.setField(testId); assertEquals(model.getCurrentPlayer(), model.getFields()[testId], "Goede veld gezet"); for (int i=0; i<BKEModel.FIELDCOUNT; i++) { if (i!=testId) { assertEquals(0, model.getFields()[i], "Veld "+i+" niet gezet"); } } } @Test void testCanSet() { int testId = 1; assertEquals(true, model.canSet(testId), "Leeg veld"); model.setField(testId); assertEquals(false, model.canSet(testId),"Veld al gevuld"); model.setField(-1); assertEquals(false, model.canSet(testId),"Id te laag"); model.setField(10); assertEquals(false, model.canSet(testId),"Id te hoog"); } @Test void testGetTurns() { assertEquals(0, model.getTurns(), "Start van het spel"); model.setField(1); assertEquals(1, model.getTurns(), "Een beurt geweest"); //zelfde veld, dus geen verandering in aantal beurten model.setField(1); assertEquals(1, model.getTurns(), "Verkeerde zet, geen extra beurt"); model.setField(2); assertEquals(2, model.getTurns(), "Twee beurten geweest"); } @Test void testReset() { //zet 2 velden in het model model.setField(1); model.setCurrentPlayer(Model.PLAYER2); model.setField(2); assertEquals(2, model.getTurns(), "2 beurten"); model.reset(); //alle velden moeten leeg zijn en huidige speler PLAYER1 assertEquals(Model.PLAYER1, model.getCurrentPlayer(),"Speler 1"); assertEquals(0, model.getTurns(), "0 beurten"); for(char check: model.getFields()) { assertEquals(0, check, "Veld is niet leeg"); } } }
DrentheCollege/LE-A4-Java-MVC-Testen
src/h7/interface3/bke/models/BKEModelTest.java
843
//zet 2 velden in het model
line_comment
nl
package h7.interface3.bke.models; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import h7.interface3.bke.interfaces.Model; class BKEModelTest { Model model; @BeforeEach void beforeEach() { model = new BKEModel(); } @Test void testGetSetCurrentPlayer() { assertEquals(Model.PLAYER1, model.getCurrentPlayer(), "Eerste speler"); model.setCurrentPlayer(Model.PLAYER2); assertEquals(Model.PLAYER2, model.getCurrentPlayer(), "Aanpassen speler"); model.setCurrentPlayer('t'); assertEquals(Model.PLAYER2, model.getCurrentPlayer(), "Ongeldige speler"); } @Test void testSetField() { int testId = 1; model.setField(testId); assertEquals(model.getCurrentPlayer(), model.getFields()[testId], "Goede veld gezet"); for (int i=0; i<BKEModel.FIELDCOUNT; i++) { if (i!=testId) { assertEquals(0, model.getFields()[i], "Veld "+i+" niet gezet"); } } } @Test void testCanSet() { int testId = 1; assertEquals(true, model.canSet(testId), "Leeg veld"); model.setField(testId); assertEquals(false, model.canSet(testId),"Veld al gevuld"); model.setField(-1); assertEquals(false, model.canSet(testId),"Id te laag"); model.setField(10); assertEquals(false, model.canSet(testId),"Id te hoog"); } @Test void testGetTurns() { assertEquals(0, model.getTurns(), "Start van het spel"); model.setField(1); assertEquals(1, model.getTurns(), "Een beurt geweest"); //zelfde veld, dus geen verandering in aantal beurten model.setField(1); assertEquals(1, model.getTurns(), "Verkeerde zet, geen extra beurt"); model.setField(2); assertEquals(2, model.getTurns(), "Twee beurten geweest"); } @Test void testReset() { //zet 2<SUF> model.setField(1); model.setCurrentPlayer(Model.PLAYER2); model.setField(2); assertEquals(2, model.getTurns(), "2 beurten"); model.reset(); //alle velden moeten leeg zijn en huidige speler PLAYER1 assertEquals(Model.PLAYER1, model.getCurrentPlayer(),"Speler 1"); assertEquals(0, model.getTurns(), "0 beurten"); for(char check: model.getFields()) { assertEquals(0, check, "Veld is niet leeg"); } } }
140933_12
package dojo.rooms.rooms.search; import contrib.components.InteractionComponent; import contrib.components.InventoryComponent; import contrib.components.UIComponent; import contrib.entities.EntityFactory; import contrib.entities.WorldItemBuilder; import contrib.hud.dialogs.OkDialog; import contrib.hud.elements.GUICombination; import contrib.hud.inventory.InventoryGUI; import contrib.item.Item; import contrib.level.generator.graphBased.RoomGenerator; import contrib.utils.components.draw.ChestAnimations; import core.Entity; import core.components.DrawComponent; import core.level.utils.DesignLabel; import core.level.utils.LevelSize; import core.utils.components.draw.Animation; import core.utils.components.path.IPath; import core.utils.components.path.SimpleIPath; import dojo.rooms.LevelRoom; import dojo.rooms.MonsterRoom; import dojo.rooms.Room; import java.io.IOException; import java.util.*; /** * Informationen für den Spieler über diesen Raum: * * <p>Der Spieler muss Schriftrollen, die verschiedene Programming Patterns und Software Development * Principles repräsentieren, den entsprechenden Truhen zuordnen. Die Truhen sind mit den Kategorien * der Programming Patterns und Software Development Principles beschriftet. Erst wenn alle * Schriftrollen korrekt zugeordnet sind, kann der Spieler in den nächsten Raum weitergehen. */ public class Fragen_Schriftrollen extends MonsterRoom { HashMap<String, ArrayList<String>> sortables; HashMap<Entity, Boolean> doneChests = new HashMap<>(); /** * Generate a new room. * * @param levelRoom the level node * @param gen the room generator * @param nextRoom the rooms next room * @param levelSize the size of this room * @param designLabel the design label of this room * @param monsterCount the number of monsters in this room * @param monsterPaths the paths of the monsters in this room * @param sortables a map of the sortables in this room */ public Fragen_Schriftrollen( LevelRoom levelRoom, RoomGenerator gen, Room nextRoom, LevelSize levelSize, DesignLabel designLabel, int monsterCount, IPath[] monsterPaths, HashMap<String, ArrayList<String>> sortables) { super(levelRoom, gen, nextRoom, levelSize, designLabel, monsterCount, monsterPaths); this.sortables = sortables; try { generate(); } catch (Exception e) { throw new RuntimeException( "Failed to generate: " + getClass().getName() + ": " + e.getMessage(), e); } } private void generate() throws IOException { // add entities to room Set<Entity> roomEntities = populateMonsters(getMonsterCount(), getMonsterPaths()); // add chest for each sortable for (Map.Entry<String, ArrayList<String>> sortable : sortables.entrySet()) { Entity chest = EntityFactory.newChest(); chest.name(sortable.getKey()); chest.remove(InventoryComponent.class); chest.add(new InventoryComponent()); InventoryComponent ic = chest.fetch(InventoryComponent.class).orElseThrow(); chest.add( new InteractionComponent( 1, true, (interacted, interactor) -> { OkDialog.showOkDialog( "Platziere die Schriftrollen die zum Thema " + sortable.getKey() + " passen in die Truhe.", "Schriftrollen sortieren", () -> { interactor .fetch(InventoryComponent.class) .ifPresent( whoIc -> { UIComponent uiComponent = new UIComponent( new GUICombination( new InventoryGUI(whoIc), new InventoryGUI(ic)), true); uiComponent.onClose( () -> { interacted .fetch(DrawComponent.class) .ifPresent( interactedDC -> { // remove all // prior // opened // animations interactedDC.deQueueByPriority( ChestAnimations.OPEN_FULL.priority()); if (ic.count() > 0) { // as long // as // there is // an // item // inside // the chest // show a // full // chest interactedDC.queueAnimation( ChestAnimations.OPEN_FULL); } else { // empty // chest // show the // empty // animation interactedDC.queueAnimation( ChestAnimations.OPEN_EMPTY); } }); // check if all items are sorted if (ic.count() == sortable.getValue().size()) { boolean allcorrect = true; // iterate over items in inventory for (Item item : ic.items()) { if (item != null && !sortable .getValue() .contains(item.description())) { allcorrect = false; } } if (allcorrect) { // all items are sorted correctly // mark chest as done doneChests.put(interacted, true); OkDialog.showOkDialog( "Gut gemacht!", "Gelöst!", () -> {}); } else { // not all items are sorted correctly // mark chest as not done doneChests.put(interacted, false); OkDialog.showOkDialog( "Die Truhe ist noch nicht richtig belegt!", "Schade!", () -> {}); } } // check if all chests are done if (doneChests.values().stream() .allMatch(Boolean::booleanValue)) { // all chests are done // open the doors openDoors(); OkDialog.showOkDialog( "Alle Truhen sind richtig belegt, die Tür ist offen!", "Geschafft!", () -> {}); } }); interactor.add(uiComponent); }); interacted .fetch(DrawComponent.class) .ifPresent( interactedDC -> { // only add opening animation when it is not // finished if (interactedDC .animation(ChestAnimations.OPENING) .map(animation -> !animation.isFinished()) .orElse(true)) { interactedDC.queueAnimation(ChestAnimations.OPENING); } }); }); })); roomEntities.add(chest); // add the sortable items to the room for (String item : sortable.getValue()) { Item newItem = new Item( "Schriftrolle", item, Animation.fromSingleImage(new SimpleIPath("items/resource/cheese.png"))); Entity itemEntity = WorldItemBuilder.buildWorldItem(newItem); roomEntities.add(itemEntity); } } // add the entities as payload to the LevelNode addRoomEntities(roomEntities); } }
Dungeon-CampusMinden/Dungeon
dojo-dungeon/src/dojo/rooms/rooms/search/Fragen_Schriftrollen.java
2,244
// open the doors
line_comment
nl
package dojo.rooms.rooms.search; import contrib.components.InteractionComponent; import contrib.components.InventoryComponent; import contrib.components.UIComponent; import contrib.entities.EntityFactory; import contrib.entities.WorldItemBuilder; import contrib.hud.dialogs.OkDialog; import contrib.hud.elements.GUICombination; import contrib.hud.inventory.InventoryGUI; import contrib.item.Item; import contrib.level.generator.graphBased.RoomGenerator; import contrib.utils.components.draw.ChestAnimations; import core.Entity; import core.components.DrawComponent; import core.level.utils.DesignLabel; import core.level.utils.LevelSize; import core.utils.components.draw.Animation; import core.utils.components.path.IPath; import core.utils.components.path.SimpleIPath; import dojo.rooms.LevelRoom; import dojo.rooms.MonsterRoom; import dojo.rooms.Room; import java.io.IOException; import java.util.*; /** * Informationen für den Spieler über diesen Raum: * * <p>Der Spieler muss Schriftrollen, die verschiedene Programming Patterns und Software Development * Principles repräsentieren, den entsprechenden Truhen zuordnen. Die Truhen sind mit den Kategorien * der Programming Patterns und Software Development Principles beschriftet. Erst wenn alle * Schriftrollen korrekt zugeordnet sind, kann der Spieler in den nächsten Raum weitergehen. */ public class Fragen_Schriftrollen extends MonsterRoom { HashMap<String, ArrayList<String>> sortables; HashMap<Entity, Boolean> doneChests = new HashMap<>(); /** * Generate a new room. * * @param levelRoom the level node * @param gen the room generator * @param nextRoom the rooms next room * @param levelSize the size of this room * @param designLabel the design label of this room * @param monsterCount the number of monsters in this room * @param monsterPaths the paths of the monsters in this room * @param sortables a map of the sortables in this room */ public Fragen_Schriftrollen( LevelRoom levelRoom, RoomGenerator gen, Room nextRoom, LevelSize levelSize, DesignLabel designLabel, int monsterCount, IPath[] monsterPaths, HashMap<String, ArrayList<String>> sortables) { super(levelRoom, gen, nextRoom, levelSize, designLabel, monsterCount, monsterPaths); this.sortables = sortables; try { generate(); } catch (Exception e) { throw new RuntimeException( "Failed to generate: " + getClass().getName() + ": " + e.getMessage(), e); } } private void generate() throws IOException { // add entities to room Set<Entity> roomEntities = populateMonsters(getMonsterCount(), getMonsterPaths()); // add chest for each sortable for (Map.Entry<String, ArrayList<String>> sortable : sortables.entrySet()) { Entity chest = EntityFactory.newChest(); chest.name(sortable.getKey()); chest.remove(InventoryComponent.class); chest.add(new InventoryComponent()); InventoryComponent ic = chest.fetch(InventoryComponent.class).orElseThrow(); chest.add( new InteractionComponent( 1, true, (interacted, interactor) -> { OkDialog.showOkDialog( "Platziere die Schriftrollen die zum Thema " + sortable.getKey() + " passen in die Truhe.", "Schriftrollen sortieren", () -> { interactor .fetch(InventoryComponent.class) .ifPresent( whoIc -> { UIComponent uiComponent = new UIComponent( new GUICombination( new InventoryGUI(whoIc), new InventoryGUI(ic)), true); uiComponent.onClose( () -> { interacted .fetch(DrawComponent.class) .ifPresent( interactedDC -> { // remove all // prior // opened // animations interactedDC.deQueueByPriority( ChestAnimations.OPEN_FULL.priority()); if (ic.count() > 0) { // as long // as // there is // an // item // inside // the chest // show a // full // chest interactedDC.queueAnimation( ChestAnimations.OPEN_FULL); } else { // empty // chest // show the // empty // animation interactedDC.queueAnimation( ChestAnimations.OPEN_EMPTY); } }); // check if all items are sorted if (ic.count() == sortable.getValue().size()) { boolean allcorrect = true; // iterate over items in inventory for (Item item : ic.items()) { if (item != null && !sortable .getValue() .contains(item.description())) { allcorrect = false; } } if (allcorrect) { // all items are sorted correctly // mark chest as done doneChests.put(interacted, true); OkDialog.showOkDialog( "Gut gemacht!", "Gelöst!", () -> {}); } else { // not all items are sorted correctly // mark chest as not done doneChests.put(interacted, false); OkDialog.showOkDialog( "Die Truhe ist noch nicht richtig belegt!", "Schade!", () -> {}); } } // check if all chests are done if (doneChests.values().stream() .allMatch(Boolean::booleanValue)) { // all chests are done // open the<SUF> openDoors(); OkDialog.showOkDialog( "Alle Truhen sind richtig belegt, die Tür ist offen!", "Geschafft!", () -> {}); } }); interactor.add(uiComponent); }); interacted .fetch(DrawComponent.class) .ifPresent( interactedDC -> { // only add opening animation when it is not // finished if (interactedDC .animation(ChestAnimations.OPENING) .map(animation -> !animation.isFinished()) .orElse(true)) { interactedDC.queueAnimation(ChestAnimations.OPENING); } }); }); })); roomEntities.add(chest); // add the sortable items to the room for (String item : sortable.getValue()) { Item newItem = new Item( "Schriftrolle", item, Animation.fromSingleImage(new SimpleIPath("items/resource/cheese.png"))); Entity itemEntity = WorldItemBuilder.buildWorldItem(newItem); roomEntities.add(itemEntity); } } // add the entities as payload to the LevelNode addRoomEntities(roomEntities); } }
84013_2
package site.nerdygadgets.views; import site.nerdygadgets.functions.ComboRenderer; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; /** * DesignPanel class * DesignPanel for infrastructures * * @author Tristan Scholten & Jordy Wielaard * @version 1.0 * @since 14-05-2020 */ public class DesignPanel extends JPanel { private JPanel jpDesign; private JPanel jpMakeDesign; private JPanel jpDisplay; private JPanel jpDisplayPanel; private JPanel jpDisplayControls; private JComboBox jcDatabase; private JComboBox jcWeb; private JComboBox jcFirewall; private JButton jbOpt; private JButton saveButton; private JLabel jlPrice; private JLabel jlAvailability; private JTable jTable; private DefaultTableModel tableModel; public DesignPanel() { setLayout(new GridLayout(0, 2)); jpMakeDesign = new JPanel(); jpMakeDesign.setPreferredSize(new Dimension(600, 650)); jpMakeDesign.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0)); //Make panel left side jpDesign = new JPanel(); add(jpDesign); jpDesign.setLayout(new FlowLayout()); jpDesign.add(jpMakeDesign); //init Content left panel jcDatabase = new JComboBox(new String[]{""}); jcDatabase.setPreferredSize(new Dimension(120, 17)); jcWeb = new JComboBox(new String[]{""}); jcWeb.setPreferredSize(new Dimension(120, 17)); jcFirewall = new JComboBox(new String[]{""}); jcFirewall.setPreferredSize(new Dimension(120, 17)); jcDatabase.setRenderer(new ComboRenderer("Databaseservers")); jcDatabase.setSelectedIndex(-1); jcWeb.setRenderer(new ComboRenderer("Webservers")); jcWeb.setSelectedIndex(-1); jcFirewall.setRenderer(new ComboRenderer("Firewall")); jcFirewall.setSelectedIndex(-1); tableModel = new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { //Add custom amount if (column == 4) return true; //make buttons function if (column == 5 || column == 6 || column == 7) return true; return false; } //Only able to enter integer in amount column @Override public Class<?> getColumnClass(int columnIndex) { if (columnIndex == 4) return Integer.class; return super.getColumnClass(columnIndex); } @Override //check if amount is not negative and/or below 1 public void fireTableCellUpdated(int row, int column) { if (column == 4) { if (Integer.parseInt(super.getValueAt(row, column).toString()) < 0) super.setValueAt(Integer.parseInt(super.getValueAt(row, column).toString()) * -1, row, column); else if (Integer.parseInt(super.getValueAt(row, column).toString()) < 1) super.setValueAt(1, row, column); } super.fireTableCellUpdated(row, column); } }; //adds the columnnames tableModel.addColumn("Type"); tableModel.addColumn("Naam"); tableModel.addColumn("Beschikbaarheid"); tableModel.addColumn("Prijs"); tableModel.addColumn("Aantal"); tableModel.addColumn("Verhogen"); tableModel.addColumn("Verlagen"); tableModel.addColumn("Verwijder"); jTable = new JTable(tableModel); JScrollPane sp = new JScrollPane(jTable); sp.setPreferredSize(new Dimension(550, 590)); sp.setBorder(BorderFactory.createLineBorder(Color.black)); saveButton = new JButton("Opslaan Als"); jpMakeDesign.add(jcDatabase); jpMakeDesign.add(jcWeb); jpMakeDesign.add(jcFirewall); jpMakeDesign.add(sp); jpMakeDesign.add(saveButton); jlPrice = new JLabel("€0.0"); jlAvailability = new JLabel("0.0%"); //Panels right side //jpDisplayPanel is for graphics jpDisplay = new JPanel(); add(jpDisplay); jpDisplay.setLayout(new FlowLayout()); jpDisplayPanel = new JPanel(); jpDisplayPanel.setPreferredSize(new Dimension(550, 590)); jpDisplayPanel.setBorder(BorderFactory.createLineBorder(Color.black)); jpDisplayControls = new JPanel(); jpDisplayControls.setPreferredSize(new Dimension(600, 650)); jpDisplayControls.setBorder(BorderFactory.createEmptyBorder(0, 50, 0, 50)); //init Content right panel jbOpt = new JButton("Optimaliseer"); //Add all content jpDisplay.add(jpDisplayControls); jpDisplayControls.add(jbOpt); jpDisplayControls.add(jpDisplayPanel); jpDisplayControls.add(new JLabel("Prijs")); jpDisplayControls.add(jlPrice); jpDisplayControls.add(new JLabel("Beschikbaarheid")); jpDisplayControls.add(jlAvailability); } public JComboBox getJcDatabase() { return jcDatabase; } public JComboBox getJcFirewall() { return jcFirewall; } public JComboBox getJcWeb() { return jcWeb; } public JButton getJbOpt() { return jbOpt; } public JButton getSaveButton() { return saveButton; } public JLabel getJlPrice() { return jlPrice; } public JLabel getJlAvailability() { return jlAvailability; } public JTable getJTable() { return jTable; } public DefaultTableModel getTableModel() { return tableModel; } public JPanel getJpDisplayPanel() { return jpDisplayPanel; } }
DylanMRoubos/ICTM2o2
NerdyGadgetsApp/src/main/java/site/nerdygadgets/views/DesignPanel.java
1,753
//init Content left panel
line_comment
nl
package site.nerdygadgets.views; import site.nerdygadgets.functions.ComboRenderer; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; /** * DesignPanel class * DesignPanel for infrastructures * * @author Tristan Scholten & Jordy Wielaard * @version 1.0 * @since 14-05-2020 */ public class DesignPanel extends JPanel { private JPanel jpDesign; private JPanel jpMakeDesign; private JPanel jpDisplay; private JPanel jpDisplayPanel; private JPanel jpDisplayControls; private JComboBox jcDatabase; private JComboBox jcWeb; private JComboBox jcFirewall; private JButton jbOpt; private JButton saveButton; private JLabel jlPrice; private JLabel jlAvailability; private JTable jTable; private DefaultTableModel tableModel; public DesignPanel() { setLayout(new GridLayout(0, 2)); jpMakeDesign = new JPanel(); jpMakeDesign.setPreferredSize(new Dimension(600, 650)); jpMakeDesign.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0)); //Make panel left side jpDesign = new JPanel(); add(jpDesign); jpDesign.setLayout(new FlowLayout()); jpDesign.add(jpMakeDesign); //init Content<SUF> jcDatabase = new JComboBox(new String[]{""}); jcDatabase.setPreferredSize(new Dimension(120, 17)); jcWeb = new JComboBox(new String[]{""}); jcWeb.setPreferredSize(new Dimension(120, 17)); jcFirewall = new JComboBox(new String[]{""}); jcFirewall.setPreferredSize(new Dimension(120, 17)); jcDatabase.setRenderer(new ComboRenderer("Databaseservers")); jcDatabase.setSelectedIndex(-1); jcWeb.setRenderer(new ComboRenderer("Webservers")); jcWeb.setSelectedIndex(-1); jcFirewall.setRenderer(new ComboRenderer("Firewall")); jcFirewall.setSelectedIndex(-1); tableModel = new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { //Add custom amount if (column == 4) return true; //make buttons function if (column == 5 || column == 6 || column == 7) return true; return false; } //Only able to enter integer in amount column @Override public Class<?> getColumnClass(int columnIndex) { if (columnIndex == 4) return Integer.class; return super.getColumnClass(columnIndex); } @Override //check if amount is not negative and/or below 1 public void fireTableCellUpdated(int row, int column) { if (column == 4) { if (Integer.parseInt(super.getValueAt(row, column).toString()) < 0) super.setValueAt(Integer.parseInt(super.getValueAt(row, column).toString()) * -1, row, column); else if (Integer.parseInt(super.getValueAt(row, column).toString()) < 1) super.setValueAt(1, row, column); } super.fireTableCellUpdated(row, column); } }; //adds the columnnames tableModel.addColumn("Type"); tableModel.addColumn("Naam"); tableModel.addColumn("Beschikbaarheid"); tableModel.addColumn("Prijs"); tableModel.addColumn("Aantal"); tableModel.addColumn("Verhogen"); tableModel.addColumn("Verlagen"); tableModel.addColumn("Verwijder"); jTable = new JTable(tableModel); JScrollPane sp = new JScrollPane(jTable); sp.setPreferredSize(new Dimension(550, 590)); sp.setBorder(BorderFactory.createLineBorder(Color.black)); saveButton = new JButton("Opslaan Als"); jpMakeDesign.add(jcDatabase); jpMakeDesign.add(jcWeb); jpMakeDesign.add(jcFirewall); jpMakeDesign.add(sp); jpMakeDesign.add(saveButton); jlPrice = new JLabel("€0.0"); jlAvailability = new JLabel("0.0%"); //Panels right side //jpDisplayPanel is for graphics jpDisplay = new JPanel(); add(jpDisplay); jpDisplay.setLayout(new FlowLayout()); jpDisplayPanel = new JPanel(); jpDisplayPanel.setPreferredSize(new Dimension(550, 590)); jpDisplayPanel.setBorder(BorderFactory.createLineBorder(Color.black)); jpDisplayControls = new JPanel(); jpDisplayControls.setPreferredSize(new Dimension(600, 650)); jpDisplayControls.setBorder(BorderFactory.createEmptyBorder(0, 50, 0, 50)); //init Content right panel jbOpt = new JButton("Optimaliseer"); //Add all content jpDisplay.add(jpDisplayControls); jpDisplayControls.add(jbOpt); jpDisplayControls.add(jpDisplayPanel); jpDisplayControls.add(new JLabel("Prijs")); jpDisplayControls.add(jlPrice); jpDisplayControls.add(new JLabel("Beschikbaarheid")); jpDisplayControls.add(jlAvailability); } public JComboBox getJcDatabase() { return jcDatabase; } public JComboBox getJcFirewall() { return jcFirewall; } public JComboBox getJcWeb() { return jcWeb; } public JButton getJbOpt() { return jbOpt; } public JButton getSaveButton() { return saveButton; } public JLabel getJlPrice() { return jlPrice; } public JLabel getJlAvailability() { return jlAvailability; } public JTable getJTable() { return jTable; } public DefaultTableModel getTableModel() { return tableModel; } public JPanel getJpDisplayPanel() { return jpDisplayPanel; } }
14044_1
// schrijf een klein rekenoefening programma die rekensommen maakt en om een input vraagt en de input checkt met het correcte antwoord. GEDAAN // # bouw een applicatie die twee random nummers uit print en hier een som van maakt. GEDAAN // # vervolgens moet deze om een invoer vragen en checken of de invoer klopt met de gegeven som. GEDAAN // # Bonus : maak de methode zo dat er een random operator wordt gebruikt van de soort + - * of /. en hier dus een som van maakt. GEDAAN // # Bonus bouw in dat je van te voren kan opgeven hoeveel vragen je wilt beantwoorden. GEDAAN // # Bonus: bouw een punten systeem erbij voor goede antwoorden en foute antwoorden. GEDAAN // # Bonus: bij het aftrekken kom je soms negatief uit. als dit het geval is draai dan de nummers om. GEDAAN // # Bonus: bij het delen kom je soms op decimalen uit. maak de functie zo dat dit niet meer het geval is. GEDAAN // # Tip modulo uitkomst van het grootste getal zetten en deze voorin in de berekening zetten GEDAAN // # Bonus: schrijf de functie zo dat je zelf kan ingeven hoe hoog de getalen mogen zijn GEDAAN import java.util.Random; import java.util.Scanner; public class Main { static char[] arithOperators = {'+', '-', '*', '/', '%'}; static int score; static int maxRounds; static int roundsCounter; static char getRandomOperator() { Random random = new Random(); return arithOperators[random.nextInt(0, arithOperators.length)]; } public static int getRandomInt(int maxBound) { Random random = new Random(); return random.nextInt(1, maxBound + 1); } // return solution as int public static int getSolution(int num1, int num2, char operator) { double solution = doTheMagic(num1, num2, operator); //round to nearest int return (int) Math.round(solution + .49999); } // check operator and calculate private static double doTheMagic(int num1, int num2, char operator) { switch (operator) { case '+': return num1 + num2; case '-': return num1 - num2; case '*': return num1 * num2; case '/': return num1 / num2; case '%': return num1 % num2; default: return -1; // Never used } } public static int getUserGuess(Scanner scanner) { String promptOne = "Guess the outcome. Whole numbers only: "; int guess = checkIfInt(scanner, promptOne); System.out.println("Your guess: " + guess); return guess; } // check if user input is an int. private static int checkIfInt(Scanner scanner, String promptOne) { int number = 0; boolean notANumber = true; while(notANumber) { System.out.print(promptOne); try { number = scanner.nextInt(); scanner.nextLine(); notANumber = false; } catch (Exception e) { System.out.println("That is not a whole number. Try again."); scanner.nextLine(); } } return number; } public static void guessedCorrect(int solution, int userGuess) { if(solution == userGuess) { System.out.println("You've guessed CORRECT and scored a point"); score++; } else { System.out.println("WRONG GUESS!! The answer was: " + solution); System.out.println("One point subtracted ):"); score--; } System.out.println("Current score: " + score); } public static int getRounds(Scanner scanner) { int rounds = 0; boolean illegalNumber = true; String promptOne = "Enter number of rounds you want to play (1-10): "; while(illegalNumber) { rounds = checkIfInt(scanner, promptOne); if(rounds < 1 || rounds > 10) { System.out.println("Only from 1-10. Try again"); } else{ illegalNumber = false; } } System.out.println("Number of rounds to play: " + rounds); return rounds; } public static int getMaxBound(Scanner scanner) { int maxBound = 0; boolean illegalNumber = true; String promptOne = "Enter the heighest number for calculation (2-100): "; while(illegalNumber) { maxBound = checkIfInt(scanner, promptOne); if(maxBound < 2 || maxBound > 100) { System.out.println("Only from 2-100. Try again"); } else{ illegalNumber = false; } } System.out.println("Heighest number to calculate with: " + maxBound); return maxBound; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); maxRounds = getRounds(scanner); int maxBound = getMaxBound(scanner); // Start of rounds while(roundsCounter < maxRounds) { // create two random integers and one random operator int randNumber1 = getRandomInt(maxBound); int randNumber2 = getRandomInt(maxBound); char randNumberOperator = getRandomOperator(); // The minus/modulo-swap, biggest number first. if((randNumberOperator == '%' || randNumberOperator == '-') && (randNumber1 < randNumber2)) { int tempNumber = randNumber1; randNumber1 = randNumber2; randNumber2 = tempNumber; } // Gameplay: System.out.println("\nROUND: " + (roundsCounter + 1)); System.out.println("\nThe challenge is: " + randNumber1 + " " + randNumberOperator + " " + randNumber2); int solution = getSolution(randNumber1, randNumber2, randNumberOperator); System.out.println("The solution is: " + solution); int userGuess = getUserGuess(scanner); guessedCorrect(solution, userGuess); roundsCounter++; System.out.println("*************"); } System.out.println("Game has ended. You've played " + maxRounds + " rounds and your final score is: " + score); } }
EAM26/CalcEx
src/Main.java
1,741
// # bouw een applicatie die twee random nummers uit print en hier een som van maakt. GEDAAN
line_comment
nl
// schrijf een klein rekenoefening programma die rekensommen maakt en om een input vraagt en de input checkt met het correcte antwoord. GEDAAN // # bouw<SUF> // # vervolgens moet deze om een invoer vragen en checken of de invoer klopt met de gegeven som. GEDAAN // # Bonus : maak de methode zo dat er een random operator wordt gebruikt van de soort + - * of /. en hier dus een som van maakt. GEDAAN // # Bonus bouw in dat je van te voren kan opgeven hoeveel vragen je wilt beantwoorden. GEDAAN // # Bonus: bouw een punten systeem erbij voor goede antwoorden en foute antwoorden. GEDAAN // # Bonus: bij het aftrekken kom je soms negatief uit. als dit het geval is draai dan de nummers om. GEDAAN // # Bonus: bij het delen kom je soms op decimalen uit. maak de functie zo dat dit niet meer het geval is. GEDAAN // # Tip modulo uitkomst van het grootste getal zetten en deze voorin in de berekening zetten GEDAAN // # Bonus: schrijf de functie zo dat je zelf kan ingeven hoe hoog de getalen mogen zijn GEDAAN import java.util.Random; import java.util.Scanner; public class Main { static char[] arithOperators = {'+', '-', '*', '/', '%'}; static int score; static int maxRounds; static int roundsCounter; static char getRandomOperator() { Random random = new Random(); return arithOperators[random.nextInt(0, arithOperators.length)]; } public static int getRandomInt(int maxBound) { Random random = new Random(); return random.nextInt(1, maxBound + 1); } // return solution as int public static int getSolution(int num1, int num2, char operator) { double solution = doTheMagic(num1, num2, operator); //round to nearest int return (int) Math.round(solution + .49999); } // check operator and calculate private static double doTheMagic(int num1, int num2, char operator) { switch (operator) { case '+': return num1 + num2; case '-': return num1 - num2; case '*': return num1 * num2; case '/': return num1 / num2; case '%': return num1 % num2; default: return -1; // Never used } } public static int getUserGuess(Scanner scanner) { String promptOne = "Guess the outcome. Whole numbers only: "; int guess = checkIfInt(scanner, promptOne); System.out.println("Your guess: " + guess); return guess; } // check if user input is an int. private static int checkIfInt(Scanner scanner, String promptOne) { int number = 0; boolean notANumber = true; while(notANumber) { System.out.print(promptOne); try { number = scanner.nextInt(); scanner.nextLine(); notANumber = false; } catch (Exception e) { System.out.println("That is not a whole number. Try again."); scanner.nextLine(); } } return number; } public static void guessedCorrect(int solution, int userGuess) { if(solution == userGuess) { System.out.println("You've guessed CORRECT and scored a point"); score++; } else { System.out.println("WRONG GUESS!! The answer was: " + solution); System.out.println("One point subtracted ):"); score--; } System.out.println("Current score: " + score); } public static int getRounds(Scanner scanner) { int rounds = 0; boolean illegalNumber = true; String promptOne = "Enter number of rounds you want to play (1-10): "; while(illegalNumber) { rounds = checkIfInt(scanner, promptOne); if(rounds < 1 || rounds > 10) { System.out.println("Only from 1-10. Try again"); } else{ illegalNumber = false; } } System.out.println("Number of rounds to play: " + rounds); return rounds; } public static int getMaxBound(Scanner scanner) { int maxBound = 0; boolean illegalNumber = true; String promptOne = "Enter the heighest number for calculation (2-100): "; while(illegalNumber) { maxBound = checkIfInt(scanner, promptOne); if(maxBound < 2 || maxBound > 100) { System.out.println("Only from 2-100. Try again"); } else{ illegalNumber = false; } } System.out.println("Heighest number to calculate with: " + maxBound); return maxBound; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); maxRounds = getRounds(scanner); int maxBound = getMaxBound(scanner); // Start of rounds while(roundsCounter < maxRounds) { // create two random integers and one random operator int randNumber1 = getRandomInt(maxBound); int randNumber2 = getRandomInt(maxBound); char randNumberOperator = getRandomOperator(); // The minus/modulo-swap, biggest number first. if((randNumberOperator == '%' || randNumberOperator == '-') && (randNumber1 < randNumber2)) { int tempNumber = randNumber1; randNumber1 = randNumber2; randNumber2 = tempNumber; } // Gameplay: System.out.println("\nROUND: " + (roundsCounter + 1)); System.out.println("\nThe challenge is: " + randNumber1 + " " + randNumberOperator + " " + randNumber2); int solution = getSolution(randNumber1, randNumber2, randNumberOperator); System.out.println("The solution is: " + solution); int userGuess = getUserGuess(scanner); guessedCorrect(solution, userGuess); roundsCounter++; System.out.println("*************"); } System.out.println("Game has ended. You've played " + maxRounds + " rounds and your final score is: " + score); } }
7423_2
import java.util.HashSet; import java.util.Objects; import java.util.Scanner; public class Main { public static void main(String[] args) { // Hier mag je je code scrijven voor de hoofd-opdracht /* deze regel mag je weg halen voor de bonus opdracht. Onderstaande code is voor de bonus opdracht. HashSet<Integer> secretnumber = randomnumbergenerator(); String stringnumber = setToStringConverter(secretnumber); System.out.println(stringnumber); feedback(); deze regel mag je weg halen voor de bonus opdracht */ } /* Deze methode is voor de bonus opdracht. */ public static void feedback(String stringnumber) { Scanner scanner = new Scanner(System.in); StringBuilder feedback = new StringBuilder(); System.out.println("take a guess"); String guess = scanner.nextLine(); if (Objects.equals(guess, stringnumber)) { System.out.println("gefeliciteerd je hebt het goed"); } else { for (int i = 0; i < 4; i++) { if (guess.substring(i, i + 1).equals(stringnumber.substring(i, i + 1))) { feedback.append("+"); } else if (stringnumber.contains(guess.substring(i, i + 1))) { feedback.append("0"); } else { feedback.append("X"); } } } System.out.println(feedback.toString()); } }
EAM26/Huiswerk-Les4
src/Main.java
415
/* Deze methode is voor de bonus opdracht. */
block_comment
nl
import java.util.HashSet; import java.util.Objects; import java.util.Scanner; public class Main { public static void main(String[] args) { // Hier mag je je code scrijven voor de hoofd-opdracht /* deze regel mag je weg halen voor de bonus opdracht. Onderstaande code is voor de bonus opdracht. HashSet<Integer> secretnumber = randomnumbergenerator(); String stringnumber = setToStringConverter(secretnumber); System.out.println(stringnumber); feedback(); deze regel mag je weg halen voor de bonus opdracht */ } /* Deze methode is<SUF>*/ public static void feedback(String stringnumber) { Scanner scanner = new Scanner(System.in); StringBuilder feedback = new StringBuilder(); System.out.println("take a guess"); String guess = scanner.nextLine(); if (Objects.equals(guess, stringnumber)) { System.out.println("gefeliciteerd je hebt het goed"); } else { for (int i = 0; i < 4; i++) { if (guess.substring(i, i + 1).equals(stringnumber.substring(i, i + 1))) { feedback.append("+"); } else if (stringnumber.contains(guess.substring(i, i + 1))) { feedback.append("0"); } else { feedback.append("X"); } } } System.out.println(feedback.toString()); } }
7379_0
package nl.novi.javaprogrammeren; import nl.novi.javaprogrammeren.overerving.*; public class AnimalMain { public static void main(String[] args) { Lion l1 = new Lion("Sinbad", "male", true, 1); l1.eat("antilope"); l1.move(); Tigre t1 = new Tigre("Shere Khan", "male", true, 2); t1.eat("Mowgli"); t1.move(); Wolf w1 = new Wolf("Akela", "male", true, 3); w1.eat("sheep"); w1.move(); Dog d1 = new Dog("Fido", "female", false, "Jan"); Zoo artis = new Zoo(); artis.addToZoo(l1); artis.addToZoo(t1); artis.addToZoo(d1); artis.showZooAnimals(); } /* Het is traditie om overerving uit te leggen met behulp van dieren. Hier ontkomen jullie dus ook niet aan. Opdracht Bekijk de beschrijving van onderstaande dieren. Bedenk wat je in de superklasse kan zetten. De subklassen hoef je nog niet te maken. Van een Leeuw slaan we de naam, naam van het hok, geslacht, weekdag dat die het laatst gevoed is en land van herkomst op en de hoeveelheid kinderen. Van een Tijger slaan we de naam, naam van het hok, geslacht, weekdag dat die het laatst gevoed is en land van herkomst op. Ook willen we het aantal strepen weten. Van een Hond slaan we naam, naam van het baasje, favoriete voedselmerk, geslacht en soort op. Van een Kat slaan we de naam, naam van het baasje, favoriete voedsel merk, geslacht en soort op. Ook willen we weten of het een binnen of buitenkat is. Van een Wolf slaan we de naam, naam van het hok, geslacht, weekdag dat die voor het laatste gevoed is en land van herkomst op. Ook willen we de naam van de roedel weten. Alle dieren moeten kunnen bewegen. Dit moet als methode toegevoegd worden. Wanneer een dier beweegt print je in de console dat deze 0.25 meter is verplaatst. Alle dieren moeten ook een maak-geluid-methode hebben waarmee je het geluid van de dieren afdrukt naar de console. Alle dieren slapen 8 uur per dag. Maak een methode slapen en print dit uit wanneer de methode wordt aangeroepen. Alle dieren eten. Maak een methode die een String ontvangt en print dan uit wat het dier eet. Alles staat hier in het Nederlands beschreven. Schrijf je klassen-, variabele en methodenamen in het Engels. */ }
EAM26/Les4Animal
src/nl/novi/javaprogrammeren/AnimalMain.java
784
/* Het is traditie om overerving uit te leggen met behulp van dieren. Hier ontkomen jullie dus ook niet aan. Opdracht Bekijk de beschrijving van onderstaande dieren. Bedenk wat je in de superklasse kan zetten. De subklassen hoef je nog niet te maken. Van een Leeuw slaan we de naam, naam van het hok, geslacht, weekdag dat die het laatst gevoed is en land van herkomst op en de hoeveelheid kinderen. Van een Tijger slaan we de naam, naam van het hok, geslacht, weekdag dat die het laatst gevoed is en land van herkomst op. Ook willen we het aantal strepen weten. Van een Hond slaan we naam, naam van het baasje, favoriete voedselmerk, geslacht en soort op. Van een Kat slaan we de naam, naam van het baasje, favoriete voedsel merk, geslacht en soort op. Ook willen we weten of het een binnen of buitenkat is. Van een Wolf slaan we de naam, naam van het hok, geslacht, weekdag dat die voor het laatste gevoed is en land van herkomst op. Ook willen we de naam van de roedel weten. Alle dieren moeten kunnen bewegen. Dit moet als methode toegevoegd worden. Wanneer een dier beweegt print je in de console dat deze 0.25 meter is verplaatst. Alle dieren moeten ook een maak-geluid-methode hebben waarmee je het geluid van de dieren afdrukt naar de console. Alle dieren slapen 8 uur per dag. Maak een methode slapen en print dit uit wanneer de methode wordt aangeroepen. Alle dieren eten. Maak een methode die een String ontvangt en print dan uit wat het dier eet. Alles staat hier in het Nederlands beschreven. Schrijf je klassen-, variabele en methodenamen in het Engels. */
block_comment
nl
package nl.novi.javaprogrammeren; import nl.novi.javaprogrammeren.overerving.*; public class AnimalMain { public static void main(String[] args) { Lion l1 = new Lion("Sinbad", "male", true, 1); l1.eat("antilope"); l1.move(); Tigre t1 = new Tigre("Shere Khan", "male", true, 2); t1.eat("Mowgli"); t1.move(); Wolf w1 = new Wolf("Akela", "male", true, 3); w1.eat("sheep"); w1.move(); Dog d1 = new Dog("Fido", "female", false, "Jan"); Zoo artis = new Zoo(); artis.addToZoo(l1); artis.addToZoo(t1); artis.addToZoo(d1); artis.showZooAnimals(); } /* Het is traditie<SUF>*/ }
68696_2
package nl.novi.uitleg.week2.debuggen; import java.io.IOException; public class Excepties { /** * Java heeft verschillende ingebouwde excepties, zoals: * * 1. ArithmeticException * 2. ArrayIndexOutOfBoundsException * 3. FileNotFoundException * 4. IOException * 5. NullPointerException * 6. StringIndexOutOfBoundException */ static char[] board; public static void main(String[] args) { voorbeeldArthmeticException(); voorbeeldArrayIndexOutOfBoundsException(); voorbeeldFileNotFoundException(); voorbeeldIOException(); voorbeeldNullPointerException(); voorbeeldStringIndexOutOfBoundException(); } //Haal de // weg op de exceptie te gooien. public static void voorbeeldArthmeticException() { //int cijfer = 12 / 0; } //Haal de // weg op de exceptie te gooien. public static void voorbeeldArrayIndexOutOfBoundsException() { int[] nummer = {1,2,3}; //System.out.println(nummer[4]); } // Spreekt voor zich public static void voorbeeldFileNotFoundException() { } /** * * @throws IOException wanneer de code toegang probeert te krijgen tot een bestand dat * al in gebruik is of als het lezen of schrijven onverwacht onderbroken wordt. */ public static void voorbeeldIOException() { } //Haal de // weg op de exceptie te fixen. public static void voorbeeldNullPointerException() { //board = new char[9]; System.out.println(board.length); } //Haal de // weg op de exceptie te fixen. public static void voorbeeldStringIndexOutOfBoundException() { String s = "aa"; //if(s.length() >= 77) { s.charAt(77); //} } }
EAM26/Lijsten-les3
src/nl/novi/uitleg/week2/debuggen/Excepties.java
518
//int cijfer = 12 / 0;
line_comment
nl
package nl.novi.uitleg.week2.debuggen; import java.io.IOException; public class Excepties { /** * Java heeft verschillende ingebouwde excepties, zoals: * * 1. ArithmeticException * 2. ArrayIndexOutOfBoundsException * 3. FileNotFoundException * 4. IOException * 5. NullPointerException * 6. StringIndexOutOfBoundException */ static char[] board; public static void main(String[] args) { voorbeeldArthmeticException(); voorbeeldArrayIndexOutOfBoundsException(); voorbeeldFileNotFoundException(); voorbeeldIOException(); voorbeeldNullPointerException(); voorbeeldStringIndexOutOfBoundException(); } //Haal de // weg op de exceptie te gooien. public static void voorbeeldArthmeticException() { //int cijfer<SUF> } //Haal de // weg op de exceptie te gooien. public static void voorbeeldArrayIndexOutOfBoundsException() { int[] nummer = {1,2,3}; //System.out.println(nummer[4]); } // Spreekt voor zich public static void voorbeeldFileNotFoundException() { } /** * * @throws IOException wanneer de code toegang probeert te krijgen tot een bestand dat * al in gebruik is of als het lezen of schrijven onverwacht onderbroken wordt. */ public static void voorbeeldIOException() { } //Haal de // weg op de exceptie te fixen. public static void voorbeeldNullPointerException() { //board = new char[9]; System.out.println(board.length); } //Haal de // weg op de exceptie te fixen. public static void voorbeeldStringIndexOutOfBoundException() { String s = "aa"; //if(s.length() >= 77) { s.charAt(77); //} } }
194334_2
package com.example.techiteasymodel.config; import com.example.techiteasymodel.filter.JwtRequestFilter; import com.example.techiteasymodel.services.CustomUserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /* Deze security is niet de enige manier om het te doen. In de andere branch van deze github repo staat een ander voorbeeld */ @Configuration @EnableWebSecurity public class SpringSecurityConfig { public final CustomUserDetailsService customUserDetailsService; private final JwtRequestFilter jwtRequestFilter; public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService, JwtRequestFilter jwtRequestFilter) { this.customUserDetailsService = customUserDetailsService; this.jwtRequestFilter = jwtRequestFilter; } // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig. // Je kunt dit ook in een aparte configuratie klasse zetten. @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // Authenticatie met customUserDetailsService en passwordEncoder @Bean public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { return http.getSharedObject(AuthenticationManagerBuilder.class) .userDetailsService(customUserDetailsService) .passwordEncoder(passwordEncoder()) .and() .build(); } // Authorizatie met jwt @Bean protected SecurityFilterChain filter (HttpSecurity http) throws Exception { http .csrf().disable() .httpBasic().disable() .cors().and() .authorizeHttpRequests() // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig. // .requestMatchers("/**").permitAll() .requestMatchers(HttpMethod.POST, "/users").permitAll() .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN") .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN") .requestMatchers(HttpMethod.GET, "/televisions").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN") // Je mag meerdere paths tegelijk definieren .requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER") .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll() .anyRequest().denyAll() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
EAM26/TechItEasyModel
src/main/java/com/example/techiteasymodel/config/SpringSecurityConfig.java
1,140
// Je kunt dit ook in een aparte configuratie klasse zetten.
line_comment
nl
package com.example.techiteasymodel.config; import com.example.techiteasymodel.filter.JwtRequestFilter; import com.example.techiteasymodel.services.CustomUserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /* Deze security is niet de enige manier om het te doen. In de andere branch van deze github repo staat een ander voorbeeld */ @Configuration @EnableWebSecurity public class SpringSecurityConfig { public final CustomUserDetailsService customUserDetailsService; private final JwtRequestFilter jwtRequestFilter; public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService, JwtRequestFilter jwtRequestFilter) { this.customUserDetailsService = customUserDetailsService; this.jwtRequestFilter = jwtRequestFilter; } // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig. // Je kunt<SUF> @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // Authenticatie met customUserDetailsService en passwordEncoder @Bean public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { return http.getSharedObject(AuthenticationManagerBuilder.class) .userDetailsService(customUserDetailsService) .passwordEncoder(passwordEncoder()) .and() .build(); } // Authorizatie met jwt @Bean protected SecurityFilterChain filter (HttpSecurity http) throws Exception { http .csrf().disable() .httpBasic().disable() .cors().and() .authorizeHttpRequests() // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig. // .requestMatchers("/**").permitAll() .requestMatchers(HttpMethod.POST, "/users").permitAll() .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN") .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN") .requestMatchers(HttpMethod.GET, "/televisions").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN") // Je mag meerdere paths tegelijk definieren .requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER") .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll() .anyRequest().denyAll() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
43514_7
package nl.novi.techiteasy1121.controllers; import nl.novi.techiteasy1121.exceptions.RecordNotFoundException; import nl.novi.techiteasy1121.models.Television; import nl.novi.techiteasy1121.repositories.TelevisionRepository; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController public class TelevisionController { // Vorige week maakten we nog gebruik van een List<String>, nu gebruiken we de repository met een echte database. // We injecteren de repository hier via de constructor, maar je mag ook @Autowired gebruiken. private final TelevisionRepository televisionRepository; // Constructor injection public TelevisionController(TelevisionRepository televisionRepository){ this.televisionRepository = televisionRepository; } // We hebben hier de RequestParam "brand" toegevoegd om te laten zien hoe dat werkt. // Als de gebruiker een brand invult, dan zoeken we op brand, anders returnen we alle televisions. @GetMapping("/televisions") public ResponseEntity<List<Television>> getAllTelevisions(@RequestParam(value = "brand", required = false) String brand) { List<Television> televisions; if (brand == null){ // Vul de televisions lijst met alle televisions televisions = televisionRepository.findAll(); } else { // Vul de televisions lijst met alle television die een bepaald brand hebben televisions = televisionRepository.findAllTelevisionsByBrandEqualsIgnoreCase(brand); } // Return de televisions lijst en een 200 status return ResponseEntity.ok().body(televisions); } // Return 1 televisie met een specifiek id @GetMapping("/televisions/{id}") public ResponseEntity<Television> getTelevision(@PathVariable("id") Long id) { // Haal de television met het gegeven id uit de database. // Het Optional datatype betekend "wel of niet". Als er geen television gevonden wordt, dan is de Optional empty, // maar als er wel een television gevonden wordt, dan staat de television in de Optional en kun je deze er uit // halen met de get-methode. Op deze manier krijg je niet meteen een error als de tv niet in de database voorkomt. // Je kunt dat probleem zelf oplossen. In dit geval doen we dat door een RecordNotFoundException op te gooien met een message. Optional<Television> television = televisionRepository.findById(id); // Check of de optional empty is. Het tegenovergestelde alternatief is "television.isPresent()" if (television.isEmpty()){ // Als er geen television in de optional staat, roepen we hier de RecordNotFoundException constructor aan met message. throw new RecordNotFoundException("No television found with id: " + id ); } else { // Als er wel een television in de optional staat, dan halen we die uit de optional met de get-methode. Television television1 = television.get(); // Return de television en een 200 status return ResponseEntity.ok().body(television1); } } // We geven hier een television mee in de parameter. Zorg dat je JSON object exact overeenkomt met het Television object. @PostMapping("/televisions") public ResponseEntity<Television> addTelevision(@RequestBody Television television) { // Sla de nieuwe tv in de database op met de save-methode van de repository Television returnTelevision = televisionRepository.save(television); // Return de gemaakte television en een 201 status return ResponseEntity.created(null).body(returnTelevision); } @DeleteMapping("/televisions/{id}") public ResponseEntity<Object> deleteTelevision(@PathVariable("id") Long id) { // Verwijder de television met het opgegeven id uit de database. televisionRepository.deleteById(id); // Return een 204 status return ResponseEntity.noContent().build(); } @PutMapping("/televisions/{id}") public ResponseEntity<Television> updateTelevision(@PathVariable Long id, @RequestBody Television newTelevision) { // Haal de aan te passen tv uit de database met het gegeven id Optional<Television> television = televisionRepository.findById(id); // Als eerste checken we of de aan te passen tv wel in de database bestaat. if (television.isEmpty()){ throw new RecordNotFoundException("No television found with id: " + id); }else { // Verander alle waardes van de television uit de database naar de waardes van de television uit de parameters. // Behalve de id. Als je de id veranderd, dan wordt er een nieuw object gemaakt in de database. Television television1 = television.get(); television1.setAmbiLight(newTelevision.getAmbiLight()); television1.setAvailableSize(newTelevision.getAvailableSize()); television1.setAmbiLight(newTelevision.getAmbiLight()); television1.setBluetooth(newTelevision.getBluetooth()); television1.setBrand(newTelevision.getBrand()); television1.setHdr(newTelevision.getHdr()); television1.setName(newTelevision.getName()); television1.setOriginalStock(newTelevision.getOriginalStock()); television1.setPrice(newTelevision.getPrice()); television1.setRefreshRate(newTelevision.getRefreshRate()); television1.setScreenQuality(newTelevision.getScreenQuality()); television1.setScreenType(newTelevision.getScreenType()); television1.setSmartTv(newTelevision.getSmartTv()); television1.setSold(newTelevision.getSold()); television1.setType(newTelevision.getType()); television1.setVoiceControl(newTelevision.getVoiceControl()); television1.setWifi(newTelevision.getWifi()); // Sla de gewijzigde waarden op in de database onder dezelfde id. Dit moet je niet vergeten. Television returnTelevision = televisionRepository.save(television1); // Return de nieuwe versie van deze tv en een 200 code return ResponseEntity.ok().body(returnTelevision); } } }
EAM26/backend-spring-boot-tech-it-easy-model-uitwerkingen
src/main/java/nl/novi/techiteasy1121/controllers/TelevisionController.java
1,708
// Return 1 televisie met een specifiek id
line_comment
nl
package nl.novi.techiteasy1121.controllers; import nl.novi.techiteasy1121.exceptions.RecordNotFoundException; import nl.novi.techiteasy1121.models.Television; import nl.novi.techiteasy1121.repositories.TelevisionRepository; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController public class TelevisionController { // Vorige week maakten we nog gebruik van een List<String>, nu gebruiken we de repository met een echte database. // We injecteren de repository hier via de constructor, maar je mag ook @Autowired gebruiken. private final TelevisionRepository televisionRepository; // Constructor injection public TelevisionController(TelevisionRepository televisionRepository){ this.televisionRepository = televisionRepository; } // We hebben hier de RequestParam "brand" toegevoegd om te laten zien hoe dat werkt. // Als de gebruiker een brand invult, dan zoeken we op brand, anders returnen we alle televisions. @GetMapping("/televisions") public ResponseEntity<List<Television>> getAllTelevisions(@RequestParam(value = "brand", required = false) String brand) { List<Television> televisions; if (brand == null){ // Vul de televisions lijst met alle televisions televisions = televisionRepository.findAll(); } else { // Vul de televisions lijst met alle television die een bepaald brand hebben televisions = televisionRepository.findAllTelevisionsByBrandEqualsIgnoreCase(brand); } // Return de televisions lijst en een 200 status return ResponseEntity.ok().body(televisions); } // Return 1<SUF> @GetMapping("/televisions/{id}") public ResponseEntity<Television> getTelevision(@PathVariable("id") Long id) { // Haal de television met het gegeven id uit de database. // Het Optional datatype betekend "wel of niet". Als er geen television gevonden wordt, dan is de Optional empty, // maar als er wel een television gevonden wordt, dan staat de television in de Optional en kun je deze er uit // halen met de get-methode. Op deze manier krijg je niet meteen een error als de tv niet in de database voorkomt. // Je kunt dat probleem zelf oplossen. In dit geval doen we dat door een RecordNotFoundException op te gooien met een message. Optional<Television> television = televisionRepository.findById(id); // Check of de optional empty is. Het tegenovergestelde alternatief is "television.isPresent()" if (television.isEmpty()){ // Als er geen television in de optional staat, roepen we hier de RecordNotFoundException constructor aan met message. throw new RecordNotFoundException("No television found with id: " + id ); } else { // Als er wel een television in de optional staat, dan halen we die uit de optional met de get-methode. Television television1 = television.get(); // Return de television en een 200 status return ResponseEntity.ok().body(television1); } } // We geven hier een television mee in de parameter. Zorg dat je JSON object exact overeenkomt met het Television object. @PostMapping("/televisions") public ResponseEntity<Television> addTelevision(@RequestBody Television television) { // Sla de nieuwe tv in de database op met de save-methode van de repository Television returnTelevision = televisionRepository.save(television); // Return de gemaakte television en een 201 status return ResponseEntity.created(null).body(returnTelevision); } @DeleteMapping("/televisions/{id}") public ResponseEntity<Object> deleteTelevision(@PathVariable("id") Long id) { // Verwijder de television met het opgegeven id uit de database. televisionRepository.deleteById(id); // Return een 204 status return ResponseEntity.noContent().build(); } @PutMapping("/televisions/{id}") public ResponseEntity<Television> updateTelevision(@PathVariable Long id, @RequestBody Television newTelevision) { // Haal de aan te passen tv uit de database met het gegeven id Optional<Television> television = televisionRepository.findById(id); // Als eerste checken we of de aan te passen tv wel in de database bestaat. if (television.isEmpty()){ throw new RecordNotFoundException("No television found with id: " + id); }else { // Verander alle waardes van de television uit de database naar de waardes van de television uit de parameters. // Behalve de id. Als je de id veranderd, dan wordt er een nieuw object gemaakt in de database. Television television1 = television.get(); television1.setAmbiLight(newTelevision.getAmbiLight()); television1.setAvailableSize(newTelevision.getAvailableSize()); television1.setAmbiLight(newTelevision.getAmbiLight()); television1.setBluetooth(newTelevision.getBluetooth()); television1.setBrand(newTelevision.getBrand()); television1.setHdr(newTelevision.getHdr()); television1.setName(newTelevision.getName()); television1.setOriginalStock(newTelevision.getOriginalStock()); television1.setPrice(newTelevision.getPrice()); television1.setRefreshRate(newTelevision.getRefreshRate()); television1.setScreenQuality(newTelevision.getScreenQuality()); television1.setScreenType(newTelevision.getScreenType()); television1.setSmartTv(newTelevision.getSmartTv()); television1.setSold(newTelevision.getSold()); television1.setType(newTelevision.getType()); television1.setVoiceControl(newTelevision.getVoiceControl()); television1.setWifi(newTelevision.getWifi()); // Sla de gewijzigde waarden op in de database onder dezelfde id. Dit moet je niet vergeten. Television returnTelevision = televisionRepository.save(television1); // Return de nieuwe versie van deze tv en een 200 code return ResponseEntity.ok().body(returnTelevision); } } }
76993_0
package nl.novi.jp.methods.senior; import java.util.Map; import java.util.HashMap; /** * Lees eerst wat een Map is: https://www.w3schools.com/java/java_hashmap.asp * * Maak de methode af. Deze moet het Nederlandse woord teruggeven van het Engelse woord. * Verzin iets wanneer het Engelse woord niet beschikbaar is. */ public class SeniorTwo { public static void main(String[] args) { Map<String,String> englishDutchWords = new HashMap<>(); englishDutchWords.put("bottle","fles"); englishDutchWords.put("phone","telefoon"); englishDutchWords.put("water","water"); englishDutchWords.put("bread","brood"); englishDutchWords.put("space","ruimte"); englishDutchWords.put("flower","bloem"); englishDutchWords.put("flour","bloem"); englishDutchWords.put("kitchen","keuken"); englishDutchWords.put("cup","beker"); englishDutchWords.put("screen","scherm"); translate(englishDutchWords, "cup"); translate(englishDutchWords, "a"); } public static String translate(Map<String, String> words, String word) { String dutchWord = words.get(word); if(dutchWord != null) { System.out.println(dutchWord); } else { System.out.println("Niet beschikbaar!"); } return ""; } }
EAM26/java-backend-oefeningen-senior-les-1
SeniorTwo.java
431
/** * Lees eerst wat een Map is: https://www.w3schools.com/java/java_hashmap.asp * * Maak de methode af. Deze moet het Nederlandse woord teruggeven van het Engelse woord. * Verzin iets wanneer het Engelse woord niet beschikbaar is. */
block_comment
nl
package nl.novi.jp.methods.senior; import java.util.Map; import java.util.HashMap; /** * Lees eerst wat<SUF>*/ public class SeniorTwo { public static void main(String[] args) { Map<String,String> englishDutchWords = new HashMap<>(); englishDutchWords.put("bottle","fles"); englishDutchWords.put("phone","telefoon"); englishDutchWords.put("water","water"); englishDutchWords.put("bread","brood"); englishDutchWords.put("space","ruimte"); englishDutchWords.put("flower","bloem"); englishDutchWords.put("flour","bloem"); englishDutchWords.put("kitchen","keuken"); englishDutchWords.put("cup","beker"); englishDutchWords.put("screen","scherm"); translate(englishDutchWords, "cup"); translate(englishDutchWords, "a"); } public static String translate(Map<String, String> words, String word) { String dutchWord = words.get(word); if(dutchWord != null) { System.out.println(dutchWord); } else { System.out.println("Niet beschikbaar!"); } return ""; } }
100654_2
package OneDimensionalArraylist; import javax.swing.*; import java.util.Arrays; import java.util.Collection; import java.util.Collections; public class Oefening1 { private int[] arrayList = {1, 5, 10, 50, 50}; public Oefening1() { } public void print() { int res = 0; for (int i = 0; i < arrayList.length; i++) { res = arrayList[i]; System.out.println(arrayList[i]); } } public void drukAfOmgekeerd() { int res = 0; for (int i = arrayList.length - 1; i >= 0; i--) { res = arrayList[i]; System.out.println(arrayList[i]); } } public void berekenSom() { int res = 0; for (int i = 0; i < arrayList.length; i++) { res += arrayList[i]; } System.out.println(res); } public void berekenGemiddelde() { double res = 0; for (int i = 0; i < arrayList.length; i++) { res += arrayList[i]; } res /= arrayList.length; System.out.println(res); } public void drukGetallenGroterTien() { int res = 0; for (int i = 0; i < arrayList.length; i++) { if (arrayList[i] > 10) { System.out.println(arrayList[i]); } } } public void vermendigvuldig() { double res = 1; for (int i = 0; i < arrayList.length; i++) { if (arrayList[i] != 0) { res *= arrayList[i]; } } System.out.println(res); } public void vervangVerschil() { int ser = 0; double res = 0; for (int i = 0; i < arrayList.length; i++) { res += arrayList[i]; } res /= arrayList.length; System.out.println("Gemiddelde: " + res); for (int i = 0; i < arrayList.length; i++) { ser = (int) (arrayList[i] - res); arrayList[i] = ser; System.out.println(arrayList[i]); } } public void vergelijkMetIngelezen() { int counter = 0; int res = Integer.parseInt(JOptionPane.showInputDialog("Geef Getal")); for (int i = 0; i < arrayList.length; i++) { if (res == arrayList[i]) { counter++; } } System.out.println("Aantal dezelfde getallen in de lijst: " + counter); } public int grootsteGetal() { int counter = 0; int res = arrayList[0]; for (int i = 0; i < arrayList.length; i++) { if (arrayList[i] > res) { res = arrayList[i]; counter++; } } arrayList[4] = res; System.out.println(res); return arrayList[4]; } //**************** public void grootsteGetalPlaats() { int kleinste = arrayList[0]; int ser = 0, seri = 0; int grootste = arrayList[0]; int j = 0; int c = 0; for (int i = 0; i < arrayList.length; i++) { if (arrayList[i] > grootste) { grootste = arrayList[i]; c = i; System.out.println("c" +c); } else if (arrayList[i] < kleinste) { kleinste = arrayList[i]; j = i; System.out.println("j" +j); } } int a = arrayList[c]; arrayList[c] = arrayList[j]; arrayList[j] = a; System.out.println("Grootste getal: " + grootste); System.out.println("Kleinste getal: " + kleinste); } // 2 4 // 1 5 10 20 50 // ***************** // public void vergelijkArrays() { // int counter = 0; // for (int i = 0; i < arrayList.length; i++) { // if (arrayList[i] == arrayList.clone()[i]) { // counter++; // } // System.out.println("Meest voorkomende getallen in lijst: " + counter); // } // } public void vergelijkArrays() { int count = 1, tempCount; int popular = arrayList[0]; int temp = 0; for (int i = 0; i < (arrayList.length - 1); i++) { temp = arrayList[i]; tempCount = 0; for (int j = 1; j < arrayList.length; j++) { if (temp == arrayList[j]) tempCount++; } if (tempCount > count) { popular = temp; count = tempCount; } } System.out.println(popular); } public void muntenEnBriefjes() { int aantal = 0; int bedrag = Integer.parseInt(JOptionPane.showInputDialog("Geef Bedrag")); System.out.println("Voor het bedrag van: " + bedrag + "€ heb je de volgende munstukken of briefjes nodig:"); for (int i = 4; i >= 0; i--) { aantal = bedrag / arrayList[i]; //3 = 163 50 //0 = 13 20 bedrag = bedrag - (aantal * arrayList[i]); //13 = 163 - 3 * 50 //0 = 13 - 0 * 20 System.out.println(aantal + " briefjes/munten van € " + arrayList[i]); } } public int[] getArrayList() { return arrayList; } public void setArrayList(int[] arrayList) { this.arrayList = arrayList; } @Override public String toString() { return "Oefening1{" + "arrayList=" + Arrays.toString(arrayList) + '}'; } }
EGSilver/Programming-fundementals
ThuisWerk2Lussen/src/OneDimensionalArraylist/Oefening1.java
1,780
// public void vergelijkArrays() {
line_comment
nl
package OneDimensionalArraylist; import javax.swing.*; import java.util.Arrays; import java.util.Collection; import java.util.Collections; public class Oefening1 { private int[] arrayList = {1, 5, 10, 50, 50}; public Oefening1() { } public void print() { int res = 0; for (int i = 0; i < arrayList.length; i++) { res = arrayList[i]; System.out.println(arrayList[i]); } } public void drukAfOmgekeerd() { int res = 0; for (int i = arrayList.length - 1; i >= 0; i--) { res = arrayList[i]; System.out.println(arrayList[i]); } } public void berekenSom() { int res = 0; for (int i = 0; i < arrayList.length; i++) { res += arrayList[i]; } System.out.println(res); } public void berekenGemiddelde() { double res = 0; for (int i = 0; i < arrayList.length; i++) { res += arrayList[i]; } res /= arrayList.length; System.out.println(res); } public void drukGetallenGroterTien() { int res = 0; for (int i = 0; i < arrayList.length; i++) { if (arrayList[i] > 10) { System.out.println(arrayList[i]); } } } public void vermendigvuldig() { double res = 1; for (int i = 0; i < arrayList.length; i++) { if (arrayList[i] != 0) { res *= arrayList[i]; } } System.out.println(res); } public void vervangVerschil() { int ser = 0; double res = 0; for (int i = 0; i < arrayList.length; i++) { res += arrayList[i]; } res /= arrayList.length; System.out.println("Gemiddelde: " + res); for (int i = 0; i < arrayList.length; i++) { ser = (int) (arrayList[i] - res); arrayList[i] = ser; System.out.println(arrayList[i]); } } public void vergelijkMetIngelezen() { int counter = 0; int res = Integer.parseInt(JOptionPane.showInputDialog("Geef Getal")); for (int i = 0; i < arrayList.length; i++) { if (res == arrayList[i]) { counter++; } } System.out.println("Aantal dezelfde getallen in de lijst: " + counter); } public int grootsteGetal() { int counter = 0; int res = arrayList[0]; for (int i = 0; i < arrayList.length; i++) { if (arrayList[i] > res) { res = arrayList[i]; counter++; } } arrayList[4] = res; System.out.println(res); return arrayList[4]; } //**************** public void grootsteGetalPlaats() { int kleinste = arrayList[0]; int ser = 0, seri = 0; int grootste = arrayList[0]; int j = 0; int c = 0; for (int i = 0; i < arrayList.length; i++) { if (arrayList[i] > grootste) { grootste = arrayList[i]; c = i; System.out.println("c" +c); } else if (arrayList[i] < kleinste) { kleinste = arrayList[i]; j = i; System.out.println("j" +j); } } int a = arrayList[c]; arrayList[c] = arrayList[j]; arrayList[j] = a; System.out.println("Grootste getal: " + grootste); System.out.println("Kleinste getal: " + kleinste); } // 2 4 // 1 5 10 20 50 // ***************** // public void<SUF> // int counter = 0; // for (int i = 0; i < arrayList.length; i++) { // if (arrayList[i] == arrayList.clone()[i]) { // counter++; // } // System.out.println("Meest voorkomende getallen in lijst: " + counter); // } // } public void vergelijkArrays() { int count = 1, tempCount; int popular = arrayList[0]; int temp = 0; for (int i = 0; i < (arrayList.length - 1); i++) { temp = arrayList[i]; tempCount = 0; for (int j = 1; j < arrayList.length; j++) { if (temp == arrayList[j]) tempCount++; } if (tempCount > count) { popular = temp; count = tempCount; } } System.out.println(popular); } public void muntenEnBriefjes() { int aantal = 0; int bedrag = Integer.parseInt(JOptionPane.showInputDialog("Geef Bedrag")); System.out.println("Voor het bedrag van: " + bedrag + "€ heb je de volgende munstukken of briefjes nodig:"); for (int i = 4; i >= 0; i--) { aantal = bedrag / arrayList[i]; //3 = 163 50 //0 = 13 20 bedrag = bedrag - (aantal * arrayList[i]); //13 = 163 - 3 * 50 //0 = 13 - 0 * 20 System.out.println(aantal + " briefjes/munten van € " + arrayList[i]); } } public int[] getArrayList() { return arrayList; } public void setArrayList(int[] arrayList) { this.arrayList = arrayList; } @Override public String toString() { return "Oefening1{" + "arrayList=" + Arrays.toString(arrayList) + '}'; } }
41675_17
/** * EGroupware - Notifications Java Desktop App * * @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License * @package notifications * @subpackage jdesk * @link http://www.egroupware.org * @author Stefan Werfling <[email protected]> * @author Maik Hüttner <[email protected]> */ package egroupwaretray; import java.awt.event.ActionListener; import java.net.InetAddress; import java.util.*; import java.util.logging.Level; import org.json.simple.parser.ContainerFactory; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** * jegwhttp * * @author Stefan Werfling <[email protected]> */ public class jegwhttp { public static final String EGWHTTP_INDEXSCRIPT = "index.php"; public static final String EGWHTTP_LOGINSCRIPT = "login.php"; public static final String EGWHTTP_LOGOUTSCRIPT = "logout.php"; public static final String EGWHTTP_TRAYMODUL = "egwnotifier/index.php"; public static final String EGWHTTP_TRAYLOGIN = "notifierlogin.php"; public static final String EGWHTTP_LOGINLINK = "login.php?cd="; public static final String EGWHTTP_POST_VAR_PASSWORD_TYPE = "passwd_type"; public static final String EGWHTTP_POST_VAR_ACCOUNT_TYPE = "account_type"; public static final String EGWHTTP_POST_VAR_LOGINDOMAIN = "logindomain"; public static final String EGWHTTP_POST_VAR_LOGIN = "login"; public static final String EGWHTTP_POST_VAR_PASSWD = "passwd"; public static final String EGWHTTP_POST_VAR_SUBMITIT = "submitit"; public static final String EGWHTTP_POST_PASSWORD_TYPE_TEXT = "text"; public static final String EGWHTTP_POST_ACCOUNT_TYPE_U = "u"; public static final String EGWHTTP_POST_LOGINDOMAIN_DEFAULT = "default"; public static final String EGWHTTP_POST_SUBMITIT = "++Anmelden++"; public static final String EGWHTTP_TAG_SECURITYID = "egwcheckid"; public static final String EGWHTTP_GET_VAR_MAKE_SECURITYID = "makecheck"; public static final String EGWHTTP_GET_VAR_SECURITYID = "checkid"; public static final String EGWHTTP_GET_MAKE_SECURITYID = "1"; public static final String EGWHTTP_GET_PHPGW_FORWARD = "phpgw_forward"; // new EPL Notifications public static final String EGWHTTP_GET_NOTIFICATIONS_ACTION = "json.php?menuaction=notifications.notifications_jdesk_ajax.get_notifications"; // new EPL Notifications public static final String EGWHTTP_GET_NOTIFICATIONS_ACTION_CONFIRM = "json.php?menuaction=notifications.notifications_jdesk_ajax.confirm_message"; public static final String[] EGWHTTP_EGW_COOKIE = new String[]{ "sessionid", "kp3", "last_loginid", "last_domain", "domain"}; public static final String[] EGWHTTP_EGW_APP = new String[]{ "name", "title", "infotext", "variables", "appdialogtext" }; public static final String[] EGWHTTP_EGW_NOTIFY = new String[]{ "app", "title", "msghtml", "link", "notify_id" }; public static final String[] EGWHTTP_EGW_APP_VAR = new String[]{ "vname", "value", "vtype" }; private BaseHttp httpcon = new BaseHttp(); private Boolean loginstatus = false; public jegwhttp(ActionListener lister) { this.httpcon.setSocketTimeOut( Integer.parseInt( jegwConst.getConstTag("egw_dc_timeout_socket"))); } /** * CheckDir * Überprüft ob hinten ein String (wie bei Verzeichnisen mit "/" abschließt), * wenn nicht wird dieser hinten drangesetzt und der String zurück geben * * @param dir * @return */ static public String checkDir(String dir) { if(dir.length() > 0) { if(dir.charAt(dir.length()-1) != "/".charAt(0) ) { dir = dir + "/"; } } return dir; } public void egwUrlLinkParser(KeyArray Config) throws Exception { String url = Config.getString("egwurl"); boolean ssl = false; if( url.indexOf("https://") > -1 ) { ssl = true; url = url.replaceAll("https://", ""); } else { url = url.replaceAll("http://", ""); } if( url.length() == 0 ) { throw new Exception("NOURL"); } String[] tmp = url.split("/"); String host = tmp[0]; String port = ""; String paht = ""; if( tmp[0].indexOf(":") != -1 ) { String[] ttmp = tmp[0].split(":"); host = ttmp[0]; port = ttmp[1]; } /** * Host auflösen */ try { InetAddress addr = InetAddress.getByName(host); } catch( Exception exp) { egwDebuging.log.log(Level.SEVERE, null, exp); throw new Exception("HOSTNOTFOUND"); } for( int i=1; i<tmp.length; i++ ) { paht = paht + tmp[i] + "/"; } /*if( paht.length() == 0 ) { paht = "/"; }*/ Config.add("host", host); if( port.length() != 0 ) { Config.add("port", port); } Config.add("subdir", paht); Config.add("ssl", ssl); /** * SSL Enable */ this.httpcon.setIsSSL(ssl); if( port.length() != 0 ) { host = host + ":" + port; } String moved = this.httpcon.isHostMoved(host, "/" + paht); if( !moved.equals("") ) { Config.add("egwurl", moved); this.egwUrlLinkParser(Config); } } public String[] getEgwLoginDomains(KeyArray Config) throws Exception { this.egwUrlLinkParser(Config); String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_LOGINSCRIPT + "?" + EGWHTTP_GET_PHPGW_FORWARD + "="; String buffer = this.httpcon.openHttpContentSite(urlhost + urllink); /** * Hidden Logindomain */ int begin = -1; int end = -1; String search = "<input type=\"hidden\" name=\"logindomain\" value=\""; if( (begin = buffer.indexOf(search)) > -1 ) { end = buffer.indexOf("\"", begin + search.length()); if( (begin != -1) && (end != -1) ) { String tmp = buffer.substring( begin + search.length(), end); return new String[]{tmp}; } } /** * Select Logindomain */ begin = -1; end = -1; search = "<select name=\"logindomain\""; if( (begin = buffer.indexOf(search)) > -1 ) { end = buffer.indexOf("</select>", begin + search.length()); if( (begin != -1) && (end != -1) ) { String tmp = buffer.substring( begin + search.length(), end); tmp = tmp.trim(); String ltmp[] = tmp.split("</option>"); String treturn[] = new String[ltmp.length]; for( int i=0; i<ltmp.length; i++ ) { String tbuffer = ltmp[i]; String tsearch = "value=\""; int tbegin = -1; int tend = -1; if( (tbegin = tbuffer.indexOf(tsearch)) > -1 ) { tend = tbuffer.indexOf("\"", tbegin + tsearch.length()); if( (begin != -1) && (tend != -1) ) { String ttmp = tbuffer.substring( tbegin + tsearch.length(), tend); treturn[i] = ttmp; } } } return treturn; } } return null; } public void egwCheckLoginDomains(KeyArray Config) throws Exception { String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_LOGINSCRIPT + "?" + EGWHTTP_GET_PHPGW_FORWARD + "="; String buffer = this.httpcon.openHttpContentSite(urlhost + urllink); /** * Hidden Logindomain */ int begin = -1; int end = -1; String search = "<input type=\"hidden\" name=\"logindomain\" value=\""; if( (begin = buffer.indexOf(search)) > -1 ) { end = buffer.indexOf("\"", begin + search.length()); if( (begin != -1) && (end != -1) ) { String tmp = buffer.substring( begin + search.length(), end); Config.add("logindomain", tmp); return; } } /** * Select Logindomain */ begin = -1; end = -1; search = "<select name=\"logindomain\""; if( (begin = buffer.indexOf(search)) > -1 ) { end = buffer.indexOf("</select>", begin + search.length()); if( (begin != -1) && (end != -1) ) { String tmp = buffer.substring( begin + search.length(), end); System.out.println(tmp); } } //Config.Add("logindomain", EGWHTTP_POST_LOGINDOMAIN_DEFAULT); Config.add("logindomain", urlhost); } /** * egwLogin * logt sich im eGroupware ein mit den Benutzerdaten aus einer Config * und gibt den Cookieinhalt zurück * * @param Config Konfigurations Einstellungen * @return Cookieinhalt */ public KeyArray egwLogin(KeyArray Config) throws Exception { this.egwUrlLinkParser(Config); //this.egwCheckLoginDomains(Config); String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_LOGINSCRIPT + "?" + EGWHTTP_GET_PHPGW_FORWARD + "="; String urlpost = EGWHTTP_POST_VAR_PASSWORD_TYPE + "=" + EGWHTTP_POST_PASSWORD_TYPE_TEXT + "&" + EGWHTTP_POST_VAR_ACCOUNT_TYPE + "=" + EGWHTTP_POST_ACCOUNT_TYPE_U + "&" + EGWHTTP_POST_VAR_LOGINDOMAIN + "=" + Config.getString("logindomain") + "&" + EGWHTTP_POST_VAR_LOGIN + "=" + Config.getString("user") + "&" + EGWHTTP_POST_VAR_PASSWD + "=" + Config.getString("password") + "&" + EGWHTTP_POST_VAR_SUBMITIT + "=" + EGWHTTP_POST_SUBMITIT; String buffer = this.httpcon.openHttpContentSitePost(urlhost + urllink, urlpost); if( buffer.length() == 0 ) { // Verbindungsfehler throw new Exception("NETERROR"); } if( this.httpcon.isNotFound() ) { throw new Exception("PAGENOTFOUND"); } int status = this.egwCheckLoginStatus(); if( status > -1 ) { throw new Exception("LOGIN:" + Integer.toString(status)); } KeyArray egwcookie = new KeyArray(EGWHTTP_EGW_COOKIE); String[] keys = egwcookie.getKeys(); for( int i=0; i<keys.length; i++ ) { String value = this.httpcon.getSocketHeaderField(this.httpcon.getCookie(), keys[i]); if( value.length() == 0 ) { // Login fehlgeschlagen return null; } egwcookie.add(keys[i], value); } this.loginstatus = true; return egwcookie; } /** * egwIsLogin * Überprüft ob eine egw Benutzer noch angemeldet ist * * @param buffer Rückgabe eines HTTP aufrufes muss hier angeben werden, * der Inhalt würd dann drauf überprüft * @param cookie Cookie Informationen zum Überprüfen * @return true = noch Angemeldet, false = nicht mehr Angemeldet */ private boolean egwIsLogin(KeyArray cookie) { String sess = this.httpcon.getCookieVariable(this.httpcon.getCookie(), "sessionid"); String location = this.httpcon.getLocation(); if( sess.length() > 0 ) { if( sess.compareTo(cookie.getString("sessionid")) != 0 ) { this.loginstatus = false; return false; } } else if( (location != null) && (location.indexOf("login.php") != -1) ) { this.loginstatus = false; return false; } this.loginstatus = true; return true; } private int egwCheckLoginStatus() { String back = ""; String buffer = this.httpcon.getLocation(); if( buffer == null ) { buffer = ""; } int pos = buffer.indexOf(jegwhttp.EGWHTTP_LOGINLINK); int end = buffer.length(); if( (pos != -1) && (end != -1) ) { back = buffer.substring( pos + jegwhttp.EGWHTTP_LOGINLINK.length(), end); } else if( (buffer.indexOf("http://") != -1) || (buffer.indexOf("https://") != -1) ) { if( buffer.indexOf("index.php?cd=yes") == -1 ) { return 999; } else { return -1; } } else { return -1; } return Integer.valueOf(back).intValue(); } public boolean egwIsEGWLogin() { return this.loginstatus; } /** * egwGetTagValue * Sucht Inhalte erraus (nach der notation vom html/xml) * * @param buff HTTP Inhalt * @param tag Inhalt umschließer * @return Inhalt */ private String egwGetTagValue(String buff, String tag) { String back = ""; int pos = buff.indexOf("<" + tag + ">"); int end = buff.indexOf("</" + tag + ">", pos); if( (pos != -1) && (end != -1) ) { back = buff.substring( pos + tag.length() +2, end); } return back; } private String egwGetTagValueWithTag(String buff, String tag) { String back = ""; int pos = buff.indexOf("<" + tag + ">"); int end = buff.indexOf("</" + tag + ">", pos); if( (pos != -1) && (end != -1) ) { back = buff.substring( pos, end + tag.length() +3); } return back; } private String egwGetNoneTagText(String buff, String tag) { String back = ""; int pos = buff.indexOf("<" + tag + ">"); int end = buff.indexOf("</" + tag + ">", pos); if( (pos != -1) && (end != -1) ) { back = buff.substring( 0, pos); back = back + buff.substring( end + tag.length() +3, buff.length()-1); } return back; } /** * egwGetEGWCookieStr * erstellt den Cookie String aus dem cookie(Array) * * @param cookie * @return */ private String egwGetEGWCookieStr(KeyArray cookie) { String cookiestr = ""; String[] keys = cookie.getKeys(); for( int i=0; i<cookie.size(); i++ ) { String tmp = keys[i] + "=" + cookie.getString(keys[i]) + ";"; if(cookiestr.length() == 0) { cookiestr = cookiestr + tmp; } else { cookiestr = cookiestr + " " + tmp; } } cookiestr = cookiestr + " storedlang=de; last_loginid=; last_domain=default; ConfigLang=de"; return cookiestr; } public ArrayList egwLoadEGWData(KeyArray Config, KeyArray cookie) throws Exception { ArrayList msglist = new ArrayList(); String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_GET_NOTIFICATIONS_ACTION; this.httpcon.setIsAjax(true); this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie)); //String buffer = this.httpcon.openHttpContentSite(urlhost + urllink); String buffer = this.httpcon.openHttpContentSitePost( urlhost + urllink, "json_data={\"request\":{\"parameters\":[null]}}" ); this.httpcon.setIsAjax(false); /** * Fehler Behandlung */ /*if( buffer.length() == 0 ) { // Verbindungsfehler throw new Exception("NETERROR"); }*/ if( this.egwIsLogin(cookie) ) { int status = this.egwCheckLoginStatus(); if( status > -1 ) { throw new Exception("LOGIN:" + Integer.toString(status)); } /** * Check auf Rechte (Permission denied!) */ String permission = "<title>Permission denied!</title>"; if( buffer.indexOf(permission) > -1 ) { throw new Exception("PERMISSIONDENIED"); } /** * JSON */ JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory(){ public List creatArrayContainer() { return new LinkedList(); } public Map createObjectContainer() { return new LinkedHashMap(); } }; try { Map json = (Map)parser.parse(buffer.trim(), containerFactory); Iterator iter = json.entrySet().iterator(); while( iter.hasNext() ) { Map.Entry entry = (Map.Entry)iter.next(); if( entry.getKey().toString().compareTo("response") == 0 ) { LinkedList response = (LinkedList) entry.getValue(); for( Integer i=0; i<response.size(); i++ ) { Map jmsg = (Map) response.get(i); Iterator jmsgiter = jmsg.entrySet().iterator(); while( jmsgiter.hasNext() ) { Map.Entry jmsgentry = (Map.Entry)jmsgiter.next(); if( (jmsgentry.getKey().toString().compareTo("type") == 0) && (jmsgentry.getValue().toString().compareTo("data") == 0) && jmsgiter.hasNext() ) { jmsgentry = (Map.Entry)jmsgiter.next(); if( jmsgentry.getKey().toString().compareTo("data") == 0 ) { KeyArray notifymsg = new KeyArray(EGWHTTP_EGW_NOTIFY); Map msgdata = (Map) jmsgentry.getValue(); Iterator dataiter = msgdata.entrySet().iterator(); while( dataiter.hasNext() ) { Map.Entry dataentry = (Map.Entry)dataiter.next(); String tkey = dataentry.getKey().toString(); Object tovalue = dataentry.getValue(); String tvalue = ""; if( tovalue != null ) { tvalue = tovalue.toString(); } if( notifymsg.existKey(tkey) ) { notifymsg.add(tkey, tvalue); } } if( notifymsg.get("notify_id") != null ) { msglist.add(notifymsg); this.egwRemoveEGWData( Config, cookie, notifymsg.getString("notify_id")); } } } } } } } } catch( ParseException pe ) { egwDebuging.log.log(Level.SEVERE, null, pe); throw new Exception("NOAPPS"); } } return msglist; } public Boolean egwRemoveEGWData(KeyArray Config, KeyArray cookie, String notifiy_id) throws Exception { String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_GET_NOTIFICATIONS_ACTION_CONFIRM; this.httpcon.setIsAjax(true); this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie)); //String buffer = this.httpcon.openHttpContentSite(urlhost + urllink); String buffer = this.httpcon.openHttpContentSitePost( urlhost + urllink, "json_data={\"request\":{\"parameters\":[\"" + notifiy_id + "\"]}}" ); this.httpcon.setIsAjax(false); return true; } /** * egwGetSecurityID * beantragt eine Sicherheitsid zum Einlogen * * @param Config Konfiguration eines Accounts * @param cookie Cookie vom einlogen * @return Sicherheitsid, war man nicht eingelogt so ist der String Leer */ public String egwGetSecurityID(KeyArray Config, KeyArray cookie) throws Exception { String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_TRAYMODUL + "?" + EGWHTTP_GET_VAR_MAKE_SECURITYID + "=" + EGWHTTP_GET_MAKE_SECURITYID; String securityid = ""; this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie)); String buffer = this.httpcon.openHttpContentSite(urlhost + urllink); if( this.egwIsLogin(cookie) ) { securityid = this.egwGetTagValue(buffer, EGWHTTP_TAG_SECURITYID); } return securityid; } public String egwGetOpenEGWLink(KeyArray Config, KeyArray cookie, String menuaction) { String urllink = ""; String urlhost = Config.getString("host"); String protocol = "http://"; if( Config.getString("egwurl").startsWith("https") ) { protocol = "https://"; } if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } urllink = urllink + protocol + jegwhttp.checkDir(urlhost) + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_INDEXSCRIPT; urllink = urllink + "?notifiy=1"; if( (menuaction != null) && (menuaction.length() > 0) ) { urllink = urllink + "&" + menuaction; } String[] keys = cookie.getKeys(); for( int i=0; i<cookie.size(); i++ ) { urllink = urllink + "&" + keys[i] + "=" + cookie.getString(keys[i]); } return urllink; } public boolean egwLogout(KeyArray Config, KeyArray cookie) throws Exception { String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = jegwhttp.checkDir(urlhost) + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_LOGOUTSCRIPT; this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie)); String buffer = this.httpcon.openHttpContentSite(urllink); if( buffer.length() == 0 ) { // Verbindungsfehler throw new Exception("NETERROR"); } if( !this.egwIsLogin(cookie) ) { return true; } return false; } }
EGroupware/egroupware
notifications/java/src/egroupwaretray/jegwhttp.java
8,113
/** * egwGetEGWCookieStr * erstellt den Cookie String aus dem cookie(Array) * * @param cookie * @return */
block_comment
nl
/** * EGroupware - Notifications Java Desktop App * * @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License * @package notifications * @subpackage jdesk * @link http://www.egroupware.org * @author Stefan Werfling <[email protected]> * @author Maik Hüttner <[email protected]> */ package egroupwaretray; import java.awt.event.ActionListener; import java.net.InetAddress; import java.util.*; import java.util.logging.Level; import org.json.simple.parser.ContainerFactory; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** * jegwhttp * * @author Stefan Werfling <[email protected]> */ public class jegwhttp { public static final String EGWHTTP_INDEXSCRIPT = "index.php"; public static final String EGWHTTP_LOGINSCRIPT = "login.php"; public static final String EGWHTTP_LOGOUTSCRIPT = "logout.php"; public static final String EGWHTTP_TRAYMODUL = "egwnotifier/index.php"; public static final String EGWHTTP_TRAYLOGIN = "notifierlogin.php"; public static final String EGWHTTP_LOGINLINK = "login.php?cd="; public static final String EGWHTTP_POST_VAR_PASSWORD_TYPE = "passwd_type"; public static final String EGWHTTP_POST_VAR_ACCOUNT_TYPE = "account_type"; public static final String EGWHTTP_POST_VAR_LOGINDOMAIN = "logindomain"; public static final String EGWHTTP_POST_VAR_LOGIN = "login"; public static final String EGWHTTP_POST_VAR_PASSWD = "passwd"; public static final String EGWHTTP_POST_VAR_SUBMITIT = "submitit"; public static final String EGWHTTP_POST_PASSWORD_TYPE_TEXT = "text"; public static final String EGWHTTP_POST_ACCOUNT_TYPE_U = "u"; public static final String EGWHTTP_POST_LOGINDOMAIN_DEFAULT = "default"; public static final String EGWHTTP_POST_SUBMITIT = "++Anmelden++"; public static final String EGWHTTP_TAG_SECURITYID = "egwcheckid"; public static final String EGWHTTP_GET_VAR_MAKE_SECURITYID = "makecheck"; public static final String EGWHTTP_GET_VAR_SECURITYID = "checkid"; public static final String EGWHTTP_GET_MAKE_SECURITYID = "1"; public static final String EGWHTTP_GET_PHPGW_FORWARD = "phpgw_forward"; // new EPL Notifications public static final String EGWHTTP_GET_NOTIFICATIONS_ACTION = "json.php?menuaction=notifications.notifications_jdesk_ajax.get_notifications"; // new EPL Notifications public static final String EGWHTTP_GET_NOTIFICATIONS_ACTION_CONFIRM = "json.php?menuaction=notifications.notifications_jdesk_ajax.confirm_message"; public static final String[] EGWHTTP_EGW_COOKIE = new String[]{ "sessionid", "kp3", "last_loginid", "last_domain", "domain"}; public static final String[] EGWHTTP_EGW_APP = new String[]{ "name", "title", "infotext", "variables", "appdialogtext" }; public static final String[] EGWHTTP_EGW_NOTIFY = new String[]{ "app", "title", "msghtml", "link", "notify_id" }; public static final String[] EGWHTTP_EGW_APP_VAR = new String[]{ "vname", "value", "vtype" }; private BaseHttp httpcon = new BaseHttp(); private Boolean loginstatus = false; public jegwhttp(ActionListener lister) { this.httpcon.setSocketTimeOut( Integer.parseInt( jegwConst.getConstTag("egw_dc_timeout_socket"))); } /** * CheckDir * Überprüft ob hinten ein String (wie bei Verzeichnisen mit "/" abschließt), * wenn nicht wird dieser hinten drangesetzt und der String zurück geben * * @param dir * @return */ static public String checkDir(String dir) { if(dir.length() > 0) { if(dir.charAt(dir.length()-1) != "/".charAt(0) ) { dir = dir + "/"; } } return dir; } public void egwUrlLinkParser(KeyArray Config) throws Exception { String url = Config.getString("egwurl"); boolean ssl = false; if( url.indexOf("https://") > -1 ) { ssl = true; url = url.replaceAll("https://", ""); } else { url = url.replaceAll("http://", ""); } if( url.length() == 0 ) { throw new Exception("NOURL"); } String[] tmp = url.split("/"); String host = tmp[0]; String port = ""; String paht = ""; if( tmp[0].indexOf(":") != -1 ) { String[] ttmp = tmp[0].split(":"); host = ttmp[0]; port = ttmp[1]; } /** * Host auflösen */ try { InetAddress addr = InetAddress.getByName(host); } catch( Exception exp) { egwDebuging.log.log(Level.SEVERE, null, exp); throw new Exception("HOSTNOTFOUND"); } for( int i=1; i<tmp.length; i++ ) { paht = paht + tmp[i] + "/"; } /*if( paht.length() == 0 ) { paht = "/"; }*/ Config.add("host", host); if( port.length() != 0 ) { Config.add("port", port); } Config.add("subdir", paht); Config.add("ssl", ssl); /** * SSL Enable */ this.httpcon.setIsSSL(ssl); if( port.length() != 0 ) { host = host + ":" + port; } String moved = this.httpcon.isHostMoved(host, "/" + paht); if( !moved.equals("") ) { Config.add("egwurl", moved); this.egwUrlLinkParser(Config); } } public String[] getEgwLoginDomains(KeyArray Config) throws Exception { this.egwUrlLinkParser(Config); String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_LOGINSCRIPT + "?" + EGWHTTP_GET_PHPGW_FORWARD + "="; String buffer = this.httpcon.openHttpContentSite(urlhost + urllink); /** * Hidden Logindomain */ int begin = -1; int end = -1; String search = "<input type=\"hidden\" name=\"logindomain\" value=\""; if( (begin = buffer.indexOf(search)) > -1 ) { end = buffer.indexOf("\"", begin + search.length()); if( (begin != -1) && (end != -1) ) { String tmp = buffer.substring( begin + search.length(), end); return new String[]{tmp}; } } /** * Select Logindomain */ begin = -1; end = -1; search = "<select name=\"logindomain\""; if( (begin = buffer.indexOf(search)) > -1 ) { end = buffer.indexOf("</select>", begin + search.length()); if( (begin != -1) && (end != -1) ) { String tmp = buffer.substring( begin + search.length(), end); tmp = tmp.trim(); String ltmp[] = tmp.split("</option>"); String treturn[] = new String[ltmp.length]; for( int i=0; i<ltmp.length; i++ ) { String tbuffer = ltmp[i]; String tsearch = "value=\""; int tbegin = -1; int tend = -1; if( (tbegin = tbuffer.indexOf(tsearch)) > -1 ) { tend = tbuffer.indexOf("\"", tbegin + tsearch.length()); if( (begin != -1) && (tend != -1) ) { String ttmp = tbuffer.substring( tbegin + tsearch.length(), tend); treturn[i] = ttmp; } } } return treturn; } } return null; } public void egwCheckLoginDomains(KeyArray Config) throws Exception { String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_LOGINSCRIPT + "?" + EGWHTTP_GET_PHPGW_FORWARD + "="; String buffer = this.httpcon.openHttpContentSite(urlhost + urllink); /** * Hidden Logindomain */ int begin = -1; int end = -1; String search = "<input type=\"hidden\" name=\"logindomain\" value=\""; if( (begin = buffer.indexOf(search)) > -1 ) { end = buffer.indexOf("\"", begin + search.length()); if( (begin != -1) && (end != -1) ) { String tmp = buffer.substring( begin + search.length(), end); Config.add("logindomain", tmp); return; } } /** * Select Logindomain */ begin = -1; end = -1; search = "<select name=\"logindomain\""; if( (begin = buffer.indexOf(search)) > -1 ) { end = buffer.indexOf("</select>", begin + search.length()); if( (begin != -1) && (end != -1) ) { String tmp = buffer.substring( begin + search.length(), end); System.out.println(tmp); } } //Config.Add("logindomain", EGWHTTP_POST_LOGINDOMAIN_DEFAULT); Config.add("logindomain", urlhost); } /** * egwLogin * logt sich im eGroupware ein mit den Benutzerdaten aus einer Config * und gibt den Cookieinhalt zurück * * @param Config Konfigurations Einstellungen * @return Cookieinhalt */ public KeyArray egwLogin(KeyArray Config) throws Exception { this.egwUrlLinkParser(Config); //this.egwCheckLoginDomains(Config); String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_LOGINSCRIPT + "?" + EGWHTTP_GET_PHPGW_FORWARD + "="; String urlpost = EGWHTTP_POST_VAR_PASSWORD_TYPE + "=" + EGWHTTP_POST_PASSWORD_TYPE_TEXT + "&" + EGWHTTP_POST_VAR_ACCOUNT_TYPE + "=" + EGWHTTP_POST_ACCOUNT_TYPE_U + "&" + EGWHTTP_POST_VAR_LOGINDOMAIN + "=" + Config.getString("logindomain") + "&" + EGWHTTP_POST_VAR_LOGIN + "=" + Config.getString("user") + "&" + EGWHTTP_POST_VAR_PASSWD + "=" + Config.getString("password") + "&" + EGWHTTP_POST_VAR_SUBMITIT + "=" + EGWHTTP_POST_SUBMITIT; String buffer = this.httpcon.openHttpContentSitePost(urlhost + urllink, urlpost); if( buffer.length() == 0 ) { // Verbindungsfehler throw new Exception("NETERROR"); } if( this.httpcon.isNotFound() ) { throw new Exception("PAGENOTFOUND"); } int status = this.egwCheckLoginStatus(); if( status > -1 ) { throw new Exception("LOGIN:" + Integer.toString(status)); } KeyArray egwcookie = new KeyArray(EGWHTTP_EGW_COOKIE); String[] keys = egwcookie.getKeys(); for( int i=0; i<keys.length; i++ ) { String value = this.httpcon.getSocketHeaderField(this.httpcon.getCookie(), keys[i]); if( value.length() == 0 ) { // Login fehlgeschlagen return null; } egwcookie.add(keys[i], value); } this.loginstatus = true; return egwcookie; } /** * egwIsLogin * Überprüft ob eine egw Benutzer noch angemeldet ist * * @param buffer Rückgabe eines HTTP aufrufes muss hier angeben werden, * der Inhalt würd dann drauf überprüft * @param cookie Cookie Informationen zum Überprüfen * @return true = noch Angemeldet, false = nicht mehr Angemeldet */ private boolean egwIsLogin(KeyArray cookie) { String sess = this.httpcon.getCookieVariable(this.httpcon.getCookie(), "sessionid"); String location = this.httpcon.getLocation(); if( sess.length() > 0 ) { if( sess.compareTo(cookie.getString("sessionid")) != 0 ) { this.loginstatus = false; return false; } } else if( (location != null) && (location.indexOf("login.php") != -1) ) { this.loginstatus = false; return false; } this.loginstatus = true; return true; } private int egwCheckLoginStatus() { String back = ""; String buffer = this.httpcon.getLocation(); if( buffer == null ) { buffer = ""; } int pos = buffer.indexOf(jegwhttp.EGWHTTP_LOGINLINK); int end = buffer.length(); if( (pos != -1) && (end != -1) ) { back = buffer.substring( pos + jegwhttp.EGWHTTP_LOGINLINK.length(), end); } else if( (buffer.indexOf("http://") != -1) || (buffer.indexOf("https://") != -1) ) { if( buffer.indexOf("index.php?cd=yes") == -1 ) { return 999; } else { return -1; } } else { return -1; } return Integer.valueOf(back).intValue(); } public boolean egwIsEGWLogin() { return this.loginstatus; } /** * egwGetTagValue * Sucht Inhalte erraus (nach der notation vom html/xml) * * @param buff HTTP Inhalt * @param tag Inhalt umschließer * @return Inhalt */ private String egwGetTagValue(String buff, String tag) { String back = ""; int pos = buff.indexOf("<" + tag + ">"); int end = buff.indexOf("</" + tag + ">", pos); if( (pos != -1) && (end != -1) ) { back = buff.substring( pos + tag.length() +2, end); } return back; } private String egwGetTagValueWithTag(String buff, String tag) { String back = ""; int pos = buff.indexOf("<" + tag + ">"); int end = buff.indexOf("</" + tag + ">", pos); if( (pos != -1) && (end != -1) ) { back = buff.substring( pos, end + tag.length() +3); } return back; } private String egwGetNoneTagText(String buff, String tag) { String back = ""; int pos = buff.indexOf("<" + tag + ">"); int end = buff.indexOf("</" + tag + ">", pos); if( (pos != -1) && (end != -1) ) { back = buff.substring( 0, pos); back = back + buff.substring( end + tag.length() +3, buff.length()-1); } return back; } /** * egwGetEGWCookieStr <SUF>*/ private String egwGetEGWCookieStr(KeyArray cookie) { String cookiestr = ""; String[] keys = cookie.getKeys(); for( int i=0; i<cookie.size(); i++ ) { String tmp = keys[i] + "=" + cookie.getString(keys[i]) + ";"; if(cookiestr.length() == 0) { cookiestr = cookiestr + tmp; } else { cookiestr = cookiestr + " " + tmp; } } cookiestr = cookiestr + " storedlang=de; last_loginid=; last_domain=default; ConfigLang=de"; return cookiestr; } public ArrayList egwLoadEGWData(KeyArray Config, KeyArray cookie) throws Exception { ArrayList msglist = new ArrayList(); String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_GET_NOTIFICATIONS_ACTION; this.httpcon.setIsAjax(true); this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie)); //String buffer = this.httpcon.openHttpContentSite(urlhost + urllink); String buffer = this.httpcon.openHttpContentSitePost( urlhost + urllink, "json_data={\"request\":{\"parameters\":[null]}}" ); this.httpcon.setIsAjax(false); /** * Fehler Behandlung */ /*if( buffer.length() == 0 ) { // Verbindungsfehler throw new Exception("NETERROR"); }*/ if( this.egwIsLogin(cookie) ) { int status = this.egwCheckLoginStatus(); if( status > -1 ) { throw new Exception("LOGIN:" + Integer.toString(status)); } /** * Check auf Rechte (Permission denied!) */ String permission = "<title>Permission denied!</title>"; if( buffer.indexOf(permission) > -1 ) { throw new Exception("PERMISSIONDENIED"); } /** * JSON */ JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory(){ public List creatArrayContainer() { return new LinkedList(); } public Map createObjectContainer() { return new LinkedHashMap(); } }; try { Map json = (Map)parser.parse(buffer.trim(), containerFactory); Iterator iter = json.entrySet().iterator(); while( iter.hasNext() ) { Map.Entry entry = (Map.Entry)iter.next(); if( entry.getKey().toString().compareTo("response") == 0 ) { LinkedList response = (LinkedList) entry.getValue(); for( Integer i=0; i<response.size(); i++ ) { Map jmsg = (Map) response.get(i); Iterator jmsgiter = jmsg.entrySet().iterator(); while( jmsgiter.hasNext() ) { Map.Entry jmsgentry = (Map.Entry)jmsgiter.next(); if( (jmsgentry.getKey().toString().compareTo("type") == 0) && (jmsgentry.getValue().toString().compareTo("data") == 0) && jmsgiter.hasNext() ) { jmsgentry = (Map.Entry)jmsgiter.next(); if( jmsgentry.getKey().toString().compareTo("data") == 0 ) { KeyArray notifymsg = new KeyArray(EGWHTTP_EGW_NOTIFY); Map msgdata = (Map) jmsgentry.getValue(); Iterator dataiter = msgdata.entrySet().iterator(); while( dataiter.hasNext() ) { Map.Entry dataentry = (Map.Entry)dataiter.next(); String tkey = dataentry.getKey().toString(); Object tovalue = dataentry.getValue(); String tvalue = ""; if( tovalue != null ) { tvalue = tovalue.toString(); } if( notifymsg.existKey(tkey) ) { notifymsg.add(tkey, tvalue); } } if( notifymsg.get("notify_id") != null ) { msglist.add(notifymsg); this.egwRemoveEGWData( Config, cookie, notifymsg.getString("notify_id")); } } } } } } } } catch( ParseException pe ) { egwDebuging.log.log(Level.SEVERE, null, pe); throw new Exception("NOAPPS"); } } return msglist; } public Boolean egwRemoveEGWData(KeyArray Config, KeyArray cookie, String notifiy_id) throws Exception { String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_GET_NOTIFICATIONS_ACTION_CONFIRM; this.httpcon.setIsAjax(true); this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie)); //String buffer = this.httpcon.openHttpContentSite(urlhost + urllink); String buffer = this.httpcon.openHttpContentSitePost( urlhost + urllink, "json_data={\"request\":{\"parameters\":[\"" + notifiy_id + "\"]}}" ); this.httpcon.setIsAjax(false); return true; } /** * egwGetSecurityID * beantragt eine Sicherheitsid zum Einlogen * * @param Config Konfiguration eines Accounts * @param cookie Cookie vom einlogen * @return Sicherheitsid, war man nicht eingelogt so ist der String Leer */ public String egwGetSecurityID(KeyArray Config, KeyArray cookie) throws Exception { String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_TRAYMODUL + "?" + EGWHTTP_GET_VAR_MAKE_SECURITYID + "=" + EGWHTTP_GET_MAKE_SECURITYID; String securityid = ""; this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie)); String buffer = this.httpcon.openHttpContentSite(urlhost + urllink); if( this.egwIsLogin(cookie) ) { securityid = this.egwGetTagValue(buffer, EGWHTTP_TAG_SECURITYID); } return securityid; } public String egwGetOpenEGWLink(KeyArray Config, KeyArray cookie, String menuaction) { String urllink = ""; String urlhost = Config.getString("host"); String protocol = "http://"; if( Config.getString("egwurl").startsWith("https") ) { protocol = "https://"; } if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } urllink = urllink + protocol + jegwhttp.checkDir(urlhost) + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_INDEXSCRIPT; urllink = urllink + "?notifiy=1"; if( (menuaction != null) && (menuaction.length() > 0) ) { urllink = urllink + "&" + menuaction; } String[] keys = cookie.getKeys(); for( int i=0; i<cookie.size(); i++ ) { urllink = urllink + "&" + keys[i] + "=" + cookie.getString(keys[i]); } return urllink; } public boolean egwLogout(KeyArray Config, KeyArray cookie) throws Exception { String urlhost = Config.getString("host"); if( Config.getString("port").length() > 0 ) { urlhost = urlhost + ":" + Config.getString("port"); } String urllink = jegwhttp.checkDir(urlhost) + jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_LOGOUTSCRIPT; this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie)); String buffer = this.httpcon.openHttpContentSite(urllink); if( buffer.length() == 0 ) { // Verbindungsfehler throw new Exception("NETERROR"); } if( !this.egwIsLogin(cookie) ) { return true; } return false; } }
17436_4
package ehb.group5.app.UI.views; import com.vaadin.flow.component.Text; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.H1; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.server.VaadinSession; import com.vaadin.flow.theme.Theme; import com.vaadin.flow.theme.lumo.Lumo; import ehb.group5.app.UI.layouts.CommonLayout; import ehb.group5.app.backend.data.DatabaseService; import ehb.group5.app.backend.data.table.CompanyEntity; @Route("support") @PageTitle("Support services") @CssImport("./styles/support.css") public class SupportView extends CommonLayout { /* Author: LAMSAKAM Zakaria email: [email protected] */ /* Ik heb het Vaadin documentatie gebruikt voor de textfield,de emailfield en de passwordfield. https://vaadin.com/docs/v14/ */ public SupportView(){ Div Supportdiv = new Div(); Supportdiv.setId("supportid"); //Titel aanmaken. Supportdiv.add(new H1("Support services")); //Knop aanmaken voor de eerste probleem. Button button = new Button("Ik heb een probleem met de facturatie"); //Notificatie tonen wanneer er op een button wordt geklikt. Dialog dialog = new Dialog(); dialog.add(new Text("Uw factuur bereikt zijn bestemming niet door onjuiste gegevens. Vraag vooraf alle gegevens op, begin met het e-mailadres van de verantwoordelijke voor de betaling van de facturen.\"" + ""+" Andere problemen bel dan deze telefoonnummer voor support: 0124592598"), //Event toevoegen om de button de sluiten new Button("Close", e -> dialog.close())); //De breedte en lengte van de notificatie initialiseren. dialog.setWidth("600px"); dialog.setHeight("250px"); //Event toevoegen om de notificatie open te doen. button.addClickListener(event -> dialog.open()); //Knop aanmaken voor de tweede probleem. Button button2 = new Button("Ik heb een probleem met de betaling"); Dialog dialog2 = new Dialog(); //Hier wordt de text die in de noficatie zitten geïnstalleerd. dialog2.add(new Text("U kan dit oplossen door één of meerdere minder dringende overschrijvingen uit te vinken.\n" + " Vervolgens tekent u enkel de aangevinkte verrichtingen. "+" " + "Andere problemen bel dan deze telefoonnummer voor support: 0124392594"), new Button("Close", e -> dialog2.close())); dialog.setWidth("600px"); dialog.setHeight("250px"); button2.addClickListener(event -> dialog2.open()); //Knop aanmaken voor de derde probleem. Button button3 = new Button("Ik heb een probleem met het bewerken van de informatie "); Dialog dialog3 = new Dialog(); dialog3.add(new Text("BIC code (Bank Identification Code) is een unieke code die één welbepaalde bank identificeert en bestaat meestal uit 8 of 11 tekens." +" Andere problemen bel dan deze telefoonnummer voor support: 0184592599"), new Button("Close", e -> dialog3.close())); dialog.setWidth("600px"); dialog.setHeight("250px"); button3.addClickListener(event -> dialog3.open()); //Knop aanmaken voor de vierde probleem. Button button4 = new Button("Ik heb een probleem met de agenda"); Dialog dialog4 = new Dialog(); dialog4.add(new Text("Zorg ervoor dat je verbinding met internet hebt, controleer of de agenda zichtbaar is, zorg dat nieuwe afspraken worden toegevoegd aan je Google Agenda." +" Andere problemen bel dan deze telefoonnummer voor support: 0124692298"), new Button("Close", e -> dialog4.close())); dialog.setWidth("600px"); dialog.setHeight("250px"); button4.addClickListener(event -> dialog4.open()); //Laatste knop aanmaken voor de vijfde probleem. Button button5 = new Button("Andere probleem"); //Wanneer er geklikt wordt op de button gaan we gestuurd worden naar de pagina van de klasse die geplaats word. button5.addClickListener(buttonClickEvent ->{ UI.getCurrent().navigate(TicketView.class); }); //Alle buttons toevoegen aan de supportdiv. Supportdiv.add(button, button2,button3,button4,button5); Supportdiv.addClassName("centered-content"); getContainer().add(Supportdiv); } }
EHB-TI/Groep5-Reservingstool_voor_winkeliers
src/main/java/ehb/group5/app/UI/views/SupportView.java
1,425
//Event toevoegen om de button de sluiten
line_comment
nl
package ehb.group5.app.UI.views; import com.vaadin.flow.component.Text; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.H1; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.server.VaadinSession; import com.vaadin.flow.theme.Theme; import com.vaadin.flow.theme.lumo.Lumo; import ehb.group5.app.UI.layouts.CommonLayout; import ehb.group5.app.backend.data.DatabaseService; import ehb.group5.app.backend.data.table.CompanyEntity; @Route("support") @PageTitle("Support services") @CssImport("./styles/support.css") public class SupportView extends CommonLayout { /* Author: LAMSAKAM Zakaria email: [email protected] */ /* Ik heb het Vaadin documentatie gebruikt voor de textfield,de emailfield en de passwordfield. https://vaadin.com/docs/v14/ */ public SupportView(){ Div Supportdiv = new Div(); Supportdiv.setId("supportid"); //Titel aanmaken. Supportdiv.add(new H1("Support services")); //Knop aanmaken voor de eerste probleem. Button button = new Button("Ik heb een probleem met de facturatie"); //Notificatie tonen wanneer er op een button wordt geklikt. Dialog dialog = new Dialog(); dialog.add(new Text("Uw factuur bereikt zijn bestemming niet door onjuiste gegevens. Vraag vooraf alle gegevens op, begin met het e-mailadres van de verantwoordelijke voor de betaling van de facturen.\"" + ""+" Andere problemen bel dan deze telefoonnummer voor support: 0124592598"), //Event toevoegen<SUF> new Button("Close", e -> dialog.close())); //De breedte en lengte van de notificatie initialiseren. dialog.setWidth("600px"); dialog.setHeight("250px"); //Event toevoegen om de notificatie open te doen. button.addClickListener(event -> dialog.open()); //Knop aanmaken voor de tweede probleem. Button button2 = new Button("Ik heb een probleem met de betaling"); Dialog dialog2 = new Dialog(); //Hier wordt de text die in de noficatie zitten geïnstalleerd. dialog2.add(new Text("U kan dit oplossen door één of meerdere minder dringende overschrijvingen uit te vinken.\n" + " Vervolgens tekent u enkel de aangevinkte verrichtingen. "+" " + "Andere problemen bel dan deze telefoonnummer voor support: 0124392594"), new Button("Close", e -> dialog2.close())); dialog.setWidth("600px"); dialog.setHeight("250px"); button2.addClickListener(event -> dialog2.open()); //Knop aanmaken voor de derde probleem. Button button3 = new Button("Ik heb een probleem met het bewerken van de informatie "); Dialog dialog3 = new Dialog(); dialog3.add(new Text("BIC code (Bank Identification Code) is een unieke code die één welbepaalde bank identificeert en bestaat meestal uit 8 of 11 tekens." +" Andere problemen bel dan deze telefoonnummer voor support: 0184592599"), new Button("Close", e -> dialog3.close())); dialog.setWidth("600px"); dialog.setHeight("250px"); button3.addClickListener(event -> dialog3.open()); //Knop aanmaken voor de vierde probleem. Button button4 = new Button("Ik heb een probleem met de agenda"); Dialog dialog4 = new Dialog(); dialog4.add(new Text("Zorg ervoor dat je verbinding met internet hebt, controleer of de agenda zichtbaar is, zorg dat nieuwe afspraken worden toegevoegd aan je Google Agenda." +" Andere problemen bel dan deze telefoonnummer voor support: 0124692298"), new Button("Close", e -> dialog4.close())); dialog.setWidth("600px"); dialog.setHeight("250px"); button4.addClickListener(event -> dialog4.open()); //Laatste knop aanmaken voor de vijfde probleem. Button button5 = new Button("Andere probleem"); //Wanneer er geklikt wordt op de button gaan we gestuurd worden naar de pagina van de klasse die geplaats word. button5.addClickListener(buttonClickEvent ->{ UI.getCurrent().navigate(TicketView.class); }); //Alle buttons toevoegen aan de supportdiv. Supportdiv.add(button, button2,button3,button4,button5); Supportdiv.addClassName("centered-content"); getContainer().add(Supportdiv); } }
34914_2
package oefening1; /** * @author Ruben Dejonckheere * */ public abstract class Spons extends OngewerveldDier implements OnderWaterLevend { /** * @param naam * @param kleur */ public Spons(String naam, Kleur kleur) { super(naam, kleur); } @Override public String maakGeluid() { // alle sponzen maken een vergelijkbaar geluid return "..."; } public int geefTijdOnderWater() { // alle sponzen kunnen even lang onder water blijven return 0; } }
EHB-TI/Programming-Essentials-2
Werkcollege4/src/oefening1/Spons.java
169
// alle sponzen maken een vergelijkbaar geluid
line_comment
nl
package oefening1; /** * @author Ruben Dejonckheere * */ public abstract class Spons extends OngewerveldDier implements OnderWaterLevend { /** * @param naam * @param kleur */ public Spons(String naam, Kleur kleur) { super(naam, kleur); } @Override public String maakGeluid() { // alle sponzen<SUF> return "..."; } public int geefTijdOnderWater() { // alle sponzen kunnen even lang onder water blijven return 0; } }
210343_1
package dao; import entity.Event; import entity.User; import java.sql.*; import java.util.ArrayList; public class EventDAO extends BaseDAO { //save event enkel met titel public void saveEvent(Event event) { try(Connection conn = getConn()){ PreparedStatement stmt = conn.prepareStatement("INSERT INTO evenementen (titel) VALUES (?)"); stmt.setString(1, event.getTitle()); stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } //save event met meer velden public void saveEventMoreFields(Event event){ Connection conn = null; try { conn = getConn(); } catch (Exception e) { e.printStackTrace(); } try (PreparedStatement ps = conn.prepareStatement("INSERT INTO evenementen (evenementid, titel, datum, organisator, bier) VALUES (NULL, ?,?,?,?)", Statement.RETURN_GENERATED_KEYS)) { ps.setString(2, event.getTitle()); ps.setDate(3, Date.valueOf(event.getEventDate())); ps.setString(4, String.valueOf(event.getOrganisingBrewery())); ps.setString(5, String.valueOf(event.getFeaturedBeer())); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } //? try (PreparedStatement ps2 = conn.prepareStatement("INSERT INTO aanwezigen (evenementid, gebruikersid) VALUES (NULL, ?)", Statement.RETURN_GENERATED_KEYS)) { for (User v : event.getVisitors()) { ps2.setInt(2, v.getUserID()); ps2.executeUpdate(); } } catch (SQLException ex) { ex.printStackTrace(); } } //findEvent by title public ArrayList<String> findEventByTitle(String searchTerm) { ArrayList<String> eventsFound = new ArrayList<>(); //wildcard % doesn't work? try (Connection conn = getConn()) { PreparedStatement stmt = conn.prepareStatement("SELECT * FROM evenementen WHERE titel LIKE ?"); stmt.setString(1, searchTerm); ResultSet rs = stmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString("titel")); eventsFound.add(rs.getString("titel")); } if (!rs.next()) { System.out.println("Done."); } } catch (Exception e) { e.printStackTrace(); } return eventsFound; } //findEvent by date, om te oefenen public void findEventByDate(Date date){ Connection conn = null; try { conn = getConn(); } catch (Exception e) { e.printStackTrace(); } try (PreparedStatement ps = conn.prepareStatement("SELECT * FROM evenementen WHERE datum = ?")) { ps.setDate(1, date); ResultSet rs = ps.executeQuery(); while (rs.next()){ System.out.println(rs.getString("titel")); System.out.println(rs.getDate("datum")); } } catch (SQLException e) { e.printStackTrace(); } } //deleteEvent by name public void deleteEvent(String title){ try(Connection conn = getConn()){ PreparedStatement stmt = conn.prepareStatement("DELETE FROM evenementen WHERE titel = ?"); stmt.setString(1, title); stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } }
EHB-TI/programming-project-groep-a
src/main/java/dao/EventDAO.java
1,014
//save event met meer velden
line_comment
nl
package dao; import entity.Event; import entity.User; import java.sql.*; import java.util.ArrayList; public class EventDAO extends BaseDAO { //save event enkel met titel public void saveEvent(Event event) { try(Connection conn = getConn()){ PreparedStatement stmt = conn.prepareStatement("INSERT INTO evenementen (titel) VALUES (?)"); stmt.setString(1, event.getTitle()); stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } //save event<SUF> public void saveEventMoreFields(Event event){ Connection conn = null; try { conn = getConn(); } catch (Exception e) { e.printStackTrace(); } try (PreparedStatement ps = conn.prepareStatement("INSERT INTO evenementen (evenementid, titel, datum, organisator, bier) VALUES (NULL, ?,?,?,?)", Statement.RETURN_GENERATED_KEYS)) { ps.setString(2, event.getTitle()); ps.setDate(3, Date.valueOf(event.getEventDate())); ps.setString(4, String.valueOf(event.getOrganisingBrewery())); ps.setString(5, String.valueOf(event.getFeaturedBeer())); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } //? try (PreparedStatement ps2 = conn.prepareStatement("INSERT INTO aanwezigen (evenementid, gebruikersid) VALUES (NULL, ?)", Statement.RETURN_GENERATED_KEYS)) { for (User v : event.getVisitors()) { ps2.setInt(2, v.getUserID()); ps2.executeUpdate(); } } catch (SQLException ex) { ex.printStackTrace(); } } //findEvent by title public ArrayList<String> findEventByTitle(String searchTerm) { ArrayList<String> eventsFound = new ArrayList<>(); //wildcard % doesn't work? try (Connection conn = getConn()) { PreparedStatement stmt = conn.prepareStatement("SELECT * FROM evenementen WHERE titel LIKE ?"); stmt.setString(1, searchTerm); ResultSet rs = stmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString("titel")); eventsFound.add(rs.getString("titel")); } if (!rs.next()) { System.out.println("Done."); } } catch (Exception e) { e.printStackTrace(); } return eventsFound; } //findEvent by date, om te oefenen public void findEventByDate(Date date){ Connection conn = null; try { conn = getConn(); } catch (Exception e) { e.printStackTrace(); } try (PreparedStatement ps = conn.prepareStatement("SELECT * FROM evenementen WHERE datum = ?")) { ps.setDate(1, date); ResultSet rs = ps.executeQuery(); while (rs.next()){ System.out.println(rs.getString("titel")); System.out.println(rs.getDate("datum")); } } catch (SQLException e) { e.printStackTrace(); } } //deleteEvent by name public void deleteEvent(String title){ try(Connection conn = getConn()){ PreparedStatement stmt = conn.prepareStatement("DELETE FROM evenementen WHERE titel = ?"); stmt.setString(1, title); stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } }
52959_0
package nl.knaw.huygens.timbuctoo.core.dto; import com.fasterxml.jackson.databind.JsonNode; import io.vavr.control.Try; import nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection; import nl.knaw.huygens.timbuctoo.model.properties.ReadableProperty; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; import static nl.knaw.huygens.timbuctoo.logging.Logmarkers.databaseInvariant; public class DisplayNameHelper { private static final Logger LOG = LoggerFactory.getLogger(DisplayNameHelper.class); public static Optional<String> getDisplayname(GraphTraversalSource traversalSource, Vertex vertex, Collection targetCollection) { ReadableProperty displayNameProperty = targetCollection.getDisplayName(); if (displayNameProperty != null) { GraphTraversal<Vertex, Try<JsonNode>> displayNameGetter = traversalSource.V(vertex.id()).union( targetCollection.getDisplayName().traversalJson() ); if (displayNameGetter.hasNext()) { Try<JsonNode> traversalResult = displayNameGetter.next(); if (!traversalResult.isSuccess()) { LOG.debug(databaseInvariant, "Retrieving displayname failed", traversalResult.getCause()); } else { if (traversalResult.get() == null) { LOG.debug(databaseInvariant, "Displayname was null"); } else { if (!traversalResult.get().isTextual()) { LOG.debug(databaseInvariant, "Displayname was not a string but " + traversalResult.get().toString()); } else { return Optional.of(traversalResult.get().asText()); } } } } else { LOG.debug(databaseInvariant, "Displayname traversal resulted in no results: " + displayNameGetter); } } else { LOG.debug("No displayname configured for " + targetCollection.getEntityTypeName()); //FIXME: deze wordt gegooid tijdens de finish. da's raar } return Optional.empty(); } }
EMResearch/EMB
jdk_11_maven/cs/graphql/timbuctoo/timbuctoo-instancev4/src/main/java/nl/knaw/huygens/timbuctoo/core/dto/DisplayNameHelper.java
675
//FIXME: deze wordt gegooid tijdens de finish. da's raar
line_comment
nl
package nl.knaw.huygens.timbuctoo.core.dto; import com.fasterxml.jackson.databind.JsonNode; import io.vavr.control.Try; import nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection; import nl.knaw.huygens.timbuctoo.model.properties.ReadableProperty; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; import static nl.knaw.huygens.timbuctoo.logging.Logmarkers.databaseInvariant; public class DisplayNameHelper { private static final Logger LOG = LoggerFactory.getLogger(DisplayNameHelper.class); public static Optional<String> getDisplayname(GraphTraversalSource traversalSource, Vertex vertex, Collection targetCollection) { ReadableProperty displayNameProperty = targetCollection.getDisplayName(); if (displayNameProperty != null) { GraphTraversal<Vertex, Try<JsonNode>> displayNameGetter = traversalSource.V(vertex.id()).union( targetCollection.getDisplayName().traversalJson() ); if (displayNameGetter.hasNext()) { Try<JsonNode> traversalResult = displayNameGetter.next(); if (!traversalResult.isSuccess()) { LOG.debug(databaseInvariant, "Retrieving displayname failed", traversalResult.getCause()); } else { if (traversalResult.get() == null) { LOG.debug(databaseInvariant, "Displayname was null"); } else { if (!traversalResult.get().isTextual()) { LOG.debug(databaseInvariant, "Displayname was not a string but " + traversalResult.get().toString()); } else { return Optional.of(traversalResult.get().asText()); } } } } else { LOG.debug(databaseInvariant, "Displayname traversal resulted in no results: " + displayNameGetter); } } else { LOG.debug("No displayname configured for " + targetCollection.getEntityTypeName()); //FIXME: deze<SUF> } return Optional.empty(); } }
98194_1
/** * In dieser Klasse werden zunächst 2 Stromtarife miteinander verglichen. * Danach wird der günsigste zunächst auf eine bestimmte Anzahl von Stellen * gerundet und danach ausgegeben. * @author robin */ public class Stromrechnung { /**... * @param args wird nicht verwednet. */ public static void main(String[] args) { /* * Zunächst legen wir 2 Variablen für den Grundpreis unserer Verträge an. Da die Preise für ein Jahr berechnet werden sollen, multiplizieren wir diese direkt mit 12 monaten. */ double grundpreisTarif1 = (5.75 * 12); double grundpreisTarif2 = (9.85 * 12); /* * Jetzt müssen wir noch 2 Variablen für die Verbrauchpreise * unserer Tarife anlegen. */ double verbrauchspreisTarif1 = 23.49; double verbrauchspreisTarif2 = 22.10; /* * Nun legen wir noch eine Variale für den Verbrauch an. */ int verbrauch = 3536; /* * Jetzt Verrechnen wir unsere beiden Tarife mit dem Verbrauch. Dazu legen wir 2 weitere Variablen für das Ergebniss an: */ double gesamtpreisTarif1 = ((verbrauchspreisTarif1 / 100) * verbrauch) + grundpreisTarif1; double gesamtpreisTarif2 = (verbrauchspreisTarif2 * verbrauch) + grundpreisTarif2; /* Nun sollen wir den erechneten Betrag auf 2 Stellen runden. dies können wir mit einer Umgestellten Rundungsformel: 100 * Zahl + 0,5 / 100 Damit diese Formel funktioniert benutzen wir einen kleinen Trick. Zunächst wandeln wir das Ergebniss der Rechnung 100 * Zahl +0.5 in eine Integervariable um. Ist eine Zahl mit 0.5 verrechnet nun größer als 0.99 wird die Zahl mit 1 addiert (da Integervariablen keine Nachkommastellen besitzen). Zu diesem Zeitpunkt ist die Zahl natürlich noch viel zu groß. Um nun die letzen beiden Stellen wieder in den Nachkommabereich zu bekommen (und nicht einfach nur abzu- schneiden) wandeln wir zunächst die Zahl wieder in eine double Zahl (welche Nachkommastellen besitzt) um und Dividieren die Zahl mit 100. */ gesamtpreisTarif1 = ((int) (100 * gesamtpreisTarif1 + 0.5)) / (double) 100; gesamtpreisTarif2 = ((int) (100 * gesamtpreisTarif2 + 0.5)) / (double) 100; /*Nun werden noch die Preise der beiden Tarife miteinander verglichen. Der Günstigste der beiden Tarife zu dem Verbrauch, welcher sich in der Variable Verbrauch befindet soll ausgegeben werden. */ double guenstigsterTarif = (gesamtpreisTarif1 < gesamtpreisTarif2 ? gesamtpreisTarif1 : gesamtpreisTarif2); System.out.println(guenstigsterTarif); } }
EPR-P-UE/epr-prak-aufgaben
epr-aufgabe-04-palkovits.java
992
/**... * @param args wird nicht verwednet. */
block_comment
nl
/** * In dieser Klasse werden zunächst 2 Stromtarife miteinander verglichen. * Danach wird der günsigste zunächst auf eine bestimmte Anzahl von Stellen * gerundet und danach ausgegeben. * @author robin */ public class Stromrechnung { /**... <SUF>*/ public static void main(String[] args) { /* * Zunächst legen wir 2 Variablen für den Grundpreis unserer Verträge an. Da die Preise für ein Jahr berechnet werden sollen, multiplizieren wir diese direkt mit 12 monaten. */ double grundpreisTarif1 = (5.75 * 12); double grundpreisTarif2 = (9.85 * 12); /* * Jetzt müssen wir noch 2 Variablen für die Verbrauchpreise * unserer Tarife anlegen. */ double verbrauchspreisTarif1 = 23.49; double verbrauchspreisTarif2 = 22.10; /* * Nun legen wir noch eine Variale für den Verbrauch an. */ int verbrauch = 3536; /* * Jetzt Verrechnen wir unsere beiden Tarife mit dem Verbrauch. Dazu legen wir 2 weitere Variablen für das Ergebniss an: */ double gesamtpreisTarif1 = ((verbrauchspreisTarif1 / 100) * verbrauch) + grundpreisTarif1; double gesamtpreisTarif2 = (verbrauchspreisTarif2 * verbrauch) + grundpreisTarif2; /* Nun sollen wir den erechneten Betrag auf 2 Stellen runden. dies können wir mit einer Umgestellten Rundungsformel: 100 * Zahl + 0,5 / 100 Damit diese Formel funktioniert benutzen wir einen kleinen Trick. Zunächst wandeln wir das Ergebniss der Rechnung 100 * Zahl +0.5 in eine Integervariable um. Ist eine Zahl mit 0.5 verrechnet nun größer als 0.99 wird die Zahl mit 1 addiert (da Integervariablen keine Nachkommastellen besitzen). Zu diesem Zeitpunkt ist die Zahl natürlich noch viel zu groß. Um nun die letzen beiden Stellen wieder in den Nachkommabereich zu bekommen (und nicht einfach nur abzu- schneiden) wandeln wir zunächst die Zahl wieder in eine double Zahl (welche Nachkommastellen besitzt) um und Dividieren die Zahl mit 100. */ gesamtpreisTarif1 = ((int) (100 * gesamtpreisTarif1 + 0.5)) / (double) 100; gesamtpreisTarif2 = ((int) (100 * gesamtpreisTarif2 + 0.5)) / (double) 100; /*Nun werden noch die Preise der beiden Tarife miteinander verglichen. Der Günstigste der beiden Tarife zu dem Verbrauch, welcher sich in der Variable Verbrauch befindet soll ausgegeben werden. */ double guenstigsterTarif = (gesamtpreisTarif1 < gesamtpreisTarif2 ? gesamtpreisTarif1 : gesamtpreisTarif2); System.out.println(guenstigsterTarif); } }
40978_4
/* * $Id: LineKey.java,v 1.16 2003/08/22 23:02:32 dwd Exp $ * * This software is provided by NOAA for full, free and open release. It is * understood by the recipient/user that NOAA assumes no liability for any * errors contained in the code. Although this software is released without * conditions or restrictions in its use, it is expected that appropriate * credit be given to its author and to the National Oceanic and Atmospheric * Administration should the software be included by the recipient as an * element in other product development. */ package gov.noaa.pmel.sgt; import com.cohort.util.MustBe; import com.cohort.util.String2; import gov.noaa.pmel.util.Point2D; import gov.noaa.pmel.util.Rectangle2D; import gov.noaa.pmel.util.Debug; import java.util.Vector; import java.util.Enumeration; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Point; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeSupport; // jdk1.2 //import java.awt.geom.Point2D; /** * <code>LineKey</code> is used to create a key for the * <code>LineCartesianRenderer</code>. Multiple * lines can be included in the key. * * @author Donald Denbo * @version $Revision: 1.16 $, $Date: 2003/08/22 23:02:32 $ * @since 1.0 **/ public class LineKey implements Cloneable, DataKey, Moveable, PropertyChangeListener { private String ident_; /** @directed */ private Layer layer_; /** @link aggregation * @supplierCardinality * * @label line*/ /*#LineCartesianRenderer lnkLineCartesianRenderer;*/ private Vector line_; /** @link aggregation * @supplierCardinality * * @label label*/ /*#SGLabel lnkSGLabel;*/ private Vector label_; private int columns_; private int style_; private int valign_; private int halign_; private Point2D.Double porigin_; private double lineLengthP_; private int maxLabelLength_; private int maxLabelHeight_; private StrokeDrawer stroke_ = null; private boolean selected_; private boolean selectable_; private boolean visible_; private boolean moveable_; private PropertyChangeSupport changes_ = new PropertyChangeSupport(this); private static final int VERTICAL_BORDER_ = 3; private static final int HORIZONTAL_BORDER_ = 15; private static final int COLUMN_SPACE_ = 10; private static final int ROW_SPACE_ = 3; private static final int LABEL_SPACE_ = 15; /** * Use plain line border. */ public static final int PLAIN_LINE = 0; /** * Use raised border. */ public static final int RAISED = 1; /** * Do not draw a border. */ public static final int NO_BORDER = 2; /** * Align to top of key. */ public static final int TOP = 0; /** * Align to middle of key. */ public static final int MIDDLE = 1; /** * Align to bottom of key. */ public static final int BOTTOM = 2; /** * Align to left of key. */ public static final int LEFT = 0; /** * Align to center of key. */ public static final int CENTER = 1; /** * Align to right of key. */ public static final int RIGHT = 2; /** * Bob Simons added this to avoid memory leak problems. */ public void releaseResources() throws Exception { try { layer_ = null; line_ = null; label_ = null; stroke_ = null; changes_ = null; if (JPane.debug) String2.log("sgt.LineKey.releaseResources() finished"); } catch (Throwable t) { String2.log(MustBe.throwableToString(t)); if (JPane.debug) String2.pressEnterToContinue(); } } /** * Default constructor. */ public LineKey() { this(new Point2D.Double(0.0, 0.0), BOTTOM, LEFT); } /** * */ public LineKey(Point2D.Double loc,int valign,int halign) { porigin_ = loc; valign_ = valign; halign_ = halign; line_ = new Vector(2,2); label_ = new Vector(2,2); // // set defaults // style_ = PLAIN_LINE; columns_ = 1; ident_ = ""; lineLengthP_ = 0.3f; selected_ = false; selectable_ = true; visible_ = true; moveable_ = true; stroke_ = PaneProxy.strokeDrawer; } /** * Create of copy of LineKey. */ public LayerChild copy() { LineKey newKey; try { newKey = (LineKey)clone(); } catch (CloneNotSupportedException e) { newKey = new LineKey(); } newKey.line_ = new Vector(2,2); newKey.label_ = new Vector(2,2); return newKey; } public void setSelected(boolean sel) { selected_ = sel; } public boolean isSelected() { return selected_; } public void setSelectable(boolean select) { selectable_ = select; } public boolean isSelectable() { return selectable_; } public boolean isMoveable() { return moveable_; } public void setMoveable(boolean moveable) { moveable_ = moveable; } /** * Set parent layer. * * @param l parent layer */ public void setLayer(Layer l) { layer_ = l; } /** * Get layer. * * @return layer */ public Layer getLayer() { return layer_; } public AbstractPane getPane() { return layer_.getPane(); } public void modified(String mess) { if(layer_ != null) layer_.modified(mess); } /** * Set LineKey identifier. * * @param id key identifier */ public void setId(String id) { ident_ = id; } /** * Get LineKey identifier * * @return identifier */ public String getId() { return ident_; } /** * Set line length. * * @param len line length */ public void setLineLengthP(double len) { if(lineLengthP_ != len) { lineLengthP_ = len; modified("LineKey: setLineLengthP()"); } } /** * Get line length * * @return line length */ public double getLineLengthP() { return lineLengthP_; } /** * Set the number of columns. * * @param col number of columns */ public void setColumns(int col) { if(columns_ != col) { columns_ = col; modified("LineKey: setColumms()"); } } /** * Get the number of columns. * * @return number of columns */ public int getColumns() { return columns_; } /** * Set border style. * * @param style border style * @see #PLAIN_LINE * @see #RAISED * @see #NO_BORDER */ public void setBorderStyle(int style) { if(style_ != style) { style_ = style; modified("LineKey: setBorderStyle()"); } } /** * Get border style. * * @return border style */ public int getBorderStyle() { return style_; } /** * Set alignment. * * @param vert vertical alignment * @param horz horizontal alignment */ public void setAlign(int vert,int horz) { if(valign_ != vert || halign_ != horz) { valign_ = vert; halign_ = horz; modified("LineKey: setAlign()"); } } /** * Set vertical alignment * * @param vert vertical alignment */ public void setVAlign(int vert) { if(valign_ != vert) { valign_ = vert; modified("LineKey: setVAlign()"); } } /** * Set horizontal alignment * * @param horz horizontal alignment */ public void setHAlign(int horz) { if(halign_ != horz) { halign_ = horz; modified("LineKey: setHAlign()"); } } /** * Get vertical alignment * * @return vertical alignment */ public int getVAlign() { return valign_; } /** * Get horizontal alignment * * @return horizontal alignment */ public int getHAlign() { return halign_; } /** * Set location of key * <BR><strong>Property Change:</strong> <code>location</code>. * * @param loc key location */ public void setLocationP(Point2D.Double loc) { if(porigin_ == null || !porigin_.equals(loc)) { Point2D.Double temp = porigin_; porigin_ = loc; changes_.firePropertyChange("location", temp, porigin_); modified("LineKey: setLocationP()"); } } /** * Set the bounds of the <code>LineKey</code> in physical units. */ public void setBoundsP(Rectangle2D.Double r) { setLocationP(new Point2D.Double(r.x, r.y)); } /** * Get key bounds in physical coordinates. * Not presently implemented. */ public Rectangle2D.Double getBoundsP() { throw new MethodNotImplementedError(); } /** * Get location of key. * * @return Key location */ public Point2D.Double getLocationP() { return porigin_; } /** * Add a LineCartesianRenderer and label to the LineKey. * * @param line LineCartesianGraph object * @param label descriptive label */ public void addLineGraph(LineCartesianRenderer line, SGLabel label) { line_.addElement(line); label.setLayer(layer_); label.setMoveable(false); label.setSelectable(false); label_.addElement(label); ((LineAttribute)line.getAttribute()).addPropertyChangeListener(this); modified("LineKey: addLineGraph()"); } /** * Add a LineCartesianRenderer and label to the LineKey. * * @param rend LineCartesianRenderer object * @param label descriptive label * @since 3.0 */ public void addGraph(CartesianRenderer rend, SGLabel label) throws IllegalArgumentException { if(!(rend instanceof LineCartesianRenderer)) throw new IllegalArgumentException("Renderer is not a LineCartesianRenderer"); addLineGraph((LineCartesianRenderer)rend, label); } /** * Remove a line from the LineKey. * */ public void removeLineGraph(SGLabel label) { } /** * Remove a line from the LineKey. * */ public void removeLineRenderer(LineCartesianRenderer line) { } /** * Remove a line from the LineKey. * */ public void removeLineGraph(String ident) { } /** * Remove all lines from the LineKey. */ public void clearAll() { LineAttribute attr; for(Enumeration e = line_.elements(); e.hasMoreElements(); ) { attr = (LineAttribute)((LineCartesianRenderer)e.nextElement()).getAttribute(); attr.removePropertyChangeListener(this); } line_.removeAllElements(); label_.removeAllElements(); modified("LineKey: clearAll()"); } /** * Remove line associated with data id from LineKey. * @since 2.0 */ public void clear(String data_id) { LineCartesianRenderer lcr; int indx = -1; for(Enumeration it = line_.elements(); it.hasMoreElements();) { indx++; lcr = (LineCartesianRenderer)it.nextElement(); if(lcr.getLine().getId().equals(data_id)) { lcr.getAttribute().removePropertyChangeListener(this); line_.removeElement(lcr); label_.removeElementAt(indx); modified("LineKey: clear()"); break; } } } /** * Return rowheight of key in pixels. * @since 2.0 */ public int getRowHeight() { Rectangle bounds; bounds = getBounds(); return ROW_SPACE_ + maxLabelHeight_; } /** * Draw the Key. */ public void draw(Graphics g) { double maxLabelLength, maxLabelHeight; int numLines, numRows, i, lineLength; int col, row, ytemp; double xloc, labelSpace; double[] xp, yp; int[] xd, yd; int[] xout, yout; Rectangle bounds; LineCartesianRenderer render = null; SGLabel label; LineAttribute attr = null; // numLines = line_.size(); if((numLines <= 0) || !visible_) return; numRows = numLines/columns_; if(numLines%columns_ != 0) numRows++; xp = new double[columns_]; xd = new int[columns_]; yp = new double[numRows]; yd = new int[numRows]; xout = new int[2]; yout = new int[2]; g.setColor(layer_.getPane().getComponent().getForeground()); bounds = getBounds(); // // compute location of rows and columns in device and physical coordinates // lineLength = layer_.getXPtoD(lineLengthP_) - layer_.getXPtoD(0.0f); labelSpace = layer_.getXDtoP(LABEL_SPACE_) - layer_.getXDtoP(0); // yd[0] = bounds.y + VERTICAL_BORDER_ + maxLabelHeight_; yp[0] = layer_.getYDtoP(yd[0]); for(i=1; i < numRows; i++) { yd[i] = yd[i-1] + ROW_SPACE_ + maxLabelHeight_; yp[i] = layer_.getYDtoP(yd[i]); } xd[0] = bounds.x + HORIZONTAL_BORDER_; xp[0] = layer_.getXDtoP(xd[0]); for(i=1; i < columns_; i++) { xd[i] = xd[i-1] + COLUMN_SPACE_ + lineLength + LABEL_SPACE_ + maxLabelLength_; xp[i] = layer_.getXDtoP(xd[i]); } // row = 0; col = 0; Object obj; Enumeration labelIt = label_.elements(); for(Enumeration lineIt = line_.elements(); lineIt.hasMoreElements();) { obj = lineIt.nextElement(); render = (LineCartesianRenderer)obj; attr = (LineAttribute)render.getAttribute(); label = (SGLabel)labelIt.nextElement(); // // draw line // g.setColor(attr.getColor()); xout[0] = xd[col]; xout[1] = xout[0] + lineLength; yout[0] = yd[row] - maxLabelHeight_/2; yout[1] = yout[0]; switch(attr.getStyle()) { case LineAttribute.MARK: render.drawMark(g, xout, yout, 2, attr); break; case LineAttribute.HIGHLIGHT: stroke_.drawHighlight(g, xout, yout, 2, attr); break; case LineAttribute.HEAVY: stroke_.drawHeavy(g, xout, yout, 2, attr); break; case LineAttribute.DASHED: stroke_.drawDashed(g, xout, yout, 2, attr); break; case LineAttribute.STROKE: stroke_.drawStroke(g, xout, yout , 2, attr); break; case LineAttribute.MARK_LINE: render.drawMark(g, xout, yout, 2, attr); default: case LineAttribute.SOLID: g.drawLine(xout[0], yout[0], xout[1], yout[1]); } // xloc = xp[col] + lineLengthP_ + labelSpace; label.setLocationP(new Point2D.Double(xloc, yp[row])); try { label.draw(g); } catch (SGException e) {} // col++; if(col >= columns_) { col = 0; row++; } } switch(style_) { case PLAIN_LINE: g.drawRect(bounds.x, bounds.y, bounds.width-1, bounds.height-1); break; case RAISED: break; default: case NO_BORDER: } } /** * Get the bounding rectangle. * * @return bounding rectangle */ public Rectangle getBounds() { int lineLength; int numLines, rows; int x, y, height, width; numLines = line_.size(); if(numLines <= 0) return new Rectangle(0, 0, 0, 0); // // find longest label // maxLabelLength_ = 0; maxLabelHeight_ = 0; SGLabel label; for(Enumeration it = label_.elements(); it.hasMoreElements();) { label = (SGLabel)it.nextElement(); Rectangle sz = label.getBounds(); maxLabelLength_ = Math.max(maxLabelLength_, sz.width); maxLabelHeight_ = Math.max(maxLabelHeight_, sz.height); } // rows = numLines/columns_; if(numLines%columns_ != 0) rows++; lineLength = layer_.getXPtoD(lineLengthP_) - layer_.getXPtoD(0.0f); width = 2*HORIZONTAL_BORDER_ + columns_*(lineLength + LABEL_SPACE_ + maxLabelLength_) + (columns_ - 1)*COLUMN_SPACE_; height = 2*VERTICAL_BORDER_ + rows*maxLabelHeight_ + (rows-1)*ROW_SPACE_; // x = layer_.getXPtoD(porigin_.x); y = layer_.getYPtoD(porigin_.y); switch(halign_) { case RIGHT: x = x - width; break; case CENTER: x = x - width/2; } switch(valign_) { case BOTTOM: y = y - height; break; case MIDDLE: y = y - height/2; } return new Rectangle(x, y, width, height); } public Point getLocation() { Rectangle bnds = getBounds(); return new Point(bnds.x, bnds.y); } public void setLocation(Point loc) { Rectangle bnds = getBounds(); setBounds(loc.x, loc.y, bnds.width, bnds.height); } /** * Set the bounds of the <code>LineKey</code>. */ public void setBounds(Rectangle r) { setBounds(r.x, r.y, r.width, r.height); } /** * Set the bounds of the <code>LineKey</code>. * <BR><strong>Property Change:</strong> <code>location</code>. */ public void setBounds(int x, int y, int width, int height) { switch(halign_) { case RIGHT: x = x + width; break; case CENTER: x = x + width/2; } switch(valign_) { case BOTTOM: y = y + height; break; case MIDDLE: y = y + height/2; } double xp = layer_.getXDtoP(x); double yp = layer_.getYDtoP(y); if(porigin_.x != xp || porigin_.y != yp) { Point2D.Double temp = porigin_; porigin_.x = xp; porigin_.y = yp; changes_.firePropertyChange("location", temp, new Point2D.Double(xp, yp)); modified("LineKey: setBounds()"); } } Object getObjectAt(Point pt) { Rectangle lbnds; Rectangle bounds; LineCartesianRenderer line; int[] xout, yout; int[] xd, yd; int numLines, numRows; int lineLength; double labelSpace; int i; numLines = line_.size(); if(numLines <= 0) return null; numRows = numLines/columns_; if(numLines%columns_ != 0) numRows++; xd = new int[columns_]; yd = new int[numRows]; xout = new int[2]; yout = new int[2]; bounds = getBounds(); // // compute location of rows and columns in device and physical coordinates // lineLength = layer_.getXPtoD(lineLengthP_) - layer_.getXPtoD(0.0); labelSpace = layer_.getXDtoP(LABEL_SPACE_) - layer_.getXDtoP(0); // yd[0] = bounds.y + VERTICAL_BORDER_ + maxLabelHeight_; for(i=1; i < numRows; i++) { yd[i] = yd[i-1] + ROW_SPACE_ + maxLabelHeight_; } xd[0] = bounds.x + HORIZONTAL_BORDER_; for(i=1; i < columns_; i++) { xd[i] = xd[i-1] + COLUMN_SPACE_ + lineLength + LABEL_SPACE_ + maxLabelLength_; } // loop over all the lines int row = 0; int col = 0; for(Enumeration lineIt = line_.elements(); lineIt.hasMoreElements();) { line = (LineCartesianRenderer)lineIt.nextElement(); xout[0] = xd[col]; xout[1] = xout[0] + lineLength + LABEL_SPACE_ + maxLabelLength_; // xout[1] = xout[0] + lineLength + LABEL_SPACE_; yout[0] = yd[row] - maxLabelHeight_; yout[1] = yd[row]; lbnds = new Rectangle(xout[0], yout[0], xout[1] - xout[0], yout[1] - yout[0]); if(lbnds.contains(pt)) { return line; } // col++; if(col >= columns_) { col = 0; row++; } } if(bounds.contains(pt)) { return this; } return null; } public String toString() { String name = getClass().getName(); return name.substring(name.lastIndexOf(".")+1) + ": " + ident_; } public boolean isVisible() { return visible_; } public void setVisible(boolean visible) { if(visible_ != visible) { visible_ = visible; modified("LineKey: setVisible()"); } } public void propertyChange(PropertyChangeEvent evt) { // if(Debug.EVENT) { // System.out.println("LineKey: " + evt); // System.out.println(" " + evt.getPropertyName()); // } modified("LineKey: propertyChange(" + evt.getSource().toString() + "[" + evt.getPropertyName() + "]" + ")"); } public void addPropertyChangeListener(PropertyChangeListener l) { changes_.addPropertyChangeListener(l); } public void removePropertyChangeListener(PropertyChangeListener l) { changes_.removePropertyChangeListener(l); } }
ERDDAP/erddap
WEB-INF/classes/gov/noaa/pmel/sgt/LineKey.java
6,853
/** * Use plain line border. */
block_comment
nl
/* * $Id: LineKey.java,v 1.16 2003/08/22 23:02:32 dwd Exp $ * * This software is provided by NOAA for full, free and open release. It is * understood by the recipient/user that NOAA assumes no liability for any * errors contained in the code. Although this software is released without * conditions or restrictions in its use, it is expected that appropriate * credit be given to its author and to the National Oceanic and Atmospheric * Administration should the software be included by the recipient as an * element in other product development. */ package gov.noaa.pmel.sgt; import com.cohort.util.MustBe; import com.cohort.util.String2; import gov.noaa.pmel.util.Point2D; import gov.noaa.pmel.util.Rectangle2D; import gov.noaa.pmel.util.Debug; import java.util.Vector; import java.util.Enumeration; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Point; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeSupport; // jdk1.2 //import java.awt.geom.Point2D; /** * <code>LineKey</code> is used to create a key for the * <code>LineCartesianRenderer</code>. Multiple * lines can be included in the key. * * @author Donald Denbo * @version $Revision: 1.16 $, $Date: 2003/08/22 23:02:32 $ * @since 1.0 **/ public class LineKey implements Cloneable, DataKey, Moveable, PropertyChangeListener { private String ident_; /** @directed */ private Layer layer_; /** @link aggregation * @supplierCardinality * * @label line*/ /*#LineCartesianRenderer lnkLineCartesianRenderer;*/ private Vector line_; /** @link aggregation * @supplierCardinality * * @label label*/ /*#SGLabel lnkSGLabel;*/ private Vector label_; private int columns_; private int style_; private int valign_; private int halign_; private Point2D.Double porigin_; private double lineLengthP_; private int maxLabelLength_; private int maxLabelHeight_; private StrokeDrawer stroke_ = null; private boolean selected_; private boolean selectable_; private boolean visible_; private boolean moveable_; private PropertyChangeSupport changes_ = new PropertyChangeSupport(this); private static final int VERTICAL_BORDER_ = 3; private static final int HORIZONTAL_BORDER_ = 15; private static final int COLUMN_SPACE_ = 10; private static final int ROW_SPACE_ = 3; private static final int LABEL_SPACE_ = 15; /** * Use plain line<SUF>*/ public static final int PLAIN_LINE = 0; /** * Use raised border. */ public static final int RAISED = 1; /** * Do not draw a border. */ public static final int NO_BORDER = 2; /** * Align to top of key. */ public static final int TOP = 0; /** * Align to middle of key. */ public static final int MIDDLE = 1; /** * Align to bottom of key. */ public static final int BOTTOM = 2; /** * Align to left of key. */ public static final int LEFT = 0; /** * Align to center of key. */ public static final int CENTER = 1; /** * Align to right of key. */ public static final int RIGHT = 2; /** * Bob Simons added this to avoid memory leak problems. */ public void releaseResources() throws Exception { try { layer_ = null; line_ = null; label_ = null; stroke_ = null; changes_ = null; if (JPane.debug) String2.log("sgt.LineKey.releaseResources() finished"); } catch (Throwable t) { String2.log(MustBe.throwableToString(t)); if (JPane.debug) String2.pressEnterToContinue(); } } /** * Default constructor. */ public LineKey() { this(new Point2D.Double(0.0, 0.0), BOTTOM, LEFT); } /** * */ public LineKey(Point2D.Double loc,int valign,int halign) { porigin_ = loc; valign_ = valign; halign_ = halign; line_ = new Vector(2,2); label_ = new Vector(2,2); // // set defaults // style_ = PLAIN_LINE; columns_ = 1; ident_ = ""; lineLengthP_ = 0.3f; selected_ = false; selectable_ = true; visible_ = true; moveable_ = true; stroke_ = PaneProxy.strokeDrawer; } /** * Create of copy of LineKey. */ public LayerChild copy() { LineKey newKey; try { newKey = (LineKey)clone(); } catch (CloneNotSupportedException e) { newKey = new LineKey(); } newKey.line_ = new Vector(2,2); newKey.label_ = new Vector(2,2); return newKey; } public void setSelected(boolean sel) { selected_ = sel; } public boolean isSelected() { return selected_; } public void setSelectable(boolean select) { selectable_ = select; } public boolean isSelectable() { return selectable_; } public boolean isMoveable() { return moveable_; } public void setMoveable(boolean moveable) { moveable_ = moveable; } /** * Set parent layer. * * @param l parent layer */ public void setLayer(Layer l) { layer_ = l; } /** * Get layer. * * @return layer */ public Layer getLayer() { return layer_; } public AbstractPane getPane() { return layer_.getPane(); } public void modified(String mess) { if(layer_ != null) layer_.modified(mess); } /** * Set LineKey identifier. * * @param id key identifier */ public void setId(String id) { ident_ = id; } /** * Get LineKey identifier * * @return identifier */ public String getId() { return ident_; } /** * Set line length. * * @param len line length */ public void setLineLengthP(double len) { if(lineLengthP_ != len) { lineLengthP_ = len; modified("LineKey: setLineLengthP()"); } } /** * Get line length * * @return line length */ public double getLineLengthP() { return lineLengthP_; } /** * Set the number of columns. * * @param col number of columns */ public void setColumns(int col) { if(columns_ != col) { columns_ = col; modified("LineKey: setColumms()"); } } /** * Get the number of columns. * * @return number of columns */ public int getColumns() { return columns_; } /** * Set border style. * * @param style border style * @see #PLAIN_LINE * @see #RAISED * @see #NO_BORDER */ public void setBorderStyle(int style) { if(style_ != style) { style_ = style; modified("LineKey: setBorderStyle()"); } } /** * Get border style. * * @return border style */ public int getBorderStyle() { return style_; } /** * Set alignment. * * @param vert vertical alignment * @param horz horizontal alignment */ public void setAlign(int vert,int horz) { if(valign_ != vert || halign_ != horz) { valign_ = vert; halign_ = horz; modified("LineKey: setAlign()"); } } /** * Set vertical alignment * * @param vert vertical alignment */ public void setVAlign(int vert) { if(valign_ != vert) { valign_ = vert; modified("LineKey: setVAlign()"); } } /** * Set horizontal alignment * * @param horz horizontal alignment */ public void setHAlign(int horz) { if(halign_ != horz) { halign_ = horz; modified("LineKey: setHAlign()"); } } /** * Get vertical alignment * * @return vertical alignment */ public int getVAlign() { return valign_; } /** * Get horizontal alignment * * @return horizontal alignment */ public int getHAlign() { return halign_; } /** * Set location of key * <BR><strong>Property Change:</strong> <code>location</code>. * * @param loc key location */ public void setLocationP(Point2D.Double loc) { if(porigin_ == null || !porigin_.equals(loc)) { Point2D.Double temp = porigin_; porigin_ = loc; changes_.firePropertyChange("location", temp, porigin_); modified("LineKey: setLocationP()"); } } /** * Set the bounds of the <code>LineKey</code> in physical units. */ public void setBoundsP(Rectangle2D.Double r) { setLocationP(new Point2D.Double(r.x, r.y)); } /** * Get key bounds in physical coordinates. * Not presently implemented. */ public Rectangle2D.Double getBoundsP() { throw new MethodNotImplementedError(); } /** * Get location of key. * * @return Key location */ public Point2D.Double getLocationP() { return porigin_; } /** * Add a LineCartesianRenderer and label to the LineKey. * * @param line LineCartesianGraph object * @param label descriptive label */ public void addLineGraph(LineCartesianRenderer line, SGLabel label) { line_.addElement(line); label.setLayer(layer_); label.setMoveable(false); label.setSelectable(false); label_.addElement(label); ((LineAttribute)line.getAttribute()).addPropertyChangeListener(this); modified("LineKey: addLineGraph()"); } /** * Add a LineCartesianRenderer and label to the LineKey. * * @param rend LineCartesianRenderer object * @param label descriptive label * @since 3.0 */ public void addGraph(CartesianRenderer rend, SGLabel label) throws IllegalArgumentException { if(!(rend instanceof LineCartesianRenderer)) throw new IllegalArgumentException("Renderer is not a LineCartesianRenderer"); addLineGraph((LineCartesianRenderer)rend, label); } /** * Remove a line from the LineKey. * */ public void removeLineGraph(SGLabel label) { } /** * Remove a line from the LineKey. * */ public void removeLineRenderer(LineCartesianRenderer line) { } /** * Remove a line from the LineKey. * */ public void removeLineGraph(String ident) { } /** * Remove all lines from the LineKey. */ public void clearAll() { LineAttribute attr; for(Enumeration e = line_.elements(); e.hasMoreElements(); ) { attr = (LineAttribute)((LineCartesianRenderer)e.nextElement()).getAttribute(); attr.removePropertyChangeListener(this); } line_.removeAllElements(); label_.removeAllElements(); modified("LineKey: clearAll()"); } /** * Remove line associated with data id from LineKey. * @since 2.0 */ public void clear(String data_id) { LineCartesianRenderer lcr; int indx = -1; for(Enumeration it = line_.elements(); it.hasMoreElements();) { indx++; lcr = (LineCartesianRenderer)it.nextElement(); if(lcr.getLine().getId().equals(data_id)) { lcr.getAttribute().removePropertyChangeListener(this); line_.removeElement(lcr); label_.removeElementAt(indx); modified("LineKey: clear()"); break; } } } /** * Return rowheight of key in pixels. * @since 2.0 */ public int getRowHeight() { Rectangle bounds; bounds = getBounds(); return ROW_SPACE_ + maxLabelHeight_; } /** * Draw the Key. */ public void draw(Graphics g) { double maxLabelLength, maxLabelHeight; int numLines, numRows, i, lineLength; int col, row, ytemp; double xloc, labelSpace; double[] xp, yp; int[] xd, yd; int[] xout, yout; Rectangle bounds; LineCartesianRenderer render = null; SGLabel label; LineAttribute attr = null; // numLines = line_.size(); if((numLines <= 0) || !visible_) return; numRows = numLines/columns_; if(numLines%columns_ != 0) numRows++; xp = new double[columns_]; xd = new int[columns_]; yp = new double[numRows]; yd = new int[numRows]; xout = new int[2]; yout = new int[2]; g.setColor(layer_.getPane().getComponent().getForeground()); bounds = getBounds(); // // compute location of rows and columns in device and physical coordinates // lineLength = layer_.getXPtoD(lineLengthP_) - layer_.getXPtoD(0.0f); labelSpace = layer_.getXDtoP(LABEL_SPACE_) - layer_.getXDtoP(0); // yd[0] = bounds.y + VERTICAL_BORDER_ + maxLabelHeight_; yp[0] = layer_.getYDtoP(yd[0]); for(i=1; i < numRows; i++) { yd[i] = yd[i-1] + ROW_SPACE_ + maxLabelHeight_; yp[i] = layer_.getYDtoP(yd[i]); } xd[0] = bounds.x + HORIZONTAL_BORDER_; xp[0] = layer_.getXDtoP(xd[0]); for(i=1; i < columns_; i++) { xd[i] = xd[i-1] + COLUMN_SPACE_ + lineLength + LABEL_SPACE_ + maxLabelLength_; xp[i] = layer_.getXDtoP(xd[i]); } // row = 0; col = 0; Object obj; Enumeration labelIt = label_.elements(); for(Enumeration lineIt = line_.elements(); lineIt.hasMoreElements();) { obj = lineIt.nextElement(); render = (LineCartesianRenderer)obj; attr = (LineAttribute)render.getAttribute(); label = (SGLabel)labelIt.nextElement(); // // draw line // g.setColor(attr.getColor()); xout[0] = xd[col]; xout[1] = xout[0] + lineLength; yout[0] = yd[row] - maxLabelHeight_/2; yout[1] = yout[0]; switch(attr.getStyle()) { case LineAttribute.MARK: render.drawMark(g, xout, yout, 2, attr); break; case LineAttribute.HIGHLIGHT: stroke_.drawHighlight(g, xout, yout, 2, attr); break; case LineAttribute.HEAVY: stroke_.drawHeavy(g, xout, yout, 2, attr); break; case LineAttribute.DASHED: stroke_.drawDashed(g, xout, yout, 2, attr); break; case LineAttribute.STROKE: stroke_.drawStroke(g, xout, yout , 2, attr); break; case LineAttribute.MARK_LINE: render.drawMark(g, xout, yout, 2, attr); default: case LineAttribute.SOLID: g.drawLine(xout[0], yout[0], xout[1], yout[1]); } // xloc = xp[col] + lineLengthP_ + labelSpace; label.setLocationP(new Point2D.Double(xloc, yp[row])); try { label.draw(g); } catch (SGException e) {} // col++; if(col >= columns_) { col = 0; row++; } } switch(style_) { case PLAIN_LINE: g.drawRect(bounds.x, bounds.y, bounds.width-1, bounds.height-1); break; case RAISED: break; default: case NO_BORDER: } } /** * Get the bounding rectangle. * * @return bounding rectangle */ public Rectangle getBounds() { int lineLength; int numLines, rows; int x, y, height, width; numLines = line_.size(); if(numLines <= 0) return new Rectangle(0, 0, 0, 0); // // find longest label // maxLabelLength_ = 0; maxLabelHeight_ = 0; SGLabel label; for(Enumeration it = label_.elements(); it.hasMoreElements();) { label = (SGLabel)it.nextElement(); Rectangle sz = label.getBounds(); maxLabelLength_ = Math.max(maxLabelLength_, sz.width); maxLabelHeight_ = Math.max(maxLabelHeight_, sz.height); } // rows = numLines/columns_; if(numLines%columns_ != 0) rows++; lineLength = layer_.getXPtoD(lineLengthP_) - layer_.getXPtoD(0.0f); width = 2*HORIZONTAL_BORDER_ + columns_*(lineLength + LABEL_SPACE_ + maxLabelLength_) + (columns_ - 1)*COLUMN_SPACE_; height = 2*VERTICAL_BORDER_ + rows*maxLabelHeight_ + (rows-1)*ROW_SPACE_; // x = layer_.getXPtoD(porigin_.x); y = layer_.getYPtoD(porigin_.y); switch(halign_) { case RIGHT: x = x - width; break; case CENTER: x = x - width/2; } switch(valign_) { case BOTTOM: y = y - height; break; case MIDDLE: y = y - height/2; } return new Rectangle(x, y, width, height); } public Point getLocation() { Rectangle bnds = getBounds(); return new Point(bnds.x, bnds.y); } public void setLocation(Point loc) { Rectangle bnds = getBounds(); setBounds(loc.x, loc.y, bnds.width, bnds.height); } /** * Set the bounds of the <code>LineKey</code>. */ public void setBounds(Rectangle r) { setBounds(r.x, r.y, r.width, r.height); } /** * Set the bounds of the <code>LineKey</code>. * <BR><strong>Property Change:</strong> <code>location</code>. */ public void setBounds(int x, int y, int width, int height) { switch(halign_) { case RIGHT: x = x + width; break; case CENTER: x = x + width/2; } switch(valign_) { case BOTTOM: y = y + height; break; case MIDDLE: y = y + height/2; } double xp = layer_.getXDtoP(x); double yp = layer_.getYDtoP(y); if(porigin_.x != xp || porigin_.y != yp) { Point2D.Double temp = porigin_; porigin_.x = xp; porigin_.y = yp; changes_.firePropertyChange("location", temp, new Point2D.Double(xp, yp)); modified("LineKey: setBounds()"); } } Object getObjectAt(Point pt) { Rectangle lbnds; Rectangle bounds; LineCartesianRenderer line; int[] xout, yout; int[] xd, yd; int numLines, numRows; int lineLength; double labelSpace; int i; numLines = line_.size(); if(numLines <= 0) return null; numRows = numLines/columns_; if(numLines%columns_ != 0) numRows++; xd = new int[columns_]; yd = new int[numRows]; xout = new int[2]; yout = new int[2]; bounds = getBounds(); // // compute location of rows and columns in device and physical coordinates // lineLength = layer_.getXPtoD(lineLengthP_) - layer_.getXPtoD(0.0); labelSpace = layer_.getXDtoP(LABEL_SPACE_) - layer_.getXDtoP(0); // yd[0] = bounds.y + VERTICAL_BORDER_ + maxLabelHeight_; for(i=1; i < numRows; i++) { yd[i] = yd[i-1] + ROW_SPACE_ + maxLabelHeight_; } xd[0] = bounds.x + HORIZONTAL_BORDER_; for(i=1; i < columns_; i++) { xd[i] = xd[i-1] + COLUMN_SPACE_ + lineLength + LABEL_SPACE_ + maxLabelLength_; } // loop over all the lines int row = 0; int col = 0; for(Enumeration lineIt = line_.elements(); lineIt.hasMoreElements();) { line = (LineCartesianRenderer)lineIt.nextElement(); xout[0] = xd[col]; xout[1] = xout[0] + lineLength + LABEL_SPACE_ + maxLabelLength_; // xout[1] = xout[0] + lineLength + LABEL_SPACE_; yout[0] = yd[row] - maxLabelHeight_; yout[1] = yd[row]; lbnds = new Rectangle(xout[0], yout[0], xout[1] - xout[0], yout[1] - yout[0]); if(lbnds.contains(pt)) { return line; } // col++; if(col >= columns_) { col = 0; row++; } } if(bounds.contains(pt)) { return this; } return null; } public String toString() { String name = getClass().getName(); return name.substring(name.lastIndexOf(".")+1) + ": " + ident_; } public boolean isVisible() { return visible_; } public void setVisible(boolean visible) { if(visible_ != visible) { visible_ = visible; modified("LineKey: setVisible()"); } } public void propertyChange(PropertyChangeEvent evt) { // if(Debug.EVENT) { // System.out.println("LineKey: " + evt); // System.out.println(" " + evt.getPropertyName()); // } modified("LineKey: propertyChange(" + evt.getSource().toString() + "[" + evt.getPropertyName() + "]" + ")"); } public void addPropertyChangeListener(PropertyChangeListener l) { changes_.addPropertyChangeListener(l); } public void removePropertyChangeListener(PropertyChangeListener l) { changes_.removePropertyChangeListener(l); } }
101550_3
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. 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. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via [email protected] or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.sla; import java.sql.Timestamp; import java.util.logging.Level; import org.compiere.model.MSLACriteria; import org.compiere.model.MSLAGoal; import org.compiere.process.ProcessInfoParameter; import org.compiere.process.SvrProcess; import org.compiere.util.AdempiereUserError; /** * Service Level Agreement Goal. * If automatic, capture measures - and calculate/update the actual measure. * * @author Jorg Janke * @version $Id: SLAGoalProcess.java,v 1.2 2006/07/30 00:51:06 jjanke Exp $ */ @org.adempiere.base.annotation.Process public class SLAGoalProcess extends SvrProcess { /** Goal */ private int p_PA_SLA_Goal_ID; /** * Prepare - e.g., get Parameters. */ protected void prepare() { ProcessInfoParameter[] para = getParameter(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else log.log(Level.SEVERE, "prepare - Unknown Parameter: " + name); } p_PA_SLA_Goal_ID = getRecord_ID(); } // prepare /** * Process * @return info * @throws Exception */ protected String doIt () throws Exception { if (log.isLoggable(Level.INFO)) log.info ("PA_SLA_Goal_ID=" + p_PA_SLA_Goal_ID); MSLAGoal goal = new MSLAGoal(getCtx(), p_PA_SLA_Goal_ID, get_TrxName()); if (goal.get_ID() == 0) throw new AdempiereUserError("@PA_SLA_Goal_ID@ " + p_PA_SLA_Goal_ID); MSLACriteria criteria = MSLACriteria.get(getCtx(), goal.getPA_SLA_Criteria_ID(), get_TrxName()); if (criteria.get_ID() == 0) throw new AdempiereUserError("@PA_SLA_Criteria_ID@ " + goal.getPA_SLA_Criteria_ID()); SLACriteria pgm = criteria.newInstance(); int no = pgm.createMeasures(goal); // goal.setMeasureActual(pgm.calculateMeasure(goal)); goal.setDateLastRun(new Timestamp(System.currentTimeMillis())); goal.saveEx(); // return "@Created@ " + no + " - @MeasureActual@=" + goal.getMeasureActual(); } // doIt } // SLAGoalProcess
ERPZI/idempiere
org.adempiere.base/src/org/compiere/sla/SLAGoalProcess.java
1,168
/** * Prepare - e.g., get Parameters. */
block_comment
nl
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. 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. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via [email protected] or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.sla; import java.sql.Timestamp; import java.util.logging.Level; import org.compiere.model.MSLACriteria; import org.compiere.model.MSLAGoal; import org.compiere.process.ProcessInfoParameter; import org.compiere.process.SvrProcess; import org.compiere.util.AdempiereUserError; /** * Service Level Agreement Goal. * If automatic, capture measures - and calculate/update the actual measure. * * @author Jorg Janke * @version $Id: SLAGoalProcess.java,v 1.2 2006/07/30 00:51:06 jjanke Exp $ */ @org.adempiere.base.annotation.Process public class SLAGoalProcess extends SvrProcess { /** Goal */ private int p_PA_SLA_Goal_ID; /** * Prepare - e.g.,<SUF>*/ protected void prepare() { ProcessInfoParameter[] para = getParameter(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else log.log(Level.SEVERE, "prepare - Unknown Parameter: " + name); } p_PA_SLA_Goal_ID = getRecord_ID(); } // prepare /** * Process * @return info * @throws Exception */ protected String doIt () throws Exception { if (log.isLoggable(Level.INFO)) log.info ("PA_SLA_Goal_ID=" + p_PA_SLA_Goal_ID); MSLAGoal goal = new MSLAGoal(getCtx(), p_PA_SLA_Goal_ID, get_TrxName()); if (goal.get_ID() == 0) throw new AdempiereUserError("@PA_SLA_Goal_ID@ " + p_PA_SLA_Goal_ID); MSLACriteria criteria = MSLACriteria.get(getCtx(), goal.getPA_SLA_Criteria_ID(), get_TrxName()); if (criteria.get_ID() == 0) throw new AdempiereUserError("@PA_SLA_Criteria_ID@ " + goal.getPA_SLA_Criteria_ID()); SLACriteria pgm = criteria.newInstance(); int no = pgm.createMeasures(goal); // goal.setMeasureActual(pgm.calculateMeasure(goal)); goal.setDateLastRun(new Timestamp(System.currentTimeMillis())); goal.saveEx(); // return "@Created@ " + no + " - @MeasureActual@=" + goal.getMeasureActual(); } // doIt } // SLAGoalProcess
51704_3
/** * This work is based on original code developed and copyrighted by TNO 2020. * Subsequent contributions are licensed to you by the developers of such code and are * made available to the Project under one or several contributor license agreements. * * This work is licensed to you under the Apache License, Version 2.0. * You may obtain a copy of the license at * * http://www.apache.org/licenses/LICENSE-2.0 * * Contributors: * TNO - Initial implementation * Manager: * TNO */ package nl.tno.esdl.esdldrive.cdo; import java.util.List; import com.ibm.websphere.security.openidconnect.token.IdToken; import nl.tno.esdl.esdldrive.cdo.UserInfo.InvalidLoginInformationException; /** * Defines access control mechanisms for Mondaine CDO * This is based on the Keycloack user_group claim, the groups a user belongs to. * * @author werkmane * */ public class AccessController { public enum FolderType { Organizations, Projects, Users } public static UserInfo userInfoFromToken(IdToken jwtToken) throws InvalidLoginInformationException { return new UserInfo(jwtToken); } public static boolean isWritable(String path, List<String> accessGroups) { return false; } public static HubPermission getPermission(String path, List<String> accessGroups) { for (String group: accessGroups) { if (path.startsWith(group)) { return new HubPermission(path, group, true, true); } else if (group.startsWith(path)) { // upper folders are not writable return new HubPermission(path, group, false, true); } } return new HubPermission(path, null, false, false); } public static boolean canAccess(String path, List<String> accessGroups) { // path = /Users/[email protected]/Vesta resultaten/vesta_output_warmtekeuze_per_buurt.esdl // path = /Projects/Mondaine/Gooi en Vechtstreek/Test_energy_system.esdl // path = /Organisations/TNO/MCS/Veluwe als PV park.esdl for (String group: accessGroups) { System.out.println("Checking " + path + " against " + group); if (path.startsWith(group) || group.startsWith(path)) { return true; } } return false; } }
ESDLMapEditorESSIM/esdl-drive
src/main/java/nl/tno/esdl/esdldrive/cdo/AccessController.java
752
// path = /Users/[email protected]/Vesta resultaten/vesta_output_warmtekeuze_per_buurt.esdl
line_comment
nl
/** * This work is based on original code developed and copyrighted by TNO 2020. * Subsequent contributions are licensed to you by the developers of such code and are * made available to the Project under one or several contributor license agreements. * * This work is licensed to you under the Apache License, Version 2.0. * You may obtain a copy of the license at * * http://www.apache.org/licenses/LICENSE-2.0 * * Contributors: * TNO - Initial implementation * Manager: * TNO */ package nl.tno.esdl.esdldrive.cdo; import java.util.List; import com.ibm.websphere.security.openidconnect.token.IdToken; import nl.tno.esdl.esdldrive.cdo.UserInfo.InvalidLoginInformationException; /** * Defines access control mechanisms for Mondaine CDO * This is based on the Keycloack user_group claim, the groups a user belongs to. * * @author werkmane * */ public class AccessController { public enum FolderType { Organizations, Projects, Users } public static UserInfo userInfoFromToken(IdToken jwtToken) throws InvalidLoginInformationException { return new UserInfo(jwtToken); } public static boolean isWritable(String path, List<String> accessGroups) { return false; } public static HubPermission getPermission(String path, List<String> accessGroups) { for (String group: accessGroups) { if (path.startsWith(group)) { return new HubPermission(path, group, true, true); } else if (group.startsWith(path)) { // upper folders are not writable return new HubPermission(path, group, false, true); } } return new HubPermission(path, null, false, false); } public static boolean canAccess(String path, List<String> accessGroups) { // path =<SUF> // path = /Projects/Mondaine/Gooi en Vechtstreek/Test_energy_system.esdl // path = /Organisations/TNO/MCS/Veluwe als PV park.esdl for (String group: accessGroups) { System.out.println("Checking " + path + " against " + group); if (path.startsWith(group) || group.startsWith(path)) { return true; } } return false; } }
138243_17
/* * @Copyright 2018-2021 HardBackNutter * @License GNU General Public License * * This file is part of NeverTooManyBooks. * * NeverTooManyBooks 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. * * NeverTooManyBooks 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 NeverTooManyBooks. If not, see <http://www.gnu.org/licenses/>. */ package com.hardbacknutter.nevertoomanybooks.searchengines.kbnl; import android.os.Bundle; import androidx.annotation.NonNull; import java.util.ArrayList; import java.util.List; import com.hardbacknutter.nevertoomanybooks.database.DBKey; import com.hardbacknutter.nevertoomanybooks.entities.Author; import com.hardbacknutter.nevertoomanybooks.entities.Book; import com.hardbacknutter.nevertoomanybooks.entities.Publisher; import com.hardbacknutter.nevertoomanybooks.entities.Series; class KbNlBookHandler extends KbNlHandlerBase { @NonNull private final Bundle mBookData; /** accumulate all authors for this book. */ @NonNull private final ArrayList<Author> authorList = new ArrayList<>(); /** accumulate all authors for this book. */ @NonNull private final ArrayList<Series> seriesList = new ArrayList<>(); /** accumulate all Publishers for this book. */ @NonNull private final ArrayList<Publisher> publisherList = new ArrayList<>(); /** * Constructor. * * @param bookData Bundle to update <em>(passed in to allow mocking)</em> */ KbNlBookHandler(@NonNull final Bundle bookData) { mBookData = bookData; } /** * Get the results. * * @return Bundle with book data */ @NonNull public Bundle getResult() { return mBookData; } @Override public void endDocument() { super.endDocument(); if (!authorList.isEmpty()) { mBookData.putParcelableArrayList(Book.BKEY_AUTHOR_LIST, authorList); } if (!seriesList.isEmpty()) { mBookData.putParcelableArrayList(Book.BKEY_SERIES_LIST, seriesList); } if (!publisherList.isEmpty()) { mBookData.putParcelableArrayList(Book.BKEY_PUBLISHER_LIST, publisherList); } // As kb.nl is dutch, and there is no 'language' field, // we're going to assume that all books are in Dutch. if (!mBookData.isEmpty() && !mBookData.containsKey(DBKey.LANGUAGE)) { mBookData.putString(DBKey.LANGUAGE, "nld"); } } /** * Labels for both Dutch (default) and English are listed. * <p> * Note that "Colorist" is also used in Dutch. */ protected void processEntry(@NonNull final String currentLabel, @NonNull final List<String> currentData) { switch (currentLabel) { case "Title": case "Titel": processTitle(currentData); break; case "Author": case "Auteur": processAuthor(currentData, Author.TYPE_WRITER); break; case "Collaborator": case "Medewerker": processAuthor(currentData, Author.TYPE_CONTRIBUTOR); break; case "Artist": case "Kunstenaar": processAuthor(currentData, Author.TYPE_ARTIST); break; case "Colorist": processAuthor(currentData, Author.TYPE_COLORIST); break; case "Translator": case "Vertaler": processAuthor(currentData, Author.TYPE_TRANSLATOR); break; case "Series": case "Reeks": processSeries(currentData); break; case "Part(s)": case "Deel / delen": // This label can appear without there being a "Series" label. // In that case, the book title is presumed to also be the Series title. processSeriesNumber(currentData); break; case "Publisher": case "Uitgever": processPublisher(currentData); break; case "Year": case "Jaar": processDatePublished(currentData); break; case "Extent": case "Omvang": processPages(currentData); break; case "ISBN": processIsbn(currentData); break; case "Illustration": case "Illustratie": // seen, but skipped for now. // Lookup: 9789063349943 // Illustratie: gekleurde ill break; case "Size": case "Formaat": // seen, but skipped for now. // Lookup: 9789063349943 // Formaat: 30 cm break; case "Editie": // [2e dr.] break; case "Note": case "Annotatie": // Omslag vermeldt: K2 //Opl. van 750 genummerde ex //Vert. van: Cromwell Stone. - Delcourt, cop. 1993 break; //case "Note": in english used a second time for a different field. Unique in dutch. case "Noot": break; case "Annex": case "Bijlage": // kleurenprent van oorspr. cover break; case "Subject heading Depot": case "Trefwoord Depot": // not used case "Request number": case "Aanvraagnummer": // not used case "Loan indication": case "Uitleenindicatie": // not used case "Lending information": case "Aanvraaginfo": // not used break; default: // ignore break; } } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text>De</psi:text> * <psi:text href="CLK?IKT=4&amp;TRM=Foundation">Foundation</psi:text> * <psi:text>/ Isaac Asimov ; [vert. uit het Engels door Jack Kröner]</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text href="CLK?IKT=12&amp;TRM=422449059&amp;REC=*"> * De buitengewone reis / Silvio Camboni * </psi:text> * </psi:line> * </psi:labelledData> * }</pre> */ private void processTitle(@NonNull final Iterable<String> currentData) { final StringBuilder sbTitle = new StringBuilder(); for (final String name : currentData) { sbTitle.append(name).append(" "); } final String cleanedTitle = sbTitle.toString().split("/")[0].trim(); mBookData.putString(DBKey.TITLE, cleanedTitle); } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text href="REL?PPN=068561504">Isaak Judovič Ozimov (1920-1992)</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text href="REL?PPN=068870728">Jean-Pol is Jean-Paul Van den Broeck</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text href="REL?PPN=070047596">Dirk Stallaert (1955-)</psi:text> * <psi:text>;</psi:text> * <psi:text href="REL?PPN=073286796">Leo Loedts</psi:text> * </psi:line> * </psi:labelledData> * * }</pre> * * * * <p> * Note that the author name in the above example can be the "actual" name, and not * the publicly known/used name, i.e. in this case "Isaac Asimov" * The second sample shows how the site is creative (hum) about authors using pen-names. * The 3rd sample shows that dates can be added... and that ";" are considered authors. * <p> * ENHANCE: we *really* need to create an 'alias' table for authors. * <p> * Getting author names: * http://opc4.kb.nl/DB=1/SET=1/TTL=1/REL?PPN=068561504 */ private void processAuthor(@NonNull final Iterable<String> currentData, @Author.Type final int type) { for (final String name : currentData) { // remove a year part in the name final String cleanedString = name.split("\\(")[0].trim(); // reject separators as for example: <psi:text>;</psi:text> if (cleanedString.length() == 1) { return; } final Author author = Author.from(cleanedString); author.setType(type); authorList.add(author); } } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text href="CLK?IKT=12&amp;TRM=841288933&amp;REC=*">Foundation-trilogie</psi:text> * <psi:text>;</psi:text> * <psi:text href="CLK?IKT=12&amp;TRM=841288933&amp;REC=*">dl. 1</psi:text> * </psi:line> * </psi:labelledData> * }</pre> */ private void processSeries(@NonNull final List<String> currentData) { if (currentData.size() > 2) { seriesList.add(Series.from(currentData.get(0), currentData.get(2))); } else { seriesList.add(Series.from(currentData.get(0))); } } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text>Deel 1</psi:text> * </psi:line> * </psi:labelledData> * }</pre> */ private void processSeriesNumber(@NonNull final List<String> currentData) { final String title = mBookData.getString(DBKey.TITLE); // should never happen, but paranoia... if (title != null) { final Series series = Series.from(title, currentData.get(0)); seriesList.add(series); } } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text mark="highlight">90-229-5335-1</psi:text> * <psi:text>(geb.)</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text mark="highlight">978-94-6373145-4</psi:text> * <psi:text> (paperback)</psi:text> * </psi:line> * <psi:line> * <psi:text>&#xA0;</psi:text> * </psi:line> * </psi:labelledData> * }</pre> */ private void processIsbn(@NonNull final List<String> currentData) { if (!mBookData.containsKey(DBKey.BOOK_ISBN)) { mBookData.putString(DBKey.BOOK_ISBN, digits(currentData.get(0), true)); if (currentData.size() > 1) { if (!mBookData.containsKey(DBKey.FORMAT)) { String format = currentData.get(1).trim(); if (format.startsWith("(")) { format = format.substring(1, format.length() - 1); } if (!format.isEmpty()) { mBookData.putString(DBKey.FORMAT, format); } } } } } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text href="CLK?IKT=3003&amp;TRM=Breda">Breda</psi:text> * <psi:text> : </psi:text> * <psi:text href="CLK?IKT=3003&amp;TRM=Dark">Dark</psi:text> * <psi:text> </psi:text> * <psi:text href="CLK?IKT=3003&amp;TRM=Dragon">Dragon</psi:text> * <psi:text> </psi:text> * <psi:text href="CLK?IKT=3003&amp;TRM=Books">Books</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text href="CLK?IKT=3003&amp;TRM=Utrecht">Utrecht</psi:text> * <psi:text>[</psi:text> * <psi:text href="CLK?IKT=3003&amp;TRM=etc.">etc.</psi:text> * <psi:text>] :</psi:text> * <psi:text href="CLK?IKT=3003&amp;TRM=Bruna">Bruna</psi:text> * </psi:line> * </psi:labelledData> * }</pre> */ private void processPublisher(@NonNull final Iterable<String> currentData) { final StringBuilder sbPublisher = new StringBuilder(); for (final String name : currentData) { if (!name.isEmpty()) { sbPublisher.append(name).append(" "); } } String publisherName = sbPublisher.toString(); if (publisherName.contains(":")) { publisherName = publisherName.split(":")[1].trim(); } publisherList.add(Publisher.from(publisherName)); } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text>1983</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text>[2019]</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text>cop. 1986</psi:text> * </psi:line> * </psi:labelledData> * * }</pre> */ private void processDatePublished(@NonNull final List<String> currentData) { if (!mBookData.containsKey(DBKey.BOOK_PUBLICATION__DATE)) { final String year = digits(currentData.get(0), false); if (year != null && !year.isEmpty()) { mBookData.putString(DBKey.BOOK_PUBLICATION__DATE, year); } } } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text>48 pagina's</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text>156 p</psi:text> * </psi:line> * </psi:labelledData> * }</pre> */ private void processPages(@NonNull final List<String> currentData) { if (!mBookData.containsKey(DBKey.PAGE_COUNT)) { try { final String cleanedString = currentData.get(0).split(" ")[0]; final int pages = Integer.parseInt(cleanedString); mBookData.putString(DBKey.PAGE_COUNT, String.valueOf(pages)); } catch (@NonNull final NumberFormatException e) { // use source mBookData.putString(DBKey.PAGE_COUNT, currentData.get(0)); } } } }
ETS-Android5/NeverTooManyBooks
app/src/main/java/com/hardbacknutter/nevertoomanybooks/searchengines/kbnl/KbNlBookHandler.java
4,788
//Vert. van: Cromwell Stone. - Delcourt, cop. 1993
line_comment
nl
/* * @Copyright 2018-2021 HardBackNutter * @License GNU General Public License * * This file is part of NeverTooManyBooks. * * NeverTooManyBooks 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. * * NeverTooManyBooks 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 NeverTooManyBooks. If not, see <http://www.gnu.org/licenses/>. */ package com.hardbacknutter.nevertoomanybooks.searchengines.kbnl; import android.os.Bundle; import androidx.annotation.NonNull; import java.util.ArrayList; import java.util.List; import com.hardbacknutter.nevertoomanybooks.database.DBKey; import com.hardbacknutter.nevertoomanybooks.entities.Author; import com.hardbacknutter.nevertoomanybooks.entities.Book; import com.hardbacknutter.nevertoomanybooks.entities.Publisher; import com.hardbacknutter.nevertoomanybooks.entities.Series; class KbNlBookHandler extends KbNlHandlerBase { @NonNull private final Bundle mBookData; /** accumulate all authors for this book. */ @NonNull private final ArrayList<Author> authorList = new ArrayList<>(); /** accumulate all authors for this book. */ @NonNull private final ArrayList<Series> seriesList = new ArrayList<>(); /** accumulate all Publishers for this book. */ @NonNull private final ArrayList<Publisher> publisherList = new ArrayList<>(); /** * Constructor. * * @param bookData Bundle to update <em>(passed in to allow mocking)</em> */ KbNlBookHandler(@NonNull final Bundle bookData) { mBookData = bookData; } /** * Get the results. * * @return Bundle with book data */ @NonNull public Bundle getResult() { return mBookData; } @Override public void endDocument() { super.endDocument(); if (!authorList.isEmpty()) { mBookData.putParcelableArrayList(Book.BKEY_AUTHOR_LIST, authorList); } if (!seriesList.isEmpty()) { mBookData.putParcelableArrayList(Book.BKEY_SERIES_LIST, seriesList); } if (!publisherList.isEmpty()) { mBookData.putParcelableArrayList(Book.BKEY_PUBLISHER_LIST, publisherList); } // As kb.nl is dutch, and there is no 'language' field, // we're going to assume that all books are in Dutch. if (!mBookData.isEmpty() && !mBookData.containsKey(DBKey.LANGUAGE)) { mBookData.putString(DBKey.LANGUAGE, "nld"); } } /** * Labels for both Dutch (default) and English are listed. * <p> * Note that "Colorist" is also used in Dutch. */ protected void processEntry(@NonNull final String currentLabel, @NonNull final List<String> currentData) { switch (currentLabel) { case "Title": case "Titel": processTitle(currentData); break; case "Author": case "Auteur": processAuthor(currentData, Author.TYPE_WRITER); break; case "Collaborator": case "Medewerker": processAuthor(currentData, Author.TYPE_CONTRIBUTOR); break; case "Artist": case "Kunstenaar": processAuthor(currentData, Author.TYPE_ARTIST); break; case "Colorist": processAuthor(currentData, Author.TYPE_COLORIST); break; case "Translator": case "Vertaler": processAuthor(currentData, Author.TYPE_TRANSLATOR); break; case "Series": case "Reeks": processSeries(currentData); break; case "Part(s)": case "Deel / delen": // This label can appear without there being a "Series" label. // In that case, the book title is presumed to also be the Series title. processSeriesNumber(currentData); break; case "Publisher": case "Uitgever": processPublisher(currentData); break; case "Year": case "Jaar": processDatePublished(currentData); break; case "Extent": case "Omvang": processPages(currentData); break; case "ISBN": processIsbn(currentData); break; case "Illustration": case "Illustratie": // seen, but skipped for now. // Lookup: 9789063349943 // Illustratie: gekleurde ill break; case "Size": case "Formaat": // seen, but skipped for now. // Lookup: 9789063349943 // Formaat: 30 cm break; case "Editie": // [2e dr.] break; case "Note": case "Annotatie": // Omslag vermeldt: K2 //Opl. van 750 genummerde ex //Vert. van:<SUF> break; //case "Note": in english used a second time for a different field. Unique in dutch. case "Noot": break; case "Annex": case "Bijlage": // kleurenprent van oorspr. cover break; case "Subject heading Depot": case "Trefwoord Depot": // not used case "Request number": case "Aanvraagnummer": // not used case "Loan indication": case "Uitleenindicatie": // not used case "Lending information": case "Aanvraaginfo": // not used break; default: // ignore break; } } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text>De</psi:text> * <psi:text href="CLK?IKT=4&amp;TRM=Foundation">Foundation</psi:text> * <psi:text>/ Isaac Asimov ; [vert. uit het Engels door Jack Kröner]</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text href="CLK?IKT=12&amp;TRM=422449059&amp;REC=*"> * De buitengewone reis / Silvio Camboni * </psi:text> * </psi:line> * </psi:labelledData> * }</pre> */ private void processTitle(@NonNull final Iterable<String> currentData) { final StringBuilder sbTitle = new StringBuilder(); for (final String name : currentData) { sbTitle.append(name).append(" "); } final String cleanedTitle = sbTitle.toString().split("/")[0].trim(); mBookData.putString(DBKey.TITLE, cleanedTitle); } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text href="REL?PPN=068561504">Isaak Judovič Ozimov (1920-1992)</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text href="REL?PPN=068870728">Jean-Pol is Jean-Paul Van den Broeck</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text href="REL?PPN=070047596">Dirk Stallaert (1955-)</psi:text> * <psi:text>;</psi:text> * <psi:text href="REL?PPN=073286796">Leo Loedts</psi:text> * </psi:line> * </psi:labelledData> * * }</pre> * * * * <p> * Note that the author name in the above example can be the "actual" name, and not * the publicly known/used name, i.e. in this case "Isaac Asimov" * The second sample shows how the site is creative (hum) about authors using pen-names. * The 3rd sample shows that dates can be added... and that ";" are considered authors. * <p> * ENHANCE: we *really* need to create an 'alias' table for authors. * <p> * Getting author names: * http://opc4.kb.nl/DB=1/SET=1/TTL=1/REL?PPN=068561504 */ private void processAuthor(@NonNull final Iterable<String> currentData, @Author.Type final int type) { for (final String name : currentData) { // remove a year part in the name final String cleanedString = name.split("\\(")[0].trim(); // reject separators as for example: <psi:text>;</psi:text> if (cleanedString.length() == 1) { return; } final Author author = Author.from(cleanedString); author.setType(type); authorList.add(author); } } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text href="CLK?IKT=12&amp;TRM=841288933&amp;REC=*">Foundation-trilogie</psi:text> * <psi:text>;</psi:text> * <psi:text href="CLK?IKT=12&amp;TRM=841288933&amp;REC=*">dl. 1</psi:text> * </psi:line> * </psi:labelledData> * }</pre> */ private void processSeries(@NonNull final List<String> currentData) { if (currentData.size() > 2) { seriesList.add(Series.from(currentData.get(0), currentData.get(2))); } else { seriesList.add(Series.from(currentData.get(0))); } } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text>Deel 1</psi:text> * </psi:line> * </psi:labelledData> * }</pre> */ private void processSeriesNumber(@NonNull final List<String> currentData) { final String title = mBookData.getString(DBKey.TITLE); // should never happen, but paranoia... if (title != null) { final Series series = Series.from(title, currentData.get(0)); seriesList.add(series); } } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text mark="highlight">90-229-5335-1</psi:text> * <psi:text>(geb.)</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text mark="highlight">978-94-6373145-4</psi:text> * <psi:text> (paperback)</psi:text> * </psi:line> * <psi:line> * <psi:text>&#xA0;</psi:text> * </psi:line> * </psi:labelledData> * }</pre> */ private void processIsbn(@NonNull final List<String> currentData) { if (!mBookData.containsKey(DBKey.BOOK_ISBN)) { mBookData.putString(DBKey.BOOK_ISBN, digits(currentData.get(0), true)); if (currentData.size() > 1) { if (!mBookData.containsKey(DBKey.FORMAT)) { String format = currentData.get(1).trim(); if (format.startsWith("(")) { format = format.substring(1, format.length() - 1); } if (!format.isEmpty()) { mBookData.putString(DBKey.FORMAT, format); } } } } } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text href="CLK?IKT=3003&amp;TRM=Breda">Breda</psi:text> * <psi:text> : </psi:text> * <psi:text href="CLK?IKT=3003&amp;TRM=Dark">Dark</psi:text> * <psi:text> </psi:text> * <psi:text href="CLK?IKT=3003&amp;TRM=Dragon">Dragon</psi:text> * <psi:text> </psi:text> * <psi:text href="CLK?IKT=3003&amp;TRM=Books">Books</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text href="CLK?IKT=3003&amp;TRM=Utrecht">Utrecht</psi:text> * <psi:text>[</psi:text> * <psi:text href="CLK?IKT=3003&amp;TRM=etc.">etc.</psi:text> * <psi:text>] :</psi:text> * <psi:text href="CLK?IKT=3003&amp;TRM=Bruna">Bruna</psi:text> * </psi:line> * </psi:labelledData> * }</pre> */ private void processPublisher(@NonNull final Iterable<String> currentData) { final StringBuilder sbPublisher = new StringBuilder(); for (final String name : currentData) { if (!name.isEmpty()) { sbPublisher.append(name).append(" "); } } String publisherName = sbPublisher.toString(); if (publisherName.contains(":")) { publisherName = publisherName.split(":")[1].trim(); } publisherList.add(Publisher.from(publisherName)); } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text>1983</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text>[2019]</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text>cop. 1986</psi:text> * </psi:line> * </psi:labelledData> * * }</pre> */ private void processDatePublished(@NonNull final List<String> currentData) { if (!mBookData.containsKey(DBKey.BOOK_PUBLICATION__DATE)) { final String year = digits(currentData.get(0), false); if (year != null && !year.isEmpty()) { mBookData.putString(DBKey.BOOK_PUBLICATION__DATE, year); } } } /** * <pre>{@code * <psi:labelledData> * <psi:line> * <psi:text>48 pagina's</psi:text> * </psi:line> * </psi:labelledData> * * <psi:labelledData> * <psi:line> * <psi:text>156 p</psi:text> * </psi:line> * </psi:labelledData> * }</pre> */ private void processPages(@NonNull final List<String> currentData) { if (!mBookData.containsKey(DBKey.PAGE_COUNT)) { try { final String cleanedString = currentData.get(0).split(" ")[0]; final int pages = Integer.parseInt(cleanedString); mBookData.putString(DBKey.PAGE_COUNT, String.valueOf(pages)); } catch (@NonNull final NumberFormatException e) { // use source mBookData.putString(DBKey.PAGE_COUNT, currentData.get(0)); } } } }
41814_4
package org.example; // need to calculate complexity... Anyway, 4x exercise copy, 1x work on UI, in necessity Tue for UI // DONE: https://codingbat.com/java // IN PROGRESS: https://www.w3resource.com/java-exercises/ // https://www.idtech.com/blog/how-to-practice-java-online-with-free-coding-websites // https://pythonistaplanet.com/java-programming-exercises-with-solutions/?utm_content=cmp-true4 // 1 already 2 done 3 done 4 done 5 done // https://www.codezclub.com/java-solved-programs-problems-solutions/ // 1 done 2 done 3 done 4 done // https://code-exercises.com/ ?? vaak te moeilijk // https://www.geeksforgeeks.org/java-programming-examples/7 /* https://edabit.com/challenge/vzhWSMR2A6wDyFK2o https://edabit.com/challenge/i8bDeBaQtZg6wDGYL https://edabit.com/challenge/pzLMEsMpbCLsPXqy2 https://edabit.com/challenge/KsowZk9crJSRd9uko https://edabit.com/challenge/ZfZMvwTzcTTG2QRzA */ // more string exercises (EdaBit? CodeWars?) // Sieve of eratostenes // rondes 1, 2 [animal game] 3, 4 [animal game 2] 5[animal game 2?] 6[animal game 2>github] public class Main { public static void main(String[] args) { System.out.println("Hello world!"); } }
EWLameijer/JavaExercises
src/main/java/org/example/Main.java
476
// https://code-exercises.com/ ?? vaak te moeilijk
line_comment
nl
package org.example; // need to calculate complexity... Anyway, 4x exercise copy, 1x work on UI, in necessity Tue for UI // DONE: https://codingbat.com/java // IN PROGRESS: https://www.w3resource.com/java-exercises/ // https://www.idtech.com/blog/how-to-practice-java-online-with-free-coding-websites // https://pythonistaplanet.com/java-programming-exercises-with-solutions/?utm_content=cmp-true4 // 1 already 2 done 3 done 4 done 5 done // https://www.codezclub.com/java-solved-programs-problems-solutions/ // 1 done 2 done 3 done 4 done // https://code-exercises.com/ ??<SUF> // https://www.geeksforgeeks.org/java-programming-examples/7 /* https://edabit.com/challenge/vzhWSMR2A6wDyFK2o https://edabit.com/challenge/i8bDeBaQtZg6wDGYL https://edabit.com/challenge/pzLMEsMpbCLsPXqy2 https://edabit.com/challenge/KsowZk9crJSRd9uko https://edabit.com/challenge/ZfZMvwTzcTTG2QRzA */ // more string exercises (EdaBit? CodeWars?) // Sieve of eratostenes // rondes 1, 2 [animal game] 3, 4 [animal game 2] 5[animal game 2?] 6[animal game 2>github] public class Main { public static void main(String[] args) { System.out.println("Hello world!"); } }
134880_1
/************************************************************************************ ** The MIT License (MIT) ** ** Copyright (c) 2016 Serg "EXL" Koles ** ** 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 ru.exlmoto.astrosmash; import java.util.Random; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Rect; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import ru.exlmoto.astrosmash.AstroSmashLauncher.AstroSmashSettings; import ru.exlmoto.astrosmash.AstroSmashEngine.GameWorld; import ru.exlmoto.astrosmash.AstroSmashEngine.Version; import ru.exlmoto.astrosmash.AstroSmashEngine.IGameWorldListener; @SuppressWarnings("unused") public class AstroSmashView extends SurfaceView implements SurfaceHolder.Callback, IGameWorldListener, Runnable { public static final int INITIAL_KEY_DELAY = 250; public static final int KEY_REPEAT_CYCLE = 75; private boolean m_bRunning = true; private boolean isGameOver = false; private Thread m_gameThread = null; private GameWorld m_gameWorld = null; private volatile boolean m_bKeyHeldDown = false; private volatile boolean m_bAfterInitialWait = false; private volatile int m_heldDownGameAction; private volatile long m_initialHoldDownTime; private boolean m_bFirstPaint = true; private long m_nStartTime; private long m_nPauseTime = 0L; private long m_nPausedTime = 0L; Thread m_currentThread = null; int m_nThreadSwitches = 0; long m_nLastMemoryUsageTime = 0L; private int screenWidth; private int screenHeight; private int screenHeightPercent; private Paint painter = null; private Canvas bitmapCanvas = null; private Canvas globalCanvas = null; private Bitmap gameScreen = null; private Bitmap touchArrowBitmap = null; private Canvas touchArrowCanvas = null; private Rect touchRect = null; private Rect bitmapRect = null; private Rect screenRect = null; private Rect screenRectPercent = null; private int px1 = 0; private int px5 = 0; private int px25 = 0; private int px25double = 0; private int arrow_Y0 = 0; private int arrow_Y1 = 0; private int arrow_Y2 = 0; private int arrow_X0 = 0; private int arrow_X1 = 0; private int screenRectChunkProcent = 0; private static Random m_random; private SurfaceHolder surfaceHolder = null; private AstroSmashActivity astroSmashActivity = null; public AstroSmashView(Context context) { super(context); astroSmashActivity = (AstroSmashActivity) context; m_random = new Random(System.currentTimeMillis()); switch (AstroSmashSettings.graphicsScale) { case AstroSmashLauncher.SCALE_120P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_120x146); break; case AstroSmashLauncher.SCALE_176P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_176x220); break; case AstroSmashLauncher.SCALE_240P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_240x320); break; case AstroSmashLauncher.SCALE_480P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_480x640); break; default: break; } surfaceHolder = getHolder(); surfaceHolder.addCallback(this); gameScreen = Bitmap.createBitmap(Version.getWidth(), Version.getHeight(), Bitmap.Config.ARGB_8888); bitmapCanvas = new Canvas(gameScreen); painter = new Paint(); m_gameWorld = new GameWorld(Version.getWidth(), Version.getHeight() - Version.getCommandHeightPixels(), this, context); this.m_bFirstPaint = true; restartGame(true); this.m_nStartTime = 0L; this.m_nPauseTime = 0L; this.m_nPausedTime = 0L; // Set screen on setKeepScreenOn(true); // Focus setFocusable(true); setFocusableInTouchMode(true); requestFocus(); } public void render(Canvas canvas) { if (canvas != null && bitmapCanvas != null) { if (this.m_bFirstPaint) { clearScreen(bitmapCanvas); this.m_bFirstPaint = false; } this.m_gameWorld.paint(bitmapCanvas, painter); if (gameScreen != null) { if (AstroSmashSettings.antialiasing) { painter.setFilterBitmap(true); } if (AstroSmashSettings.showTouchRect) { canvas.drawBitmap(gameScreen, bitmapRect, screenRectPercent, painter); canvas.drawBitmap(touchArrowBitmap, 0, screenRectChunkProcent, painter); } else { canvas.drawBitmap(gameScreen, bitmapRect, screenRect, painter); } } } } private int px(float dips) { float dp = getResources().getDisplayMetrics().density; return Math.round(dips * dp); } private void drawTouchArrow(Canvas canvas, Paint paint) { paint.setColor(Version.GREENCOLOR_DARK); canvas.drawRect(0, 0, screenWidth, screenHeightPercent, paint); paint.setStrokeCap(Cap.ROUND); paint.setAntiAlias(true); for (int i = 0; i < 2; ++i) { if (i == 0) { paint.setColor(Version.GRAYCOLOR); paint.setStrokeWidth(px5); } else { paint.setColor(Version.DARKCOLOR); paint.setStrokeWidth(px1); } canvas.drawLine(px25, arrow_Y0, arrow_X0, arrow_Y0, paint); canvas.drawLine(px25, arrow_Y0, px25double, arrow_Y1, paint); canvas.drawLine(px25, arrow_Y0, px25double, arrow_Y2, paint); canvas.drawLine(arrow_X0, arrow_Y0, arrow_X1, arrow_Y1, paint); canvas.drawLine(arrow_X0, arrow_Y0, arrow_X1, arrow_Y2, paint); } } public boolean isM_bRunning() { return m_bRunning; } public boolean isGameOver() { return isGameOver; } public void SetisGameOver(boolean gameOver) { isGameOver = gameOver; } public int getScreenHeightPercent() { return screenHeightPercent; } public void setScreenHeightPercent(int screenHeightPercent) { this.screenHeightPercent = screenHeightPercent; } public void resetStartTime() { this.m_nStartTime = System.currentTimeMillis(); this.m_nPauseTime = 0L; this.m_nPausedTime = 0L; } public void pause(boolean paused) { AstroSmashActivity.toDebug("Paused: " + paused); this.m_gameWorld.pause(paused); } public void exit() { this.m_bRunning = false; this.m_gameThread = null; } public void start() { if (Version.getDemoFlag()) { if (this.m_nPauseTime > 0L) { this.m_nPausedTime += System.currentTimeMillis() - this.m_nPauseTime; } this.m_nPauseTime = 0L; } this.m_bRunning = true; this.m_gameThread = new Thread(this); this.m_gameThread.start(); this.m_gameWorld.pause(false); } public int getPeakScore() { return this.m_gameWorld.getPeakScore(); } public void restartGame(boolean constructor) { resetStartTime(); this.m_gameWorld.reset(); this.m_bFirstPaint = true; if (!constructor) { init(); start(); } } public int getGameAction(int paramInt) { switch (paramInt) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_SPACE: case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_5: return 9; // Fire case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_W: case KeyEvent.KEYCODE_8: return 1; // Auto Fire case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_A: case KeyEvent.KEYCODE_4: return 2; // Left case KeyEvent.KEYCODE_DPAD_RIGHT: case KeyEvent.KEYCODE_D: case KeyEvent.KEYCODE_6: return 5; // Right case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_S: case KeyEvent.KEYCODE_2: return 6; // Hyper case KeyEvent.KEYCODE_Q: case KeyEvent.KEYCODE_E: case KeyEvent.KEYCODE_7: return 10; // Unknown } return 0; // return super.getGameAction(paramInt); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { this.m_bKeyHeldDown = false; return super.onKeyUp(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { try { int i = getGameAction(keyCode); if (this.m_bRunning) { this.m_gameWorld.handleAction(i); } this.m_heldDownGameAction = i; this.m_bKeyHeldDown = true; this.m_initialHoldDownTime = System.currentTimeMillis(); } catch (Exception localException) { System.out.println(localException.getMessage()); localException.printStackTrace(); } return super.onKeyDown(keyCode, event); } private int getPercentChunkHeight(int sideSize, int percent) { return Math.round(sideSize * percent / 100); } private void init() { screenHeightPercent = getPercentChunkHeight(screenHeight, 15); touchRect = new Rect(0, screenHeight - screenHeightPercent, screenWidth, screenHeight); bitmapRect = new Rect(0, 0, gameScreen.getWidth(), gameScreen.getHeight()); screenRect = new Rect(0, 0, screenWidth, screenHeight); screenRectPercent = new Rect(0, 0, screenWidth, screenHeight - screenHeightPercent); px1 = px(1); px5 = px(5); px25 = px(25); px25double = px25 * 2; arrow_Y0 = touchRect.height() / 2; arrow_Y1 = touchRect.height() / 4; arrow_Y2 = touchRect.height() / 4 * 3; arrow_X0 = screenWidth - px25; arrow_X1 = screenWidth - px25double; screenRectChunkProcent = screenHeight - screenHeightPercent; touchArrowBitmap = Bitmap.createBitmap(screenWidth, screenHeightPercent, Bitmap.Config.ARGB_8888); touchArrowCanvas = new Canvas(touchArrowBitmap); drawTouchArrow(touchArrowCanvas, painter); } @Override public void surfaceCreated(SurfaceHolder holder) { AstroSmashActivity.toDebug("Surface created"); screenWidth = holder.getSurfaceFrame().width(); screenHeight = holder.getSurfaceFrame().height(); init(); start(); if (AstroSmashActivity.paused) { pause(true); } if (isGameOver) { gameIsOver(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { AstroSmashActivity.toDebug("Surface changed: " + width + "x" + height + "|" + screenWidth + "x" + screenHeight); } @Override public void surfaceDestroyed(SurfaceHolder holder) { AstroSmashActivity.toDebug("Surface destroyed"); boolean shutdown = false; this.m_bRunning = false; while (!shutdown) { try { if (m_gameThread != null) { this.m_gameThread.join(); } shutdown = true; } catch (InterruptedException e) { AstroSmashActivity.toDebug("Error joining to Game Thread"); } } } public int getScorePosition(int score) { for (int i = 0; i < AstroSmashLauncher.HISCORE_PLAYERS; i++) { if (score > AstroSmashSettings.playerScores[i]) { return i; } } return -1; } public int addScore(int score, int restartGame) { int i = getScorePosition(score); if (i == -1) { return i; } Intent intent = new Intent(this.getContext(), AstroSmashHighScoreDialog.class); intent.putExtra("peakScore", score); intent.putExtra("indexScore", i); intent.putExtra("restartGame", restartGame); astroSmashActivity.startActivity(intent); return i; } public int checkHiScores(int restartGame) { int peakScore = m_gameWorld.getPeakScore(); AstroSmashActivity.toDebug("HiScore is: " + peakScore); return addScore(peakScore, restartGame); } public void setShipX(int xCoord) { this.m_gameWorld.getShip().setX(xCoord); } public void fire() { this.m_gameWorld.fireBullet(); } protected void clearScreen(Canvas canvas) { canvas.drawColor(Version.WHITECOLOR); } @Override public void gameIsOver() { isGameOver = true; AstroSmashActivity.toDebug("Game Over!"); AstroSmashLauncher.playGameOverSound(); this.m_bRunning = false; this.m_gameThread = null; } public static int getAbsRandomInt() { m_random.setSeed(System.currentTimeMillis() + m_random.nextInt()); return Math.abs(m_random.nextInt()); } public static int getRandomIntBetween(int min, int max) { return (int) ((Math.random() * (max - min)) + min); } public static int getRandomInt() { m_random.setSeed(System.currentTimeMillis() + m_random.nextInt()); return m_random.nextInt(); } public int getScreenWidth() { return screenWidth; } public int getScreenHeight() { return screenHeight; } public int getScreenRectChunkProcent() { return screenRectChunkProcent; } @Override public void run() { try { // long l1 = System.currentTimeMillis(); long l2 = System.currentTimeMillis(); long l5 = l2; this.m_nLastMemoryUsageTime = 0L; while (this.m_bRunning) { long l3 = System.currentTimeMillis(); long l4 = l3 - l2; // if (AstroSmashVersion.getDebugFlag()) { // if ((AstroSmashVersion.getDebugMemoryFlag()) && (l3 - this.m_nLastMemoryUsageTime > AstroSmashVersion.getDebugMemoryInterval())) { // // AstroSmashMidlet.printMemoryUsage("AstrosmashScreen.run (" + (l3 - l1) / 1000L + " secs)"); // this.m_nLastMemoryUsageTime = l3; // } // if (this.m_currentThread != Thread.currentThread()) { // this.m_currentThread = Thread.currentThread(); // this.m_nThreadSwitches += 1; // System.out.println("AstrosmashScreen.run: Game thread switch (" + this.m_nThreadSwitches + " total)"); // } // } // if ((AstroSmashVersion.getDemoFlag()) && (l3 - this.m_nStartTime - this.m_nPausedTime >= AstroSmashVersion.getDemoDuration() * 1000)) { // this.m_gameWorld.suspendEnemies(); // } if ((this.m_bKeyHeldDown) && (l3 - this.m_initialHoldDownTime > 250L) && (l3 - l5 > 75L)) { l5 = l3; this.m_gameWorld.handleAction(this.m_heldDownGameAction); } this.m_gameWorld.tick(l4); try { this.globalCanvas = surfaceHolder.lockCanvas(); synchronized (surfaceHolder) { render(this.globalCanvas); } } finally { if (this.globalCanvas != null) { surfaceHolder.unlockCanvasAndPost(this.globalCanvas); } } l2 = l3; } } catch (Exception localException) { System.out.println(localException.getMessage()); localException.printStackTrace(); } } }
EXL/AstroSmash
astrosmash/src/main/java/ru/exlmoto/astrosmash/AstroSmashView.java
5,293
// Set screen on
line_comment
nl
/************************************************************************************ ** The MIT License (MIT) ** ** Copyright (c) 2016 Serg "EXL" Koles ** ** 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 ru.exlmoto.astrosmash; import java.util.Random; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Rect; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import ru.exlmoto.astrosmash.AstroSmashLauncher.AstroSmashSettings; import ru.exlmoto.astrosmash.AstroSmashEngine.GameWorld; import ru.exlmoto.astrosmash.AstroSmashEngine.Version; import ru.exlmoto.astrosmash.AstroSmashEngine.IGameWorldListener; @SuppressWarnings("unused") public class AstroSmashView extends SurfaceView implements SurfaceHolder.Callback, IGameWorldListener, Runnable { public static final int INITIAL_KEY_DELAY = 250; public static final int KEY_REPEAT_CYCLE = 75; private boolean m_bRunning = true; private boolean isGameOver = false; private Thread m_gameThread = null; private GameWorld m_gameWorld = null; private volatile boolean m_bKeyHeldDown = false; private volatile boolean m_bAfterInitialWait = false; private volatile int m_heldDownGameAction; private volatile long m_initialHoldDownTime; private boolean m_bFirstPaint = true; private long m_nStartTime; private long m_nPauseTime = 0L; private long m_nPausedTime = 0L; Thread m_currentThread = null; int m_nThreadSwitches = 0; long m_nLastMemoryUsageTime = 0L; private int screenWidth; private int screenHeight; private int screenHeightPercent; private Paint painter = null; private Canvas bitmapCanvas = null; private Canvas globalCanvas = null; private Bitmap gameScreen = null; private Bitmap touchArrowBitmap = null; private Canvas touchArrowCanvas = null; private Rect touchRect = null; private Rect bitmapRect = null; private Rect screenRect = null; private Rect screenRectPercent = null; private int px1 = 0; private int px5 = 0; private int px25 = 0; private int px25double = 0; private int arrow_Y0 = 0; private int arrow_Y1 = 0; private int arrow_Y2 = 0; private int arrow_X0 = 0; private int arrow_X1 = 0; private int screenRectChunkProcent = 0; private static Random m_random; private SurfaceHolder surfaceHolder = null; private AstroSmashActivity astroSmashActivity = null; public AstroSmashView(Context context) { super(context); astroSmashActivity = (AstroSmashActivity) context; m_random = new Random(System.currentTimeMillis()); switch (AstroSmashSettings.graphicsScale) { case AstroSmashLauncher.SCALE_120P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_120x146); break; case AstroSmashLauncher.SCALE_176P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_176x220); break; case AstroSmashLauncher.SCALE_240P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_240x320); break; case AstroSmashLauncher.SCALE_480P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_480x640); break; default: break; } surfaceHolder = getHolder(); surfaceHolder.addCallback(this); gameScreen = Bitmap.createBitmap(Version.getWidth(), Version.getHeight(), Bitmap.Config.ARGB_8888); bitmapCanvas = new Canvas(gameScreen); painter = new Paint(); m_gameWorld = new GameWorld(Version.getWidth(), Version.getHeight() - Version.getCommandHeightPixels(), this, context); this.m_bFirstPaint = true; restartGame(true); this.m_nStartTime = 0L; this.m_nPauseTime = 0L; this.m_nPausedTime = 0L; // Set screen<SUF> setKeepScreenOn(true); // Focus setFocusable(true); setFocusableInTouchMode(true); requestFocus(); } public void render(Canvas canvas) { if (canvas != null && bitmapCanvas != null) { if (this.m_bFirstPaint) { clearScreen(bitmapCanvas); this.m_bFirstPaint = false; } this.m_gameWorld.paint(bitmapCanvas, painter); if (gameScreen != null) { if (AstroSmashSettings.antialiasing) { painter.setFilterBitmap(true); } if (AstroSmashSettings.showTouchRect) { canvas.drawBitmap(gameScreen, bitmapRect, screenRectPercent, painter); canvas.drawBitmap(touchArrowBitmap, 0, screenRectChunkProcent, painter); } else { canvas.drawBitmap(gameScreen, bitmapRect, screenRect, painter); } } } } private int px(float dips) { float dp = getResources().getDisplayMetrics().density; return Math.round(dips * dp); } private void drawTouchArrow(Canvas canvas, Paint paint) { paint.setColor(Version.GREENCOLOR_DARK); canvas.drawRect(0, 0, screenWidth, screenHeightPercent, paint); paint.setStrokeCap(Cap.ROUND); paint.setAntiAlias(true); for (int i = 0; i < 2; ++i) { if (i == 0) { paint.setColor(Version.GRAYCOLOR); paint.setStrokeWidth(px5); } else { paint.setColor(Version.DARKCOLOR); paint.setStrokeWidth(px1); } canvas.drawLine(px25, arrow_Y0, arrow_X0, arrow_Y0, paint); canvas.drawLine(px25, arrow_Y0, px25double, arrow_Y1, paint); canvas.drawLine(px25, arrow_Y0, px25double, arrow_Y2, paint); canvas.drawLine(arrow_X0, arrow_Y0, arrow_X1, arrow_Y1, paint); canvas.drawLine(arrow_X0, arrow_Y0, arrow_X1, arrow_Y2, paint); } } public boolean isM_bRunning() { return m_bRunning; } public boolean isGameOver() { return isGameOver; } public void SetisGameOver(boolean gameOver) { isGameOver = gameOver; } public int getScreenHeightPercent() { return screenHeightPercent; } public void setScreenHeightPercent(int screenHeightPercent) { this.screenHeightPercent = screenHeightPercent; } public void resetStartTime() { this.m_nStartTime = System.currentTimeMillis(); this.m_nPauseTime = 0L; this.m_nPausedTime = 0L; } public void pause(boolean paused) { AstroSmashActivity.toDebug("Paused: " + paused); this.m_gameWorld.pause(paused); } public void exit() { this.m_bRunning = false; this.m_gameThread = null; } public void start() { if (Version.getDemoFlag()) { if (this.m_nPauseTime > 0L) { this.m_nPausedTime += System.currentTimeMillis() - this.m_nPauseTime; } this.m_nPauseTime = 0L; } this.m_bRunning = true; this.m_gameThread = new Thread(this); this.m_gameThread.start(); this.m_gameWorld.pause(false); } public int getPeakScore() { return this.m_gameWorld.getPeakScore(); } public void restartGame(boolean constructor) { resetStartTime(); this.m_gameWorld.reset(); this.m_bFirstPaint = true; if (!constructor) { init(); start(); } } public int getGameAction(int paramInt) { switch (paramInt) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_SPACE: case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_5: return 9; // Fire case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_W: case KeyEvent.KEYCODE_8: return 1; // Auto Fire case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_A: case KeyEvent.KEYCODE_4: return 2; // Left case KeyEvent.KEYCODE_DPAD_RIGHT: case KeyEvent.KEYCODE_D: case KeyEvent.KEYCODE_6: return 5; // Right case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_S: case KeyEvent.KEYCODE_2: return 6; // Hyper case KeyEvent.KEYCODE_Q: case KeyEvent.KEYCODE_E: case KeyEvent.KEYCODE_7: return 10; // Unknown } return 0; // return super.getGameAction(paramInt); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { this.m_bKeyHeldDown = false; return super.onKeyUp(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { try { int i = getGameAction(keyCode); if (this.m_bRunning) { this.m_gameWorld.handleAction(i); } this.m_heldDownGameAction = i; this.m_bKeyHeldDown = true; this.m_initialHoldDownTime = System.currentTimeMillis(); } catch (Exception localException) { System.out.println(localException.getMessage()); localException.printStackTrace(); } return super.onKeyDown(keyCode, event); } private int getPercentChunkHeight(int sideSize, int percent) { return Math.round(sideSize * percent / 100); } private void init() { screenHeightPercent = getPercentChunkHeight(screenHeight, 15); touchRect = new Rect(0, screenHeight - screenHeightPercent, screenWidth, screenHeight); bitmapRect = new Rect(0, 0, gameScreen.getWidth(), gameScreen.getHeight()); screenRect = new Rect(0, 0, screenWidth, screenHeight); screenRectPercent = new Rect(0, 0, screenWidth, screenHeight - screenHeightPercent); px1 = px(1); px5 = px(5); px25 = px(25); px25double = px25 * 2; arrow_Y0 = touchRect.height() / 2; arrow_Y1 = touchRect.height() / 4; arrow_Y2 = touchRect.height() / 4 * 3; arrow_X0 = screenWidth - px25; arrow_X1 = screenWidth - px25double; screenRectChunkProcent = screenHeight - screenHeightPercent; touchArrowBitmap = Bitmap.createBitmap(screenWidth, screenHeightPercent, Bitmap.Config.ARGB_8888); touchArrowCanvas = new Canvas(touchArrowBitmap); drawTouchArrow(touchArrowCanvas, painter); } @Override public void surfaceCreated(SurfaceHolder holder) { AstroSmashActivity.toDebug("Surface created"); screenWidth = holder.getSurfaceFrame().width(); screenHeight = holder.getSurfaceFrame().height(); init(); start(); if (AstroSmashActivity.paused) { pause(true); } if (isGameOver) { gameIsOver(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { AstroSmashActivity.toDebug("Surface changed: " + width + "x" + height + "|" + screenWidth + "x" + screenHeight); } @Override public void surfaceDestroyed(SurfaceHolder holder) { AstroSmashActivity.toDebug("Surface destroyed"); boolean shutdown = false; this.m_bRunning = false; while (!shutdown) { try { if (m_gameThread != null) { this.m_gameThread.join(); } shutdown = true; } catch (InterruptedException e) { AstroSmashActivity.toDebug("Error joining to Game Thread"); } } } public int getScorePosition(int score) { for (int i = 0; i < AstroSmashLauncher.HISCORE_PLAYERS; i++) { if (score > AstroSmashSettings.playerScores[i]) { return i; } } return -1; } public int addScore(int score, int restartGame) { int i = getScorePosition(score); if (i == -1) { return i; } Intent intent = new Intent(this.getContext(), AstroSmashHighScoreDialog.class); intent.putExtra("peakScore", score); intent.putExtra("indexScore", i); intent.putExtra("restartGame", restartGame); astroSmashActivity.startActivity(intent); return i; } public int checkHiScores(int restartGame) { int peakScore = m_gameWorld.getPeakScore(); AstroSmashActivity.toDebug("HiScore is: " + peakScore); return addScore(peakScore, restartGame); } public void setShipX(int xCoord) { this.m_gameWorld.getShip().setX(xCoord); } public void fire() { this.m_gameWorld.fireBullet(); } protected void clearScreen(Canvas canvas) { canvas.drawColor(Version.WHITECOLOR); } @Override public void gameIsOver() { isGameOver = true; AstroSmashActivity.toDebug("Game Over!"); AstroSmashLauncher.playGameOverSound(); this.m_bRunning = false; this.m_gameThread = null; } public static int getAbsRandomInt() { m_random.setSeed(System.currentTimeMillis() + m_random.nextInt()); return Math.abs(m_random.nextInt()); } public static int getRandomIntBetween(int min, int max) { return (int) ((Math.random() * (max - min)) + min); } public static int getRandomInt() { m_random.setSeed(System.currentTimeMillis() + m_random.nextInt()); return m_random.nextInt(); } public int getScreenWidth() { return screenWidth; } public int getScreenHeight() { return screenHeight; } public int getScreenRectChunkProcent() { return screenRectChunkProcent; } @Override public void run() { try { // long l1 = System.currentTimeMillis(); long l2 = System.currentTimeMillis(); long l5 = l2; this.m_nLastMemoryUsageTime = 0L; while (this.m_bRunning) { long l3 = System.currentTimeMillis(); long l4 = l3 - l2; // if (AstroSmashVersion.getDebugFlag()) { // if ((AstroSmashVersion.getDebugMemoryFlag()) && (l3 - this.m_nLastMemoryUsageTime > AstroSmashVersion.getDebugMemoryInterval())) { // // AstroSmashMidlet.printMemoryUsage("AstrosmashScreen.run (" + (l3 - l1) / 1000L + " secs)"); // this.m_nLastMemoryUsageTime = l3; // } // if (this.m_currentThread != Thread.currentThread()) { // this.m_currentThread = Thread.currentThread(); // this.m_nThreadSwitches += 1; // System.out.println("AstrosmashScreen.run: Game thread switch (" + this.m_nThreadSwitches + " total)"); // } // } // if ((AstroSmashVersion.getDemoFlag()) && (l3 - this.m_nStartTime - this.m_nPausedTime >= AstroSmashVersion.getDemoDuration() * 1000)) { // this.m_gameWorld.suspendEnemies(); // } if ((this.m_bKeyHeldDown) && (l3 - this.m_initialHoldDownTime > 250L) && (l3 - l5 > 75L)) { l5 = l3; this.m_gameWorld.handleAction(this.m_heldDownGameAction); } this.m_gameWorld.tick(l4); try { this.globalCanvas = surfaceHolder.lockCanvas(); synchronized (surfaceHolder) { render(this.globalCanvas); } } finally { if (this.globalCanvas != null) { surfaceHolder.unlockCanvasAndPost(this.globalCanvas); } } l2 = l3; } } catch (Exception localException) { System.out.println(localException.getMessage()); localException.printStackTrace(); } } }
39118_9
import java.io.*; // importeren van de input en output import java.net.Socket; // importeren van de socket import java.util.Scanner; // importeren van de scanner public class Connection { final protected Socket echoSocket; // socket om met de server te connecten public static final int portNumber; // poort nummer van de server public static final String hostName; // hostnaam van de server static { int conts_1; String const_2; try(Scanner s = new Scanner(new File("./resources/config.properties"))) { // proberen om een scanner te creeren om de config file te lezen conts_1 = s.nextInt(); // poort nummer van de server const_2 = s.next(); // hostnaam van de server } catch (FileNotFoundException e) { // als er een fout optreedt wordt een runtime exception gegooid throw new RuntimeException(e); } portNumber = conts_1; hostName = const_2; } { try { // proberen om een socket te creeren om met de server te connecten echoSocket = new Socket(hostName, portNumber); // socket om met de server te connecten } catch (IOException ex) { throw new RuntimeException(ex); // als er een fout optreedt wordt een runtime exception gegooid } } static PrintWriter out; // printwriter om data naar de server te sturen { try { out = new PrintWriter(echoSocket.getOutputStream(), true); // true zorgt ervoor dat de data direct wordt verstuurd } catch (IOException ex) { throw new RuntimeException(ex); // als er een fout optreedt wordt een runtime exception gegooid } } static BufferedReader in; // bufferedreader om data van de server te lezen { try { // proberen om een bufferedreader te creeren om data van de server te lezen in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); // bufferedreader om data van de server te lezen } catch (IOException ex) { // als er een fout optreedt wordt een runtime exception gegooid throw new RuntimeException(ex); } } }
EZ-2B3/ISY
src/Connection.java
588
// als er een fout optreedt wordt een runtime exception gegooid
line_comment
nl
import java.io.*; // importeren van de input en output import java.net.Socket; // importeren van de socket import java.util.Scanner; // importeren van de scanner public class Connection { final protected Socket echoSocket; // socket om met de server te connecten public static final int portNumber; // poort nummer van de server public static final String hostName; // hostnaam van de server static { int conts_1; String const_2; try(Scanner s = new Scanner(new File("./resources/config.properties"))) { // proberen om een scanner te creeren om de config file te lezen conts_1 = s.nextInt(); // poort nummer van de server const_2 = s.next(); // hostnaam van de server } catch (FileNotFoundException e) { // als er<SUF> throw new RuntimeException(e); } portNumber = conts_1; hostName = const_2; } { try { // proberen om een socket te creeren om met de server te connecten echoSocket = new Socket(hostName, portNumber); // socket om met de server te connecten } catch (IOException ex) { throw new RuntimeException(ex); // als er een fout optreedt wordt een runtime exception gegooid } } static PrintWriter out; // printwriter om data naar de server te sturen { try { out = new PrintWriter(echoSocket.getOutputStream(), true); // true zorgt ervoor dat de data direct wordt verstuurd } catch (IOException ex) { throw new RuntimeException(ex); // als er een fout optreedt wordt een runtime exception gegooid } } static BufferedReader in; // bufferedreader om data van de server te lezen { try { // proberen om een bufferedreader te creeren om data van de server te lezen in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); // bufferedreader om data van de server te lezen } catch (IOException ex) { // als er een fout optreedt wordt een runtime exception gegooid throw new RuntimeException(ex); } } }
181683_1
package mage.cards.b; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.Mode; import mage.abilities.effects.ContinuousRuleModifyingEffectImpl; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.TapTargetEffect; import mage.abilities.keyword.EntwineAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.PhaseStep; import mage.filter.common.FilterCreaturePermanent; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.events.GameEvent.EventType; import mage.game.permanent.Permanent; import mage.game.turn.Step; import mage.players.Player; import mage.target.TargetPlayer; import mage.target.common.TargetCreaturePermanent; /** * * @author LevelX2 */ public final class BlindingBeam extends CardImpl { public BlindingBeam(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{2}{W}"); // Choose one - this.getSpellAbility().getModes().setMinModes(1); this.getSpellAbility().getModes().setMaxModes(1); // Tap two target creatures; this.getSpellAbility().addEffect(new TapTargetEffect()); this.getSpellAbility().addTarget(new TargetCreaturePermanent(2,2)); // or creatures don't untap during target player's next untap step. Mode mode = new Mode(new BlindingBeamEffect()); mode.addTarget(new TargetPlayer()); this.getSpellAbility().getModes().addMode(mode); // Entwine {1} this.addAbility(new EntwineAbility("{1}")); } private BlindingBeam(final BlindingBeam card) { super(card); } @Override public BlindingBeam copy() { return new BlindingBeam(this); } } class BlindingBeamEffect extends OneShotEffect { BlindingBeamEffect() { super(Outcome.Tap); staticText = "creatures don't untap during target player's next untap step"; } private BlindingBeamEffect(final BlindingBeamEffect effect) { super(effect); } @Override public boolean apply(Game game, Ability source) { Player player = game.getPlayer(getTargetPointer().getFirst(game, source)); if (player != null) { game.addEffect(new BlindingBeamEffect2(player.getId()), source); return true; } return false; } @Override public BlindingBeamEffect copy() { return new BlindingBeamEffect(this); } } class BlindingBeamEffect2 extends ContinuousRuleModifyingEffectImpl { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent(); private final UUID targetPlayerId; public BlindingBeamEffect2(UUID targetPlayerId) { super(Duration.Custom, Outcome.Detriment); this.targetPlayerId = targetPlayerId; } private BlindingBeamEffect2(final BlindingBeamEffect2 effect) { super(effect); this.targetPlayerId = effect.targetPlayerId; } @Override public BlindingBeamEffect2 copy() { return new BlindingBeamEffect2(this); } @Override public boolean isInactive(Ability source, Game game) { // the PRE step part is directly after the UNTAP events for permanents if (game.getPhase().getStep().getType() == PhaseStep.UNTAP && game.getStep().getStepPart() == Step.StepPart.PRE) { if (game.isActivePlayer(targetPlayerId) || game.getPlayer(source.getControllerId()).hasReachedNextTurnAfterLeaving()) { return true; } } return false; } @Override public boolean checksEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.UNTAP; } @Override public boolean applies(GameEvent event, Ability source, Game game) { // prevent untap event of creatures of target player if (game.getTurnStepType() == PhaseStep.UNTAP) { Permanent permanent = game.getPermanent(event.getTargetId()); if (permanent != null && permanent.isControlledBy(targetPlayerId) && filter.match(permanent, game)) { return true; } } return false; } }
Ebola16/mage
Mage.Sets/src/mage/cards/b/BlindingBeam.java
1,291
// Choose one -
line_comment
nl
package mage.cards.b; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.Mode; import mage.abilities.effects.ContinuousRuleModifyingEffectImpl; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.TapTargetEffect; import mage.abilities.keyword.EntwineAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.PhaseStep; import mage.filter.common.FilterCreaturePermanent; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.events.GameEvent.EventType; import mage.game.permanent.Permanent; import mage.game.turn.Step; import mage.players.Player; import mage.target.TargetPlayer; import mage.target.common.TargetCreaturePermanent; /** * * @author LevelX2 */ public final class BlindingBeam extends CardImpl { public BlindingBeam(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{2}{W}"); // Choose one<SUF> this.getSpellAbility().getModes().setMinModes(1); this.getSpellAbility().getModes().setMaxModes(1); // Tap two target creatures; this.getSpellAbility().addEffect(new TapTargetEffect()); this.getSpellAbility().addTarget(new TargetCreaturePermanent(2,2)); // or creatures don't untap during target player's next untap step. Mode mode = new Mode(new BlindingBeamEffect()); mode.addTarget(new TargetPlayer()); this.getSpellAbility().getModes().addMode(mode); // Entwine {1} this.addAbility(new EntwineAbility("{1}")); } private BlindingBeam(final BlindingBeam card) { super(card); } @Override public BlindingBeam copy() { return new BlindingBeam(this); } } class BlindingBeamEffect extends OneShotEffect { BlindingBeamEffect() { super(Outcome.Tap); staticText = "creatures don't untap during target player's next untap step"; } private BlindingBeamEffect(final BlindingBeamEffect effect) { super(effect); } @Override public boolean apply(Game game, Ability source) { Player player = game.getPlayer(getTargetPointer().getFirst(game, source)); if (player != null) { game.addEffect(new BlindingBeamEffect2(player.getId()), source); return true; } return false; } @Override public BlindingBeamEffect copy() { return new BlindingBeamEffect(this); } } class BlindingBeamEffect2 extends ContinuousRuleModifyingEffectImpl { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent(); private final UUID targetPlayerId; public BlindingBeamEffect2(UUID targetPlayerId) { super(Duration.Custom, Outcome.Detriment); this.targetPlayerId = targetPlayerId; } private BlindingBeamEffect2(final BlindingBeamEffect2 effect) { super(effect); this.targetPlayerId = effect.targetPlayerId; } @Override public BlindingBeamEffect2 copy() { return new BlindingBeamEffect2(this); } @Override public boolean isInactive(Ability source, Game game) { // the PRE step part is directly after the UNTAP events for permanents if (game.getPhase().getStep().getType() == PhaseStep.UNTAP && game.getStep().getStepPart() == Step.StepPart.PRE) { if (game.isActivePlayer(targetPlayerId) || game.getPlayer(source.getControllerId()).hasReachedNextTurnAfterLeaving()) { return true; } } return false; } @Override public boolean checksEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.UNTAP; } @Override public boolean applies(GameEvent event, Ability source, Game game) { // prevent untap event of creatures of target player if (game.getTurnStepType() == PhaseStep.UNTAP) { Permanent permanent = game.getPermanent(event.getTargetId()); if (permanent != null && permanent.isControlledBy(targetPlayerId) && filter.match(permanent, game)) { return true; } } return false; } }
185302_5
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.register.client; import java.util.Date; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import org.springframework.jms.core.JmsTemplate; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * Basis implementatie voor blocking en caching register service. * @param <T> regsiter type */ public abstract class AbstractRegisterServiceImpl<T> implements RegisterService<T>, MessageListener { private static final int REGISTER_MAX_LOOPS = 6; private static final Logger LOG = LoggerFactory.getLogger(); private static final int DEFAULT_TIMEOUT = 10; private static final TimeUnit DEFAULT_TIMEOUT_UNIT = TimeUnit.SECONDS; private final Object lock = new Object(); private final int timeout; private final TimeUnit timeoutUnit; private volatile CountDownLatch registerOntvangenLatch = new CountDownLatch(1); private volatile boolean started; private volatile T register; private JmsTemplate jmsTemplate; private String laatsteBericht; private Long laatsteOntvangst; /** * Constructor. */ protected AbstractRegisterServiceImpl() { this(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT); } /** * Constructor. * @param timeout timeout * @param timeoutUnit timeout unit */ protected AbstractRegisterServiceImpl(final int timeout, final TimeUnit timeoutUnit) { this.timeout = timeout; this.timeoutUnit = timeoutUnit; } /** * Zet het JMS Template. * @param jmsTemplate het te zetten JMS Template */ @Required public final void setJmsTemplate(final JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } @Override @Transactional(transactionManager = "registerTransactionManager", propagation = Propagation.REQUIRES_NEW) public final void refreshRegister() { synchronized (lock) { LOG.info("Versturen register verzoek ({})", getClass()); jmsTemplate.send(session -> session.createTextMessage(maakVerzoek())); started = true; } } /** * Maak het register verzoek bericht. * @return verzoek bericht */ protected abstract String maakVerzoek(); @Override public final void clearRegister() { synchronized (lock) { started = false; register = null; laatsteBericht = null; laatsteOntvangst = null; registerOntvangenLatch = new CountDownLatch(1); } } @Override public final T geefRegister() { if (!started) { refreshRegister(); } try { int waitLoop = 0; while (!registerOntvangenLatch.await(timeout, timeoutUnit)) { waitLoop++; LOG.info("Register ({}) niet ontvangen na {} {}", getClass(), waitLoop * timeout, timeoutUnit.toString()); if (waitLoop >= REGISTER_MAX_LOOPS) { throw new IllegalArgumentException("Register niet ontvangen, verwerking wordt afgebroken"); } } } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } return register; } @Override public final void onMessage(final Message message) { synchronized (lock) { try { LOG.info("Ontvangen register ({})", getClass()); final String bericht = leesMessage(message); laatsteBericht = bericht; laatsteOntvangst = System.currentTimeMillis(); register = leesRegister(bericht); registerOntvangenLatch.countDown(); } catch (final JMSException e) { LOG.warn("Kon binnenkomend bericht voor register niet verwerken. Bericht wordt genegeerd ...", e); } } } @Override public final String getLaatsteBericht() { return laatsteBericht; } @Override public final Date getLaatsteOntvangst() { return laatsteOntvangst == null ? null : new Date(laatsteOntvangst); } @Override public final String getRegisterAsString() { return register == null ? null : register.toString(); } /** * Lees het register uit het gepubliceerde bericht. * @param bericht bericht * @return register * @throws JMSException bij lees fouten */ protected abstract T leesRegister(String bericht) throws JMSException; private static String leesMessage(final Message message) throws JMSException { // content final String content; if (message instanceof TextMessage) { content = ((TextMessage) message).getText(); } else { throw new IllegalArgumentException("Message type niet ondersteund: " + message); } return content; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-register-client/src/main/java/nl/bzk/migratiebrp/register/client/AbstractRegisterServiceImpl.java
1,524
/** * Maak het register verzoek bericht. * @return verzoek bericht */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.register.client; import java.util.Date; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import org.springframework.jms.core.JmsTemplate; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * Basis implementatie voor blocking en caching register service. * @param <T> regsiter type */ public abstract class AbstractRegisterServiceImpl<T> implements RegisterService<T>, MessageListener { private static final int REGISTER_MAX_LOOPS = 6; private static final Logger LOG = LoggerFactory.getLogger(); private static final int DEFAULT_TIMEOUT = 10; private static final TimeUnit DEFAULT_TIMEOUT_UNIT = TimeUnit.SECONDS; private final Object lock = new Object(); private final int timeout; private final TimeUnit timeoutUnit; private volatile CountDownLatch registerOntvangenLatch = new CountDownLatch(1); private volatile boolean started; private volatile T register; private JmsTemplate jmsTemplate; private String laatsteBericht; private Long laatsteOntvangst; /** * Constructor. */ protected AbstractRegisterServiceImpl() { this(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT); } /** * Constructor. * @param timeout timeout * @param timeoutUnit timeout unit */ protected AbstractRegisterServiceImpl(final int timeout, final TimeUnit timeoutUnit) { this.timeout = timeout; this.timeoutUnit = timeoutUnit; } /** * Zet het JMS Template. * @param jmsTemplate het te zetten JMS Template */ @Required public final void setJmsTemplate(final JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } @Override @Transactional(transactionManager = "registerTransactionManager", propagation = Propagation.REQUIRES_NEW) public final void refreshRegister() { synchronized (lock) { LOG.info("Versturen register verzoek ({})", getClass()); jmsTemplate.send(session -> session.createTextMessage(maakVerzoek())); started = true; } } /** * Maak het register<SUF>*/ protected abstract String maakVerzoek(); @Override public final void clearRegister() { synchronized (lock) { started = false; register = null; laatsteBericht = null; laatsteOntvangst = null; registerOntvangenLatch = new CountDownLatch(1); } } @Override public final T geefRegister() { if (!started) { refreshRegister(); } try { int waitLoop = 0; while (!registerOntvangenLatch.await(timeout, timeoutUnit)) { waitLoop++; LOG.info("Register ({}) niet ontvangen na {} {}", getClass(), waitLoop * timeout, timeoutUnit.toString()); if (waitLoop >= REGISTER_MAX_LOOPS) { throw new IllegalArgumentException("Register niet ontvangen, verwerking wordt afgebroken"); } } } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } return register; } @Override public final void onMessage(final Message message) { synchronized (lock) { try { LOG.info("Ontvangen register ({})", getClass()); final String bericht = leesMessage(message); laatsteBericht = bericht; laatsteOntvangst = System.currentTimeMillis(); register = leesRegister(bericht); registerOntvangenLatch.countDown(); } catch (final JMSException e) { LOG.warn("Kon binnenkomend bericht voor register niet verwerken. Bericht wordt genegeerd ...", e); } } } @Override public final String getLaatsteBericht() { return laatsteBericht; } @Override public final Date getLaatsteOntvangst() { return laatsteOntvangst == null ? null : new Date(laatsteOntvangst); } @Override public final String getRegisterAsString() { return register == null ? null : register.toString(); } /** * Lees het register uit het gepubliceerde bericht. * @param bericht bericht * @return register * @throws JMSException bij lees fouten */ protected abstract T leesRegister(String bericht) throws JMSException; private static String leesMessage(final Message message) throws JMSException { // content final String content; if (message instanceof TextMessage) { content = ((TextMessage) message).getText(); } else { throw new IllegalArgumentException("Message type niet ondersteund: " + message); } return content; } }
121704_3
package hoken.ast; import hoken.parser.HokenParser; import java.util.ArrayList; import java.util.List; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; import org.antlr.runtime.tree.Tree; /** * AST node waarin een of meerdere identifiers van een bepaald type worden * gedeclareerd, al dan niet als constante. * */ public class DeclarationNode extends HokenNode { /** * Het basisadres van deze declaratie. Als deze declaratienode geldt voor * meerde identifiers, geldt er wellicht een offset. **/ public int address = -1; /** Boolean die aangeeft of dit een constante declaratie is. **/ public boolean isConstant = false; /** Lijst met identifiers die in deze node gedeclareerd zijn. **/ public List<String> ids = new ArrayList<String>(); public DeclarationNode(Token t) { token = t; } public DeclarationNode(DeclarationNode node) { super(node); } public DeclarationNode(int tokenType) { super(new CommonToken(tokenType, HokenParser.tokenNames[tokenType])); } public Tree dupNode() { return new DeclarationNode(this); } public String toString() { return token.getText() + "<DeclarationNode>"; } /** * Bepaalt op basis van de gegeven <code>IdNode</code> het adres van de * identifier in het geheugen. * * @param id * de identifier * @return het adres van de identifier */ public int getOffsettedAddress(IdNode id) { return this.address + this.ids.indexOf(id.getText()); } }
EerdeBruining/vertalerbouw
src/hoken/ast/DeclarationNode.java
473
/** Lijst met identifiers die in deze node gedeclareerd zijn. **/
block_comment
nl
package hoken.ast; import hoken.parser.HokenParser; import java.util.ArrayList; import java.util.List; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; import org.antlr.runtime.tree.Tree; /** * AST node waarin een of meerdere identifiers van een bepaald type worden * gedeclareerd, al dan niet als constante. * */ public class DeclarationNode extends HokenNode { /** * Het basisadres van deze declaratie. Als deze declaratienode geldt voor * meerde identifiers, geldt er wellicht een offset. **/ public int address = -1; /** Boolean die aangeeft of dit een constante declaratie is. **/ public boolean isConstant = false; /** Lijst met identifiers<SUF>*/ public List<String> ids = new ArrayList<String>(); public DeclarationNode(Token t) { token = t; } public DeclarationNode(DeclarationNode node) { super(node); } public DeclarationNode(int tokenType) { super(new CommonToken(tokenType, HokenParser.tokenNames[tokenType])); } public Tree dupNode() { return new DeclarationNode(this); } public String toString() { return token.getText() + "<DeclarationNode>"; } /** * Bepaalt op basis van de gegeven <code>IdNode</code> het adres van de * identifier in het geheugen. * * @param id * de identifier * @return het adres van de identifier */ public int getOffsettedAddress(IdNode id) { return this.address + this.ids.indexOf(id.getText()); } }
207756_4
package org.eggiecode.rummikub.models.core; import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedList; public class StoneSet implements Serializable { public static void main(String[] ars) { StoneSet s = new StoneSet(); if (s.isValid()) System.out.println("Is goed"); else System.out.println("Is fout"); } public void add(Stone stone) { set.add(stone); stone.setOnTable(true); stone.setOnPlayerBoard(false); } private LinkedList<Stone> set = new LinkedList(); public Stone[] getStones() { return set.toArray(new Stone[0]); } public boolean isValid() { if(set.size() < 3) return false; if (validateNumberInOrder()){ return true; } if (validateNumbersASC()) { return true; } if (validateNumbersDESC()) { return true; } return false; } private boolean validateNumbersDESC() { boolean isValid = true; boolean joker = false; // Cijfer van laag naar hoog int value = set.get(set.size() - 1).getNumber() -1; // 1 (0) int color = set.get(set.size() - 1).getColor(); for (int i = set.size() - 1; i >= 0; i--) { // 1 2 3 Stone s = set.get(i); if (joker == true && s.getNumber() == -1) { return false; } if (s.getNumber() == -1) joker = true; if (color != s.getColor() && s.getNumber() != -1) return false; if (s.getNumber() - 1 == value|| s.getNumber() != -1) { value = s.getNumber(); } else { return false; } } return true; } private boolean validateNumbersASC() { boolean isValid = true; boolean joker = false; // Cijfer van laag naar hoog int value = set.get(0).getNumber() -1; // 1 (0) int color = set.get(0).getColor(); for (Stone s : set) { // 1 2 3 if (joker == true && s.getNumber() == -1) { return false; } if (s.getNumber() == -1) joker = true; if (color != s.getColor() && s.getNumber() != -1) return false; if (s.getNumber() - 1 == value || s.getNumber() != -1) { value = s.getNumber(); } else { return false; } } return true; } private boolean validateNumberInOrder() { boolean joker = false; int value = set.get(0).getNumber(); ArrayList<Integer> colors = new ArrayList(); // Cijfers het zelfde for (Stone s : set) { if (joker == true && value == -1) { return false; } if (s.getNumber() == -1) joker = true; if (colors.contains(s.getColor()) && s.getNumber()!= -1) { return false; } colors.add(s.getColor()); if (value != s.getNumber() && s.getNumber() != -1) { return false; } } return true; } }
EggieCode/rummikub
src/org/eggiecode/rummikub/models/core/StoneSet.java
991
// Cijfers het zelfde
line_comment
nl
package org.eggiecode.rummikub.models.core; import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedList; public class StoneSet implements Serializable { public static void main(String[] ars) { StoneSet s = new StoneSet(); if (s.isValid()) System.out.println("Is goed"); else System.out.println("Is fout"); } public void add(Stone stone) { set.add(stone); stone.setOnTable(true); stone.setOnPlayerBoard(false); } private LinkedList<Stone> set = new LinkedList(); public Stone[] getStones() { return set.toArray(new Stone[0]); } public boolean isValid() { if(set.size() < 3) return false; if (validateNumberInOrder()){ return true; } if (validateNumbersASC()) { return true; } if (validateNumbersDESC()) { return true; } return false; } private boolean validateNumbersDESC() { boolean isValid = true; boolean joker = false; // Cijfer van laag naar hoog int value = set.get(set.size() - 1).getNumber() -1; // 1 (0) int color = set.get(set.size() - 1).getColor(); for (int i = set.size() - 1; i >= 0; i--) { // 1 2 3 Stone s = set.get(i); if (joker == true && s.getNumber() == -1) { return false; } if (s.getNumber() == -1) joker = true; if (color != s.getColor() && s.getNumber() != -1) return false; if (s.getNumber() - 1 == value|| s.getNumber() != -1) { value = s.getNumber(); } else { return false; } } return true; } private boolean validateNumbersASC() { boolean isValid = true; boolean joker = false; // Cijfer van laag naar hoog int value = set.get(0).getNumber() -1; // 1 (0) int color = set.get(0).getColor(); for (Stone s : set) { // 1 2 3 if (joker == true && s.getNumber() == -1) { return false; } if (s.getNumber() == -1) joker = true; if (color != s.getColor() && s.getNumber() != -1) return false; if (s.getNumber() - 1 == value || s.getNumber() != -1) { value = s.getNumber(); } else { return false; } } return true; } private boolean validateNumberInOrder() { boolean joker = false; int value = set.get(0).getNumber(); ArrayList<Integer> colors = new ArrayList(); // Cijfers het<SUF> for (Stone s : set) { if (joker == true && value == -1) { return false; } if (s.getNumber() == -1) joker = true; if (colors.contains(s.getColor()) && s.getNumber()!= -1) { return false; } colors.add(s.getColor()); if (value != s.getNumber() && s.getNumber() != -1) { return false; } } return true; } }
50470_7
package cn.crap.controller.user; import cn.crap.adapter.ErrorAdapter; import cn.crap.adapter.InterfaceAdapter; import cn.crap.dto.CategoryDto; import cn.crap.dto.DictionaryDto; import cn.crap.dto.InterfacePDFDto; import cn.crap.enu.ArticleType; import cn.crap.enu.MyError; import cn.crap.enu.ProjectType; import cn.crap.framework.JsonResult; import cn.crap.framework.MyException; import cn.crap.framework.base.BaseController; import cn.crap.model.*; import cn.crap.model.Error; import cn.crap.query.ArticleQuery; import cn.crap.query.ErrorQuery; import cn.crap.query.InterfaceQuery; import cn.crap.query.ModuleQuery; import cn.crap.service.ArticleService; import cn.crap.service.ErrorService; import cn.crap.service.InterfaceService; import cn.crap.service.ModuleService; import cn.crap.utils.*; import net.sf.json.JSONArray; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/user/staticize") public class StaticizeController extends BaseController{ @Autowired private ModuleService moduleService; @Autowired private InterfaceService interfaceService; @Autowired private ErrorService errorService; @Autowired private ArticleService articleService; /** * 静态化错误码列表 */ @RequestMapping("/errorList.do") public ModelAndView staticizeError(HttpServletRequest req, @RequestParam String projectId,@RequestParam int currentPage, String needStaticizes, @RequestParam String secretKey) throws MyException { // 验证是否是非法请求 if( !settingCache.get(S_SECRETKEY).getValue().equals(secretKey) ){ throw new MyException(MyError.E000056); } ProjectPO project = projectCache.get(projectId); String path = Tools.getStaticPath(project); if(project.getType() != ProjectType.PUBLIC.getType()){ Tools.deleteFile(path); // 删除旧的静态化文件 throw new MyException(MyError.E000044); } Map<String, Object> returnMap = getProjectModuleInfor(null, project, "-错误码"); ErrorQuery errorQuery = new ErrorQuery().setProjectId(projectId); errorQuery.setCurrentPage(currentPage); Page page = new Page(errorQuery); List<Error> errorModels = errorService.query(errorQuery); page.setAllRow(errorService.count(errorQuery)); returnMap.put("page", page); returnMap.put("errorList", ErrorAdapter.getDto(errorModels)); returnMap.put("activePage","errorList"); returnMap.put("url", "errorList"); returnMap.put("needStaticizes", needStaticizes); return new ModelAndView("WEB-INF/views/staticize/default/errorList.jsp",returnMap); } /** * 静态化接口列表 */ @RequestMapping("/interfaceList.do") public ModelAndView interfaceList(HttpServletRequest req, @RequestParam String moduleId, @RequestParam int currentPage, String needStaticizes, @RequestParam String secretKey) throws MyException { // 验证是否是非法请求 if( !settingCache.get(S_SECRETKEY).getValue().equals(secretKey) ){ throw new MyException(MyError.E000056); } ModulePO module = moduleCache.get(moduleId); ProjectPO project = projectCache.get(module.getProjectId()); String path = Tools.getStaticPath(project); if(project.getType() != ProjectType.PUBLIC.getType()){ Tools.deleteFile(path); // 删除旧的静态化文件 throw new MyException(MyError.E000044); } Map<String, Object> returnMap = getProjectModuleInfor(module, project, "-接口"); Map<String, Object> map = Tools.getMap("moduleId", moduleId); InterfaceQuery interfaceQuery = new InterfaceQuery().setCurrentPage(currentPage).setModuleId(moduleId); Page page = new Page(interfaceQuery); page.setAllRow(interfaceService.count(interfaceQuery)); returnMap.put("page", page); returnMap.put("interfaceList", InterfaceAdapter.getDto(interfaceService.query(interfaceQuery), module, null)); returnMap.put("activePage",moduleId+"_interface"); returnMap.put("url", module.getId() + "-interfaceList"); returnMap.put("needStaticizes", needStaticizes); return new ModelAndView("WEB-INF/views/staticize/default/interfaceList.jsp",returnMap); } /** * 静态化模块文档列表 */ @RequestMapping("/articleList.do") public ModelAndView staticizeModule(HttpServletRequest req, @RequestParam String moduleId,@RequestParam String category,@RequestParam int currentPage, String type, String needStaticizes, @RequestParam String secretKey) throws MyException { // 验证是否是非法请求 if( !settingCache.get(S_SECRETKEY).getValue().equals(secretKey) ){ throw new MyException(MyError.E000056); } ModulePO module = moduleCache.get(moduleId); ProjectPO project = projectCache.get(module.getProjectId()); String path = Tools.getStaticPath(project); if(project.getType() != ProjectType.PUBLIC.getType()){ Tools.deleteFile(path); // 删除旧的静态化文件 throw new MyException(MyError.E000044); } Map<String, Object> returnMap = getProjectModuleInfor(module, project, "-文档"); // 当前类目 if( category.equals(IConst.ALL) ){ category = ""; returnMap.put("md5Category", ""); }else{ returnMap.put("md5Category", MD5.encrytMD5(category, "").substring(0, 10)); } if(MyString.isEmpty(type)){ type = "ARTICLE"; } if(type.equals("ARTICLE")){ // 获取所有类目 // 静态化模块文档 List<String> categorys = moduleService.queryCategoryByModuleId(module.getId()); List<CategoryDto> categoryDtos = new ArrayList<CategoryDto>(); // 文档分类,按类目静态化 for(String c: categorys){ if(MyString.isEmpty(c)){ continue; } CategoryDto categoryDto = new CategoryDto(); categoryDto.setMd5Category(MD5.encrytMD5(c, "").substring(0, 10)); categoryDto.setCategory(c); categoryDtos.add( categoryDto ); } returnMap.put("categoryDtos", categoryDtos); returnMap.put("activePage",module.getId()+"_article"); returnMap.put("url", module.getId() + "-articleList-"+returnMap.get("md5Category")); }else{ returnMap.put("activePage",module.getId()+"_dictionary"); returnMap.put("url", module.getId() + "-dictionary"); } Map<String, Object> map = Tools.getMap("moduleId", moduleId, "type", type, "category", category); ArticleQuery articleQuery = new ArticleQuery().setCurrentPage(currentPage).setModuleId(moduleId).setType(type).setCategory(category); Page page = new Page(articleQuery); page.setAllRow(articleService.count(articleQuery)); List<Article> articleList = articleService.query(articleQuery); returnMap.put("page", page); returnMap.put("articleList", articleList); returnMap.put("needStaticizes", needStaticizes); return new ModelAndView("WEB-INF/views/staticize/default/articleList.jsp",returnMap); } /** * 静态化文档 * @param req * @param articleId * @return * @throws MyException */ @RequestMapping("/articleDetail.do") public ModelAndView staticizeArticle(HttpServletRequest req, @RequestParam String articleId, String needStaticizes, @RequestParam String secretKey) throws MyException { // 验证是否是非法请求 if( !settingCache.get(S_SECRETKEY).getValue().equals(secretKey) ){ throw new MyException(MyError.E000056); } ArticleWithBLOBs article = articleService.getById(articleId); ModulePO module = moduleCache.get(article.getModuleId()); ProjectPO project = projectCache.get(module.getProjectId()); String path = Tools.getStaticPath(project); if(project.getType() != ProjectType.PUBLIC.getType()){ Tools.deleteFile(path); // 删除旧的静态化文件 throw new MyException(MyError.E000044); } if(article.getType().equals(ArticleType.ARTICLE.name())){ Map<String, Object> returnMap = getProjectModuleInfor(module, project, "-文档详情"); returnMap.put("article", article); // 项目备注将静态化成网站的description returnMap.put("description", article.getBrief()); // 模块名称将静态化成网站标题 returnMap.put("title", article.getName()); returnMap.put("activePage",module.getId()+"_article"); returnMap.put("needStaticizes", needStaticizes); return new ModelAndView("WEB-INF/views/staticize/default/articleDetail.jsp",returnMap); }else{ Map<String, Object> returnMap = getProjectModuleInfor(module, project, "-数据库表详情"); returnMap.put("article", article); returnMap.put("activePage",module.getId()+"_dictionary"); returnMap.put("dictionaryFields", JSONArray.toArray(JSONArray.fromObject(article.getContent()), DictionaryDto.class)); returnMap.put("needStaticizes", needStaticizes); return new ModelAndView("WEB-INF/views/staticize/default/dictionaryDetail.jsp",returnMap); } } /** * 静态化接口详情 * @param req * @return * @throws MyException */ @RequestMapping("/interfaceDetail.do") public ModelAndView interfaceDetail(HttpServletRequest req, @RequestParam String interfaceId, String needStaticizes, @RequestParam String secretKey) throws MyException { // 验证是否是非法请求 if( !settingCache.get(S_SECRETKEY).getValue().equals(secretKey) ){ throw new MyException(MyError.E000056); } InterfaceWithBLOBs interFace = interfaceService.getById(interfaceId); ModulePO module = moduleCache.get(interFace.getModuleId()); ProjectPO project = projectCache.get(module.getProjectId()); String path = Tools.getStaticPath(project); if(project.getType() != ProjectType.PUBLIC.getType()){ Tools.deleteFile(path); // 删除旧的静态化文件 throw new MyException(MyError.E000044); } Map<String, Object> returnMap = getProjectModuleInfor(module, project, "-接口详情"); List<InterfacePDFDto> interfaces = new ArrayList<InterfacePDFDto>(); interfaces.add(interfaceService.getInterPDFDto(interFace, module, false, false)); returnMap.put("interfaces", interfaces); returnMap.put("activePage",module.getId()+"_interface"); returnMap.put("needStaticizes", needStaticizes); return new ModelAndView("WEB-INF/views/staticize/default/interfaceDetail.jsp",returnMap); } /** * 删除静态化 * @throws Exception * @throws UnsupportedEncodingException */ @RequestMapping("/delStaticize.do") @ResponseBody public JsonResult delStaticize(HttpServletRequest req, @RequestParam String projectId, String needStaticizes) throws UnsupportedEncodingException, Exception { ProjectPO project = projectCache.get(projectId); checkPermission(project); String path = Tools.getStaticPath(project); Tools.deleteFile(path); return new JsonResult(1, null ); } /** * 下载静态化文件 * @throws Exception * @throws UnsupportedEncodingException */ @RequestMapping("/downloadStaticize.do") @ResponseBody public JsonResult downloadStaticize(HttpServletRequest req, @RequestParam String projectId, String needStaticizes) throws UnsupportedEncodingException, Exception { ProjectPO project = projectCache.get(projectId); checkPermission(project); String path = Tools.getStaticPath(project); File file = new File(path); if( !file.exists()){ throw new MyException(MyError.E000057); } String webBasePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort() + req.getContextPath() +"/"; Tools.createFile(path + "/downLoad/"); //获取html,提取url,替换线上文件路径,准本下载文件夹 String[] childFilePaths = file.list(); List<String> filePaths = new ArrayList<>(); for(String childFilePath : childFilePaths){ if( !childFilePath.endsWith(".html") ){ continue; } String html = Tools.readFile(file.getAbsolutePath() +"/"+ childFilePath); Tools.getHrefFromText(html, filePaths); html = html.replaceAll(webBasePath, ""); Tools.staticize(html, path + "/downLoad/" + new File(childFilePath).getName()); } // 拷贝文件文件 for(String sourcePath:filePaths){ if(sourcePath.startsWith(webBasePath) && !sourcePath.endsWith(".do")){ sourcePath = sourcePath.replace(webBasePath, "").split("\"")[0].split("\\?")[0].trim(); if(sourcePath.endsWith(".do")){ continue; } // 创建文件目录 String sourcePathFile = sourcePath.substring(0, sourcePath.lastIndexOf("/")); Tools.createFile(path + "/downLoad/"+ sourcePathFile.replace(Tools.getServicePath(), "")); Tools.copyFile(Tools.getServicePath() + sourcePath , path + "/downLoad/"+ sourcePath ); } } //压缩 Tools.createZip(path + "/downLoad/", path + "/" + projectId + ".zip"); // 返回下载页面 return new JsonResult(1, webBasePath + "static/"+project.getId() + "/" + projectId + ".zip" ); } /** * 静态化 * @throws Exception * @throws UnsupportedEncodingException */ @RequestMapping("/staticize.do") @ResponseBody public JsonResult staticize(HttpServletRequest req, @RequestParam String projectId, String needStaticizes) throws UnsupportedEncodingException, Exception { if(MyString.isEmpty(needStaticizes)){ needStaticizes = ",article,"; }else{ needStaticizes = ",article," + needStaticizes + ","; } String secretKey = settingCache.get(S_SECRETKEY).getValue(); ProjectPO project = projectCache.get(projectId); checkPermission(project); String path = Tools.getStaticPath(project); Tools.createFile(path); if(project.getType() != ProjectType.PUBLIC.getType()){ Tools.deleteFile(path); // 删除旧的静态化文件 throw new MyException(MyError.E000044); } // 静态化错误码// 查询页码 int pageSize = 15; int totalPage = 0; if(needStaticizes.indexOf(",error,") >= 0){ int errorSize = errorService.count(new ErrorQuery().setProjectId(projectId).setPageSize(IConst.ALL_PAGE_SIZE)); // 计算总页数 totalPage = (errorSize+pageSize-1)/pageSize; if(totalPage == 0){ totalPage = 1; } for(int i=1 ; i<= totalPage; i++){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/errorList.do?projectId="+projectId +"&currentPage="+i + "&needStaticizes=" + needStaticizes + "&secretKey=" + secretKey, null, null, 10 * 1000); // list-类目摘要-页码 Tools.staticize(html, path + "/errorList-" + i + ".html"); } } Map<String, Object> map = new HashMap<>(); for(ModulePO module : moduleService.select(new ModuleQuery().setProjectId(projectId).setPageSize(IConst.ALL_PAGE_SIZE))){ if(needStaticizes.indexOf(",article,") >= 0){ // 静态化模块文档,分类 List<String> categorys = moduleService.queryCategoryByModuleId(module.getId()); // 文档分类,按类目静态化 for(String category: categorys){ if( MyString.isEmpty( category )){ continue; // 空类目不静态化 } // 查询页码 ArticleQuery articleQuery = new ArticleQuery(); articleQuery.setModuleId(module.getId()).setType(ArticleType.ARTICLE.name()).setCategory(category); int articleSize = articleService.count(articleQuery); // 计算总页数 totalPage = (articleSize+pageSize-1)/pageSize; if(totalPage == 0){ totalPage = 1; } for(int i=1 ; i<= totalPage; i++){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/articleList.do?moduleId="+ module.getId()+"&category="+ category+"&currentPage="+i + "&needStaticizes="+needStaticizes + "&secretKey=" + secretKey, null, null, 10 * 1000); // list-类目摘要-页码 Tools.staticize(html, path + "/" + module.getId() +"-articleList-"+ MD5.encrytMD5(category, "").substring(0, 10) + "-" + i + ".html"); } } // 文档分类,不分类 ArticleQuery articleQuery = new ArticleQuery(); articleQuery.setModuleId(module.getId()).setType(ArticleType.ARTICLE.name()); int articleSize = articleService.count(articleQuery); // 计算总页数 totalPage = (articleSize+pageSize-1)/pageSize; if(totalPage == 0){ totalPage = 1; } for(int i=1 ; i<= totalPage; i++){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/articleList.do?moduleId="+ module.getId()+ "&category="+ IConst.ALL+"&currentPage="+i + "&needStaticizes="+needStaticizes+ "&secretKey=" + secretKey, null, null, 10 * 1000); // list-类目摘要-页码 Tools.staticize(html, path + "/" + module.getId() +"-articleList--" + i + ".html"); } // 静态化文档 articleQuery.setPageSize(ALL_PAGE_SIZE); for(Article article: articleService.query(articleQuery)){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/articleDetail.do?articleId="+ article.getId() + "&needStaticizes="+needStaticizes+ "&secretKey=" + secretKey, null, null, 10 * 1000); Tools.staticize(html, path + "/" + article.getId()+".html"); } } if(needStaticizes.indexOf(",dictionary,") >= 0){ // 数据库表列表 ArticleQuery articleQuery = new ArticleQuery().setModuleId(module.getId()).setType(ArticleType.DICTIONARY.name()).setPageSize(IConst.ALL_PAGE_SIZE); int articleSize = articleService.count(articleQuery); // 计算总页数 totalPage = (articleSize+pageSize-1)/pageSize; if(totalPage == 0){ totalPage = 1; } for(int i=1 ; i<= totalPage; i++){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/articleList.do?moduleId="+ module.getId()+ "&category="+ IConst.ALL+"&currentPage="+i+"&type=DICTIONARY" + "&needStaticizes="+needStaticizes+ "&secretKey=" + secretKey, null, null, 10 * 1000); // list-类目摘要-页码 Tools.staticize(html, path + "/" + module.getId() +"-dictionaryList-" + i + ".html"); } // 静态化数据库表详情 articleQuery.setPageSize(ALL_PAGE_SIZE); for(Article article: articleService.query(articleQuery)){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/articleDetail.do?articleId="+ article.getId() + "&needStaticizes="+needStaticizes+ "&secretKey=" + secretKey, null, null, 10 * 1000); Tools.staticize(html, path + "/" + article.getId()+".html"); } } if(needStaticizes.indexOf("interface") >= 0){ // 接口列表 // 计算总页数 InterfaceQuery interfaceQuery = new InterfaceQuery().setModuleId(module.getId()).setPageSize(IConst.ALL_PAGE_SIZE); totalPage = (interfaceService.count(interfaceQuery)+pageSize-1)/pageSize; if(totalPage == 0){ totalPage = 1; } for(int i=1 ; i<= totalPage; i++){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/interfaceList.do?moduleId="+ module.getId()+"&currentPage="+i + "&needStaticizes="+needStaticizes+ "&secretKey=" + secretKey, null, null, 10 * 1000); // list-类目摘要-页码 Tools.staticize(html, path + "/" + module.getId() +"-interfaceList-" + i + ".html"); } // 静态化接口详情 interfaceQuery.setPageSize(ALL_PAGE_SIZE); for(Interface inter: interfaceService.query(interfaceQuery)){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/interfaceDetail.do?interfaceId="+ inter.getId() + "&needStaticizes="+needStaticizes+ "&secretKey=" + secretKey, null, null, 10 * 1000); Tools.staticize(html, path + "/" + inter.getId()+".html"); } } // 推送给百度 // try{ // if( !config.getBaidu().equals("") ) // HttpPostGet.postBody(config.getBaidu(), Tools.getUrlPath() +"/resources/html/staticize/"+project.getId()+"/"+module.getId()+"/list.html", null); // }catch(Exception e){ // e.printStackTrace(); // } } return new JsonResult(1, null ); } private Map<String, Object> getProjectModuleInfor(ModulePO module, ProjectPO project, String typeName) throws MyException{ if(!MyString.isEmpty(project.getCover())){ if(!project.getCover().startsWith("http:") && !project.getCover().startsWith("https:") ){ project.setCover(Tools.getUrlPath() +"/"+ project.getCover()); } } Map<String,Object> returnMap = new HashMap<>(); returnMap.put("settings", settingCache.getCommonMap()); returnMap.put("project", project); returnMap.put("module", module); // 将选中的模块放到第一位 List<ModulePO> moduleList = moduleService.select(new ModuleQuery().setProjectId(project.getId()).setPageSize(ALL_PAGE_SIZE)); if(module != null){ for(ModulePO m:moduleList){ if(m.getId().equals(module.getId())){ moduleList.remove(m); break; } } moduleList.add(0, module); } returnMap.put("moduleList", moduleList); //returnMap.put("menuList", menuService.getLeftMenu(null)); // 模块将静态化成网站的keywords returnMap.put("keywords", module!=null ? module.getRemark():project.getRemark()); // 项目备注将静态化成网站的description returnMap.put("description", project.getRemark()); // 模块名称将静态化成网站标题 returnMap.put("title", module!=null ? module.getName() + typeName: project.getName() + typeName); return returnMap; } }
EhsanTang/ApiManager
api/src/main/java/cn/crap/controller/user/StaticizeController.java
7,255
//"+req.getServerName()+":"+req.getServerPort() + req.getContextPath() +"/";
line_comment
nl
package cn.crap.controller.user; import cn.crap.adapter.ErrorAdapter; import cn.crap.adapter.InterfaceAdapter; import cn.crap.dto.CategoryDto; import cn.crap.dto.DictionaryDto; import cn.crap.dto.InterfacePDFDto; import cn.crap.enu.ArticleType; import cn.crap.enu.MyError; import cn.crap.enu.ProjectType; import cn.crap.framework.JsonResult; import cn.crap.framework.MyException; import cn.crap.framework.base.BaseController; import cn.crap.model.*; import cn.crap.model.Error; import cn.crap.query.ArticleQuery; import cn.crap.query.ErrorQuery; import cn.crap.query.InterfaceQuery; import cn.crap.query.ModuleQuery; import cn.crap.service.ArticleService; import cn.crap.service.ErrorService; import cn.crap.service.InterfaceService; import cn.crap.service.ModuleService; import cn.crap.utils.*; import net.sf.json.JSONArray; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/user/staticize") public class StaticizeController extends BaseController{ @Autowired private ModuleService moduleService; @Autowired private InterfaceService interfaceService; @Autowired private ErrorService errorService; @Autowired private ArticleService articleService; /** * 静态化错误码列表 */ @RequestMapping("/errorList.do") public ModelAndView staticizeError(HttpServletRequest req, @RequestParam String projectId,@RequestParam int currentPage, String needStaticizes, @RequestParam String secretKey) throws MyException { // 验证是否是非法请求 if( !settingCache.get(S_SECRETKEY).getValue().equals(secretKey) ){ throw new MyException(MyError.E000056); } ProjectPO project = projectCache.get(projectId); String path = Tools.getStaticPath(project); if(project.getType() != ProjectType.PUBLIC.getType()){ Tools.deleteFile(path); // 删除旧的静态化文件 throw new MyException(MyError.E000044); } Map<String, Object> returnMap = getProjectModuleInfor(null, project, "-错误码"); ErrorQuery errorQuery = new ErrorQuery().setProjectId(projectId); errorQuery.setCurrentPage(currentPage); Page page = new Page(errorQuery); List<Error> errorModels = errorService.query(errorQuery); page.setAllRow(errorService.count(errorQuery)); returnMap.put("page", page); returnMap.put("errorList", ErrorAdapter.getDto(errorModels)); returnMap.put("activePage","errorList"); returnMap.put("url", "errorList"); returnMap.put("needStaticizes", needStaticizes); return new ModelAndView("WEB-INF/views/staticize/default/errorList.jsp",returnMap); } /** * 静态化接口列表 */ @RequestMapping("/interfaceList.do") public ModelAndView interfaceList(HttpServletRequest req, @RequestParam String moduleId, @RequestParam int currentPage, String needStaticizes, @RequestParam String secretKey) throws MyException { // 验证是否是非法请求 if( !settingCache.get(S_SECRETKEY).getValue().equals(secretKey) ){ throw new MyException(MyError.E000056); } ModulePO module = moduleCache.get(moduleId); ProjectPO project = projectCache.get(module.getProjectId()); String path = Tools.getStaticPath(project); if(project.getType() != ProjectType.PUBLIC.getType()){ Tools.deleteFile(path); // 删除旧的静态化文件 throw new MyException(MyError.E000044); } Map<String, Object> returnMap = getProjectModuleInfor(module, project, "-接口"); Map<String, Object> map = Tools.getMap("moduleId", moduleId); InterfaceQuery interfaceQuery = new InterfaceQuery().setCurrentPage(currentPage).setModuleId(moduleId); Page page = new Page(interfaceQuery); page.setAllRow(interfaceService.count(interfaceQuery)); returnMap.put("page", page); returnMap.put("interfaceList", InterfaceAdapter.getDto(interfaceService.query(interfaceQuery), module, null)); returnMap.put("activePage",moduleId+"_interface"); returnMap.put("url", module.getId() + "-interfaceList"); returnMap.put("needStaticizes", needStaticizes); return new ModelAndView("WEB-INF/views/staticize/default/interfaceList.jsp",returnMap); } /** * 静态化模块文档列表 */ @RequestMapping("/articleList.do") public ModelAndView staticizeModule(HttpServletRequest req, @RequestParam String moduleId,@RequestParam String category,@RequestParam int currentPage, String type, String needStaticizes, @RequestParam String secretKey) throws MyException { // 验证是否是非法请求 if( !settingCache.get(S_SECRETKEY).getValue().equals(secretKey) ){ throw new MyException(MyError.E000056); } ModulePO module = moduleCache.get(moduleId); ProjectPO project = projectCache.get(module.getProjectId()); String path = Tools.getStaticPath(project); if(project.getType() != ProjectType.PUBLIC.getType()){ Tools.deleteFile(path); // 删除旧的静态化文件 throw new MyException(MyError.E000044); } Map<String, Object> returnMap = getProjectModuleInfor(module, project, "-文档"); // 当前类目 if( category.equals(IConst.ALL) ){ category = ""; returnMap.put("md5Category", ""); }else{ returnMap.put("md5Category", MD5.encrytMD5(category, "").substring(0, 10)); } if(MyString.isEmpty(type)){ type = "ARTICLE"; } if(type.equals("ARTICLE")){ // 获取所有类目 // 静态化模块文档 List<String> categorys = moduleService.queryCategoryByModuleId(module.getId()); List<CategoryDto> categoryDtos = new ArrayList<CategoryDto>(); // 文档分类,按类目静态化 for(String c: categorys){ if(MyString.isEmpty(c)){ continue; } CategoryDto categoryDto = new CategoryDto(); categoryDto.setMd5Category(MD5.encrytMD5(c, "").substring(0, 10)); categoryDto.setCategory(c); categoryDtos.add( categoryDto ); } returnMap.put("categoryDtos", categoryDtos); returnMap.put("activePage",module.getId()+"_article"); returnMap.put("url", module.getId() + "-articleList-"+returnMap.get("md5Category")); }else{ returnMap.put("activePage",module.getId()+"_dictionary"); returnMap.put("url", module.getId() + "-dictionary"); } Map<String, Object> map = Tools.getMap("moduleId", moduleId, "type", type, "category", category); ArticleQuery articleQuery = new ArticleQuery().setCurrentPage(currentPage).setModuleId(moduleId).setType(type).setCategory(category); Page page = new Page(articleQuery); page.setAllRow(articleService.count(articleQuery)); List<Article> articleList = articleService.query(articleQuery); returnMap.put("page", page); returnMap.put("articleList", articleList); returnMap.put("needStaticizes", needStaticizes); return new ModelAndView("WEB-INF/views/staticize/default/articleList.jsp",returnMap); } /** * 静态化文档 * @param req * @param articleId * @return * @throws MyException */ @RequestMapping("/articleDetail.do") public ModelAndView staticizeArticle(HttpServletRequest req, @RequestParam String articleId, String needStaticizes, @RequestParam String secretKey) throws MyException { // 验证是否是非法请求 if( !settingCache.get(S_SECRETKEY).getValue().equals(secretKey) ){ throw new MyException(MyError.E000056); } ArticleWithBLOBs article = articleService.getById(articleId); ModulePO module = moduleCache.get(article.getModuleId()); ProjectPO project = projectCache.get(module.getProjectId()); String path = Tools.getStaticPath(project); if(project.getType() != ProjectType.PUBLIC.getType()){ Tools.deleteFile(path); // 删除旧的静态化文件 throw new MyException(MyError.E000044); } if(article.getType().equals(ArticleType.ARTICLE.name())){ Map<String, Object> returnMap = getProjectModuleInfor(module, project, "-文档详情"); returnMap.put("article", article); // 项目备注将静态化成网站的description returnMap.put("description", article.getBrief()); // 模块名称将静态化成网站标题 returnMap.put("title", article.getName()); returnMap.put("activePage",module.getId()+"_article"); returnMap.put("needStaticizes", needStaticizes); return new ModelAndView("WEB-INF/views/staticize/default/articleDetail.jsp",returnMap); }else{ Map<String, Object> returnMap = getProjectModuleInfor(module, project, "-数据库表详情"); returnMap.put("article", article); returnMap.put("activePage",module.getId()+"_dictionary"); returnMap.put("dictionaryFields", JSONArray.toArray(JSONArray.fromObject(article.getContent()), DictionaryDto.class)); returnMap.put("needStaticizes", needStaticizes); return new ModelAndView("WEB-INF/views/staticize/default/dictionaryDetail.jsp",returnMap); } } /** * 静态化接口详情 * @param req * @return * @throws MyException */ @RequestMapping("/interfaceDetail.do") public ModelAndView interfaceDetail(HttpServletRequest req, @RequestParam String interfaceId, String needStaticizes, @RequestParam String secretKey) throws MyException { // 验证是否是非法请求 if( !settingCache.get(S_SECRETKEY).getValue().equals(secretKey) ){ throw new MyException(MyError.E000056); } InterfaceWithBLOBs interFace = interfaceService.getById(interfaceId); ModulePO module = moduleCache.get(interFace.getModuleId()); ProjectPO project = projectCache.get(module.getProjectId()); String path = Tools.getStaticPath(project); if(project.getType() != ProjectType.PUBLIC.getType()){ Tools.deleteFile(path); // 删除旧的静态化文件 throw new MyException(MyError.E000044); } Map<String, Object> returnMap = getProjectModuleInfor(module, project, "-接口详情"); List<InterfacePDFDto> interfaces = new ArrayList<InterfacePDFDto>(); interfaces.add(interfaceService.getInterPDFDto(interFace, module, false, false)); returnMap.put("interfaces", interfaces); returnMap.put("activePage",module.getId()+"_interface"); returnMap.put("needStaticizes", needStaticizes); return new ModelAndView("WEB-INF/views/staticize/default/interfaceDetail.jsp",returnMap); } /** * 删除静态化 * @throws Exception * @throws UnsupportedEncodingException */ @RequestMapping("/delStaticize.do") @ResponseBody public JsonResult delStaticize(HttpServletRequest req, @RequestParam String projectId, String needStaticizes) throws UnsupportedEncodingException, Exception { ProjectPO project = projectCache.get(projectId); checkPermission(project); String path = Tools.getStaticPath(project); Tools.deleteFile(path); return new JsonResult(1, null ); } /** * 下载静态化文件 * @throws Exception * @throws UnsupportedEncodingException */ @RequestMapping("/downloadStaticize.do") @ResponseBody public JsonResult downloadStaticize(HttpServletRequest req, @RequestParam String projectId, String needStaticizes) throws UnsupportedEncodingException, Exception { ProjectPO project = projectCache.get(projectId); checkPermission(project); String path = Tools.getStaticPath(project); File file = new File(path); if( !file.exists()){ throw new MyException(MyError.E000057); } String webBasePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort() +<SUF> Tools.createFile(path + "/downLoad/"); //获取html,提取url,替换线上文件路径,准本下载文件夹 String[] childFilePaths = file.list(); List<String> filePaths = new ArrayList<>(); for(String childFilePath : childFilePaths){ if( !childFilePath.endsWith(".html") ){ continue; } String html = Tools.readFile(file.getAbsolutePath() +"/"+ childFilePath); Tools.getHrefFromText(html, filePaths); html = html.replaceAll(webBasePath, ""); Tools.staticize(html, path + "/downLoad/" + new File(childFilePath).getName()); } // 拷贝文件文件 for(String sourcePath:filePaths){ if(sourcePath.startsWith(webBasePath) && !sourcePath.endsWith(".do")){ sourcePath = sourcePath.replace(webBasePath, "").split("\"")[0].split("\\?")[0].trim(); if(sourcePath.endsWith(".do")){ continue; } // 创建文件目录 String sourcePathFile = sourcePath.substring(0, sourcePath.lastIndexOf("/")); Tools.createFile(path + "/downLoad/"+ sourcePathFile.replace(Tools.getServicePath(), "")); Tools.copyFile(Tools.getServicePath() + sourcePath , path + "/downLoad/"+ sourcePath ); } } //压缩 Tools.createZip(path + "/downLoad/", path + "/" + projectId + ".zip"); // 返回下载页面 return new JsonResult(1, webBasePath + "static/"+project.getId() + "/" + projectId + ".zip" ); } /** * 静态化 * @throws Exception * @throws UnsupportedEncodingException */ @RequestMapping("/staticize.do") @ResponseBody public JsonResult staticize(HttpServletRequest req, @RequestParam String projectId, String needStaticizes) throws UnsupportedEncodingException, Exception { if(MyString.isEmpty(needStaticizes)){ needStaticizes = ",article,"; }else{ needStaticizes = ",article," + needStaticizes + ","; } String secretKey = settingCache.get(S_SECRETKEY).getValue(); ProjectPO project = projectCache.get(projectId); checkPermission(project); String path = Tools.getStaticPath(project); Tools.createFile(path); if(project.getType() != ProjectType.PUBLIC.getType()){ Tools.deleteFile(path); // 删除旧的静态化文件 throw new MyException(MyError.E000044); } // 静态化错误码// 查询页码 int pageSize = 15; int totalPage = 0; if(needStaticizes.indexOf(",error,") >= 0){ int errorSize = errorService.count(new ErrorQuery().setProjectId(projectId).setPageSize(IConst.ALL_PAGE_SIZE)); // 计算总页数 totalPage = (errorSize+pageSize-1)/pageSize; if(totalPage == 0){ totalPage = 1; } for(int i=1 ; i<= totalPage; i++){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/errorList.do?projectId="+projectId +"&currentPage="+i + "&needStaticizes=" + needStaticizes + "&secretKey=" + secretKey, null, null, 10 * 1000); // list-类目摘要-页码 Tools.staticize(html, path + "/errorList-" + i + ".html"); } } Map<String, Object> map = new HashMap<>(); for(ModulePO module : moduleService.select(new ModuleQuery().setProjectId(projectId).setPageSize(IConst.ALL_PAGE_SIZE))){ if(needStaticizes.indexOf(",article,") >= 0){ // 静态化模块文档,分类 List<String> categorys = moduleService.queryCategoryByModuleId(module.getId()); // 文档分类,按类目静态化 for(String category: categorys){ if( MyString.isEmpty( category )){ continue; // 空类目不静态化 } // 查询页码 ArticleQuery articleQuery = new ArticleQuery(); articleQuery.setModuleId(module.getId()).setType(ArticleType.ARTICLE.name()).setCategory(category); int articleSize = articleService.count(articleQuery); // 计算总页数 totalPage = (articleSize+pageSize-1)/pageSize; if(totalPage == 0){ totalPage = 1; } for(int i=1 ; i<= totalPage; i++){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/articleList.do?moduleId="+ module.getId()+"&category="+ category+"&currentPage="+i + "&needStaticizes="+needStaticizes + "&secretKey=" + secretKey, null, null, 10 * 1000); // list-类目摘要-页码 Tools.staticize(html, path + "/" + module.getId() +"-articleList-"+ MD5.encrytMD5(category, "").substring(0, 10) + "-" + i + ".html"); } } // 文档分类,不分类 ArticleQuery articleQuery = new ArticleQuery(); articleQuery.setModuleId(module.getId()).setType(ArticleType.ARTICLE.name()); int articleSize = articleService.count(articleQuery); // 计算总页数 totalPage = (articleSize+pageSize-1)/pageSize; if(totalPage == 0){ totalPage = 1; } for(int i=1 ; i<= totalPage; i++){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/articleList.do?moduleId="+ module.getId()+ "&category="+ IConst.ALL+"&currentPage="+i + "&needStaticizes="+needStaticizes+ "&secretKey=" + secretKey, null, null, 10 * 1000); // list-类目摘要-页码 Tools.staticize(html, path + "/" + module.getId() +"-articleList--" + i + ".html"); } // 静态化文档 articleQuery.setPageSize(ALL_PAGE_SIZE); for(Article article: articleService.query(articleQuery)){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/articleDetail.do?articleId="+ article.getId() + "&needStaticizes="+needStaticizes+ "&secretKey=" + secretKey, null, null, 10 * 1000); Tools.staticize(html, path + "/" + article.getId()+".html"); } } if(needStaticizes.indexOf(",dictionary,") >= 0){ // 数据库表列表 ArticleQuery articleQuery = new ArticleQuery().setModuleId(module.getId()).setType(ArticleType.DICTIONARY.name()).setPageSize(IConst.ALL_PAGE_SIZE); int articleSize = articleService.count(articleQuery); // 计算总页数 totalPage = (articleSize+pageSize-1)/pageSize; if(totalPage == 0){ totalPage = 1; } for(int i=1 ; i<= totalPage; i++){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/articleList.do?moduleId="+ module.getId()+ "&category="+ IConst.ALL+"&currentPage="+i+"&type=DICTIONARY" + "&needStaticizes="+needStaticizes+ "&secretKey=" + secretKey, null, null, 10 * 1000); // list-类目摘要-页码 Tools.staticize(html, path + "/" + module.getId() +"-dictionaryList-" + i + ".html"); } // 静态化数据库表详情 articleQuery.setPageSize(ALL_PAGE_SIZE); for(Article article: articleService.query(articleQuery)){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/articleDetail.do?articleId="+ article.getId() + "&needStaticizes="+needStaticizes+ "&secretKey=" + secretKey, null, null, 10 * 1000); Tools.staticize(html, path + "/" + article.getId()+".html"); } } if(needStaticizes.indexOf("interface") >= 0){ // 接口列表 // 计算总页数 InterfaceQuery interfaceQuery = new InterfaceQuery().setModuleId(module.getId()).setPageSize(IConst.ALL_PAGE_SIZE); totalPage = (interfaceService.count(interfaceQuery)+pageSize-1)/pageSize; if(totalPage == 0){ totalPage = 1; } for(int i=1 ; i<= totalPage; i++){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/interfaceList.do?moduleId="+ module.getId()+"&currentPage="+i + "&needStaticizes="+needStaticizes+ "&secretKey=" + secretKey, null, null, 10 * 1000); // list-类目摘要-页码 Tools.staticize(html, path + "/" + module.getId() +"-interfaceList-" + i + ".html"); } // 静态化接口详情 interfaceQuery.setPageSize(ALL_PAGE_SIZE); for(Interface inter: interfaceService.query(interfaceQuery)){ String html = HttpPostGet.get(Tools.getUrlPath() + "/user/staticize/interfaceDetail.do?interfaceId="+ inter.getId() + "&needStaticizes="+needStaticizes+ "&secretKey=" + secretKey, null, null, 10 * 1000); Tools.staticize(html, path + "/" + inter.getId()+".html"); } } // 推送给百度 // try{ // if( !config.getBaidu().equals("") ) // HttpPostGet.postBody(config.getBaidu(), Tools.getUrlPath() +"/resources/html/staticize/"+project.getId()+"/"+module.getId()+"/list.html", null); // }catch(Exception e){ // e.printStackTrace(); // } } return new JsonResult(1, null ); } private Map<String, Object> getProjectModuleInfor(ModulePO module, ProjectPO project, String typeName) throws MyException{ if(!MyString.isEmpty(project.getCover())){ if(!project.getCover().startsWith("http:") && !project.getCover().startsWith("https:") ){ project.setCover(Tools.getUrlPath() +"/"+ project.getCover()); } } Map<String,Object> returnMap = new HashMap<>(); returnMap.put("settings", settingCache.getCommonMap()); returnMap.put("project", project); returnMap.put("module", module); // 将选中的模块放到第一位 List<ModulePO> moduleList = moduleService.select(new ModuleQuery().setProjectId(project.getId()).setPageSize(ALL_PAGE_SIZE)); if(module != null){ for(ModulePO m:moduleList){ if(m.getId().equals(module.getId())){ moduleList.remove(m); break; } } moduleList.add(0, module); } returnMap.put("moduleList", moduleList); //returnMap.put("menuList", menuService.getLeftMenu(null)); // 模块将静态化成网站的keywords returnMap.put("keywords", module!=null ? module.getRemark():project.getRemark()); // 项目备注将静态化成网站的description returnMap.put("description", project.getRemark()); // 模块名称将静态化成网站标题 returnMap.put("title", module!=null ? module.getName() + typeName: project.getName() + typeName); return returnMap; } }
35222_4
/* LanguageTool, a natural language style checker * Copyright (C) 2006 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.tokenizers.nl; import junit.framework.TestCase; import org.languagetool.TestTools; import org.languagetool.language.Dutch; import org.languagetool.tokenizers.SRXSentenceTokenizer; /** * @author Daniel Naber * @author Adapted by R. Baars for Dutch * @author Pander OpenTaal added examples from Wikipedia and Taaladvies */ public class DutchSRXSentenceTokenizerTest extends TestCase { private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Dutch()); public void testTokenize() { // NOTE: sentences here need to end with a space character so they // have correct whitespace when appended: testSplit("Dit is een zin."); testSplit("Dit is een zin. ", "Nog een."); testSplit("Een zin! ", "Nog een."); testSplit("Een zin... ", "Nog een."); testSplit("Op http://www.test.de vind je een website."); testSplit("De brief is op 3-10 gedateerd."); testSplit("De brief is op 31-1 gedateerd."); testSplit("De breif is op 3-10-2000 gedateerd."); testSplit("Vandaag is het 13-12-2004."); testSplit("Op 24.09 begint het."); testSplit("Om 17:00 begint het."); testSplit("In paragraaf 3.9.1 is dat beschreven."); testSplit("Januari jl. is dat vastgelegd."); testSplit("Appel en pruimen enz. werden gekocht."); testSplit("De afkorting n.v.t. betekent niet van toepassing."); testSplit("Bla et al. blah blah."); testSplit("Dat is,, of het is bla."); testSplit("Dat is het.. ", "Zo gaat het verder."); testSplit("Dit hier is een(!) zin."); testSplit("Dit hier is een(!!) zin."); testSplit("Dit hier is een(?) zin."); testSplit("Dit hier is een(???) zin."); testSplit("Dit hier is een(???) zin."); testSplit("Als voetballer wordt hij nooit een prof. ", "Maar prof. N.A.W. Th.Ch. Janssen wordt dat wel."); // TODO, zin na dubbele punt testSplit("Dat was het: helemaal niets."); testSplit("Dat was het: het is een nieuwe zin."); // https://nl.wikipedia.org/wiki/Aanhalingsteken testSplit("Jan zei: \"Hallo.\""); testSplit("Jan zei: “Hallo.”"); testSplit("„Hallo,” zei Jan, „waar ga je naartoe?”"); testSplit("„Gisteren”, zei Jan, „was het veel beter weer.”"); testSplit("Jan zei: „Annette zei ‚Hallo’.”"); testSplit("Jan zei: “Annette zei ‘Hallo’.”"); testSplit("Jan zei: «Annette zei ‹Hallo›.»"); testSplit("Wegens zijn „ziekte” hoefde hij niet te werken."); testSplit("de letter „a”"); testSplit("het woord „beta” is afkomstig van ..."); // http://taaladvies.net/taal/advies/vraag/11 testSplit("De voorzitter zei: 'Ik zie hier geen been in.'"); testSplit("De voorzitter zei: \"Ik zie hier geen been in.\""); testSplit("De koning zei: \"Ik herinner me nog dat iemand 'Vive la république' riep tijdens mijn eedaflegging.\""); testSplit("De koning zei: 'Ik herinner me nog dat iemand \"Vive la république\" riep tijdens mijn eedaflegging.'"); testSplit("De koning zei: 'Ik herinner me nog dat iemand 'Vive la république' riep tijdens mijn eedaflegging.'"); testSplit("Otto dacht: wat een nare verhalen hoor je toch tegenwoordig."); // http://taaladvies.net/taal/advies/vraag/871 testSplit("'Ik vrees', zei Rob, 'dat de brug zal instorten.'"); testSplit("'Ieder land', aldus minister Powell, 'moet rekenschap afleggen over de wijze waarop het zijn burgers behandelt.'"); testSplit("'Zeg Rob,' vroeg Jolanda, 'denk jij dat de brug zal instorten?'"); testSplit("'Deze man heeft er niets mee te maken,' aldus korpschef Jan de Vries, 'maar hij heeft momenteel geen leven.'"); testSplit("'Ik vrees,' zei Rob, 'dat de brug zal instorten.'"); testSplit("'Ieder land,' aldus minister Powell, 'moet rekenschap afleggen over de wijze waarop het zijn burgers behandelt.'"); testSplit("'Zeg Rob,' vroeg Jolanda, 'denk jij dat de brug zal instorten?'"); testSplit("'Deze man heeft er niets mee te maken,' aldus korpschef Jan de Vries, 'maar hij heeft momenteel geen leven.'"); // http://taaladvies.net/taal/advies/vraag/872 testSplit("Zij antwoordde: 'Ik denk niet dat ik nog langer met je om wil gaan.'"); testSplit("Zij fluisterde iets van 'eeuwig trouw' en 'altijd blijven houden van'."); testSplit("'Heb je dat boek al gelezen?', vroeg hij."); testSplit("De auteur vermeldt: 'Deze opvatting van het vorstendom heeft lang doorgewerkt.'"); // http://taaladvies.net/taal/advies/vraag/1557 testSplit("'Gaat u zitten', zei zij. ", "'De dokter komt zo.'"); testSplit("'Mijn broer woont ook in Den Haag', vertelde ze. ", "'Hij woont al een paar jaar samen.'"); testSplit("'Je bent grappig', zei ze. ", "'Echt, ik vind je grappig.'"); testSplit("'Is Jan thuis?', vroeg Piet. ", "'Ik wil hem wat vragen.'"); testSplit("'Ik denk er niet over!', riep ze. ", "'Dat gaat echt te ver, hoor!'"); testSplit("'Ik vermoed', zei Piet, 'dat Jan al wel thuis is.'"); } private void testSplit(String... sentences) { TestTools.testSplit(sentences, stokenizer); } }
EirikBirkeland/languagetool
languagetool-language-modules/nl/src/test/java/org/languagetool/tokenizers/nl/DutchSRXSentenceTokenizerTest.java
1,918
//www.test.de vind je een website.");
line_comment
nl
/* LanguageTool, a natural language style checker * Copyright (C) 2006 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.tokenizers.nl; import junit.framework.TestCase; import org.languagetool.TestTools; import org.languagetool.language.Dutch; import org.languagetool.tokenizers.SRXSentenceTokenizer; /** * @author Daniel Naber * @author Adapted by R. Baars for Dutch * @author Pander OpenTaal added examples from Wikipedia and Taaladvies */ public class DutchSRXSentenceTokenizerTest extends TestCase { private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Dutch()); public void testTokenize() { // NOTE: sentences here need to end with a space character so they // have correct whitespace when appended: testSplit("Dit is een zin."); testSplit("Dit is een zin. ", "Nog een."); testSplit("Een zin! ", "Nog een."); testSplit("Een zin... ", "Nog een."); testSplit("Op http://www.test.de vind<SUF> testSplit("De brief is op 3-10 gedateerd."); testSplit("De brief is op 31-1 gedateerd."); testSplit("De breif is op 3-10-2000 gedateerd."); testSplit("Vandaag is het 13-12-2004."); testSplit("Op 24.09 begint het."); testSplit("Om 17:00 begint het."); testSplit("In paragraaf 3.9.1 is dat beschreven."); testSplit("Januari jl. is dat vastgelegd."); testSplit("Appel en pruimen enz. werden gekocht."); testSplit("De afkorting n.v.t. betekent niet van toepassing."); testSplit("Bla et al. blah blah."); testSplit("Dat is,, of het is bla."); testSplit("Dat is het.. ", "Zo gaat het verder."); testSplit("Dit hier is een(!) zin."); testSplit("Dit hier is een(!!) zin."); testSplit("Dit hier is een(?) zin."); testSplit("Dit hier is een(???) zin."); testSplit("Dit hier is een(???) zin."); testSplit("Als voetballer wordt hij nooit een prof. ", "Maar prof. N.A.W. Th.Ch. Janssen wordt dat wel."); // TODO, zin na dubbele punt testSplit("Dat was het: helemaal niets."); testSplit("Dat was het: het is een nieuwe zin."); // https://nl.wikipedia.org/wiki/Aanhalingsteken testSplit("Jan zei: \"Hallo.\""); testSplit("Jan zei: “Hallo.”"); testSplit("„Hallo,” zei Jan, „waar ga je naartoe?”"); testSplit("„Gisteren”, zei Jan, „was het veel beter weer.”"); testSplit("Jan zei: „Annette zei ‚Hallo’.”"); testSplit("Jan zei: “Annette zei ‘Hallo’.”"); testSplit("Jan zei: «Annette zei ‹Hallo›.»"); testSplit("Wegens zijn „ziekte” hoefde hij niet te werken."); testSplit("de letter „a”"); testSplit("het woord „beta” is afkomstig van ..."); // http://taaladvies.net/taal/advies/vraag/11 testSplit("De voorzitter zei: 'Ik zie hier geen been in.'"); testSplit("De voorzitter zei: \"Ik zie hier geen been in.\""); testSplit("De koning zei: \"Ik herinner me nog dat iemand 'Vive la république' riep tijdens mijn eedaflegging.\""); testSplit("De koning zei: 'Ik herinner me nog dat iemand \"Vive la république\" riep tijdens mijn eedaflegging.'"); testSplit("De koning zei: 'Ik herinner me nog dat iemand 'Vive la république' riep tijdens mijn eedaflegging.'"); testSplit("Otto dacht: wat een nare verhalen hoor je toch tegenwoordig."); // http://taaladvies.net/taal/advies/vraag/871 testSplit("'Ik vrees', zei Rob, 'dat de brug zal instorten.'"); testSplit("'Ieder land', aldus minister Powell, 'moet rekenschap afleggen over de wijze waarop het zijn burgers behandelt.'"); testSplit("'Zeg Rob,' vroeg Jolanda, 'denk jij dat de brug zal instorten?'"); testSplit("'Deze man heeft er niets mee te maken,' aldus korpschef Jan de Vries, 'maar hij heeft momenteel geen leven.'"); testSplit("'Ik vrees,' zei Rob, 'dat de brug zal instorten.'"); testSplit("'Ieder land,' aldus minister Powell, 'moet rekenschap afleggen over de wijze waarop het zijn burgers behandelt.'"); testSplit("'Zeg Rob,' vroeg Jolanda, 'denk jij dat de brug zal instorten?'"); testSplit("'Deze man heeft er niets mee te maken,' aldus korpschef Jan de Vries, 'maar hij heeft momenteel geen leven.'"); // http://taaladvies.net/taal/advies/vraag/872 testSplit("Zij antwoordde: 'Ik denk niet dat ik nog langer met je om wil gaan.'"); testSplit("Zij fluisterde iets van 'eeuwig trouw' en 'altijd blijven houden van'."); testSplit("'Heb je dat boek al gelezen?', vroeg hij."); testSplit("De auteur vermeldt: 'Deze opvatting van het vorstendom heeft lang doorgewerkt.'"); // http://taaladvies.net/taal/advies/vraag/1557 testSplit("'Gaat u zitten', zei zij. ", "'De dokter komt zo.'"); testSplit("'Mijn broer woont ook in Den Haag', vertelde ze. ", "'Hij woont al een paar jaar samen.'"); testSplit("'Je bent grappig', zei ze. ", "'Echt, ik vind je grappig.'"); testSplit("'Is Jan thuis?', vroeg Piet. ", "'Ik wil hem wat vragen.'"); testSplit("'Ik denk er niet over!', riep ze. ", "'Dat gaat echt te ver, hoor!'"); testSplit("'Ik vermoed', zei Piet, 'dat Jan al wel thuis is.'"); } private void testSplit(String... sentences) { TestTools.testSplit(sentences, stokenizer); } }
33359_14
package jmri.jmrix.zimo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents a single command or response to the Zimo Binary Protocol. * <p> * Content is represented with ints to avoid the problems with sign-extension * that bytes have, and because a Java char is actually a variable number of * bytes in Unicode. * * @author Kevin Dickerson Copyright (C) 2014 * * Adapted by Sip Bosch for use with zimo MX-1 * */ public class Mx1Message extends jmri.jmrix.NetMessage { public Mx1Message(int len) { this(len, Mx1Packetizer.ASCII); } /** * Create a new object, representing a specific-length message. * * @param len Total bytes in message, including opcode and * error-detection byte. * @param protocol one of {@link Mx1Packetizer#ASCII} or * {@link Mx1Packetizer#BINARY} */ public Mx1Message(int len, boolean protocol) { super(len); this.protocol = protocol; if (!protocol) { if (len > 15 || len < 0) { log.error("Invalid length in ctor: " + len); } } } boolean protocol = Mx1Packetizer.ASCII; //Version 5 and above allow for a message size greater than 15 bytes public Mx1Message(Integer[] contents) { super(contents.length); protocol = Mx1Packetizer.BINARY; for (int i = 0; i < contents.length; i++) { this.setElement(i, contents[i]); } } //Version 5 and above allow for a message size greater than 15 bytes public Mx1Message(byte[] contents) { super(contents.length); protocol = Mx1Packetizer.BINARY; for (int i = 0; i < contents.length; i++) { this.setElement(i, (contents[i] & 0xff)); } } public boolean getLongMessage() { if (protocol == Mx1Packetizer.BINARY) { if ((getElement(1) & 0x80) == 0x80) { return true; } } return false; } final static int PRIMARY = 0x00; final static int ACKREP1 = 0x40; final static int REPLY2 = 0x20; final static int ACK2 = 0x60; /** * Indicates where the message is to/from in the header byte. * <p> * Up to JMRI 4.3.5, this was doing {@code ((mod & MX1) == MX1)} for the * first test, which is really 0 == 0 and always true. At that point it was * changed to just check the bottom two bits. * * @return one of {@link #MX1}, {@link #MX8}, {@link #MX9} or 0x0F */ public int getModule() { int mod = getElement(1) & 0x0F; if ((mod & 0x03) == MX1) { return MX1; } if ((mod & 0x03) == MX8) { return MX8; } if ((mod & 0x03) == MX9) { return MX9; } return mod; } public int getMessageType() { return getElement(1) & 0x60; } public int getPrimaryMessage() { return getElement(2); } /** * Message to/from Command Station MX1 */ static final int MX1 = 0x00; /** * Message to/from Accessory module MX8 */ static final int MX8 = 0x01; /** * Message to/from Track Section module MX9 */ static final int MX9 = 0x02; /** * Indicates the message source is a command station. {@value #CS} * * @see #messageSource() */ final static boolean CS = true; /** * Indicates the message source is a command station. {@value #PC} * * @see #messageSource() */ final static boolean PC = false; /** * Indicates the source of the message. * * @return {@link #PC} or {@link #CS} */ public boolean messageSource() { if ((getElement(0) & 0x08) == 0x08) { return PC; } return CS; } long timeStamp = 0L; protected long getTimeStamp() { return timeStamp; } protected void setTimeStamp(long ts) { timeStamp = ts; } int retries = 3; public int getRetry() { return retries; } public void setRetries(int i) { retries = i; } //byte sequenceNo = 0x00; public boolean replyL1Expected() { return true; } byte[] rawPacket; public void setRawPacket(byte[] b) { rawPacket = b; } protected byte[] getRawPacket() { return rawPacket; } public void setSequenceNo(byte s) { setElement(0, (s & 0xff)); } public int getSequenceNo() { return (getElement(0) & 0xff); } boolean crcError = false; public void setCRCError() { crcError = true; } public boolean isCRCError() { return crcError; } /** * Check if the message has a valid parity (actually check for CR or LF as * end of message). * * @return true if message has correct parity bit */ @Override public boolean checkParity() { //javax.swing.JOptionPane.showMessageDialog(null, "A-Programma komt tot hier!"); int len = getNumDataElements(); return (getElement(len - 1) == (0x0D | 0x0A)); } // programma komt hier volgens mij nooit // in fact set CR as end of message @Override public void setParity() { javax.swing.JOptionPane.showMessageDialog(null, "B-Programma komt tot hier!"); int len = getNumDataElements(); setElement(len - 1, 0x0D); } // decode messages of a particular form public String getStringMsg() { StringBuilder txt = new StringBuilder(); if (protocol == Mx1Packetizer.BINARY) { if (isCRCError()) { txt.append(" === CRC ERROR === "); } if (getNumDataElements() <= 3) { txt.append("Short Packet "); return txt.toString(); } if ((getElement(1) & 0x10) == 0x10) { txt.append("From PC"); } else { txt.append("From CS"); } txt.append(" Seq ").append(getElement(0) & 0xff); if (getLongMessage()) { txt.append(" (L)"); } else { txt.append(" (S)"); } int offset; switch (getMessageType()) { case PRIMARY: txt.append(" Prim"); break; case ACKREP1: txt.append(" Ack/Reply 1"); break; case REPLY2: txt.append(" Reply 2"); break; case ACK2: txt.append(" Ack 2"); break; default: txt.append(" Unknown msg"); break; } if (getModule() == MX1) { //was (getElement(1)&0x00) == 0x00 txt.append(" to/from CS (MX1)"); switch (getPrimaryMessage()) { //was getElement(2) case TRACKCTL: offset = 0; if (getMessageType() == ACKREP1) { offset++; } txt.append(" Track Control "); if ((getElement(3 + offset) & 0x03) == 0x03) { txt.append(" Query Track Status "); } else if ((getElement(3 + offset) & 0x01) == 0x01) { txt.append(" Turn Track Off "); } else if ((getElement(3 + offset) & 0x02) == 0x02) { txt.append(" Turn Track On "); } else { txt.append(" Stop All Locos "); } break; case 3: txt.append(" Loco Control : "); if (getMessageType() == PRIMARY) { txt.append(getLocoAddress(getElement((3)), getElement(4))); txt.append(((getElement(6) & 0x20) == 0x20) ? " Fwd " : " Rev "); txt.append(((getElement(6) & 0x10) == 0x10) ? " F0: On " : " F0: Off "); txt.append(decodeFunctionStates(getElement(7), getElement(8))); } break; case 4: txt.append(" Loco Funct "); break; case 5: txt.append(" Loco Acc/Dec "); break; case 6: txt.append(" Shuttle "); break; case 7: txt.append(" Accessory "); if (getMessageType() == PRIMARY) { txt.append(getLocoAddress(getElement((3)), getElement(4))); txt.append(((getElement(5) & 0x04) == 0x04) ? " Thrown " : " Closed "); } break; case 8: txt.append(" Loco Status "); break; case 9: txt.append(" Acc Status "); break; case 10: txt.append(" Address Control "); break; case 11: txt.append(" CS State "); break; case 12: txt.append(" Read/Write CS CV "); break; case 13: txt.append(" CS Equip Query "); break; case 17: txt.append(" Tool Type "); break; case PROGCMD: offset = 0; if (getMessageType() == ACKREP1) { txt.append(" Prog CV "); break; } if (getMessageType() == REPLY2) { offset++; } if (getMessageType() == ACK2) { txt.append("Ack to CS Message"); break; } if (getNumDataElements() == 7 && getMessageType() == ACKREP1) { txt.append(" Error Occured "); txt.append(getErrorCode(getElement(6))); txt.append(" Loco: ").append(getLocoAddress(getElement((3 + offset)), getElement(4 + offset))); break; } /*if(getNumDataElements()<7){ txt.append(" Ack L1 "); break; }*/ if ((getMessageType() == PRIMARY && getNumDataElements() == 8)) { txt.append(" Write CV "); } else { txt.append(" Read CV "); } txt.append("Loco: ").append(getLocoAddress(getElement((3 + offset)), getElement(4 + offset))); if ((getElement(3 + offset) & 0x80) == 0x80) { txt.append(" DCC"); } int cv = (((getElement(5 + offset) & 0xff) << 8) + (getElement(6 + offset) & 0xff)); txt.append(" CV: ").append(cv); if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet txt.append(" Set To: ").append(getElement(7 + offset) & 0xff); } break; case 254: txt.append(" Cur Acc Memory "); break; case 255: txt.append(" Cur Loco Memory "); break; default: txt.append(" Unknown "); } } else if ((getElement(1) & 0x01) == 0x01) { txt.append(" to/from Accessory Mod (MX8)"); } else if ((getElement(1) & 0x02) == 0x02) { txt.append(" to/from Track Section (MX9)"); } else { txt.append(" unknown"); } } //int type = getElement(2); return txt.toString(); } private String decodeFunctionStates(int cData2, int cData3) { StringBuilder txt = new StringBuilder(); txt.append(((cData2 & 0x1) == 0x1) ? " F1: On " : " F1: Off "); txt.append(((cData2 & 0x2) == 0x2) ? " F2: On " : " F2: Off "); txt.append(((cData2 & 0x4) == 0x4) ? " F3: On " : " F3: Off "); txt.append(((cData2 & 0x8) == 0x8) ? " F4: On " : " F4: Off "); txt.append(((cData2 & 0x10) == 0x10) ? " F5: On " : " F5: Off "); txt.append(((cData2 & 0x20) == 0x20) ? " F6: On " : " F6: Off "); txt.append(((cData2 & 0x40) == 0x40) ? " F7: On " : " F7: Off "); txt.append(((cData2 & 0x80) == 0x80) ? " F8: On " : " F8: Off "); txt.append(((cData3 & 0x1) == 0x1) ? " F9: On " : " F9: Off "); txt.append(((cData3 & 0x2) == 0x2) ? " F10: On " : " F10: Off "); txt.append(((cData3 & 0x4) == 0x4) ? " F11: On " : " F11: Off "); txt.append(((cData3 & 0x8) == 0x8) ? " F12: On " : " F12: Off "); return txt.toString(); } public int getLocoAddress() { int offset = 0; if (getMessageType() == REPLY2) { offset++; } else if (getMessageType() == ACKREP1) { offset = +2; } if (getNumDataElements() == (4 + offset)) { return getLocoAddress(getElement(3 + offset), getElement(4 + offset)); } return -1; } public int getCvValue() { int offset = 0; if (getMessageType() == REPLY2) { offset++; } else if (getMessageType() == ACKREP1) { offset = +2; } if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet return (getElement(7 + offset) & 0xff); } return -1; } int getLocoAddress(int hi, int lo) { hi = hi & 0x3F; if (hi == 0) { return lo; } else { hi = (((hi & 255) - 192) << 8); hi = hi + (lo & 255); return hi; } } String getErrorCode(int i) { switch (i) { case NO_ERROR: return "No Error"; case ERR_ADDRESS: return "Invalid Address"; case ERR_INDEX: return "Invalid Index"; case ERR_FORWARD: return "Could not be Forwarded"; case ERR_BUSY: return "CMD Busy"; case ERR_NO_MOT: return "Motorola Jump Off"; case ERR_NO_DCC: return "DCC Jump Off"; case ERR_CV_ADDRESS: return "Invalid CV"; case ERR_SECTION: return "Invalid Section"; case ERR_NO_MODUL: return "No Module Found"; case ERR_MESSAGE: return "Error in Message"; case ERR_SPEED: return "Invalid Speed"; default: return "Unknown Error"; } } final static int NO_ERROR = 0x00; final static int ERR_ADDRESS = 0x01; final static int ERR_INDEX = 0x02; final static int ERR_FORWARD = 0x03; final static int ERR_BUSY = 0x04; final static int ERR_NO_MOT = 0x05; final static int ERR_NO_DCC = 0x06; final static int ERR_CV_ADDRESS = 0x07; final static int ERR_SECTION = 0x08; final static int ERR_NO_MODUL = 0x09; final static int ERR_MESSAGE = 0x0a; final static int ERR_SPEED = 0x0b; final static int TRACKCTL = 0x02; final static int PROGCMD = 0x13; final static int LOCOCMD = 0x03; final static int ACCCMD = 0x07; static public Mx1Message getCmdStnDetails() { Mx1Message m = new Mx1Message(4); m.setElement(1, 0x10); m.setElement(2, 0x13); m.setElement(3, 0x00); return m; } /** * Set Track Power Off/Emergency Stop * * @return MrcMessage */ static public Mx1Message setPowerOff() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x01); return m; } static public Mx1Message setPowerOn() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x02); return m; } static public Mx1Message getTrackStatus() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x03); return m; } /** * Create a message to read or write a CV. * * @param locoAddress address of the loco * @param cv CV to read or write * @param value value to write to CV, if -1 CV is read * @param dcc true if decoder is DCC; false if decoder is Motorola * @return a message to read or write a CV */ // javadoc did indicate locoAddress could be blank to use programming track, but that's not possible with an int static public Mx1Message getDecProgCmd(int locoAddress, int cv, int value, boolean dcc) { Mx1Message m; if (value == -1) { m = new Mx1Message(7, Mx1Packetizer.BINARY); } else { m = new Mx1Message(8, Mx1Packetizer.BINARY); } m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, PROGCMD); int locoHi = locoAddress >> 8; if (dcc) { locoHi = locoHi + 128; } else { locoHi = locoHi + 64; } m.setElement(3, (locoHi)); m.setElement(4, (locoAddress & 0xff)); m.setElement(5, cv >> 8); m.setElement(6, cv & 0xff); if (value != -1) { m.setElement(7, value); } return m; } /** * Create a locomotive control message. * * @param locoAddress address of the loco * @param speed Speed Step in the actual Speed Step System * @param dcc true if decoder is DCC; false if decoder is Motorola * @param cData1 ??? * @param cData2 functions output 0-7 * @param cData3 functions output 9-12 * @return message controlling a locomotive */ static public Mx1Message getLocoControl(int locoAddress, int speed, boolean dcc, int cData1, int cData2, int cData3) { Mx1Message m = new Mx1Message(9, Mx1Packetizer.BINARY); m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, LOCOCMD); //High add 80 to indicate DCC int locoHi = locoAddress >> 8; if (dcc) { locoHi = locoHi + 128; } else { locoHi = locoHi + 64; } m.setElement(3, (locoHi)); m.setElement(4, (locoAddress & 0xff)); m.setElement(5, speed); m.setElement(6, cData1); m.setElement(7, cData2); m.setElement(8, cData3); return m; } static public Mx1Message getSwitchMsg(int accAddress, int setting, boolean dcc) { Mx1Message m = new Mx1Message(6, Mx1Packetizer.BINARY); m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, ACCCMD); //High add 80 to indicate DCC int accHi = accAddress >> 8; if (dcc) { accHi = accHi + 128; } else { accHi = accHi + 64; } m.setElement(3, (accHi)); m.setElement(4, (accAddress & 0xff)); m.setElement(5, 0x00); if (setting == jmri.Turnout.THROWN) { m.setElement(5, 0x04); } return m; } // initialize logging private final static Logger log = LoggerFactory.getLogger(Mx1Message.class); }
ElasticCoder/JMRI
java/src/jmri/jmrix/zimo/Mx1Message.java
6,429
// programma komt hier volgens mij nooit
line_comment
nl
package jmri.jmrix.zimo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents a single command or response to the Zimo Binary Protocol. * <p> * Content is represented with ints to avoid the problems with sign-extension * that bytes have, and because a Java char is actually a variable number of * bytes in Unicode. * * @author Kevin Dickerson Copyright (C) 2014 * * Adapted by Sip Bosch for use with zimo MX-1 * */ public class Mx1Message extends jmri.jmrix.NetMessage { public Mx1Message(int len) { this(len, Mx1Packetizer.ASCII); } /** * Create a new object, representing a specific-length message. * * @param len Total bytes in message, including opcode and * error-detection byte. * @param protocol one of {@link Mx1Packetizer#ASCII} or * {@link Mx1Packetizer#BINARY} */ public Mx1Message(int len, boolean protocol) { super(len); this.protocol = protocol; if (!protocol) { if (len > 15 || len < 0) { log.error("Invalid length in ctor: " + len); } } } boolean protocol = Mx1Packetizer.ASCII; //Version 5 and above allow for a message size greater than 15 bytes public Mx1Message(Integer[] contents) { super(contents.length); protocol = Mx1Packetizer.BINARY; for (int i = 0; i < contents.length; i++) { this.setElement(i, contents[i]); } } //Version 5 and above allow for a message size greater than 15 bytes public Mx1Message(byte[] contents) { super(contents.length); protocol = Mx1Packetizer.BINARY; for (int i = 0; i < contents.length; i++) { this.setElement(i, (contents[i] & 0xff)); } } public boolean getLongMessage() { if (protocol == Mx1Packetizer.BINARY) { if ((getElement(1) & 0x80) == 0x80) { return true; } } return false; } final static int PRIMARY = 0x00; final static int ACKREP1 = 0x40; final static int REPLY2 = 0x20; final static int ACK2 = 0x60; /** * Indicates where the message is to/from in the header byte. * <p> * Up to JMRI 4.3.5, this was doing {@code ((mod & MX1) == MX1)} for the * first test, which is really 0 == 0 and always true. At that point it was * changed to just check the bottom two bits. * * @return one of {@link #MX1}, {@link #MX8}, {@link #MX9} or 0x0F */ public int getModule() { int mod = getElement(1) & 0x0F; if ((mod & 0x03) == MX1) { return MX1; } if ((mod & 0x03) == MX8) { return MX8; } if ((mod & 0x03) == MX9) { return MX9; } return mod; } public int getMessageType() { return getElement(1) & 0x60; } public int getPrimaryMessage() { return getElement(2); } /** * Message to/from Command Station MX1 */ static final int MX1 = 0x00; /** * Message to/from Accessory module MX8 */ static final int MX8 = 0x01; /** * Message to/from Track Section module MX9 */ static final int MX9 = 0x02; /** * Indicates the message source is a command station. {@value #CS} * * @see #messageSource() */ final static boolean CS = true; /** * Indicates the message source is a command station. {@value #PC} * * @see #messageSource() */ final static boolean PC = false; /** * Indicates the source of the message. * * @return {@link #PC} or {@link #CS} */ public boolean messageSource() { if ((getElement(0) & 0x08) == 0x08) { return PC; } return CS; } long timeStamp = 0L; protected long getTimeStamp() { return timeStamp; } protected void setTimeStamp(long ts) { timeStamp = ts; } int retries = 3; public int getRetry() { return retries; } public void setRetries(int i) { retries = i; } //byte sequenceNo = 0x00; public boolean replyL1Expected() { return true; } byte[] rawPacket; public void setRawPacket(byte[] b) { rawPacket = b; } protected byte[] getRawPacket() { return rawPacket; } public void setSequenceNo(byte s) { setElement(0, (s & 0xff)); } public int getSequenceNo() { return (getElement(0) & 0xff); } boolean crcError = false; public void setCRCError() { crcError = true; } public boolean isCRCError() { return crcError; } /** * Check if the message has a valid parity (actually check for CR or LF as * end of message). * * @return true if message has correct parity bit */ @Override public boolean checkParity() { //javax.swing.JOptionPane.showMessageDialog(null, "A-Programma komt tot hier!"); int len = getNumDataElements(); return (getElement(len - 1) == (0x0D | 0x0A)); } // programma komt<SUF> // in fact set CR as end of message @Override public void setParity() { javax.swing.JOptionPane.showMessageDialog(null, "B-Programma komt tot hier!"); int len = getNumDataElements(); setElement(len - 1, 0x0D); } // decode messages of a particular form public String getStringMsg() { StringBuilder txt = new StringBuilder(); if (protocol == Mx1Packetizer.BINARY) { if (isCRCError()) { txt.append(" === CRC ERROR === "); } if (getNumDataElements() <= 3) { txt.append("Short Packet "); return txt.toString(); } if ((getElement(1) & 0x10) == 0x10) { txt.append("From PC"); } else { txt.append("From CS"); } txt.append(" Seq ").append(getElement(0) & 0xff); if (getLongMessage()) { txt.append(" (L)"); } else { txt.append(" (S)"); } int offset; switch (getMessageType()) { case PRIMARY: txt.append(" Prim"); break; case ACKREP1: txt.append(" Ack/Reply 1"); break; case REPLY2: txt.append(" Reply 2"); break; case ACK2: txt.append(" Ack 2"); break; default: txt.append(" Unknown msg"); break; } if (getModule() == MX1) { //was (getElement(1)&0x00) == 0x00 txt.append(" to/from CS (MX1)"); switch (getPrimaryMessage()) { //was getElement(2) case TRACKCTL: offset = 0; if (getMessageType() == ACKREP1) { offset++; } txt.append(" Track Control "); if ((getElement(3 + offset) & 0x03) == 0x03) { txt.append(" Query Track Status "); } else if ((getElement(3 + offset) & 0x01) == 0x01) { txt.append(" Turn Track Off "); } else if ((getElement(3 + offset) & 0x02) == 0x02) { txt.append(" Turn Track On "); } else { txt.append(" Stop All Locos "); } break; case 3: txt.append(" Loco Control : "); if (getMessageType() == PRIMARY) { txt.append(getLocoAddress(getElement((3)), getElement(4))); txt.append(((getElement(6) & 0x20) == 0x20) ? " Fwd " : " Rev "); txt.append(((getElement(6) & 0x10) == 0x10) ? " F0: On " : " F0: Off "); txt.append(decodeFunctionStates(getElement(7), getElement(8))); } break; case 4: txt.append(" Loco Funct "); break; case 5: txt.append(" Loco Acc/Dec "); break; case 6: txt.append(" Shuttle "); break; case 7: txt.append(" Accessory "); if (getMessageType() == PRIMARY) { txt.append(getLocoAddress(getElement((3)), getElement(4))); txt.append(((getElement(5) & 0x04) == 0x04) ? " Thrown " : " Closed "); } break; case 8: txt.append(" Loco Status "); break; case 9: txt.append(" Acc Status "); break; case 10: txt.append(" Address Control "); break; case 11: txt.append(" CS State "); break; case 12: txt.append(" Read/Write CS CV "); break; case 13: txt.append(" CS Equip Query "); break; case 17: txt.append(" Tool Type "); break; case PROGCMD: offset = 0; if (getMessageType() == ACKREP1) { txt.append(" Prog CV "); break; } if (getMessageType() == REPLY2) { offset++; } if (getMessageType() == ACK2) { txt.append("Ack to CS Message"); break; } if (getNumDataElements() == 7 && getMessageType() == ACKREP1) { txt.append(" Error Occured "); txt.append(getErrorCode(getElement(6))); txt.append(" Loco: ").append(getLocoAddress(getElement((3 + offset)), getElement(4 + offset))); break; } /*if(getNumDataElements()<7){ txt.append(" Ack L1 "); break; }*/ if ((getMessageType() == PRIMARY && getNumDataElements() == 8)) { txt.append(" Write CV "); } else { txt.append(" Read CV "); } txt.append("Loco: ").append(getLocoAddress(getElement((3 + offset)), getElement(4 + offset))); if ((getElement(3 + offset) & 0x80) == 0x80) { txt.append(" DCC"); } int cv = (((getElement(5 + offset) & 0xff) << 8) + (getElement(6 + offset) & 0xff)); txt.append(" CV: ").append(cv); if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet txt.append(" Set To: ").append(getElement(7 + offset) & 0xff); } break; case 254: txt.append(" Cur Acc Memory "); break; case 255: txt.append(" Cur Loco Memory "); break; default: txt.append(" Unknown "); } } else if ((getElement(1) & 0x01) == 0x01) { txt.append(" to/from Accessory Mod (MX8)"); } else if ((getElement(1) & 0x02) == 0x02) { txt.append(" to/from Track Section (MX9)"); } else { txt.append(" unknown"); } } //int type = getElement(2); return txt.toString(); } private String decodeFunctionStates(int cData2, int cData3) { StringBuilder txt = new StringBuilder(); txt.append(((cData2 & 0x1) == 0x1) ? " F1: On " : " F1: Off "); txt.append(((cData2 & 0x2) == 0x2) ? " F2: On " : " F2: Off "); txt.append(((cData2 & 0x4) == 0x4) ? " F3: On " : " F3: Off "); txt.append(((cData2 & 0x8) == 0x8) ? " F4: On " : " F4: Off "); txt.append(((cData2 & 0x10) == 0x10) ? " F5: On " : " F5: Off "); txt.append(((cData2 & 0x20) == 0x20) ? " F6: On " : " F6: Off "); txt.append(((cData2 & 0x40) == 0x40) ? " F7: On " : " F7: Off "); txt.append(((cData2 & 0x80) == 0x80) ? " F8: On " : " F8: Off "); txt.append(((cData3 & 0x1) == 0x1) ? " F9: On " : " F9: Off "); txt.append(((cData3 & 0x2) == 0x2) ? " F10: On " : " F10: Off "); txt.append(((cData3 & 0x4) == 0x4) ? " F11: On " : " F11: Off "); txt.append(((cData3 & 0x8) == 0x8) ? " F12: On " : " F12: Off "); return txt.toString(); } public int getLocoAddress() { int offset = 0; if (getMessageType() == REPLY2) { offset++; } else if (getMessageType() == ACKREP1) { offset = +2; } if (getNumDataElements() == (4 + offset)) { return getLocoAddress(getElement(3 + offset), getElement(4 + offset)); } return -1; } public int getCvValue() { int offset = 0; if (getMessageType() == REPLY2) { offset++; } else if (getMessageType() == ACKREP1) { offset = +2; } if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet return (getElement(7 + offset) & 0xff); } return -1; } int getLocoAddress(int hi, int lo) { hi = hi & 0x3F; if (hi == 0) { return lo; } else { hi = (((hi & 255) - 192) << 8); hi = hi + (lo & 255); return hi; } } String getErrorCode(int i) { switch (i) { case NO_ERROR: return "No Error"; case ERR_ADDRESS: return "Invalid Address"; case ERR_INDEX: return "Invalid Index"; case ERR_FORWARD: return "Could not be Forwarded"; case ERR_BUSY: return "CMD Busy"; case ERR_NO_MOT: return "Motorola Jump Off"; case ERR_NO_DCC: return "DCC Jump Off"; case ERR_CV_ADDRESS: return "Invalid CV"; case ERR_SECTION: return "Invalid Section"; case ERR_NO_MODUL: return "No Module Found"; case ERR_MESSAGE: return "Error in Message"; case ERR_SPEED: return "Invalid Speed"; default: return "Unknown Error"; } } final static int NO_ERROR = 0x00; final static int ERR_ADDRESS = 0x01; final static int ERR_INDEX = 0x02; final static int ERR_FORWARD = 0x03; final static int ERR_BUSY = 0x04; final static int ERR_NO_MOT = 0x05; final static int ERR_NO_DCC = 0x06; final static int ERR_CV_ADDRESS = 0x07; final static int ERR_SECTION = 0x08; final static int ERR_NO_MODUL = 0x09; final static int ERR_MESSAGE = 0x0a; final static int ERR_SPEED = 0x0b; final static int TRACKCTL = 0x02; final static int PROGCMD = 0x13; final static int LOCOCMD = 0x03; final static int ACCCMD = 0x07; static public Mx1Message getCmdStnDetails() { Mx1Message m = new Mx1Message(4); m.setElement(1, 0x10); m.setElement(2, 0x13); m.setElement(3, 0x00); return m; } /** * Set Track Power Off/Emergency Stop * * @return MrcMessage */ static public Mx1Message setPowerOff() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x01); return m; } static public Mx1Message setPowerOn() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x02); return m; } static public Mx1Message getTrackStatus() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x03); return m; } /** * Create a message to read or write a CV. * * @param locoAddress address of the loco * @param cv CV to read or write * @param value value to write to CV, if -1 CV is read * @param dcc true if decoder is DCC; false if decoder is Motorola * @return a message to read or write a CV */ // javadoc did indicate locoAddress could be blank to use programming track, but that's not possible with an int static public Mx1Message getDecProgCmd(int locoAddress, int cv, int value, boolean dcc) { Mx1Message m; if (value == -1) { m = new Mx1Message(7, Mx1Packetizer.BINARY); } else { m = new Mx1Message(8, Mx1Packetizer.BINARY); } m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, PROGCMD); int locoHi = locoAddress >> 8; if (dcc) { locoHi = locoHi + 128; } else { locoHi = locoHi + 64; } m.setElement(3, (locoHi)); m.setElement(4, (locoAddress & 0xff)); m.setElement(5, cv >> 8); m.setElement(6, cv & 0xff); if (value != -1) { m.setElement(7, value); } return m; } /** * Create a locomotive control message. * * @param locoAddress address of the loco * @param speed Speed Step in the actual Speed Step System * @param dcc true if decoder is DCC; false if decoder is Motorola * @param cData1 ??? * @param cData2 functions output 0-7 * @param cData3 functions output 9-12 * @return message controlling a locomotive */ static public Mx1Message getLocoControl(int locoAddress, int speed, boolean dcc, int cData1, int cData2, int cData3) { Mx1Message m = new Mx1Message(9, Mx1Packetizer.BINARY); m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, LOCOCMD); //High add 80 to indicate DCC int locoHi = locoAddress >> 8; if (dcc) { locoHi = locoHi + 128; } else { locoHi = locoHi + 64; } m.setElement(3, (locoHi)); m.setElement(4, (locoAddress & 0xff)); m.setElement(5, speed); m.setElement(6, cData1); m.setElement(7, cData2); m.setElement(8, cData3); return m; } static public Mx1Message getSwitchMsg(int accAddress, int setting, boolean dcc) { Mx1Message m = new Mx1Message(6, Mx1Packetizer.BINARY); m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, ACCCMD); //High add 80 to indicate DCC int accHi = accAddress >> 8; if (dcc) { accHi = accHi + 128; } else { accHi = accHi + 64; } m.setElement(3, (accHi)); m.setElement(4, (accAddress & 0xff)); m.setElement(5, 0x00); if (setting == jmri.Turnout.THROWN) { m.setElement(5, 0x04); } return m; } // initialize logging private final static Logger log = LoggerFactory.getLogger(Mx1Message.class); }
177009_1
package mage.cards.m; import java.util.UUID; import mage.abilities.effects.common.discard.DiscardTargetEffect; import mage.abilities.keyword.AwakenAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.target.common.TargetOpponent; /** * * @author LevelX2 */ public final class MiresMalice extends CardImpl { public MiresMalice(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{3}{B}"); // Target opponent discards two cards. this.getSpellAbility().addEffect(new DiscardTargetEffect(2)); this.getSpellAbility().addTarget(new TargetOpponent()); // Awaken 3 - {5}{B} this.addAbility(new AwakenAbility(this, 3, "{5}{B}")); } private MiresMalice(final MiresMalice card) { super(card); } @Override public MiresMalice copy() { return new MiresMalice(this); } }
ElchananHaas/mage
Mage.Sets/src/mage/cards/m/MiresMalice.java
322
// Target opponent discards two cards.
line_comment
nl
package mage.cards.m; import java.util.UUID; import mage.abilities.effects.common.discard.DiscardTargetEffect; import mage.abilities.keyword.AwakenAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.target.common.TargetOpponent; /** * * @author LevelX2 */ public final class MiresMalice extends CardImpl { public MiresMalice(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{3}{B}"); // Target opponent<SUF> this.getSpellAbility().addEffect(new DiscardTargetEffect(2)); this.getSpellAbility().addTarget(new TargetOpponent()); // Awaken 3 - {5}{B} this.addAbility(new AwakenAbility(this, 3, "{5}{B}")); } private MiresMalice(final MiresMalice card) { super(card); } @Override public MiresMalice copy() { return new MiresMalice(this); } }
174670_15
package de.robv.android.xposed; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; import android.preference.PreferenceManager; import android.util.Log; import com.android.internal.util.XmlUtils; import com.elderdrivers.riru.edxp.bridge.BuildConfig; import com.elderdrivers.riru.edxp.util.MetaDataReader; import org.xmlpull.v1.XmlPullParserException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.AccessDeniedException; import java.nio.file.ClosedWatchServiceException; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.security.MessageDigest; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import de.robv.android.xposed.services.FileResult; /** * This class is basically the same as SharedPreferencesImpl from AOSP, but * read-only and without listeners support. Instead, it is made to be * compatible with all ROMs. */ public final class XSharedPreferences implements SharedPreferences { private static final String TAG = "XSharedPreferences"; private static final HashMap<WatchKey, PrefsData> sWatcherKeyInstances = new HashMap<>(); private static final Object sContent = new Object(); private static Thread sWatcherDaemon = null; private static WatchService sWatcher; private final HashMap<OnSharedPreferenceChangeListener, Object> mListeners = new HashMap<>(); private final File mFile; private final String mFilename; private Map<String, Object> mMap; private boolean mLoaded = false; private long mLastModified; private long mFileSize; private WatchKey mWatchKey; private static void initWatcherDaemon() { sWatcherDaemon = new Thread() { @Override public void run() { if (BuildConfig.DEBUG) Log.d(TAG, "Watcher daemon thread started"); while (true) { WatchKey key; try { key = sWatcher.take(); } catch (ClosedWatchServiceException ignored) { if (BuildConfig.DEBUG) Log.d(TAG, "Watcher daemon thread finished"); sWatcher = null; return; } catch (InterruptedException ignored) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } Path dir = (Path) key.watchable(); Path path = dir.resolve((Path) event.context()); String pathStr = path.toString(); if (BuildConfig.DEBUG) Log.v(TAG, "File " + path.toString() + " event: " + kind.name()); // We react to both real and backup files due to rare race conditions if (pathStr.endsWith(".bak")) { if (kind != StandardWatchEventKinds.ENTRY_DELETE) { continue; } } else if (SELinuxHelper.getAppDataFileService().checkFileExists(pathStr + ".bak")) { continue; } PrefsData data = sWatcherKeyInstances.get(key); if (data != null && data.hasChanged()) { for (OnSharedPreferenceChangeListener l : data.mPrefs.mListeners.keySet()) { try { l.onSharedPreferenceChanged(data.mPrefs, null); } catch (Throwable t) { if (BuildConfig.DEBUG) Log.e(TAG, "Fail in preference change listener", t); } } } } key.reset(); } } }; sWatcherDaemon.setName(TAG + "-Daemon"); sWatcherDaemon.setDaemon(true); sWatcherDaemon.start(); } /** * Read settings from the specified file. * * @param prefFile The file to read the preferences from. */ public XSharedPreferences(File prefFile) { mFile = prefFile; mFilename = prefFile.getAbsolutePath(); init(); } /** * Read settings from the default preferences for a package. * These preferences are returned by {@link PreferenceManager#getDefaultSharedPreferences}. * * @param packageName The package name. */ public XSharedPreferences(String packageName) { this(packageName, packageName + "_preferences"); } /** * Read settings from a custom preferences file for a package. * These preferences are returned by {@link Context#getSharedPreferences(String, int)}. * * @param packageName The package name. * @param prefFileName The file name without ".xml". */ public XSharedPreferences(String packageName, String prefFileName) { boolean newModule = false; Set<String> modules = XposedInit.getLoadedModules(); for (String m : modules) { if (m.contains("/" + packageName + "-")) { boolean isModule = false; int xposedminversion = -1; boolean xposedsharedprefs = false; try { Map<String, Object> metaData = MetaDataReader.getMetaData(new File(m)); isModule = metaData.containsKey("xposedmodule"); if (isModule) { Object minVersionRaw = metaData.get("xposedminversion"); if (minVersionRaw instanceof Integer) { xposedminversion = (Integer) minVersionRaw; } else if (minVersionRaw instanceof String) { xposedminversion = MetaDataReader.extractIntPart((String) minVersionRaw); } xposedsharedprefs = metaData.containsKey("xposedsharedprefs"); } } catch (NumberFormatException | IOException e) { Log.w(TAG, "Apk parser fails: " + e); } newModule = isModule && (xposedminversion > 92 || xposedsharedprefs); } } if (newModule && XposedInit.prefsBasePath != null) { mFile = new File(XposedInit.prefsBasePath, packageName + "/" + prefFileName + ".xml"); } else { mFile = new File(Environment.getDataDirectory(), "data/" + packageName + "/shared_prefs/" + prefFileName + ".xml"); } mFilename = mFile.getAbsolutePath(); init(); } private void tryRegisterWatcher() { if (mWatchKey != null && mWatchKey.isValid()) { return; } synchronized (sWatcherKeyInstances) { Path path = mFile.toPath(); try { if (sWatcher == null) { sWatcher = new File(XposedInit.prefsBasePath).toPath().getFileSystem().newWatchService(); if (BuildConfig.DEBUG) Log.d(TAG, "Created WatchService instance"); } mWatchKey = path.getParent().register(sWatcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); sWatcherKeyInstances.put(mWatchKey, new PrefsData(this)); if (sWatcherDaemon == null || !sWatcherDaemon.isAlive()) { initWatcherDaemon(); } if (BuildConfig.DEBUG) Log.d(TAG, "tryRegisterWatcher: registered file watcher for " + path); } catch (AccessDeniedException accDeniedEx) { if (BuildConfig.DEBUG) Log.e(TAG, "tryRegisterWatcher: access denied to " + path); } catch (Exception e) { Log.e(TAG, "tryRegisterWatcher: failed to register file watcher", e); } } } private void tryUnregisterWatcher() { synchronized (sWatcherKeyInstances) { if (mWatchKey != null) { sWatcherKeyInstances.remove(mWatchKey); mWatchKey.cancel(); mWatchKey = null; } boolean atLeastOneValid = false; for (WatchKey key : sWatcherKeyInstances.keySet()) { atLeastOneValid |= key.isValid(); } if (!atLeastOneValid) { try { sWatcher.close(); } catch (Exception ignore) { } } } } private void init() { startLoadFromDisk(); } private static long tryGetFileSize(String filename) { try { return SELinuxHelper.getAppDataFileService().getFileSize(filename); } catch (IOException ignored) { return 0; } } private static byte[] tryGetFileHash(String filename) { try { MessageDigest md = MessageDigest.getInstance("MD5"); try (InputStream is = SELinuxHelper.getAppDataFileService().getFileInputStream(filename)) { byte[] buf = new byte[4096]; int read; while ((read = is.read(buf)) != -1) { md.update(buf, 0, read); } } return md.digest(); } catch (Exception ignored) { return new byte[0]; } } /** * Tries to make the preferences file world-readable. * * <p><strong>Warning:</strong> This is only meant to work around permission "fix" functions that are part * of some recoveries. It doesn't replace the need to open preferences with {@code MODE_WORLD_READABLE} * in the module's UI code. Otherwise, Android will set stricter permissions again during the next save. * * <p>This will only work if executed as root (e.g. {@code initZygote()}) and only if SELinux is disabled. * * @return {@code true} in case the file could be made world-readable. */ @SuppressLint("SetWorldReadable") public boolean makeWorldReadable() { if (!SELinuxHelper.getAppDataFileService().hasDirectFileAccess()) return false; // It doesn't make much sense to make the file readable if we wouldn't be able to access it anyway. if (!mFile.exists()) // Just in case - the file should never be created if it doesn't exist. return false; if (!mFile.setReadable(true, false)) return false; // Watcher service needs read access to parent directory (looks like execute is not enough) if (mFile.getParentFile() != null) { mFile.getParentFile().setReadable(true, false); } if (mListeners.size() > 0) { tryRegisterWatcher(); } return true; } /** * Returns the file that is backing these preferences. * * <p><strong>Warning:</strong> The file might not be accessible directly. */ public File getFile() { return mFile; } private void startLoadFromDisk() { synchronized (this) { mLoaded = false; } new Thread("XSharedPreferences-load") { @Override public void run() { synchronized (XSharedPreferences.this) { loadFromDiskLocked(); } } }.start(); } @SuppressWarnings({"rawtypes", "unchecked"}) private void loadFromDiskLocked() { if (mLoaded) { return; } Map map = null; FileResult result = null; try { result = SELinuxHelper.getAppDataFileService().getFileInputStream(mFilename, mFileSize, mLastModified); if (result.stream != null) { map = XmlUtils.readMapXml(result.stream); result.stream.close(); } else { // The file is unchanged, keep the current values map = mMap; } } catch (XmlPullParserException e) { Log.w(TAG, "getSharedPreferences failed for: " + mFilename, e); } catch (FileNotFoundException ignored) { // SharedPreferencesImpl has a canRead() check, so it doesn't log anything in case the file doesn't exist } catch (IOException e) { Log.w(TAG, "getSharedPreferences failed for: " + mFilename, e); } finally { if (result != null && result.stream != null) { try { result.stream.close(); } catch (RuntimeException rethrown) { throw rethrown; } catch (Exception ignored) { } } } mLoaded = true; if (map != null) { mMap = map; mLastModified = result.mtime; mFileSize = result.size; } else { mMap = new HashMap<>(); } notifyAll(); } /** * Reload the settings from file if they have changed. * * <p><strong>Warning:</strong> With enforcing SELinux, this call might be quite expensive. */ public synchronized void reload() { if (hasFileChanged()) { init(); } } /** * Check whether the file has changed since the last time it has been loaded. * * <p><strong>Warning:</strong> With enforcing SELinux, this call might be quite expensive. */ public synchronized boolean hasFileChanged() { try { FileResult result = SELinuxHelper.getAppDataFileService().statFile(mFilename); return mLastModified != result.mtime || mFileSize != result.size; } catch (FileNotFoundException ignored) { // SharedPreferencesImpl doesn't log anything in case the file doesn't exist return true; } catch (IOException e) { Log.w(TAG, "hasFileChanged", e); return true; } } private void awaitLoadedLocked() { while (!mLoaded) { try { wait(); } catch (InterruptedException unused) { } } } /** * @hide */ @Override public Map<String, ?> getAll() { synchronized (this) { awaitLoadedLocked(); return new HashMap<>(mMap); } } /** * @hide */ @Override public String getString(String key, String defValue) { synchronized (this) { awaitLoadedLocked(); String v = (String) mMap.get(key); return v != null ? v : defValue; } } /** * @hide */ @Override @SuppressWarnings("unchecked") public Set<String> getStringSet(String key, Set<String> defValues) { synchronized (this) { awaitLoadedLocked(); Set<String> v = (Set<String>) mMap.get(key); return v != null ? v : defValues; } } /** * @hide */ @Override public int getInt(String key, int defValue) { synchronized (this) { awaitLoadedLocked(); Integer v = (Integer) mMap.get(key); return v != null ? v : defValue; } } /** * @hide */ @Override public long getLong(String key, long defValue) { synchronized (this) { awaitLoadedLocked(); Long v = (Long) mMap.get(key); return v != null ? v : defValue; } } /** * @hide */ @Override public float getFloat(String key, float defValue) { synchronized (this) { awaitLoadedLocked(); Float v = (Float) mMap.get(key); return v != null ? v : defValue; } } /** * @hide */ @Override public boolean getBoolean(String key, boolean defValue) { synchronized (this) { awaitLoadedLocked(); Boolean v = (Boolean) mMap.get(key); return v != null ? v : defValue; } } /** * @hide */ @Override public boolean contains(String key) { synchronized (this) { awaitLoadedLocked(); return mMap.containsKey(key); } } /** * @deprecated Not supported by this implementation. */ @Deprecated @Override public Editor edit() { throw new UnsupportedOperationException("read-only implementation"); } /** * Registers a callback to be invoked when a change happens to a preference file.<br> * Note that it is not possible to determine which preference changed exactly and thus * preference key in callback invocation will always be null. * * @param listener The callback that will run. * @see #unregisterOnSharedPreferenceChangeListener */ @Override public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { if (listener == null) throw new IllegalArgumentException("listener cannot be null"); synchronized(this) { if (mListeners.put(listener, sContent) == null) { tryRegisterWatcher(); } } } /** * Unregisters a previous callback. * * @param listener The callback that should be unregistered. * @see #registerOnSharedPreferenceChangeListener */ @Override public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { synchronized(this) { if (mListeners.remove(listener) != null && mListeners.isEmpty()) { tryUnregisterWatcher(); } } } private static class PrefsData { public final XSharedPreferences mPrefs; private long mSize; private byte[] mHash; public PrefsData(XSharedPreferences prefs) { mPrefs = prefs; mSize = tryGetFileSize(prefs.mFilename); mHash = tryGetFileHash(prefs.mFilename); } public boolean hasChanged() { long size = tryGetFileSize(mPrefs.mFilename); if (size < 1) { if (BuildConfig.DEBUG) Log.d(TAG, "Ignoring empty prefs file"); return false; } if (size != mSize) { mSize = size; mHash = tryGetFileHash(mPrefs.mFilename); if (BuildConfig.DEBUG) Log.d(TAG, "Prefs file size changed"); return true; } byte[] hash = tryGetFileHash(mPrefs.mFilename); if (!Arrays.equals(hash, mHash)) { mHash = hash; if (BuildConfig.DEBUG) Log.d(TAG, "Prefs file hash changed"); return true; } if (BuildConfig.DEBUG) Log.d(TAG, "Prefs file not changed"); return false; } } }
ElderDrivers/EdXposed
xposed-bridge/src/main/java/de/robv/android/xposed/XSharedPreferences.java
5,208
/** * @hide */
block_comment
nl
package de.robv.android.xposed; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; import android.preference.PreferenceManager; import android.util.Log; import com.android.internal.util.XmlUtils; import com.elderdrivers.riru.edxp.bridge.BuildConfig; import com.elderdrivers.riru.edxp.util.MetaDataReader; import org.xmlpull.v1.XmlPullParserException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.AccessDeniedException; import java.nio.file.ClosedWatchServiceException; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.security.MessageDigest; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import de.robv.android.xposed.services.FileResult; /** * This class is basically the same as SharedPreferencesImpl from AOSP, but * read-only and without listeners support. Instead, it is made to be * compatible with all ROMs. */ public final class XSharedPreferences implements SharedPreferences { private static final String TAG = "XSharedPreferences"; private static final HashMap<WatchKey, PrefsData> sWatcherKeyInstances = new HashMap<>(); private static final Object sContent = new Object(); private static Thread sWatcherDaemon = null; private static WatchService sWatcher; private final HashMap<OnSharedPreferenceChangeListener, Object> mListeners = new HashMap<>(); private final File mFile; private final String mFilename; private Map<String, Object> mMap; private boolean mLoaded = false; private long mLastModified; private long mFileSize; private WatchKey mWatchKey; private static void initWatcherDaemon() { sWatcherDaemon = new Thread() { @Override public void run() { if (BuildConfig.DEBUG) Log.d(TAG, "Watcher daemon thread started"); while (true) { WatchKey key; try { key = sWatcher.take(); } catch (ClosedWatchServiceException ignored) { if (BuildConfig.DEBUG) Log.d(TAG, "Watcher daemon thread finished"); sWatcher = null; return; } catch (InterruptedException ignored) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } Path dir = (Path) key.watchable(); Path path = dir.resolve((Path) event.context()); String pathStr = path.toString(); if (BuildConfig.DEBUG) Log.v(TAG, "File " + path.toString() + " event: " + kind.name()); // We react to both real and backup files due to rare race conditions if (pathStr.endsWith(".bak")) { if (kind != StandardWatchEventKinds.ENTRY_DELETE) { continue; } } else if (SELinuxHelper.getAppDataFileService().checkFileExists(pathStr + ".bak")) { continue; } PrefsData data = sWatcherKeyInstances.get(key); if (data != null && data.hasChanged()) { for (OnSharedPreferenceChangeListener l : data.mPrefs.mListeners.keySet()) { try { l.onSharedPreferenceChanged(data.mPrefs, null); } catch (Throwable t) { if (BuildConfig.DEBUG) Log.e(TAG, "Fail in preference change listener", t); } } } } key.reset(); } } }; sWatcherDaemon.setName(TAG + "-Daemon"); sWatcherDaemon.setDaemon(true); sWatcherDaemon.start(); } /** * Read settings from the specified file. * * @param prefFile The file to read the preferences from. */ public XSharedPreferences(File prefFile) { mFile = prefFile; mFilename = prefFile.getAbsolutePath(); init(); } /** * Read settings from the default preferences for a package. * These preferences are returned by {@link PreferenceManager#getDefaultSharedPreferences}. * * @param packageName The package name. */ public XSharedPreferences(String packageName) { this(packageName, packageName + "_preferences"); } /** * Read settings from a custom preferences file for a package. * These preferences are returned by {@link Context#getSharedPreferences(String, int)}. * * @param packageName The package name. * @param prefFileName The file name without ".xml". */ public XSharedPreferences(String packageName, String prefFileName) { boolean newModule = false; Set<String> modules = XposedInit.getLoadedModules(); for (String m : modules) { if (m.contains("/" + packageName + "-")) { boolean isModule = false; int xposedminversion = -1; boolean xposedsharedprefs = false; try { Map<String, Object> metaData = MetaDataReader.getMetaData(new File(m)); isModule = metaData.containsKey("xposedmodule"); if (isModule) { Object minVersionRaw = metaData.get("xposedminversion"); if (minVersionRaw instanceof Integer) { xposedminversion = (Integer) minVersionRaw; } else if (minVersionRaw instanceof String) { xposedminversion = MetaDataReader.extractIntPart((String) minVersionRaw); } xposedsharedprefs = metaData.containsKey("xposedsharedprefs"); } } catch (NumberFormatException | IOException e) { Log.w(TAG, "Apk parser fails: " + e); } newModule = isModule && (xposedminversion > 92 || xposedsharedprefs); } } if (newModule && XposedInit.prefsBasePath != null) { mFile = new File(XposedInit.prefsBasePath, packageName + "/" + prefFileName + ".xml"); } else { mFile = new File(Environment.getDataDirectory(), "data/" + packageName + "/shared_prefs/" + prefFileName + ".xml"); } mFilename = mFile.getAbsolutePath(); init(); } private void tryRegisterWatcher() { if (mWatchKey != null && mWatchKey.isValid()) { return; } synchronized (sWatcherKeyInstances) { Path path = mFile.toPath(); try { if (sWatcher == null) { sWatcher = new File(XposedInit.prefsBasePath).toPath().getFileSystem().newWatchService(); if (BuildConfig.DEBUG) Log.d(TAG, "Created WatchService instance"); } mWatchKey = path.getParent().register(sWatcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); sWatcherKeyInstances.put(mWatchKey, new PrefsData(this)); if (sWatcherDaemon == null || !sWatcherDaemon.isAlive()) { initWatcherDaemon(); } if (BuildConfig.DEBUG) Log.d(TAG, "tryRegisterWatcher: registered file watcher for " + path); } catch (AccessDeniedException accDeniedEx) { if (BuildConfig.DEBUG) Log.e(TAG, "tryRegisterWatcher: access denied to " + path); } catch (Exception e) { Log.e(TAG, "tryRegisterWatcher: failed to register file watcher", e); } } } private void tryUnregisterWatcher() { synchronized (sWatcherKeyInstances) { if (mWatchKey != null) { sWatcherKeyInstances.remove(mWatchKey); mWatchKey.cancel(); mWatchKey = null; } boolean atLeastOneValid = false; for (WatchKey key : sWatcherKeyInstances.keySet()) { atLeastOneValid |= key.isValid(); } if (!atLeastOneValid) { try { sWatcher.close(); } catch (Exception ignore) { } } } } private void init() { startLoadFromDisk(); } private static long tryGetFileSize(String filename) { try { return SELinuxHelper.getAppDataFileService().getFileSize(filename); } catch (IOException ignored) { return 0; } } private static byte[] tryGetFileHash(String filename) { try { MessageDigest md = MessageDigest.getInstance("MD5"); try (InputStream is = SELinuxHelper.getAppDataFileService().getFileInputStream(filename)) { byte[] buf = new byte[4096]; int read; while ((read = is.read(buf)) != -1) { md.update(buf, 0, read); } } return md.digest(); } catch (Exception ignored) { return new byte[0]; } } /** * Tries to make the preferences file world-readable. * * <p><strong>Warning:</strong> This is only meant to work around permission "fix" functions that are part * of some recoveries. It doesn't replace the need to open preferences with {@code MODE_WORLD_READABLE} * in the module's UI code. Otherwise, Android will set stricter permissions again during the next save. * * <p>This will only work if executed as root (e.g. {@code initZygote()}) and only if SELinux is disabled. * * @return {@code true} in case the file could be made world-readable. */ @SuppressLint("SetWorldReadable") public boolean makeWorldReadable() { if (!SELinuxHelper.getAppDataFileService().hasDirectFileAccess()) return false; // It doesn't make much sense to make the file readable if we wouldn't be able to access it anyway. if (!mFile.exists()) // Just in case - the file should never be created if it doesn't exist. return false; if (!mFile.setReadable(true, false)) return false; // Watcher service needs read access to parent directory (looks like execute is not enough) if (mFile.getParentFile() != null) { mFile.getParentFile().setReadable(true, false); } if (mListeners.size() > 0) { tryRegisterWatcher(); } return true; } /** * Returns the file that is backing these preferences. * * <p><strong>Warning:</strong> The file might not be accessible directly. */ public File getFile() { return mFile; } private void startLoadFromDisk() { synchronized (this) { mLoaded = false; } new Thread("XSharedPreferences-load") { @Override public void run() { synchronized (XSharedPreferences.this) { loadFromDiskLocked(); } } }.start(); } @SuppressWarnings({"rawtypes", "unchecked"}) private void loadFromDiskLocked() { if (mLoaded) { return; } Map map = null; FileResult result = null; try { result = SELinuxHelper.getAppDataFileService().getFileInputStream(mFilename, mFileSize, mLastModified); if (result.stream != null) { map = XmlUtils.readMapXml(result.stream); result.stream.close(); } else { // The file is unchanged, keep the current values map = mMap; } } catch (XmlPullParserException e) { Log.w(TAG, "getSharedPreferences failed for: " + mFilename, e); } catch (FileNotFoundException ignored) { // SharedPreferencesImpl has a canRead() check, so it doesn't log anything in case the file doesn't exist } catch (IOException e) { Log.w(TAG, "getSharedPreferences failed for: " + mFilename, e); } finally { if (result != null && result.stream != null) { try { result.stream.close(); } catch (RuntimeException rethrown) { throw rethrown; } catch (Exception ignored) { } } } mLoaded = true; if (map != null) { mMap = map; mLastModified = result.mtime; mFileSize = result.size; } else { mMap = new HashMap<>(); } notifyAll(); } /** * Reload the settings from file if they have changed. * * <p><strong>Warning:</strong> With enforcing SELinux, this call might be quite expensive. */ public synchronized void reload() { if (hasFileChanged()) { init(); } } /** * Check whether the file has changed since the last time it has been loaded. * * <p><strong>Warning:</strong> With enforcing SELinux, this call might be quite expensive. */ public synchronized boolean hasFileChanged() { try { FileResult result = SELinuxHelper.getAppDataFileService().statFile(mFilename); return mLastModified != result.mtime || mFileSize != result.size; } catch (FileNotFoundException ignored) { // SharedPreferencesImpl doesn't log anything in case the file doesn't exist return true; } catch (IOException e) { Log.w(TAG, "hasFileChanged", e); return true; } } private void awaitLoadedLocked() { while (!mLoaded) { try { wait(); } catch (InterruptedException unused) { } } } /** * @hide <SUF>*/ @Override public Map<String, ?> getAll() { synchronized (this) { awaitLoadedLocked(); return new HashMap<>(mMap); } } /** * @hide */ @Override public String getString(String key, String defValue) { synchronized (this) { awaitLoadedLocked(); String v = (String) mMap.get(key); return v != null ? v : defValue; } } /** * @hide */ @Override @SuppressWarnings("unchecked") public Set<String> getStringSet(String key, Set<String> defValues) { synchronized (this) { awaitLoadedLocked(); Set<String> v = (Set<String>) mMap.get(key); return v != null ? v : defValues; } } /** * @hide */ @Override public int getInt(String key, int defValue) { synchronized (this) { awaitLoadedLocked(); Integer v = (Integer) mMap.get(key); return v != null ? v : defValue; } } /** * @hide */ @Override public long getLong(String key, long defValue) { synchronized (this) { awaitLoadedLocked(); Long v = (Long) mMap.get(key); return v != null ? v : defValue; } } /** * @hide */ @Override public float getFloat(String key, float defValue) { synchronized (this) { awaitLoadedLocked(); Float v = (Float) mMap.get(key); return v != null ? v : defValue; } } /** * @hide */ @Override public boolean getBoolean(String key, boolean defValue) { synchronized (this) { awaitLoadedLocked(); Boolean v = (Boolean) mMap.get(key); return v != null ? v : defValue; } } /** * @hide */ @Override public boolean contains(String key) { synchronized (this) { awaitLoadedLocked(); return mMap.containsKey(key); } } /** * @deprecated Not supported by this implementation. */ @Deprecated @Override public Editor edit() { throw new UnsupportedOperationException("read-only implementation"); } /** * Registers a callback to be invoked when a change happens to a preference file.<br> * Note that it is not possible to determine which preference changed exactly and thus * preference key in callback invocation will always be null. * * @param listener The callback that will run. * @see #unregisterOnSharedPreferenceChangeListener */ @Override public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { if (listener == null) throw new IllegalArgumentException("listener cannot be null"); synchronized(this) { if (mListeners.put(listener, sContent) == null) { tryRegisterWatcher(); } } } /** * Unregisters a previous callback. * * @param listener The callback that should be unregistered. * @see #registerOnSharedPreferenceChangeListener */ @Override public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { synchronized(this) { if (mListeners.remove(listener) != null && mListeners.isEmpty()) { tryUnregisterWatcher(); } } } private static class PrefsData { public final XSharedPreferences mPrefs; private long mSize; private byte[] mHash; public PrefsData(XSharedPreferences prefs) { mPrefs = prefs; mSize = tryGetFileSize(prefs.mFilename); mHash = tryGetFileHash(prefs.mFilename); } public boolean hasChanged() { long size = tryGetFileSize(mPrefs.mFilename); if (size < 1) { if (BuildConfig.DEBUG) Log.d(TAG, "Ignoring empty prefs file"); return false; } if (size != mSize) { mSize = size; mHash = tryGetFileHash(mPrefs.mFilename); if (BuildConfig.DEBUG) Log.d(TAG, "Prefs file size changed"); return true; } byte[] hash = tryGetFileHash(mPrefs.mFilename); if (!Arrays.equals(hash, mHash)) { mHash = hash; if (BuildConfig.DEBUG) Log.d(TAG, "Prefs file hash changed"); return true; } if (BuildConfig.DEBUG) Log.d(TAG, "Prefs file not changed"); return false; } } }
92309_5
package lolstats.eldin.com.lolstats; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import com.robrua.orianna.api.core.RiotAPI; import com.robrua.orianna.api.dto.BaseRiotAPI; import com.robrua.orianna.type.core.common.Region; import com.robrua.orianna.type.dto.currentgame.Mastery; import com.robrua.orianna.type.dto.currentgame.Participant; import com.robrua.orianna.type.dto.currentgame.Rune; import com.robrua.orianna.type.dto.league.League; import com.robrua.orianna.type.dto.staticdata.BasicDataStats; import com.robrua.orianna.type.dto.staticdata.Champion; import com.robrua.orianna.type.dto.staticdata.ChampionList; import com.robrua.orianna.type.dto.staticdata.MasteryList; import com.robrua.orianna.type.dto.staticdata.RuneList; import com.robrua.orianna.type.dto.staticdata.SummonerSpellList; import com.robrua.orianna.type.dto.stats.ChampionStats; import com.robrua.orianna.type.dto.summoner.Summoner; import com.robrua.orianna.type.exception.APIException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Eldin on 18-5-2015. */ public class currentMatch extends AsyncTask<Void, Void, Void>{ static String sName; String userName; ArrayList<String> Summoners = new ArrayList<>(); ArrayList<String> Champpicks = new ArrayList<>(); ArrayList<String> Divs = new ArrayList<>(); ArrayList<Long> SummonerSpell1 = new ArrayList<>(); ArrayList<Long> SummonerSpell2 = new ArrayList<>(); ArrayList<String> SummonerKills = new ArrayList<>(); ArrayList<String> SummonerDeaths = new ArrayList<>(); ArrayList<String> SummonerAssists = new ArrayList<>(); Double blueKans; String[] sortedChamps; public boolean sFound; ProgressDialog p; Activity mActivity; int blueScore = 0; int redScore = 0; Activity o; public currentMatch(Activity activity){ mActivity = activity; } @Override protected void onPreExecute(){ p = ProgressDialog.show(mActivity, "Loading", "Retrieving and calculating data..", true); } @Override protected Void doInBackground(Void... params) { try { BaseRiotAPI.setMirror(Region.NA); BaseRiotAPI.setRegion(Region.NA); BaseRiotAPI.setAPIKey("ebe43318-cee4-4d2a-bf19-1c195a32aa93"); // Zoekt de summoner op stopt hem in een map Map<String, com.robrua.orianna.type.dto.summoner.Summoner> summoners = BaseRiotAPI.getSummonersByName(sName); // zorgt ervoor dat de key lowercase is en geen spaties meer bevat String lCase = sName.toLowerCase(); String sumName = lCase.replaceAll("\\s+", ""); // hier haalt die hem eruit met de key com.robrua.orianna.type.dto.summoner.Summoner summoner = summoners.get(sumName); // pakt de summoner id en naam userName = summoner.getName(); long sd = summoner.getId(); // doet de server request naar riot en haalt alle static data op van runes. RuneList runes = BaseRiotAPI.getRunes(); // stopt de runes in een lijst List<com.robrua.orianna.type.dto.staticdata.Rune> runess = new ArrayList<>(runes.getData().values()); // server call riot, static data masteries MasteryList masteryList = BaseRiotAPI.getMasteries(); // list mastery enzo List<com.robrua.orianna.type.dto.staticdata.Mastery> masteryArray = new ArrayList<>(masteryList.getData().values()); ChampionList champs = BaseRiotAPI.getChampions(); Champion testchampname = BaseRiotAPI.getChampion(89); String test = testchampname.getName(); List<Champion> champions = new ArrayList<>(champs.getData().values()); String[] nrOfChamps = new String[champions.size()]; Log.d("Test champid", champions.get(79).getName() + " " + nrOfChamps.length + "."); Log.d("Test title", champions.get(79).getTitle() + "."); Log.d("Test key", champions.get(79).getKey() + "."); Log.d("Test spell", champions.get(79).getSpells() + "."); for(int x = 0; x < nrOfChamps.length; x++){ nrOfChamps [x] = champions.get(x).getName(); if(x == nrOfChamps.length - 1){ Arrays.sort(nrOfChamps); sortedChamps = nrOfChamps; } } Log.d("Array sorted ", Arrays.toString(sortedChamps)); List<Participant> p = BaseRiotAPI.getCurrentGame(sd).getParticipants(); List<ChampionStats> r = BaseRiotAPI.getRankedStats(sd).getChampions(); for (int i = 0; i < p.size(); i++) { long b = 0; String pName = p.get(i).getSummonerName(); long champ = p.get(i).getChampionId(); long team = p.get(i).getTeamId(); b = champ; Champion champy = BaseRiotAPI.getChampion(b); String chosenchamp = champy.getName(); long pId = p.get(i).getSummonerId(); long sums1 = p.get(i).getSpell1Id(); long sums2 = p.get(i).getSpell2Id(); Summoners.add(pName); Champpicks.add(chosenchamp); SummonerSpell1.add(sums1); SummonerSpell2.add(sums2); int games = r.get(i).getStats().getTotalSessionsPlayed(); int kills = r.get(i).getStats().getTotalChampionKills(); int deaths = r.get(i).getStats().getTotalDeathsPerSession(); int assists = r.get(i).getStats().getTotalAssists(); String avgKills = kda(games, kills); String avgDeaths = kda(games, deaths); String avgAssists = kda(games, assists); SummonerKills.add(avgKills); SummonerDeaths.add(avgDeaths); SummonerAssists.add(avgAssists); String div = null; try { Map<Long, List<League>> league = BaseRiotAPI.getSummonerLeagueEntries(pId); div = league.get(pId).get(0).getTier() + " " + league.get(pId).get(0).getEntries().get(0).getDivision(); } catch (APIException e) { div = "unranked"; } Divs.add(div); if (team == 100) { blueScore += (int)getdMap(div); Log.d("Blue team", pName + " as " + chosenchamp + " " + div + " "+ sums1 + " " + sums2 + " " + getdMap(div) + blueScore + " " + games + " "+ avgKills + " "+ avgDeaths + " " + avgAssists); } else { Log.d("Red team", pName + " as " + chosenchamp + " " + div + " "+ sums1 + " " + sums2 + " " + getdMap(div) + redScore); redScore += (int)getdMap(div); } } blueKans = kans(blueScore, redScore); sFound = true; }catch (APIException e){ sFound = false; Log.d("apiex","apiex"); } catch (NullPointerException e){ sFound = false; Log.d("nullex","nullex"); } return null; } @Override protected void onPostExecute(Void unused){ p.dismiss(); if (sFound){ super.onPostExecute(unused); Intent intent = new Intent(mActivity, currentMatchPage.class); intent.putExtra("name", sName); intent.putStringArrayListExtra("SummonerNames", Summoners); intent.putStringArrayListExtra("Picks", Champpicks); intent.putStringArrayListExtra("Divisions", Divs); intent.putStringArrayListExtra("Kills", SummonerKills); intent.putStringArrayListExtra("Deaths", SummonerDeaths); intent.putStringArrayListExtra("Assists", SummonerAssists); intent.putExtra("blueKans", blueKans); intent.putExtra("Summoner1Div", Divs.get(0)); intent.putExtra("Summoner2Div",Divs.get(1)); intent.putExtra("Summoner3Div",Divs.get(2)); intent.putExtra("Summoner4Div",Divs.get(3)); intent.putExtra("Summoner5Div",Divs.get(4)); intent.putExtra("Summoner6Div",Divs.get(5)); intent.putExtra("Summoner7Div",Divs.get(6)); intent.putExtra("Summoner8Div",Divs.get(7)); intent.putExtra("Summoner9Div",Divs.get(8)); intent.putExtra("Summoner10Div",Divs.get(9)); intent.putExtra("Summoner1Spell1", SummonerSpell1.get(0)); intent.putExtra("Summoner1Spell2", SummonerSpell2.get(0)); intent.putExtra("Summoner2Spell1", SummonerSpell1.get(1)); intent.putExtra("Summoner2Spell2", SummonerSpell2.get(1)); intent.putExtra("Summoner3Spell1", SummonerSpell1.get(2)); intent.putExtra("Summoner3Spell2", SummonerSpell2.get(2)); intent.putExtra("Summoner4Spell1", SummonerSpell1.get(3)); intent.putExtra("Summoner4Spell2", SummonerSpell2.get(3)); intent.putExtra("Summoner5Spell1", SummonerSpell1.get(4)); intent.putExtra("Summoner5Spell2", SummonerSpell2.get(4)); intent.putExtra("Summoner6Spell1", SummonerSpell1.get(5)); intent.putExtra("Summoner6Spell2", SummonerSpell2.get(5)); intent.putExtra("Summoner7Spell1", SummonerSpell1.get(6)); intent.putExtra("Summoner7Spell2", SummonerSpell2.get(6)); intent.putExtra("Summoner8Spell1", SummonerSpell1.get(7)); intent.putExtra("Summoner8Spell2", SummonerSpell2.get(7)); intent.putExtra("Summoner9Spell1", SummonerSpell1.get(8)); intent.putExtra("Summoner9Spell2", SummonerSpell2.get(8)); intent.putExtra("Summoner10Spell1", SummonerSpell1.get(9)); intent.putExtra("Summoner10Spell2", SummonerSpell2.get(9)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mActivity.startActivity(intent); } else { AlertDialog.Builder builder1 = new AlertDialog.Builder(mActivity); builder1.setMessage("Summoner not in game."); builder1.setCancelable(true); builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); final AlertDialog alert11 = builder1.create(); alert11.show(); } } public Object getdMap(String div){ HashMap dMap = new HashMap<String, Integer>(); dMap.put("BRONZE V", 0); dMap.put("BRONZE IV", 1); dMap.put("BRONZE III", 2); dMap.put("BRONZE II", 3); dMap.put("BRONZE I", 4); dMap.put("SILVER V", 6); dMap.put("SILVER IV", 8); dMap.put("SILVER III", 10); dMap.put("SILVER II", 12); dMap.put("SILVER I", 14); dMap.put("GOLD V", 17); dMap.put("GOLD IV", 20); dMap.put("GOLD III", 23); dMap.put("GOLD II", 26); dMap.put("GOLD I", 29); dMap.put("PLATINUM V", 33); dMap.put("PLATINUM IV", 37); dMap.put("PLATINUM III", 41); dMap.put("PLATINUM II", 45); dMap.put("PLATINUM I", 49); dMap.put("DIAMOND V", 54); dMap.put("DIAMOND IV", 59); dMap.put("DIAMOND III", 64); dMap.put("DIAMOND II", 69); dMap.put("DIAMOND I", 74); dMap.put("MASTER I", 80); dMap.put("CHALLENGER 1", 90); dMap.put("unranked", 34); return dMap.get(div); } public double kans(int a, int b){ double diff; diff = a - b; diff = diff * 1.5; return 50 + diff; } public String kda(int games, int data){ String x; try{ x = data / games + ""; } catch (Exception e){ x = "0"; } return x; } }
Eldin61/LoLStats
app/src/main/java/lolstats/eldin/com/lolstats/currentMatch.java
4,169
// doet de server request naar riot en haalt alle static data op van runes.
line_comment
nl
package lolstats.eldin.com.lolstats; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import com.robrua.orianna.api.core.RiotAPI; import com.robrua.orianna.api.dto.BaseRiotAPI; import com.robrua.orianna.type.core.common.Region; import com.robrua.orianna.type.dto.currentgame.Mastery; import com.robrua.orianna.type.dto.currentgame.Participant; import com.robrua.orianna.type.dto.currentgame.Rune; import com.robrua.orianna.type.dto.league.League; import com.robrua.orianna.type.dto.staticdata.BasicDataStats; import com.robrua.orianna.type.dto.staticdata.Champion; import com.robrua.orianna.type.dto.staticdata.ChampionList; import com.robrua.orianna.type.dto.staticdata.MasteryList; import com.robrua.orianna.type.dto.staticdata.RuneList; import com.robrua.orianna.type.dto.staticdata.SummonerSpellList; import com.robrua.orianna.type.dto.stats.ChampionStats; import com.robrua.orianna.type.dto.summoner.Summoner; import com.robrua.orianna.type.exception.APIException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Eldin on 18-5-2015. */ public class currentMatch extends AsyncTask<Void, Void, Void>{ static String sName; String userName; ArrayList<String> Summoners = new ArrayList<>(); ArrayList<String> Champpicks = new ArrayList<>(); ArrayList<String> Divs = new ArrayList<>(); ArrayList<Long> SummonerSpell1 = new ArrayList<>(); ArrayList<Long> SummonerSpell2 = new ArrayList<>(); ArrayList<String> SummonerKills = new ArrayList<>(); ArrayList<String> SummonerDeaths = new ArrayList<>(); ArrayList<String> SummonerAssists = new ArrayList<>(); Double blueKans; String[] sortedChamps; public boolean sFound; ProgressDialog p; Activity mActivity; int blueScore = 0; int redScore = 0; Activity o; public currentMatch(Activity activity){ mActivity = activity; } @Override protected void onPreExecute(){ p = ProgressDialog.show(mActivity, "Loading", "Retrieving and calculating data..", true); } @Override protected Void doInBackground(Void... params) { try { BaseRiotAPI.setMirror(Region.NA); BaseRiotAPI.setRegion(Region.NA); BaseRiotAPI.setAPIKey("ebe43318-cee4-4d2a-bf19-1c195a32aa93"); // Zoekt de summoner op stopt hem in een map Map<String, com.robrua.orianna.type.dto.summoner.Summoner> summoners = BaseRiotAPI.getSummonersByName(sName); // zorgt ervoor dat de key lowercase is en geen spaties meer bevat String lCase = sName.toLowerCase(); String sumName = lCase.replaceAll("\\s+", ""); // hier haalt die hem eruit met de key com.robrua.orianna.type.dto.summoner.Summoner summoner = summoners.get(sumName); // pakt de summoner id en naam userName = summoner.getName(); long sd = summoner.getId(); // doet de<SUF> RuneList runes = BaseRiotAPI.getRunes(); // stopt de runes in een lijst List<com.robrua.orianna.type.dto.staticdata.Rune> runess = new ArrayList<>(runes.getData().values()); // server call riot, static data masteries MasteryList masteryList = BaseRiotAPI.getMasteries(); // list mastery enzo List<com.robrua.orianna.type.dto.staticdata.Mastery> masteryArray = new ArrayList<>(masteryList.getData().values()); ChampionList champs = BaseRiotAPI.getChampions(); Champion testchampname = BaseRiotAPI.getChampion(89); String test = testchampname.getName(); List<Champion> champions = new ArrayList<>(champs.getData().values()); String[] nrOfChamps = new String[champions.size()]; Log.d("Test champid", champions.get(79).getName() + " " + nrOfChamps.length + "."); Log.d("Test title", champions.get(79).getTitle() + "."); Log.d("Test key", champions.get(79).getKey() + "."); Log.d("Test spell", champions.get(79).getSpells() + "."); for(int x = 0; x < nrOfChamps.length; x++){ nrOfChamps [x] = champions.get(x).getName(); if(x == nrOfChamps.length - 1){ Arrays.sort(nrOfChamps); sortedChamps = nrOfChamps; } } Log.d("Array sorted ", Arrays.toString(sortedChamps)); List<Participant> p = BaseRiotAPI.getCurrentGame(sd).getParticipants(); List<ChampionStats> r = BaseRiotAPI.getRankedStats(sd).getChampions(); for (int i = 0; i < p.size(); i++) { long b = 0; String pName = p.get(i).getSummonerName(); long champ = p.get(i).getChampionId(); long team = p.get(i).getTeamId(); b = champ; Champion champy = BaseRiotAPI.getChampion(b); String chosenchamp = champy.getName(); long pId = p.get(i).getSummonerId(); long sums1 = p.get(i).getSpell1Id(); long sums2 = p.get(i).getSpell2Id(); Summoners.add(pName); Champpicks.add(chosenchamp); SummonerSpell1.add(sums1); SummonerSpell2.add(sums2); int games = r.get(i).getStats().getTotalSessionsPlayed(); int kills = r.get(i).getStats().getTotalChampionKills(); int deaths = r.get(i).getStats().getTotalDeathsPerSession(); int assists = r.get(i).getStats().getTotalAssists(); String avgKills = kda(games, kills); String avgDeaths = kda(games, deaths); String avgAssists = kda(games, assists); SummonerKills.add(avgKills); SummonerDeaths.add(avgDeaths); SummonerAssists.add(avgAssists); String div = null; try { Map<Long, List<League>> league = BaseRiotAPI.getSummonerLeagueEntries(pId); div = league.get(pId).get(0).getTier() + " " + league.get(pId).get(0).getEntries().get(0).getDivision(); } catch (APIException e) { div = "unranked"; } Divs.add(div); if (team == 100) { blueScore += (int)getdMap(div); Log.d("Blue team", pName + " as " + chosenchamp + " " + div + " "+ sums1 + " " + sums2 + " " + getdMap(div) + blueScore + " " + games + " "+ avgKills + " "+ avgDeaths + " " + avgAssists); } else { Log.d("Red team", pName + " as " + chosenchamp + " " + div + " "+ sums1 + " " + sums2 + " " + getdMap(div) + redScore); redScore += (int)getdMap(div); } } blueKans = kans(blueScore, redScore); sFound = true; }catch (APIException e){ sFound = false; Log.d("apiex","apiex"); } catch (NullPointerException e){ sFound = false; Log.d("nullex","nullex"); } return null; } @Override protected void onPostExecute(Void unused){ p.dismiss(); if (sFound){ super.onPostExecute(unused); Intent intent = new Intent(mActivity, currentMatchPage.class); intent.putExtra("name", sName); intent.putStringArrayListExtra("SummonerNames", Summoners); intent.putStringArrayListExtra("Picks", Champpicks); intent.putStringArrayListExtra("Divisions", Divs); intent.putStringArrayListExtra("Kills", SummonerKills); intent.putStringArrayListExtra("Deaths", SummonerDeaths); intent.putStringArrayListExtra("Assists", SummonerAssists); intent.putExtra("blueKans", blueKans); intent.putExtra("Summoner1Div", Divs.get(0)); intent.putExtra("Summoner2Div",Divs.get(1)); intent.putExtra("Summoner3Div",Divs.get(2)); intent.putExtra("Summoner4Div",Divs.get(3)); intent.putExtra("Summoner5Div",Divs.get(4)); intent.putExtra("Summoner6Div",Divs.get(5)); intent.putExtra("Summoner7Div",Divs.get(6)); intent.putExtra("Summoner8Div",Divs.get(7)); intent.putExtra("Summoner9Div",Divs.get(8)); intent.putExtra("Summoner10Div",Divs.get(9)); intent.putExtra("Summoner1Spell1", SummonerSpell1.get(0)); intent.putExtra("Summoner1Spell2", SummonerSpell2.get(0)); intent.putExtra("Summoner2Spell1", SummonerSpell1.get(1)); intent.putExtra("Summoner2Spell2", SummonerSpell2.get(1)); intent.putExtra("Summoner3Spell1", SummonerSpell1.get(2)); intent.putExtra("Summoner3Spell2", SummonerSpell2.get(2)); intent.putExtra("Summoner4Spell1", SummonerSpell1.get(3)); intent.putExtra("Summoner4Spell2", SummonerSpell2.get(3)); intent.putExtra("Summoner5Spell1", SummonerSpell1.get(4)); intent.putExtra("Summoner5Spell2", SummonerSpell2.get(4)); intent.putExtra("Summoner6Spell1", SummonerSpell1.get(5)); intent.putExtra("Summoner6Spell2", SummonerSpell2.get(5)); intent.putExtra("Summoner7Spell1", SummonerSpell1.get(6)); intent.putExtra("Summoner7Spell2", SummonerSpell2.get(6)); intent.putExtra("Summoner8Spell1", SummonerSpell1.get(7)); intent.putExtra("Summoner8Spell2", SummonerSpell2.get(7)); intent.putExtra("Summoner9Spell1", SummonerSpell1.get(8)); intent.putExtra("Summoner9Spell2", SummonerSpell2.get(8)); intent.putExtra("Summoner10Spell1", SummonerSpell1.get(9)); intent.putExtra("Summoner10Spell2", SummonerSpell2.get(9)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mActivity.startActivity(intent); } else { AlertDialog.Builder builder1 = new AlertDialog.Builder(mActivity); builder1.setMessage("Summoner not in game."); builder1.setCancelable(true); builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); final AlertDialog alert11 = builder1.create(); alert11.show(); } } public Object getdMap(String div){ HashMap dMap = new HashMap<String, Integer>(); dMap.put("BRONZE V", 0); dMap.put("BRONZE IV", 1); dMap.put("BRONZE III", 2); dMap.put("BRONZE II", 3); dMap.put("BRONZE I", 4); dMap.put("SILVER V", 6); dMap.put("SILVER IV", 8); dMap.put("SILVER III", 10); dMap.put("SILVER II", 12); dMap.put("SILVER I", 14); dMap.put("GOLD V", 17); dMap.put("GOLD IV", 20); dMap.put("GOLD III", 23); dMap.put("GOLD II", 26); dMap.put("GOLD I", 29); dMap.put("PLATINUM V", 33); dMap.put("PLATINUM IV", 37); dMap.put("PLATINUM III", 41); dMap.put("PLATINUM II", 45); dMap.put("PLATINUM I", 49); dMap.put("DIAMOND V", 54); dMap.put("DIAMOND IV", 59); dMap.put("DIAMOND III", 64); dMap.put("DIAMOND II", 69); dMap.put("DIAMOND I", 74); dMap.put("MASTER I", 80); dMap.put("CHALLENGER 1", 90); dMap.put("unranked", 34); return dMap.get(div); } public double kans(int a, int b){ double diff; diff = a - b; diff = diff * 1.5; return 50 + diff; } public String kda(int games, int data){ String x; try{ x = data / games + ""; } catch (Exception e){ x = "0"; } return x; } }
109767_40
/***************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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. ****************************************************************/ package no.ecc.vectortile; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.locationtech.jts.algorithm.Area; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryCollection; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.LinearRing; import org.locationtech.jts.geom.MultiLineString; import org.locationtech.jts.geom.MultiPoint; import org.locationtech.jts.geom.MultiPolygon; import org.locationtech.jts.geom.Point; import org.locationtech.jts.geom.Polygon; import org.locationtech.jts.geom.TopologyException; import org.locationtech.jts.geom.prep.PreparedGeometry; import org.locationtech.jts.geom.prep.PreparedGeometryFactory; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import org.locationtech.jts.simplify.DouglasPeuckerSimplifier; import org.locationtech.jts.simplify.TopologyPreservingSimplifier; import vector_tile.VectorTile; import vector_tile.VectorTile.Tile.GeomType; public class VectorTileEncoder { private final Map<String, Layer> layers = new LinkedHashMap<String, Layer>(); private final int extent; private final double minimumLength; private final double minimumArea; protected final Geometry clipGeometry; protected final Envelope clipEnvelope; protected final PreparedGeometry clipGeometryPrepared; private final boolean autoScale; private long autoincrement; private final boolean autoincrementIds; private final double simplificationDistanceTolerance; private final GeometryFactory gf = new GeometryFactory(); /** * Create a {@link VectorTileEncoder} with the default extent of 4096 and * clip buffer of 8. */ public VectorTileEncoder() { this(4096, 8, true); } /** * Create a {@link VectorTileEncoder} with the given extent and a clip * buffer of 8. * * @param extent a int to specify vector tile extent. 4096 is a good value. */ public VectorTileEncoder(int extent) { this(extent, 8, true); } public VectorTileEncoder(int extent, int clipBuffer, boolean autoScale) { this(extent, clipBuffer, autoScale, false); } public VectorTileEncoder(int extent, int clipBuffer, boolean autoScale, boolean autoincrementIds) { this(extent, clipBuffer, autoScale, autoincrementIds, -1.0); } /** * Create a {@link VectorTileEncoder} with the given extent value. * <p> * The extent value control how detailed the coordinates are encoded in the * vector tile. 4096 is a good default, 256 can be used to reduce density. * <p> * The clip buffer value control how large the clipping area is outside of the * tile for geometries. 0 means that the clipping is done at the tile border. 8 * is a good default. * * @param extent * a int with extent value. 4096 is a good value. * @param clipBuffer * a int with clip buffer size for geometries. 8 is a good value. * @param autoScale * when true, the encoder expects coordinates in the 0..255 range and * will scale them automatically to the 0..extent-1 range before * encoding. when false, the encoder expects coordinates in the * 0..extent-1 range. * @param autoincrementIds * when true the vector tile feature id is auto incremented when using * {@link #addFeature(String, Map, Geometry)} * @param simplificationDistanceTolerance * a positive double representing the distance tolerance to be used * for non-points before (optional) scaling and encoding. A value * &lt;=0 will prevent simplifying geometry. 0.1 seems to be a good * value when {@code autoScale} is turned on. */ public VectorTileEncoder(int extent, int clipBuffer, boolean autoScale, boolean autoincrementIds, double simplificationDistanceTolerance) { this.extent = extent; this.autoScale = autoScale; this.minimumLength = autoScale ? (256.0 / extent) : 1.0; this.minimumArea = this.minimumLength * this.minimumLength; this.autoincrementIds = autoincrementIds; this.autoincrement = 1; this.simplificationDistanceTolerance = simplificationDistanceTolerance; final int size = autoScale ? 256 : extent; clipGeometry = createTileEnvelope(clipBuffer, size); clipEnvelope = clipGeometry.getEnvelopeInternal(); clipGeometryPrepared = PreparedGeometryFactory.prepare(clipGeometry); } private static Geometry createTileEnvelope(int buffer, int size) { Coordinate[] coords = new Coordinate[5]; coords[0] = new Coordinate(0 - buffer, size + buffer); coords[1] = new Coordinate(size + buffer, size + buffer); coords[2] = new Coordinate(size + buffer, 0 - buffer); coords[3] = new Coordinate(0 - buffer, 0 - buffer); coords[4] = coords[0]; return new GeometryFactory().createPolygon(coords); } public void addFeature(String layerName, Map<String, ?> attributes, Geometry geometry) { this.addFeature(layerName, attributes, geometry, this.autoincrementIds ? this.autoincrement++ : -1); } /** * Add a feature with layer name (typically feature type name), some attributes * and a Geometry. The Geometry must be in "pixel" space 0,0 upper left and * 256,256 lower right. * <p> * For optimization, geometries will be clipped and simplified. Features with * geometries outside of the tile will be skipped. * * @param layerName a {@link String} with the vector tile layer name. * @param attributes a {@link Map} with the vector tile feature attributes. * @param geometry a {@link Geometry} for the vector tile feature. * @param id a long with the vector tile feature id field. */ public void addFeature(String layerName, Map<String, ?> attributes, Geometry geometry, long id) { // skip small Polygon/LineString. if (geometry instanceof MultiPolygon && geometry.getArea() < minimumArea) { return; } if (geometry instanceof Polygon && geometry.getArea() < minimumArea) { return; } if (geometry instanceof LineString && geometry.getLength() < minimumLength) { return; } // special handling of GeometryCollection. subclasses are not handled here. if (geometry.getClass().equals(GeometryCollection.class)) { for (int i = 0; i < geometry.getNumGeometries(); i++) { Geometry subGeometry = geometry.getGeometryN(i); // keeping the id. any better suggestion? addFeature(layerName, attributes, subGeometry, id); } return; } // About to simplify and clip. Looks like simplification before clipping is // faster than clipping before simplification // simplify non-points if (simplificationDistanceTolerance > 0.0 && !(geometry instanceof Point)) { if (geometry instanceof LineString || geometry instanceof MultiLineString) { geometry = DouglasPeuckerSimplifier.simplify(geometry, simplificationDistanceTolerance); } else if (geometry instanceof Polygon || geometry instanceof MultiPolygon) { Geometry simplified = DouglasPeuckerSimplifier.simplify(geometry, simplificationDistanceTolerance); // extra check to prevent polygon converted to line if (simplified instanceof Polygon || simplified instanceof MultiPolygon) { geometry = simplified; } else { geometry = TopologyPreservingSimplifier.simplify(geometry, simplificationDistanceTolerance); } } else { geometry = TopologyPreservingSimplifier.simplify(geometry, simplificationDistanceTolerance); } } // clip geometry if (geometry instanceof Point) { if (!clipCovers(geometry)) { return; } } else { geometry = clipGeometry(geometry); } // no need to add empty geometry if (geometry == null || geometry.isEmpty()) { return; } // extra check for GeometryCollection after clipping as it can cause // GeometryCollection. Subclasses not handled here. if (geometry.getClass().equals(GeometryCollection.class)) { for (int i = 0; i < geometry.getNumGeometries(); i++) { Geometry subGeometry = geometry.getGeometryN(i); // keeping the id. any better suggestion? addFeature(layerName, attributes, subGeometry, id); } return; } Layer layer = layers.get(layerName); if (layer == null) { layer = new Layer(); layers.put(layerName, layer); } Feature feature = new Feature(); feature.geometry = geometry; feature.id = id; this.autoincrement = Math.max(this.autoincrement, id + 1); for (Map.Entry<String, ?> e : attributes.entrySet()) { // skip attribute without value if (e.getValue() == null) { continue; } feature.tags.add(layer.key(e.getKey())); feature.tags.add(layer.value(e.getValue())); } layer.features.add(feature); } /** * A short circuit clip to the tile extent (tile boundary + buffer) for * points to improve performance. This method can be overridden to change * clipping behavior. See also {@link #clipGeometry(Geometry)}. * * @param geom a {@link Geometry} to check for "covers" * @return a boolean true when the current clip geometry covers the given geom. */ protected boolean clipCovers(Geometry geom) { if (geom instanceof Point) { Point p = (Point) geom; return clipGeometry.getEnvelopeInternal().covers(p.getCoordinate()); } return clipEnvelope.covers(geom.getEnvelopeInternal()); } /** * Clip geometry according to buffer given at construct time. This method * can be overridden to change clipping behavior. See also * {@link #clipCovers(Geometry)}. * * @param geometry a {@link Geometry} to check for intersection with the current clip geometry * @return a boolean true when current clip geometry intersects with the given geometry. */ protected Geometry clipGeometry(Geometry geometry) { try { if (clipEnvelope.contains(geometry.getEnvelopeInternal())) { return geometry; } Geometry original = geometry; geometry = clipGeometry.intersection(original); // some times a intersection is returned as an empty geometry. // going via wkt fixes the problem. if (geometry.isEmpty() && clipGeometryPrepared.intersects(original)) { Geometry originalViaWkt = new WKTReader().read(original.toText()); geometry = clipGeometry.intersection(originalViaWkt); } return geometry; } catch (TopologyException e) { // could not intersect. original geometry will be used instead. return geometry; } catch (ParseException e1) { // could not encode/decode WKT. original geometry will be used // instead. return geometry; } } /** * Validate and potentially repair the given {@link List} of commands for the * given {@link Geometry}. Will return a {@link List} of the validated and/or * repaired commands. * <p> * This can be overridden to change behavior. By returning just the incoming * {@link List} of commands instead, the encoding will be faster, but * potentially less safe. * * @param commands * @param geometry * @return */ protected List<Integer> validateAndRepairCommands(List<Integer> commands, Geometry geometry) { if (commands.isEmpty()) { return commands; } GeomType geomType = toGeomType(geometry); if (simplificationDistanceTolerance > 0.0 && geomType == GeomType.POLYGON) { double scale = autoScale ? (extent / 256.0) : 1.0; Geometry decodedGeometry = VectorTileDecoder.decodeGeometry(gf, geomType, commands, scale); if (!isValid(decodedGeometry)) { // Invalid. Try more simplification and without preserving topology. geometry = DouglasPeuckerSimplifier.simplify(geometry, simplificationDistanceTolerance * 2.0); if (geometry.isEmpty()) { Collections.emptyList(); } geomType = toGeomType(geometry); x = 0; y = 0; return commands(geometry); } } return commands; } /** * @return a byte array with the vector tile */ public byte[] encode() { VectorTile.Tile.Builder tile = VectorTile.Tile.newBuilder(); for (Map.Entry<String, Layer> e : layers.entrySet()) { String layerName = e.getKey(); Layer layer = e.getValue(); VectorTile.Tile.Layer.Builder tileLayer = VectorTile.Tile.Layer.newBuilder(); tileLayer.setVersion(2); tileLayer.setName(layerName); tileLayer.addAllKeys(layer.keys()); for (Object value : layer.values()) { VectorTile.Tile.Value.Builder tileValue = VectorTile.Tile.Value.newBuilder(); if (value instanceof String) { tileValue.setStringValue((String) value); } else if (value instanceof Integer) { tileValue.setSintValue(((Integer) value).intValue()); } else if (value instanceof Long) { tileValue.setSintValue(((Long) value).longValue()); } else if (value instanceof Float) { tileValue.setFloatValue(((Float) value).floatValue()); } else if (value instanceof Double) { tileValue.setDoubleValue(((Double) value).doubleValue()); } else if (value instanceof BigDecimal) { tileValue.setStringValue(value.toString()); } else if (value instanceof Number) { tileValue.setDoubleValue(((Number) value).doubleValue()); } else if (value instanceof Boolean) { tileValue.setBoolValue(((Boolean) value).booleanValue()); } else { tileValue.setStringValue(value.toString()); } tileLayer.addValues(tileValue.build()); } tileLayer.setExtent(extent); for (Feature feature : layer.features) { Geometry geometry = feature.geometry; VectorTile.Tile.Feature.Builder featureBuilder = VectorTile.Tile.Feature.newBuilder(); featureBuilder.addAllTags(feature.tags); if (feature.id >= 0) { featureBuilder.setId(feature.id); } GeomType geomType = toGeomType(geometry); x = 0; y = 0; List<Integer> commands = commands(geometry); // Extra step to parse and check validity and try to repair. commands = validateAndRepairCommands(commands, geometry); // skip features with no geometry commands if (commands.isEmpty()) { continue; } featureBuilder.setType(geomType); featureBuilder.addAllGeometry(commands); tileLayer.addFeatures(featureBuilder.build()); } tile.addLayers(tileLayer.build()); } return tile.build().toByteArray(); } private static final boolean isValid(Geometry geometry) { try { return geometry.isValid(); } catch (RuntimeException e) { return false; } } static VectorTile.Tile.GeomType toGeomType(Geometry geometry) { if (geometry instanceof Point) { return VectorTile.Tile.GeomType.POINT; } if (geometry instanceof MultiPoint) { return VectorTile.Tile.GeomType.POINT; } if (geometry instanceof LineString) { return VectorTile.Tile.GeomType.LINESTRING; } if (geometry instanceof MultiLineString) { return VectorTile.Tile.GeomType.LINESTRING; } if (geometry instanceof Polygon) { return VectorTile.Tile.GeomType.POLYGON; } if (geometry instanceof MultiPolygon) { return VectorTile.Tile.GeomType.POLYGON; } return VectorTile.Tile.GeomType.UNKNOWN; } static boolean shouldClosePath(Geometry geometry) { return (geometry instanceof Polygon) || (geometry instanceof LinearRing); } List<Integer> commands(Geometry geometry) { if (geometry instanceof MultiLineString) { return commands((MultiLineString) geometry); } if (geometry instanceof Polygon) { return commands((Polygon) geometry); } if (geometry instanceof MultiPolygon) { return commands((MultiPolygon) geometry); } return commands(geometry.getCoordinates(), shouldClosePath(geometry), geometry instanceof MultiPoint); } List<Integer> commands(MultiLineString mls) { List<Integer> commands = new ArrayList<Integer>(); for (int i = 0; i < mls.getNumGeometries(); i++) { final int oldX = x; final int oldY = y; final List<Integer> geomCommands = commands(mls.getGeometryN(i).getCoordinates(), false); if (geomCommands.size() > 3) { // if the geometry consists of all identical points (after Math.round()) commands // returns a single move_to command, which is not valid according to the vector tile // specifications. // (https://github.com/mapbox/vector-tile-spec/tree/master/2.1#4343-linestring-geometry-type) commands.addAll(geomCommands); } else { // reset x and y to the previous value x = oldX; y = oldY; } } return commands; } List<Integer> commands(MultiPolygon mp) { List<Integer> commands = new ArrayList<Integer>(); for (int i = 0; i < mp.getNumGeometries(); i++) { Polygon polygon = (Polygon) mp.getGeometryN(i); commands.addAll(commands(polygon)); } return commands; } List<Integer> commands(Polygon polygon) { List<Integer> commands = new ArrayList<Integer>(); // According to the vector tile specification, the exterior ring of a polygon // must be in clockwise order, while the interior ring in counter-clockwise order. // In the tile coordinate system, Y axis is positive down. // // However, in geographic coordinate system, Y axis is positive up. // Therefore, we must reverse the coordinates. // So, the code below will make sure that exterior ring is in counter-clockwise order // and interior ring in clockwise order. LineString exteriorRing = polygon.getExteriorRing(); if (Area.ofRingSigned(exteriorRing.getCoordinates()) > 0) { exteriorRing = exteriorRing.reverse(); } commands.addAll(commands(exteriorRing.getCoordinates(), true)); for (int i = 0; i < polygon.getNumInteriorRing(); i++) { LineString interiorRing = polygon.getInteriorRingN(i); if (Area.ofRingSigned(interiorRing.getCoordinates()) < 0) { interiorRing = interiorRing.reverse(); } commands.addAll(commands(interiorRing.getCoordinates(), true)); } return commands; } private int x = 0; private int y = 0; /** * // // // Ex.: MoveTo(3, 6), LineTo(8, 12), LineTo(20, 34), ClosePath // * Encoded as: [ 9 3 6 18 5 6 12 22 15 ] // == command type 7 (ClosePath), * length 1 // ===== relative LineTo(+12, +22) == LineTo(20, 34) // === * relative LineTo(+5, +6) == LineTo(8, 12) // == [00010 010] = command type * 2 (LineTo), length 2 // === relative MoveTo(+3, +6) // == [00001 001] = * command type 1 (MoveTo), length 1 // Commands are encoded as uint32 * varints, vertex parameters are // encoded as sint32 varints (zigzag). * Vertex parameters are // also encoded as deltas to the previous position. * The original // position is (0,0) * * @param cs * @return */ List<Integer> commands(Coordinate[] cs, boolean closePathAtEnd) { return commands(cs, closePathAtEnd, false); } List<Integer> commands(Coordinate[] cs, boolean closePathAtEnd, boolean multiPoint) { if (cs.length == 0) { return Collections.emptyList(); } List<Integer> r = new ArrayList<Integer>(); int lineToIndex = 0; int lineToLength = 0; double scale = autoScale ? (extent / 256.0) : 1.0; for (int i = 0; i < cs.length; i++) { Coordinate c = cs[i]; if (i == 0) { r.add(commandAndLength(Command.MoveTo, multiPoint ? cs.length : 1)); } int _x = (int) Math.round(c.x * scale); int _y = (int) Math.round(c.y * scale); // prevent point equal to the previous if (i > 0 && _x == x && _y == y) { lineToLength--; continue; } // prevent double closing if (closePathAtEnd && cs.length > 1 && i == (cs.length - 1) && cs[0].equals(c)) { lineToLength--; continue; } // delta, then zigzag r.add(zigZagEncode(_x - x)); r.add(zigZagEncode(_y - y)); x = _x; y = _y; if (i == 0 && cs.length > 1 && !multiPoint) { // can length be too long? lineToIndex = r.size(); lineToLength = cs.length - 1; r.add(commandAndLength(Command.LineTo, lineToLength)); } } // update LineTo length if (lineToIndex > 0) { if (lineToLength == 0) { // remove empty LineTo r.remove(lineToIndex); } else { // update LineTo with new length r.set(lineToIndex, commandAndLength(Command.LineTo, lineToLength)); } } if (closePathAtEnd) { r.add(commandAndLength(Command.ClosePath, 1)); } return r; } static int commandAndLength(int command, int repeat) { return repeat << 3 | command; } static int zigZagEncode(int n) { // https://developers.google.com/protocol-buffers/docs/encoding#types return (n << 1) ^ (n >> 31); } private static final class Layer { final List<Feature> features = new ArrayList<VectorTileEncoder.Feature>(); private final Map<String, Integer> keys = new LinkedHashMap<String, Integer>(); private final Map<Object, Integer> values = new LinkedHashMap<Object, Integer>(); public Integer key(String key) { Integer i = keys.get(key); if (i == null) { i = Integer.valueOf(keys.size()); keys.put(key, i); } return i; } public List<String> keys() { return new ArrayList<String>(keys.keySet()); } public Integer value(Object value) { Integer i = values.get(value); if (i == null) { i = Integer.valueOf(values.size()); values.put(value, i); } return i; } public List<Object> values() { return Collections.unmodifiableList(new ArrayList<Object>(values.keySet())); } } private static final class Feature { long id; Geometry geometry; final List<Integer> tags = new ArrayList<Integer>(); } }
ElectronicChartCentre/java-vector-tile
src/main/java/no/ecc/vectortile/VectorTileEncoder.java
7,059
// delta, then zigzag
line_comment
nl
/***************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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. ****************************************************************/ package no.ecc.vectortile; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.locationtech.jts.algorithm.Area; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryCollection; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.LinearRing; import org.locationtech.jts.geom.MultiLineString; import org.locationtech.jts.geom.MultiPoint; import org.locationtech.jts.geom.MultiPolygon; import org.locationtech.jts.geom.Point; import org.locationtech.jts.geom.Polygon; import org.locationtech.jts.geom.TopologyException; import org.locationtech.jts.geom.prep.PreparedGeometry; import org.locationtech.jts.geom.prep.PreparedGeometryFactory; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import org.locationtech.jts.simplify.DouglasPeuckerSimplifier; import org.locationtech.jts.simplify.TopologyPreservingSimplifier; import vector_tile.VectorTile; import vector_tile.VectorTile.Tile.GeomType; public class VectorTileEncoder { private final Map<String, Layer> layers = new LinkedHashMap<String, Layer>(); private final int extent; private final double minimumLength; private final double minimumArea; protected final Geometry clipGeometry; protected final Envelope clipEnvelope; protected final PreparedGeometry clipGeometryPrepared; private final boolean autoScale; private long autoincrement; private final boolean autoincrementIds; private final double simplificationDistanceTolerance; private final GeometryFactory gf = new GeometryFactory(); /** * Create a {@link VectorTileEncoder} with the default extent of 4096 and * clip buffer of 8. */ public VectorTileEncoder() { this(4096, 8, true); } /** * Create a {@link VectorTileEncoder} with the given extent and a clip * buffer of 8. * * @param extent a int to specify vector tile extent. 4096 is a good value. */ public VectorTileEncoder(int extent) { this(extent, 8, true); } public VectorTileEncoder(int extent, int clipBuffer, boolean autoScale) { this(extent, clipBuffer, autoScale, false); } public VectorTileEncoder(int extent, int clipBuffer, boolean autoScale, boolean autoincrementIds) { this(extent, clipBuffer, autoScale, autoincrementIds, -1.0); } /** * Create a {@link VectorTileEncoder} with the given extent value. * <p> * The extent value control how detailed the coordinates are encoded in the * vector tile. 4096 is a good default, 256 can be used to reduce density. * <p> * The clip buffer value control how large the clipping area is outside of the * tile for geometries. 0 means that the clipping is done at the tile border. 8 * is a good default. * * @param extent * a int with extent value. 4096 is a good value. * @param clipBuffer * a int with clip buffer size for geometries. 8 is a good value. * @param autoScale * when true, the encoder expects coordinates in the 0..255 range and * will scale them automatically to the 0..extent-1 range before * encoding. when false, the encoder expects coordinates in the * 0..extent-1 range. * @param autoincrementIds * when true the vector tile feature id is auto incremented when using * {@link #addFeature(String, Map, Geometry)} * @param simplificationDistanceTolerance * a positive double representing the distance tolerance to be used * for non-points before (optional) scaling and encoding. A value * &lt;=0 will prevent simplifying geometry. 0.1 seems to be a good * value when {@code autoScale} is turned on. */ public VectorTileEncoder(int extent, int clipBuffer, boolean autoScale, boolean autoincrementIds, double simplificationDistanceTolerance) { this.extent = extent; this.autoScale = autoScale; this.minimumLength = autoScale ? (256.0 / extent) : 1.0; this.minimumArea = this.minimumLength * this.minimumLength; this.autoincrementIds = autoincrementIds; this.autoincrement = 1; this.simplificationDistanceTolerance = simplificationDistanceTolerance; final int size = autoScale ? 256 : extent; clipGeometry = createTileEnvelope(clipBuffer, size); clipEnvelope = clipGeometry.getEnvelopeInternal(); clipGeometryPrepared = PreparedGeometryFactory.prepare(clipGeometry); } private static Geometry createTileEnvelope(int buffer, int size) { Coordinate[] coords = new Coordinate[5]; coords[0] = new Coordinate(0 - buffer, size + buffer); coords[1] = new Coordinate(size + buffer, size + buffer); coords[2] = new Coordinate(size + buffer, 0 - buffer); coords[3] = new Coordinate(0 - buffer, 0 - buffer); coords[4] = coords[0]; return new GeometryFactory().createPolygon(coords); } public void addFeature(String layerName, Map<String, ?> attributes, Geometry geometry) { this.addFeature(layerName, attributes, geometry, this.autoincrementIds ? this.autoincrement++ : -1); } /** * Add a feature with layer name (typically feature type name), some attributes * and a Geometry. The Geometry must be in "pixel" space 0,0 upper left and * 256,256 lower right. * <p> * For optimization, geometries will be clipped and simplified. Features with * geometries outside of the tile will be skipped. * * @param layerName a {@link String} with the vector tile layer name. * @param attributes a {@link Map} with the vector tile feature attributes. * @param geometry a {@link Geometry} for the vector tile feature. * @param id a long with the vector tile feature id field. */ public void addFeature(String layerName, Map<String, ?> attributes, Geometry geometry, long id) { // skip small Polygon/LineString. if (geometry instanceof MultiPolygon && geometry.getArea() < minimumArea) { return; } if (geometry instanceof Polygon && geometry.getArea() < minimumArea) { return; } if (geometry instanceof LineString && geometry.getLength() < minimumLength) { return; } // special handling of GeometryCollection. subclasses are not handled here. if (geometry.getClass().equals(GeometryCollection.class)) { for (int i = 0; i < geometry.getNumGeometries(); i++) { Geometry subGeometry = geometry.getGeometryN(i); // keeping the id. any better suggestion? addFeature(layerName, attributes, subGeometry, id); } return; } // About to simplify and clip. Looks like simplification before clipping is // faster than clipping before simplification // simplify non-points if (simplificationDistanceTolerance > 0.0 && !(geometry instanceof Point)) { if (geometry instanceof LineString || geometry instanceof MultiLineString) { geometry = DouglasPeuckerSimplifier.simplify(geometry, simplificationDistanceTolerance); } else if (geometry instanceof Polygon || geometry instanceof MultiPolygon) { Geometry simplified = DouglasPeuckerSimplifier.simplify(geometry, simplificationDistanceTolerance); // extra check to prevent polygon converted to line if (simplified instanceof Polygon || simplified instanceof MultiPolygon) { geometry = simplified; } else { geometry = TopologyPreservingSimplifier.simplify(geometry, simplificationDistanceTolerance); } } else { geometry = TopologyPreservingSimplifier.simplify(geometry, simplificationDistanceTolerance); } } // clip geometry if (geometry instanceof Point) { if (!clipCovers(geometry)) { return; } } else { geometry = clipGeometry(geometry); } // no need to add empty geometry if (geometry == null || geometry.isEmpty()) { return; } // extra check for GeometryCollection after clipping as it can cause // GeometryCollection. Subclasses not handled here. if (geometry.getClass().equals(GeometryCollection.class)) { for (int i = 0; i < geometry.getNumGeometries(); i++) { Geometry subGeometry = geometry.getGeometryN(i); // keeping the id. any better suggestion? addFeature(layerName, attributes, subGeometry, id); } return; } Layer layer = layers.get(layerName); if (layer == null) { layer = new Layer(); layers.put(layerName, layer); } Feature feature = new Feature(); feature.geometry = geometry; feature.id = id; this.autoincrement = Math.max(this.autoincrement, id + 1); for (Map.Entry<String, ?> e : attributes.entrySet()) { // skip attribute without value if (e.getValue() == null) { continue; } feature.tags.add(layer.key(e.getKey())); feature.tags.add(layer.value(e.getValue())); } layer.features.add(feature); } /** * A short circuit clip to the tile extent (tile boundary + buffer) for * points to improve performance. This method can be overridden to change * clipping behavior. See also {@link #clipGeometry(Geometry)}. * * @param geom a {@link Geometry} to check for "covers" * @return a boolean true when the current clip geometry covers the given geom. */ protected boolean clipCovers(Geometry geom) { if (geom instanceof Point) { Point p = (Point) geom; return clipGeometry.getEnvelopeInternal().covers(p.getCoordinate()); } return clipEnvelope.covers(geom.getEnvelopeInternal()); } /** * Clip geometry according to buffer given at construct time. This method * can be overridden to change clipping behavior. See also * {@link #clipCovers(Geometry)}. * * @param geometry a {@link Geometry} to check for intersection with the current clip geometry * @return a boolean true when current clip geometry intersects with the given geometry. */ protected Geometry clipGeometry(Geometry geometry) { try { if (clipEnvelope.contains(geometry.getEnvelopeInternal())) { return geometry; } Geometry original = geometry; geometry = clipGeometry.intersection(original); // some times a intersection is returned as an empty geometry. // going via wkt fixes the problem. if (geometry.isEmpty() && clipGeometryPrepared.intersects(original)) { Geometry originalViaWkt = new WKTReader().read(original.toText()); geometry = clipGeometry.intersection(originalViaWkt); } return geometry; } catch (TopologyException e) { // could not intersect. original geometry will be used instead. return geometry; } catch (ParseException e1) { // could not encode/decode WKT. original geometry will be used // instead. return geometry; } } /** * Validate and potentially repair the given {@link List} of commands for the * given {@link Geometry}. Will return a {@link List} of the validated and/or * repaired commands. * <p> * This can be overridden to change behavior. By returning just the incoming * {@link List} of commands instead, the encoding will be faster, but * potentially less safe. * * @param commands * @param geometry * @return */ protected List<Integer> validateAndRepairCommands(List<Integer> commands, Geometry geometry) { if (commands.isEmpty()) { return commands; } GeomType geomType = toGeomType(geometry); if (simplificationDistanceTolerance > 0.0 && geomType == GeomType.POLYGON) { double scale = autoScale ? (extent / 256.0) : 1.0; Geometry decodedGeometry = VectorTileDecoder.decodeGeometry(gf, geomType, commands, scale); if (!isValid(decodedGeometry)) { // Invalid. Try more simplification and without preserving topology. geometry = DouglasPeuckerSimplifier.simplify(geometry, simplificationDistanceTolerance * 2.0); if (geometry.isEmpty()) { Collections.emptyList(); } geomType = toGeomType(geometry); x = 0; y = 0; return commands(geometry); } } return commands; } /** * @return a byte array with the vector tile */ public byte[] encode() { VectorTile.Tile.Builder tile = VectorTile.Tile.newBuilder(); for (Map.Entry<String, Layer> e : layers.entrySet()) { String layerName = e.getKey(); Layer layer = e.getValue(); VectorTile.Tile.Layer.Builder tileLayer = VectorTile.Tile.Layer.newBuilder(); tileLayer.setVersion(2); tileLayer.setName(layerName); tileLayer.addAllKeys(layer.keys()); for (Object value : layer.values()) { VectorTile.Tile.Value.Builder tileValue = VectorTile.Tile.Value.newBuilder(); if (value instanceof String) { tileValue.setStringValue((String) value); } else if (value instanceof Integer) { tileValue.setSintValue(((Integer) value).intValue()); } else if (value instanceof Long) { tileValue.setSintValue(((Long) value).longValue()); } else if (value instanceof Float) { tileValue.setFloatValue(((Float) value).floatValue()); } else if (value instanceof Double) { tileValue.setDoubleValue(((Double) value).doubleValue()); } else if (value instanceof BigDecimal) { tileValue.setStringValue(value.toString()); } else if (value instanceof Number) { tileValue.setDoubleValue(((Number) value).doubleValue()); } else if (value instanceof Boolean) { tileValue.setBoolValue(((Boolean) value).booleanValue()); } else { tileValue.setStringValue(value.toString()); } tileLayer.addValues(tileValue.build()); } tileLayer.setExtent(extent); for (Feature feature : layer.features) { Geometry geometry = feature.geometry; VectorTile.Tile.Feature.Builder featureBuilder = VectorTile.Tile.Feature.newBuilder(); featureBuilder.addAllTags(feature.tags); if (feature.id >= 0) { featureBuilder.setId(feature.id); } GeomType geomType = toGeomType(geometry); x = 0; y = 0; List<Integer> commands = commands(geometry); // Extra step to parse and check validity and try to repair. commands = validateAndRepairCommands(commands, geometry); // skip features with no geometry commands if (commands.isEmpty()) { continue; } featureBuilder.setType(geomType); featureBuilder.addAllGeometry(commands); tileLayer.addFeatures(featureBuilder.build()); } tile.addLayers(tileLayer.build()); } return tile.build().toByteArray(); } private static final boolean isValid(Geometry geometry) { try { return geometry.isValid(); } catch (RuntimeException e) { return false; } } static VectorTile.Tile.GeomType toGeomType(Geometry geometry) { if (geometry instanceof Point) { return VectorTile.Tile.GeomType.POINT; } if (geometry instanceof MultiPoint) { return VectorTile.Tile.GeomType.POINT; } if (geometry instanceof LineString) { return VectorTile.Tile.GeomType.LINESTRING; } if (geometry instanceof MultiLineString) { return VectorTile.Tile.GeomType.LINESTRING; } if (geometry instanceof Polygon) { return VectorTile.Tile.GeomType.POLYGON; } if (geometry instanceof MultiPolygon) { return VectorTile.Tile.GeomType.POLYGON; } return VectorTile.Tile.GeomType.UNKNOWN; } static boolean shouldClosePath(Geometry geometry) { return (geometry instanceof Polygon) || (geometry instanceof LinearRing); } List<Integer> commands(Geometry geometry) { if (geometry instanceof MultiLineString) { return commands((MultiLineString) geometry); } if (geometry instanceof Polygon) { return commands((Polygon) geometry); } if (geometry instanceof MultiPolygon) { return commands((MultiPolygon) geometry); } return commands(geometry.getCoordinates(), shouldClosePath(geometry), geometry instanceof MultiPoint); } List<Integer> commands(MultiLineString mls) { List<Integer> commands = new ArrayList<Integer>(); for (int i = 0; i < mls.getNumGeometries(); i++) { final int oldX = x; final int oldY = y; final List<Integer> geomCommands = commands(mls.getGeometryN(i).getCoordinates(), false); if (geomCommands.size() > 3) { // if the geometry consists of all identical points (after Math.round()) commands // returns a single move_to command, which is not valid according to the vector tile // specifications. // (https://github.com/mapbox/vector-tile-spec/tree/master/2.1#4343-linestring-geometry-type) commands.addAll(geomCommands); } else { // reset x and y to the previous value x = oldX; y = oldY; } } return commands; } List<Integer> commands(MultiPolygon mp) { List<Integer> commands = new ArrayList<Integer>(); for (int i = 0; i < mp.getNumGeometries(); i++) { Polygon polygon = (Polygon) mp.getGeometryN(i); commands.addAll(commands(polygon)); } return commands; } List<Integer> commands(Polygon polygon) { List<Integer> commands = new ArrayList<Integer>(); // According to the vector tile specification, the exterior ring of a polygon // must be in clockwise order, while the interior ring in counter-clockwise order. // In the tile coordinate system, Y axis is positive down. // // However, in geographic coordinate system, Y axis is positive up. // Therefore, we must reverse the coordinates. // So, the code below will make sure that exterior ring is in counter-clockwise order // and interior ring in clockwise order. LineString exteriorRing = polygon.getExteriorRing(); if (Area.ofRingSigned(exteriorRing.getCoordinates()) > 0) { exteriorRing = exteriorRing.reverse(); } commands.addAll(commands(exteriorRing.getCoordinates(), true)); for (int i = 0; i < polygon.getNumInteriorRing(); i++) { LineString interiorRing = polygon.getInteriorRingN(i); if (Area.ofRingSigned(interiorRing.getCoordinates()) < 0) { interiorRing = interiorRing.reverse(); } commands.addAll(commands(interiorRing.getCoordinates(), true)); } return commands; } private int x = 0; private int y = 0; /** * // // // Ex.: MoveTo(3, 6), LineTo(8, 12), LineTo(20, 34), ClosePath // * Encoded as: [ 9 3 6 18 5 6 12 22 15 ] // == command type 7 (ClosePath), * length 1 // ===== relative LineTo(+12, +22) == LineTo(20, 34) // === * relative LineTo(+5, +6) == LineTo(8, 12) // == [00010 010] = command type * 2 (LineTo), length 2 // === relative MoveTo(+3, +6) // == [00001 001] = * command type 1 (MoveTo), length 1 // Commands are encoded as uint32 * varints, vertex parameters are // encoded as sint32 varints (zigzag). * Vertex parameters are // also encoded as deltas to the previous position. * The original // position is (0,0) * * @param cs * @return */ List<Integer> commands(Coordinate[] cs, boolean closePathAtEnd) { return commands(cs, closePathAtEnd, false); } List<Integer> commands(Coordinate[] cs, boolean closePathAtEnd, boolean multiPoint) { if (cs.length == 0) { return Collections.emptyList(); } List<Integer> r = new ArrayList<Integer>(); int lineToIndex = 0; int lineToLength = 0; double scale = autoScale ? (extent / 256.0) : 1.0; for (int i = 0; i < cs.length; i++) { Coordinate c = cs[i]; if (i == 0) { r.add(commandAndLength(Command.MoveTo, multiPoint ? cs.length : 1)); } int _x = (int) Math.round(c.x * scale); int _y = (int) Math.round(c.y * scale); // prevent point equal to the previous if (i > 0 && _x == x && _y == y) { lineToLength--; continue; } // prevent double closing if (closePathAtEnd && cs.length > 1 && i == (cs.length - 1) && cs[0].equals(c)) { lineToLength--; continue; } // delta, then<SUF> r.add(zigZagEncode(_x - x)); r.add(zigZagEncode(_y - y)); x = _x; y = _y; if (i == 0 && cs.length > 1 && !multiPoint) { // can length be too long? lineToIndex = r.size(); lineToLength = cs.length - 1; r.add(commandAndLength(Command.LineTo, lineToLength)); } } // update LineTo length if (lineToIndex > 0) { if (lineToLength == 0) { // remove empty LineTo r.remove(lineToIndex); } else { // update LineTo with new length r.set(lineToIndex, commandAndLength(Command.LineTo, lineToLength)); } } if (closePathAtEnd) { r.add(commandAndLength(Command.ClosePath, 1)); } return r; } static int commandAndLength(int command, int repeat) { return repeat << 3 | command; } static int zigZagEncode(int n) { // https://developers.google.com/protocol-buffers/docs/encoding#types return (n << 1) ^ (n >> 31); } private static final class Layer { final List<Feature> features = new ArrayList<VectorTileEncoder.Feature>(); private final Map<String, Integer> keys = new LinkedHashMap<String, Integer>(); private final Map<Object, Integer> values = new LinkedHashMap<Object, Integer>(); public Integer key(String key) { Integer i = keys.get(key); if (i == null) { i = Integer.valueOf(keys.size()); keys.put(key, i); } return i; } public List<String> keys() { return new ArrayList<String>(keys.keySet()); } public Integer value(Object value) { Integer i = values.get(value); if (i == null) { i = Integer.valueOf(values.size()); values.put(value, i); } return i; } public List<Object> values() { return Collections.unmodifiableList(new ArrayList<Object>(values.keySet())); } } private static final class Feature { long id; Geometry geometry; final List<Integer> tags = new ArrayList<Integer>(); } }
22108_1
package be.kdg.dobbelen.view; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; public class DobbelenView extends GridPane { // Attributes // 3.0.1 We hebben drie controls nodig: twee ImageView controls en een Button control. Maak deze controls aan als attributen. private ImageView imgDobel1; private ImageView imgDobel2; private Button butWerp; // Constructors public DobbelenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods private void initialiseNodes() { // 3.1.1 Voorzie de drie attributen van een waarde. this.imgDobel1 = new ImageView(); this.imgDobel2 = new ImageView(); this.butWerp = new Button("Werp"); // 3.1.2 De knop moet een geprefereerde breedte van 80 pixels hebben. this.butWerp.prefWidth(80); } private void layoutNodes() { // x this.setStyle("-fx-background-color: #000000"); // 3.2.1 Maak gebruik van de add methode van de klasse GridPane om de twee images en de knop op de juiste plaats te krijgen. // De knop overspant twee kolommen. this.add(this.butWerp,0,2); this.add(this.imgDobel1,0,1); this.add(this.imgDobel2,2,1); // (0,0) (1,0) (2,0) // (0,1) (1,1) (2,1) // (0,2) (1,2) (2,2) // 3.2.2 Zorg voor een horizontale en verticale "gap" van 10 pixels tussen de cellen van de GridPane. this.setHgap(10); this.setVgap(10); // 3.2.2 Zorg ook voor een "padding" van 10 (20) pixels. this.setPadding(new Insets(20)); } Button getButWerp() { // Get.. return this.butWerp; } public void setImgDobel1(String path) { // Set.. this.imgDobel1.setImage(new Image(path)); } public void setImgDobel2(String path) { // Set.. this.imgDobel2.setImage(new Image(path)); } }
EliasDeHondt/ComputerProgramming1-JavaFX
W13P3/Dobbelen/src/be/kdg/dobbelen/view/DobbelenView.java
709
// 3.1.1 Voorzie de drie attributen van een waarde.
line_comment
nl
package be.kdg.dobbelen.view; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; public class DobbelenView extends GridPane { // Attributes // 3.0.1 We hebben drie controls nodig: twee ImageView controls en een Button control. Maak deze controls aan als attributen. private ImageView imgDobel1; private ImageView imgDobel2; private Button butWerp; // Constructors public DobbelenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods private void initialiseNodes() { // 3.1.1 Voorzie<SUF> this.imgDobel1 = new ImageView(); this.imgDobel2 = new ImageView(); this.butWerp = new Button("Werp"); // 3.1.2 De knop moet een geprefereerde breedte van 80 pixels hebben. this.butWerp.prefWidth(80); } private void layoutNodes() { // x this.setStyle("-fx-background-color: #000000"); // 3.2.1 Maak gebruik van de add methode van de klasse GridPane om de twee images en de knop op de juiste plaats te krijgen. // De knop overspant twee kolommen. this.add(this.butWerp,0,2); this.add(this.imgDobel1,0,1); this.add(this.imgDobel2,2,1); // (0,0) (1,0) (2,0) // (0,1) (1,1) (2,1) // (0,2) (1,2) (2,2) // 3.2.2 Zorg voor een horizontale en verticale "gap" van 10 pixels tussen de cellen van de GridPane. this.setHgap(10); this.setVgap(10); // 3.2.2 Zorg ook voor een "padding" van 10 (20) pixels. this.setPadding(new Insets(20)); } Button getButWerp() { // Get.. return this.butWerp; } public void setImgDobel1(String path) { // Set.. this.imgDobel1.setImage(new Image(path)); } public void setImgDobel2(String path) { // Set.. this.imgDobel2.setImage(new Image(path)); } }
14633_0
/** @author Elias De Hondt * 28/11/2022 */ public class Arend implements Dier,Eierleggend,Vliegend { // Attributen private String naam; private int aantalEierenPerJaar; private double maxVliegsnelheid; private double duiksnelheid; // Constructors public Arend(String naam, int aantalEierenPerJaar, double maxVliegsnelheid, double duiksnelheid) { this.naam = naam; this.aantalEierenPerJaar = aantalEierenPerJaar; this.maxVliegsnelheid = maxVliegsnelheid; this.duiksnelheid = duiksnelheid; } // Methode public String getNaam() { return this.naam; } public int getAantalEierenPerJaar() { return this.aantalEierenPerJaar; } public double getMaxVliegsnelheid() { return this.maxVliegsnelheid; } public double getDuiksnelheid() { return duiksnelheid; } @Override public String toString() { // @Override van toString return String.format( """ Naam: %s Eieren: %d Snelheid: %.0f km/h Duiksnelheid: %.0f km/h """, this.getNaam(),this.getAantalEierenPerJaar(), this.getMaxVliegsnelheid(),this.getDuiksnelheid()); } }
EliasDeHondt/ComputerProgramming1-OOConcepts
W9P2/W9P2 Dierenrijk/src/Arend.java
430
/** @author Elias De Hondt * 28/11/2022 */
block_comment
nl
/** @author Elias De<SUF>*/ public class Arend implements Dier,Eierleggend,Vliegend { // Attributen private String naam; private int aantalEierenPerJaar; private double maxVliegsnelheid; private double duiksnelheid; // Constructors public Arend(String naam, int aantalEierenPerJaar, double maxVliegsnelheid, double duiksnelheid) { this.naam = naam; this.aantalEierenPerJaar = aantalEierenPerJaar; this.maxVliegsnelheid = maxVliegsnelheid; this.duiksnelheid = duiksnelheid; } // Methode public String getNaam() { return this.naam; } public int getAantalEierenPerJaar() { return this.aantalEierenPerJaar; } public double getMaxVliegsnelheid() { return this.maxVliegsnelheid; } public double getDuiksnelheid() { return duiksnelheid; } @Override public String toString() { // @Override van toString return String.format( """ Naam: %s Eieren: %d Snelheid: %.0f km/h Duiksnelheid: %.0f km/h """, this.getNaam(),this.getAantalEierenPerJaar(), this.getMaxVliegsnelheid(),this.getDuiksnelheid()); } }
1684_13
/** * @author Vera Wise * @author Elias De Hondt * @since 08/12/2022 */ // ===================================================================================================================== /* * Canvas KdG * @see https://canvas.kdg.be/courses/37158/pages/afspraken-en-deadlines?module_item_id=663060 * * Github * @see https://github.com/EliasDeHondt/Memo-Race * * Google Docs * @see https://docs.google.com/spreadsheets/d/199y9TW0weDEmgGD8Iv0UWyqQnMW8zF_RrBZ8XB4lQBc/edit#gid=0 * */ // ===================================================================================================================== // TODO: - Voorzie een startscherm waar je de namen van de spelers kan ingeven. // - Elke speler kan een avatar kiezen of zelf een foto toevoegen. // - Voorzie een lijst op het scherm met eerder aangemaakte spelers. Sla deze op in een bestand. // - Zorg voor een mooi grafische vormgeving. // - Tijdens het spelverloop moet volgende zichtbaar zijn: // - Een dobbelsteen. // - Het speelveld met in het midden de omgedraaide kaarten. // - Per speler zijn naam, de avatar en de gewonnen kaarten. // - Een pion die automatisch verplaatst na een worp. // - Kaarten moeten met de muis omgedraaid kunnen worden. // - Als een figuur gevonden is moet het overeenkomstige vak een alternatieve opmaak // (bv. donkerder) krijgen zodat duidelijk is dat de pion deze vakken mag overslaan. // - Maak visueel zichtbaar welke speler aan de beurt is. // ===================================================================================================================== // SPELBESCHRIJVING /* * MemoRace is een variant op memory, maar een dobbelsteen zorgt voor een extra dimensie. Het * spel leert kinderen dezelfde vaardigheden als Memory en de dobbelsteen bevorderd het tellen. * Een pion loopt op een pad met in elk vak een verschillende afbeelding rond een speelveld. In het * speelveld liggen omgedraaide kaarten met de verschillende afbeeldingen. De spelers moeten * zoveel mogelijk van de afbeeldingen op het pad terugvinden bij de omgedraaide kaarten in het * midden van het speelveld. De speler die op het einde de meeste kaarten gevonden heeft wint * het spel. Het kan gespeeld worden met 2 tot 6 spelers * Hieronder een overzicht van de belangrijkste spelonderdelen: * • een spelbord * • 16 kaarten die willekeurig in het midden van het spelbord gelegd worden * • 1 dobbelsteen * • 1 pion */ // ===================================================================================================================== // SPELVERLOOP /* * Er wordt om de beurt gespeeld. Het spel beslist random in welke * volgorde de spelers mogen spelen. De pion start op “go”. De eerste * speler werpt de dobbelsteen en zet de pion evenveel vakken (groene * genummerd in de afbeelding) vooruit. Elk vak toont een afbeelding. * Het is de bedoeling dat de speler de kaart met dezelfde afbeelding * omdraait (kaarten zijn de witte vakjes in de afbeelding). Als dat lukt, * dan krijgt hij de kaart. In het andere geval wordt de kaart terug * omgedraaid. Hierna is de beurt van deze speler om en is het aan de * volgende speler. Hij gooit en verplaatst de pion. Ook hij moet proberen * die kaart om te draaien die overeenkomt met de afbeelding van het * vak waar de pion nu op staat. Het spel loopt zo verder tot alle kaarten van het veld verdwenen * zijn. De persoon met de meeste kaarten wint het spel. De pion slaat de vakken met reeds * gevonden figuren en de hoekvakken over. */ // =====================================================================================================================
EliasDeHondt/Memo-Race
TODO.java
1,134
// (bv. donkerder) krijgen zodat duidelijk is dat de pion deze vakken mag overslaan.
line_comment
nl
/** * @author Vera Wise * @author Elias De Hondt * @since 08/12/2022 */ // ===================================================================================================================== /* * Canvas KdG * @see https://canvas.kdg.be/courses/37158/pages/afspraken-en-deadlines?module_item_id=663060 * * Github * @see https://github.com/EliasDeHondt/Memo-Race * * Google Docs * @see https://docs.google.com/spreadsheets/d/199y9TW0weDEmgGD8Iv0UWyqQnMW8zF_RrBZ8XB4lQBc/edit#gid=0 * */ // ===================================================================================================================== // TODO: - Voorzie een startscherm waar je de namen van de spelers kan ingeven. // - Elke speler kan een avatar kiezen of zelf een foto toevoegen. // - Voorzie een lijst op het scherm met eerder aangemaakte spelers. Sla deze op in een bestand. // - Zorg voor een mooi grafische vormgeving. // - Tijdens het spelverloop moet volgende zichtbaar zijn: // - Een dobbelsteen. // - Het speelveld met in het midden de omgedraaide kaarten. // - Per speler zijn naam, de avatar en de gewonnen kaarten. // - Een pion die automatisch verplaatst na een worp. // - Kaarten moeten met de muis omgedraaid kunnen worden. // - Als een figuur gevonden is moet het overeenkomstige vak een alternatieve opmaak // (bv. donkerder)<SUF> // - Maak visueel zichtbaar welke speler aan de beurt is. // ===================================================================================================================== // SPELBESCHRIJVING /* * MemoRace is een variant op memory, maar een dobbelsteen zorgt voor een extra dimensie. Het * spel leert kinderen dezelfde vaardigheden als Memory en de dobbelsteen bevorderd het tellen. * Een pion loopt op een pad met in elk vak een verschillende afbeelding rond een speelveld. In het * speelveld liggen omgedraaide kaarten met de verschillende afbeeldingen. De spelers moeten * zoveel mogelijk van de afbeeldingen op het pad terugvinden bij de omgedraaide kaarten in het * midden van het speelveld. De speler die op het einde de meeste kaarten gevonden heeft wint * het spel. Het kan gespeeld worden met 2 tot 6 spelers * Hieronder een overzicht van de belangrijkste spelonderdelen: * • een spelbord * • 16 kaarten die willekeurig in het midden van het spelbord gelegd worden * • 1 dobbelsteen * • 1 pion */ // ===================================================================================================================== // SPELVERLOOP /* * Er wordt om de beurt gespeeld. Het spel beslist random in welke * volgorde de spelers mogen spelen. De pion start op “go”. De eerste * speler werpt de dobbelsteen en zet de pion evenveel vakken (groene * genummerd in de afbeelding) vooruit. Elk vak toont een afbeelding. * Het is de bedoeling dat de speler de kaart met dezelfde afbeelding * omdraait (kaarten zijn de witte vakjes in de afbeelding). Als dat lukt, * dan krijgt hij de kaart. In het andere geval wordt de kaart terug * omgedraaid. Hierna is de beurt van deze speler om en is het aan de * volgende speler. Hij gooit en verplaatst de pion. Ook hij moet proberen * die kaart om te draaien die overeenkomt met de afbeelding van het * vak waar de pion nu op staat. Het spel loopt zo verder tot alle kaarten van het veld verdwenen * zijn. De persoon met de meeste kaarten wint het spel. De pion slaat de vakken met reeds * gevonden figuren en de hoekvakken over. */ // =====================================================================================================================
28168_3
package org.thomasmore.oo3.course.resortui.facade; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.ejb.Stateless; import org.thomasmore.oo3.course.resortui.business.entity.BungalowEntity; import org.thomasmore.oo3.course.resortui.business.entity.CustomerEntity; import org.thomasmore.oo3.course.resortui.business.entity.ParkEntity; import org.thomasmore.oo3.course.resortui.business.entity.ReservationEntity; import org.thomasmore.oo3.course.resortui.controller.ScheduleController; import org.thomasmore.oo3.course.resortui.dao.BungalowDao; import org.thomasmore.oo3.course.resortui.dao.CustomerDao; import org.thomasmore.oo3.course.resortui.dao.ParkDao; import org.thomasmore.oo3.course.resortui.dao.ReservationDao; import org.thomasmore.oo3.course.resortui.model.ReservationListDetailDto; import org.thomasmore.oo3.course.resortui.model.ReservationPageDto; @Stateless public class ReservationFacade { @EJB private ScheduleController schedulecontroller; @EJB private ReservationDao reservationsDao; @EJB private BungalowDao bungalowsDao; @EJB private CustomerDao customersDao; @EJB private ParkDao parkDao; private final SimpleDateFormat dateDate = new SimpleDateFormat("dd/MM/yyyy"); @PostConstruct public void init() { schedulecontroller.LoadBungalowSchedule(); } public ReservationPageDto loadReservationOverviewPage(String editId, String deleteId) { ReservationPageDto dto = new ReservationPageDto(); if (editId != null) { ReservationEntity reservationEntity = reservationsDao.findById(editId); if (reservationEntity != null) { dto.getDetail().setId(reservationEntity.getId()); dto.getDetail().setBungalowName(reservationEntity.getBungalowName()); dto.getDetail().setCustomerName(reservationEntity.getCustomerName()); dto.getDetail().setEndDate(reservationEntity.getEndDate()); dto.getDetail().setEndDateFormatted(reservationEntity.getEndDateFormatted()); dto.getDetail().setEndTime(reservationEntity.getEndTime()); dto.getDetail().setParkName(reservationEntity.getParkName()); dto.getDetail().setStartDate(reservationEntity.getStartDate()); dto.getDetail().setStartDateFormatted(reservationEntity.getStartDateFormatted()); dto.getDetail().setStartTime(reservationEntity.getStartTime()); } schedulecontroller.LoadBungalowSchedule(); } if (deleteId != null) { reservationsDao.deleteById(deleteId); schedulecontroller.LoadBungalowSchedule(); } List<CustomerEntity> customers = customersDao.listAll(); for (CustomerEntity customer : customers) { dto.getCustomerList().add(customer.getFirstname() + " " + customer.getLastname()); } List<ParkEntity> parks = parkDao.listAll(); for (ParkEntity park : parks) { dto.getParkList().add(park.getName()); } List<BungalowEntity> bungalows = bungalowsDao.listAll(); for (BungalowEntity bungalow : bungalows) { dto.getBungalowList().add(bungalow.getName()); } List<ReservationEntity> reservations = reservationsDao.listAll(); for (ReservationEntity reservation : reservations) { ReservationListDetailDto listDetail = new ReservationListDetailDto(); listDetail.setId(reservation.getId()); listDetail.setBungalowName(reservation.getBungalowName()); listDetail.setCustomerName(reservation.getCustomerName()); // Datum formateren listDetail.setStartDateFormatted(schedulecontroller.DateAndTime(reservation.getStartDate(), reservation.getStartTime())); listDetail.setEndDateFormatted(schedulecontroller.DateAndTime(reservation.getEndDate(), reservation.getEndTime())); try { listDetail.setStartDate(schedulecontroller.parseDate(listDetail.getStartDateFormatted())); listDetail.setStartDate(schedulecontroller.parseDate(listDetail.getEndDateFormatted())); } catch (ParseException ex) { Logger.getLogger(EventFacade.class.getName()).log(Level.SEVERE, null, ex); } listDetail.setStartDate(reservation.getStartTime()); listDetail.setEndDate(reservation.getEndTime()); // Tot hier wordt datum geformateerd listDetail.setParkName(reservation.getParkName()); dto.getList().add(listDetail); } return dto; } public ReservationPageDto add(ReservationPageDto dto) { ReservationEntity reservationEntity = null; //als de id niet geset is kennen we hem 1 toe; if (dto.getDetail().getId() == null || dto.getDetail().getId().isEmpty()) { dto.getDetail().setId(UUID.randomUUID().toString()); } else { reservationEntity = reservationsDao.findById(dto.getDetail().getId()); } if (reservationEntity == null) { reservationEntity = new ReservationEntity(); } reservationEntity.setId(dto.getDetail().getId()); reservationEntity.setBungalowName(dto.getDetail().getBungalowName()); reservationEntity.setCustomerName(dto.getDetail().getCustomerName()); reservationEntity.setEndDate(dto.getDetail().getEndDate()); reservationEntity.setEndDateFormatted(dto.getDetail().getEndDateFormatted()); reservationEntity.setEndTime(dto.getDetail().getEndTime()); reservationEntity.setParkName(dto.getDetail().getParkName()); reservationEntity.setStartDate(dto.getDetail().getStartDate()); reservationEntity.setStartDateFormatted(dto.getDetail().getStartDateFormatted()); reservationEntity.setStartTime(dto.getDetail().getStartTime()); reservationsDao.save(reservationEntity); schedulecontroller.LoadBungalowSchedule(); return dto; } public String checkBooking(ReservationPageDto dto) { // Check of begintijd na eindtijd komt if (dto.getDetail().getStartDate().after(dto.getDetail().getEndDate())) { return "begindateAfterEnddate"; } // Check of begintijd voor vandaag komt if (dto.getDetail().getStartDate().before(schedulecontroller.yesterday())) { return "beginDateBeforeToday"; } // Dubbele boeking nagaan List<ReservationEntity> reservations = reservationsDao.listAll(); for (ReservationEntity res : reservations) { // Voeg datum en tijd samen Date reservationStartDate = res.getStartDate(); Date reservationEndDate = res.getEndDate(); Date dtoStartDate = dto.getDetail().getStartDate(); Date dtoEndDate = dto.getDetail().getEndDate(); System.out.println(reservationStartDate + ", " + reservationEndDate + ", " + dtoStartDate + ", " + dtoEndDate); // Checkt of datum en tijd tussen een reeds geboekte tijd ligt voor een bepaalde locatie // OPGELET! De !=null moet aanwezig zijn want anders wordt een nullpointer gegeven wanneer vergeleken wordt met een lege waarde if (// Nullpointers vermijden reservationStartDate != null && reservationEndDate != null && res.getBungalowName() != null && // Check of gekozen datum niet dezelfde datum is dan begin of einddatum (dtoStartDate.equals(reservationStartDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoEndDate.equals(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoStartDate.equals(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoEndDate.equals(reservationStartDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || // Als reservation tussen begin en einddatum ligt en Zelfde locatie heeft (dtoStartDate.before(reservationStartDate) && dtoEndDate.after(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || // Als begintijd = binnen range of eindtijd is binnen range (dtoStartDate.after(reservationStartDate) && dtoStartDate.before(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoEndDate.after(reservationStartDate) && dtoEndDate.before(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName()))) { return "doubleBooking: <p>Locatie " + res.getBungalowName() + " is reeds volboekt van</p><p>" + res.getStartDateFormatted() + " tot " + res.getEndDateFormatted() + ".</p><p>Gelieve andere datum te selecteren.</p>"; } } add(dto); return ""; } }
EliasSerneels/Project1
ResortUI/src/main/java/org/thomasmore/oo3/course/resortui/facade/ReservationFacade.java
2,723
// Check of begintijd voor vandaag komt
line_comment
nl
package org.thomasmore.oo3.course.resortui.facade; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.ejb.Stateless; import org.thomasmore.oo3.course.resortui.business.entity.BungalowEntity; import org.thomasmore.oo3.course.resortui.business.entity.CustomerEntity; import org.thomasmore.oo3.course.resortui.business.entity.ParkEntity; import org.thomasmore.oo3.course.resortui.business.entity.ReservationEntity; import org.thomasmore.oo3.course.resortui.controller.ScheduleController; import org.thomasmore.oo3.course.resortui.dao.BungalowDao; import org.thomasmore.oo3.course.resortui.dao.CustomerDao; import org.thomasmore.oo3.course.resortui.dao.ParkDao; import org.thomasmore.oo3.course.resortui.dao.ReservationDao; import org.thomasmore.oo3.course.resortui.model.ReservationListDetailDto; import org.thomasmore.oo3.course.resortui.model.ReservationPageDto; @Stateless public class ReservationFacade { @EJB private ScheduleController schedulecontroller; @EJB private ReservationDao reservationsDao; @EJB private BungalowDao bungalowsDao; @EJB private CustomerDao customersDao; @EJB private ParkDao parkDao; private final SimpleDateFormat dateDate = new SimpleDateFormat("dd/MM/yyyy"); @PostConstruct public void init() { schedulecontroller.LoadBungalowSchedule(); } public ReservationPageDto loadReservationOverviewPage(String editId, String deleteId) { ReservationPageDto dto = new ReservationPageDto(); if (editId != null) { ReservationEntity reservationEntity = reservationsDao.findById(editId); if (reservationEntity != null) { dto.getDetail().setId(reservationEntity.getId()); dto.getDetail().setBungalowName(reservationEntity.getBungalowName()); dto.getDetail().setCustomerName(reservationEntity.getCustomerName()); dto.getDetail().setEndDate(reservationEntity.getEndDate()); dto.getDetail().setEndDateFormatted(reservationEntity.getEndDateFormatted()); dto.getDetail().setEndTime(reservationEntity.getEndTime()); dto.getDetail().setParkName(reservationEntity.getParkName()); dto.getDetail().setStartDate(reservationEntity.getStartDate()); dto.getDetail().setStartDateFormatted(reservationEntity.getStartDateFormatted()); dto.getDetail().setStartTime(reservationEntity.getStartTime()); } schedulecontroller.LoadBungalowSchedule(); } if (deleteId != null) { reservationsDao.deleteById(deleteId); schedulecontroller.LoadBungalowSchedule(); } List<CustomerEntity> customers = customersDao.listAll(); for (CustomerEntity customer : customers) { dto.getCustomerList().add(customer.getFirstname() + " " + customer.getLastname()); } List<ParkEntity> parks = parkDao.listAll(); for (ParkEntity park : parks) { dto.getParkList().add(park.getName()); } List<BungalowEntity> bungalows = bungalowsDao.listAll(); for (BungalowEntity bungalow : bungalows) { dto.getBungalowList().add(bungalow.getName()); } List<ReservationEntity> reservations = reservationsDao.listAll(); for (ReservationEntity reservation : reservations) { ReservationListDetailDto listDetail = new ReservationListDetailDto(); listDetail.setId(reservation.getId()); listDetail.setBungalowName(reservation.getBungalowName()); listDetail.setCustomerName(reservation.getCustomerName()); // Datum formateren listDetail.setStartDateFormatted(schedulecontroller.DateAndTime(reservation.getStartDate(), reservation.getStartTime())); listDetail.setEndDateFormatted(schedulecontroller.DateAndTime(reservation.getEndDate(), reservation.getEndTime())); try { listDetail.setStartDate(schedulecontroller.parseDate(listDetail.getStartDateFormatted())); listDetail.setStartDate(schedulecontroller.parseDate(listDetail.getEndDateFormatted())); } catch (ParseException ex) { Logger.getLogger(EventFacade.class.getName()).log(Level.SEVERE, null, ex); } listDetail.setStartDate(reservation.getStartTime()); listDetail.setEndDate(reservation.getEndTime()); // Tot hier wordt datum geformateerd listDetail.setParkName(reservation.getParkName()); dto.getList().add(listDetail); } return dto; } public ReservationPageDto add(ReservationPageDto dto) { ReservationEntity reservationEntity = null; //als de id niet geset is kennen we hem 1 toe; if (dto.getDetail().getId() == null || dto.getDetail().getId().isEmpty()) { dto.getDetail().setId(UUID.randomUUID().toString()); } else { reservationEntity = reservationsDao.findById(dto.getDetail().getId()); } if (reservationEntity == null) { reservationEntity = new ReservationEntity(); } reservationEntity.setId(dto.getDetail().getId()); reservationEntity.setBungalowName(dto.getDetail().getBungalowName()); reservationEntity.setCustomerName(dto.getDetail().getCustomerName()); reservationEntity.setEndDate(dto.getDetail().getEndDate()); reservationEntity.setEndDateFormatted(dto.getDetail().getEndDateFormatted()); reservationEntity.setEndTime(dto.getDetail().getEndTime()); reservationEntity.setParkName(dto.getDetail().getParkName()); reservationEntity.setStartDate(dto.getDetail().getStartDate()); reservationEntity.setStartDateFormatted(dto.getDetail().getStartDateFormatted()); reservationEntity.setStartTime(dto.getDetail().getStartTime()); reservationsDao.save(reservationEntity); schedulecontroller.LoadBungalowSchedule(); return dto; } public String checkBooking(ReservationPageDto dto) { // Check of begintijd na eindtijd komt if (dto.getDetail().getStartDate().after(dto.getDetail().getEndDate())) { return "begindateAfterEnddate"; } // Check of<SUF> if (dto.getDetail().getStartDate().before(schedulecontroller.yesterday())) { return "beginDateBeforeToday"; } // Dubbele boeking nagaan List<ReservationEntity> reservations = reservationsDao.listAll(); for (ReservationEntity res : reservations) { // Voeg datum en tijd samen Date reservationStartDate = res.getStartDate(); Date reservationEndDate = res.getEndDate(); Date dtoStartDate = dto.getDetail().getStartDate(); Date dtoEndDate = dto.getDetail().getEndDate(); System.out.println(reservationStartDate + ", " + reservationEndDate + ", " + dtoStartDate + ", " + dtoEndDate); // Checkt of datum en tijd tussen een reeds geboekte tijd ligt voor een bepaalde locatie // OPGELET! De !=null moet aanwezig zijn want anders wordt een nullpointer gegeven wanneer vergeleken wordt met een lege waarde if (// Nullpointers vermijden reservationStartDate != null && reservationEndDate != null && res.getBungalowName() != null && // Check of gekozen datum niet dezelfde datum is dan begin of einddatum (dtoStartDate.equals(reservationStartDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoEndDate.equals(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoStartDate.equals(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoEndDate.equals(reservationStartDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || // Als reservation tussen begin en einddatum ligt en Zelfde locatie heeft (dtoStartDate.before(reservationStartDate) && dtoEndDate.after(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || // Als begintijd = binnen range of eindtijd is binnen range (dtoStartDate.after(reservationStartDate) && dtoStartDate.before(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoEndDate.after(reservationStartDate) && dtoEndDate.before(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName()))) { return "doubleBooking: <p>Locatie " + res.getBungalowName() + " is reeds volboekt van</p><p>" + res.getStartDateFormatted() + " tot " + res.getEndDateFormatted() + ".</p><p>Gelieve andere datum te selecteren.</p>"; } } add(dto); return ""; } }
35889_3
package tpr; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import Bundler.Bundler; import Plaatsers.BoundingBoxBundleCC; import Plaatsers.PlacementManipulatorIOCLB; import Plaatsers.Rplace; import Plaatsers.Vplace; import PlacementParser.Placement; import PlacementParser.ReadPlacement; import TRouter.ConnectionRouterBB; import TRouter.VerificationModule; import architecture.FourLutSanitizedDisjoint; import circuit.Circuit; import circuit.parser.conlist.ParseException; import circuit.parser.conlist.Readconlist; import circuit.writer.PlacementWriter; import com.lexicalscope.jewel.cli.CliFactory; public class ExportTPAR { /** * @param args * @throws FileNotFoundException * @throws ParseException * @throws architecture.ParseException * @throws PlacementParser.ParseException */ public static void main(String[] args) throws FileNotFoundException, ParseException, PlacementParser.ParseException { System.out.println("Version information: TPack:advanced bundling, TPlace:SA with BB Bundle Estimation, TRoute:CrouteHwithConSmallestBBFirstOrder"); /* String[] testArgs1 = { "-p", "temp.p", "-n", "testcases/BVHCell-tconmap_out.net", "-w", "8", "-h", "8", "--routeOnly"}; String[] testArgs2 = { "--help" }; */ final Arguments cli = CliFactory.parseArguments(Arguments.class, args); if(cli.getPlacementOnly()){ if(cli.getRouteOnly()){ System.out.println("Error: conflicting command line options; 'Route only' and 'Placement only'"); }else{ placementOnly(cli.getHeight(),cli.getWidth(),cli.getPlacementEffort(),cli.getNetFilename(),cli.getPlacementFileName(),cli.getLogFileName()); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); writeToFile("---timeStamp---"+dateFormat.format(date)+"\n", cli.getLogFileName()); } }else if(cli.getRouteOnly()){ routeOnly(cli.getHeight(),cli.getWidth(),cli.getChannelWidth(),cli.getNrOfRoutingIterations(),cli.getNetFilename(),cli.getPlacementFileName(),cli.getLogFileName()); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); writeToFile("---timeStamp---"+dateFormat.format(date)+"\n", cli.getLogFileName()); }else{ par(cli.getHeight(), cli.getWidth(), cli.getChannelWidth(), cli.getPlacementEffort(), cli.getNrOfRoutingIterations(), cli.getNetFilename(), cli.getPlacementFileName(), cli.getLogFileName()); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); writeToFile("---timeStamp---"+dateFormat.format(date)+"\n", cli.getLogFileName()); } } public static int par(int height, int width, int channelWidth, int placementEffort, int routingIterations, String netFile, String pFile, String logFile) throws FileNotFoundException, circuit.parser.conlist.ParseException{ //Read in con netlist. System.out.println("Read in con netlist "+netFile+".. "); Readconlist parser=new Readconlist(new FileInputStream(new File(netFile))); Circuit c=parser.read(); c.createBundles(); //Architecture Check if(c.clbs.size()>(height*width)){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of CLBs in the circuit exceeds the number of physical CLBs present on the FPGA."); } if(c.inputs.size()>(2*(height+width))){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of inputs in the circuit exceeds the number of physical IOBs present on the FPGA."); } if(c.outputs.size()>(2*(height+width))){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of outputs in the circuit exceeds the number of physical IOBs present on the FPGA."); } //Bundler System.out.println("Start bundling.. "); Bundler blr = new Bundler(c); final long startTime0 = System.nanoTime(); final long endTime0; try { blr.bundle(); } finally { endTime0 = System.nanoTime(); } final long duration0 = endTime0 - startTime0; System.out.println("Runtime: "+(duration0/1.0E9)); System.out.println("Connections are bundled in "+c.bundles.size()+" bundles"); // blr.printBundles(); //Aanmaken van de architectuur. System.out.println("Aanmaken van de architectuur."); FourLutSanitizedDisjoint a = new FourLutSanitizedDisjoint(width,height,channelWidth); Random rand = new Random(1); PlacementManipulatorIOCLB pm0 = new PlacementManipulatorIOCLB(a,c,rand); BoundingBoxBundleCC bbbcc = new BoundingBoxBundleCC(c); //Random placement Rplace.placeCLBsandIOs(c, a, rand); pm0.placementCLBsConsistencyCheck(); System.out.println("Total Cost random placement BBbundle cc: "+bbbcc.calculateTotalCost()); //Time placement process Vplace placer1= new Vplace(pm0,bbbcc); final long startTime1 = System.nanoTime(); final long endTime1; try { placer1.place(placementEffort); } finally { endTime1 = System.nanoTime(); } final long duration1 = endTime1 - startTime1; System.out.println("Runtime: "+(duration1/1.0E9)); System.out.println("Total BB Cost after placement with bb bundle cc: "+bbbcc.calculateTotalCost()); //Dump placement PlacementWriter.dumpPlacement(c, pFile); int its = -1; ConnectionRouterBB router = new ConnectionRouterBB(c); final long startTime2 = System.nanoTime(); final long endTime2; try { its = router.crouteHwithConSmallestBBFirstOrder(a, routingIterations); } finally { endTime2 = System.nanoTime(); } final long duration2 = endTime2 - startTime2; System.out.println("Runtime: "+(duration2/1.0E9)); System.out.println("Number of wires: "+c.totalWires()); if(c.totalWires()>0){ VerificationModule vfmodule = new VerificationModule(c); System.out.println("Starting verification... "+vfmodule.verificateConnectionRouter()); } String line = "Placement effort: "+placementEffort+",\tchannel width: "+channelWidth+"\t, routing iterations: "+routingIterations+",\tnet file: " + netFile + "\n\t" + "Bundling: rt = "+(duration0/1.0E9)+", "+c.bundles.size()+" bundles" + "\n\t" + "Placement: rt = "+(duration1/1.0E9)+", Total BBB Cost: "+bbbcc.calculateTotalCost() + "\n\t" + "Routing: rt = "+(duration2/1.0E9)+", wires = "+c.totalWires()+"\n"; writeToFile(line,logFile); return its; } public static int routeOnly(int height, int width, int channelWidth, int routingIterations, String netFile, String pFile, String logFile) throws FileNotFoundException, circuit.parser.conlist.ParseException, PlacementParser.ParseException{ //Read in con netlist. System.out.println("Read in con netlist "+netFile+".. "); Readconlist parser=new Readconlist(new FileInputStream(new File(netFile))); Circuit c=parser.read(); c.createBundles(); //Architecture Check if(c.clbs.size()>(height*width)){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of CLBs in the circuit exceeds the number of physical CLBs present on the FPGA."); } if(c.inputs.size()>(2*(height+width))){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of inputs in the circuit exceeds the number of physical IOBs present on the FPGA."); } if(c.outputs.size()>(2*(height+width))){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of outputs in the circuit exceeds the number of physical IOBs present on the FPGA."); } //Bundler System.out.println("Start bundling.. "); Bundler blr = new Bundler(c); final long startTime0 = System.nanoTime(); final long endTime0; try { blr.bundle(); } finally { endTime0 = System.nanoTime(); } final long duration0 = endTime0 - startTime0; System.out.println("Runtime: "+(duration0/1.0E9)); System.out.println("Connections are bundled in "+c.bundles.size()+" bundles"); // blr.printBundles(); //Aanmaken van de architectuur. System.out.println("Aanmaken van de architectuur."); FourLutSanitizedDisjoint a = new FourLutSanitizedDisjoint(width,height,channelWidth); ReadPlacement plaats_parser=new ReadPlacement(new FileInputStream(pFile)); Placement p=plaats_parser.read(); c.applyPlacement(p, a); int its = -1; ConnectionRouterBB router = new ConnectionRouterBB(c); final long startTime2 = System.nanoTime(); final long endTime2; try { its = router.crouteHwithConSmallestBBFirstOrder(a, routingIterations); } finally { endTime2 = System.nanoTime(); } final long duration2 = endTime2 - startTime2; System.out.println("Runtime: "+(duration2/1.0E9)); System.out.println("Number of wires: "+c.totalWires()); if(c.totalWires()>0){ VerificationModule vfmodule = new VerificationModule(c); System.out.println("Starting verification... "+vfmodule.verificateConnectionRouter()); } String line = "Channel Width:"+channelWidth+",\tRouting Iterations:"+routingIterations+ "\t,net file:" + netFile + "\n\t" + "Bundling: rt = "+(duration0/1.0E9)+", "+c.bundles.size()+" bundles" + "\n\t" + "Routing: rt = "+(duration2/1.0E9)+", wires = "+c.totalWires()+"\n"; writeToFile(line,logFile); return its; } public static void placementOnly(int height, int width, int placementEffort, String netFile, String pFile, String logFile) throws FileNotFoundException, circuit.parser.conlist.ParseException{ //Read in con netlist. System.out.println("Read in con netlist "+netFile+".. "); Readconlist parser=new Readconlist(new FileInputStream(new File(netFile))); Circuit c=parser.read(); c.createBundles(); //Architecture Check if(c.clbs.size()>(height*width)){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of CLBs in the circuit exceeds the number of physical CLBs present on the FPGA."); } if(c.inputs.size()>(2*(height+width))){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of inputs in the circuit exceeds the number of physical IOBs present on the FPGA."); } if(c.outputs.size()>(2*(height+width))){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of outputs in the circuit exceeds the number of physical IOBs present on the FPGA."); } //Bundler System.out.println("Start bundling.. "); Bundler blr = new Bundler(c); final long startTime0 = System.nanoTime(); final long endTime0; try { blr.bundle(); } finally { endTime0 = System.nanoTime(); } final long duration0 = endTime0 - startTime0; System.out.println("Runtime: "+(duration0/1.0E9)); System.out.println("Connections are bundled in "+c.bundles.size()+" bundles"); // blr.printBundles(); //Aanmaken van de architectuur. System.out.println("Aanmaken van de architectuur."); FourLutSanitizedDisjoint a = new FourLutSanitizedDisjoint(width,height,1); Random rand = new Random(1); PlacementManipulatorIOCLB pm0 = new PlacementManipulatorIOCLB(a,c,rand); BoundingBoxBundleCC bbbcc = new BoundingBoxBundleCC(c); //Random placement Rplace.placeCLBsandIOs(c, a, rand); pm0.placementCLBsConsistencyCheck(); System.out.println("Total Cost random placement BBbundle cc: "+bbbcc.calculateTotalCost()); //Time placement process Vplace placer1= new Vplace(pm0,bbbcc); final long startTime1 = System.nanoTime(); final long endTime1; try { placer1.place(placementEffort); } finally { endTime1 = System.nanoTime(); } final long duration1 = endTime1 - startTime1; System.out.println("Runtime: "+(duration1/1.0E9)); System.out.println("Total BB Cost after placement with bb bundle cc: "+bbbcc.calculateTotalCost()); //Dump placement PlacementWriter.dumpPlacement(c, pFile); String line = "Placement effort: "+placementEffort+",\tnet file: " + netFile + "\n\t" + "Bundling: rt = "+(duration0/1.0E9)+", "+c.bundles.size()+" bundles" + "\n\t" + "Placement: rt = "+(duration1/1.0E9)+", Total BBB Cost: "+bbbcc.calculateTotalCost(); writeToFile(line,logFile); } public static void writeToFile(String str, String filename){ try{ // Create file FileWriter fstream = new FileWriter(filename,true); BufferedWriter out = new BufferedWriter(fstream); out.write(str); //Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }
EliasVansteenkiste/tpar
src/tpr/ExportTPAR.java
4,267
//Aanmaken van de architectuur.
line_comment
nl
package tpr; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import Bundler.Bundler; import Plaatsers.BoundingBoxBundleCC; import Plaatsers.PlacementManipulatorIOCLB; import Plaatsers.Rplace; import Plaatsers.Vplace; import PlacementParser.Placement; import PlacementParser.ReadPlacement; import TRouter.ConnectionRouterBB; import TRouter.VerificationModule; import architecture.FourLutSanitizedDisjoint; import circuit.Circuit; import circuit.parser.conlist.ParseException; import circuit.parser.conlist.Readconlist; import circuit.writer.PlacementWriter; import com.lexicalscope.jewel.cli.CliFactory; public class ExportTPAR { /** * @param args * @throws FileNotFoundException * @throws ParseException * @throws architecture.ParseException * @throws PlacementParser.ParseException */ public static void main(String[] args) throws FileNotFoundException, ParseException, PlacementParser.ParseException { System.out.println("Version information: TPack:advanced bundling, TPlace:SA with BB Bundle Estimation, TRoute:CrouteHwithConSmallestBBFirstOrder"); /* String[] testArgs1 = { "-p", "temp.p", "-n", "testcases/BVHCell-tconmap_out.net", "-w", "8", "-h", "8", "--routeOnly"}; String[] testArgs2 = { "--help" }; */ final Arguments cli = CliFactory.parseArguments(Arguments.class, args); if(cli.getPlacementOnly()){ if(cli.getRouteOnly()){ System.out.println("Error: conflicting command line options; 'Route only' and 'Placement only'"); }else{ placementOnly(cli.getHeight(),cli.getWidth(),cli.getPlacementEffort(),cli.getNetFilename(),cli.getPlacementFileName(),cli.getLogFileName()); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); writeToFile("---timeStamp---"+dateFormat.format(date)+"\n", cli.getLogFileName()); } }else if(cli.getRouteOnly()){ routeOnly(cli.getHeight(),cli.getWidth(),cli.getChannelWidth(),cli.getNrOfRoutingIterations(),cli.getNetFilename(),cli.getPlacementFileName(),cli.getLogFileName()); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); writeToFile("---timeStamp---"+dateFormat.format(date)+"\n", cli.getLogFileName()); }else{ par(cli.getHeight(), cli.getWidth(), cli.getChannelWidth(), cli.getPlacementEffort(), cli.getNrOfRoutingIterations(), cli.getNetFilename(), cli.getPlacementFileName(), cli.getLogFileName()); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); writeToFile("---timeStamp---"+dateFormat.format(date)+"\n", cli.getLogFileName()); } } public static int par(int height, int width, int channelWidth, int placementEffort, int routingIterations, String netFile, String pFile, String logFile) throws FileNotFoundException, circuit.parser.conlist.ParseException{ //Read in con netlist. System.out.println("Read in con netlist "+netFile+".. "); Readconlist parser=new Readconlist(new FileInputStream(new File(netFile))); Circuit c=parser.read(); c.createBundles(); //Architecture Check if(c.clbs.size()>(height*width)){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of CLBs in the circuit exceeds the number of physical CLBs present on the FPGA."); } if(c.inputs.size()>(2*(height+width))){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of inputs in the circuit exceeds the number of physical IOBs present on the FPGA."); } if(c.outputs.size()>(2*(height+width))){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of outputs in the circuit exceeds the number of physical IOBs present on the FPGA."); } //Bundler System.out.println("Start bundling.. "); Bundler blr = new Bundler(c); final long startTime0 = System.nanoTime(); final long endTime0; try { blr.bundle(); } finally { endTime0 = System.nanoTime(); } final long duration0 = endTime0 - startTime0; System.out.println("Runtime: "+(duration0/1.0E9)); System.out.println("Connections are bundled in "+c.bundles.size()+" bundles"); // blr.printBundles(); //Aanmaken van<SUF> System.out.println("Aanmaken van de architectuur."); FourLutSanitizedDisjoint a = new FourLutSanitizedDisjoint(width,height,channelWidth); Random rand = new Random(1); PlacementManipulatorIOCLB pm0 = new PlacementManipulatorIOCLB(a,c,rand); BoundingBoxBundleCC bbbcc = new BoundingBoxBundleCC(c); //Random placement Rplace.placeCLBsandIOs(c, a, rand); pm0.placementCLBsConsistencyCheck(); System.out.println("Total Cost random placement BBbundle cc: "+bbbcc.calculateTotalCost()); //Time placement process Vplace placer1= new Vplace(pm0,bbbcc); final long startTime1 = System.nanoTime(); final long endTime1; try { placer1.place(placementEffort); } finally { endTime1 = System.nanoTime(); } final long duration1 = endTime1 - startTime1; System.out.println("Runtime: "+(duration1/1.0E9)); System.out.println("Total BB Cost after placement with bb bundle cc: "+bbbcc.calculateTotalCost()); //Dump placement PlacementWriter.dumpPlacement(c, pFile); int its = -1; ConnectionRouterBB router = new ConnectionRouterBB(c); final long startTime2 = System.nanoTime(); final long endTime2; try { its = router.crouteHwithConSmallestBBFirstOrder(a, routingIterations); } finally { endTime2 = System.nanoTime(); } final long duration2 = endTime2 - startTime2; System.out.println("Runtime: "+(duration2/1.0E9)); System.out.println("Number of wires: "+c.totalWires()); if(c.totalWires()>0){ VerificationModule vfmodule = new VerificationModule(c); System.out.println("Starting verification... "+vfmodule.verificateConnectionRouter()); } String line = "Placement effort: "+placementEffort+",\tchannel width: "+channelWidth+"\t, routing iterations: "+routingIterations+",\tnet file: " + netFile + "\n\t" + "Bundling: rt = "+(duration0/1.0E9)+", "+c.bundles.size()+" bundles" + "\n\t" + "Placement: rt = "+(duration1/1.0E9)+", Total BBB Cost: "+bbbcc.calculateTotalCost() + "\n\t" + "Routing: rt = "+(duration2/1.0E9)+", wires = "+c.totalWires()+"\n"; writeToFile(line,logFile); return its; } public static int routeOnly(int height, int width, int channelWidth, int routingIterations, String netFile, String pFile, String logFile) throws FileNotFoundException, circuit.parser.conlist.ParseException, PlacementParser.ParseException{ //Read in con netlist. System.out.println("Read in con netlist "+netFile+".. "); Readconlist parser=new Readconlist(new FileInputStream(new File(netFile))); Circuit c=parser.read(); c.createBundles(); //Architecture Check if(c.clbs.size()>(height*width)){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of CLBs in the circuit exceeds the number of physical CLBs present on the FPGA."); } if(c.inputs.size()>(2*(height+width))){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of inputs in the circuit exceeds the number of physical IOBs present on the FPGA."); } if(c.outputs.size()>(2*(height+width))){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of outputs in the circuit exceeds the number of physical IOBs present on the FPGA."); } //Bundler System.out.println("Start bundling.. "); Bundler blr = new Bundler(c); final long startTime0 = System.nanoTime(); final long endTime0; try { blr.bundle(); } finally { endTime0 = System.nanoTime(); } final long duration0 = endTime0 - startTime0; System.out.println("Runtime: "+(duration0/1.0E9)); System.out.println("Connections are bundled in "+c.bundles.size()+" bundles"); // blr.printBundles(); //Aanmaken van de architectuur. System.out.println("Aanmaken van de architectuur."); FourLutSanitizedDisjoint a = new FourLutSanitizedDisjoint(width,height,channelWidth); ReadPlacement plaats_parser=new ReadPlacement(new FileInputStream(pFile)); Placement p=plaats_parser.read(); c.applyPlacement(p, a); int its = -1; ConnectionRouterBB router = new ConnectionRouterBB(c); final long startTime2 = System.nanoTime(); final long endTime2; try { its = router.crouteHwithConSmallestBBFirstOrder(a, routingIterations); } finally { endTime2 = System.nanoTime(); } final long duration2 = endTime2 - startTime2; System.out.println("Runtime: "+(duration2/1.0E9)); System.out.println("Number of wires: "+c.totalWires()); if(c.totalWires()>0){ VerificationModule vfmodule = new VerificationModule(c); System.out.println("Starting verification... "+vfmodule.verificateConnectionRouter()); } String line = "Channel Width:"+channelWidth+",\tRouting Iterations:"+routingIterations+ "\t,net file:" + netFile + "\n\t" + "Bundling: rt = "+(duration0/1.0E9)+", "+c.bundles.size()+" bundles" + "\n\t" + "Routing: rt = "+(duration2/1.0E9)+", wires = "+c.totalWires()+"\n"; writeToFile(line,logFile); return its; } public static void placementOnly(int height, int width, int placementEffort, String netFile, String pFile, String logFile) throws FileNotFoundException, circuit.parser.conlist.ParseException{ //Read in con netlist. System.out.println("Read in con netlist "+netFile+".. "); Readconlist parser=new Readconlist(new FileInputStream(new File(netFile))); Circuit c=parser.read(); c.createBundles(); //Architecture Check if(c.clbs.size()>(height*width)){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of CLBs in the circuit exceeds the number of physical CLBs present on the FPGA."); } if(c.inputs.size()>(2*(height+width))){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of inputs in the circuit exceeds the number of physical IOBs present on the FPGA."); } if(c.outputs.size()>(2*(height+width))){ System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of outputs in the circuit exceeds the number of physical IOBs present on the FPGA."); } //Bundler System.out.println("Start bundling.. "); Bundler blr = new Bundler(c); final long startTime0 = System.nanoTime(); final long endTime0; try { blr.bundle(); } finally { endTime0 = System.nanoTime(); } final long duration0 = endTime0 - startTime0; System.out.println("Runtime: "+(duration0/1.0E9)); System.out.println("Connections are bundled in "+c.bundles.size()+" bundles"); // blr.printBundles(); //Aanmaken van de architectuur. System.out.println("Aanmaken van de architectuur."); FourLutSanitizedDisjoint a = new FourLutSanitizedDisjoint(width,height,1); Random rand = new Random(1); PlacementManipulatorIOCLB pm0 = new PlacementManipulatorIOCLB(a,c,rand); BoundingBoxBundleCC bbbcc = new BoundingBoxBundleCC(c); //Random placement Rplace.placeCLBsandIOs(c, a, rand); pm0.placementCLBsConsistencyCheck(); System.out.println("Total Cost random placement BBbundle cc: "+bbbcc.calculateTotalCost()); //Time placement process Vplace placer1= new Vplace(pm0,bbbcc); final long startTime1 = System.nanoTime(); final long endTime1; try { placer1.place(placementEffort); } finally { endTime1 = System.nanoTime(); } final long duration1 = endTime1 - startTime1; System.out.println("Runtime: "+(duration1/1.0E9)); System.out.println("Total BB Cost after placement with bb bundle cc: "+bbbcc.calculateTotalCost()); //Dump placement PlacementWriter.dumpPlacement(c, pFile); String line = "Placement effort: "+placementEffort+",\tnet file: " + netFile + "\n\t" + "Bundling: rt = "+(duration0/1.0E9)+", "+c.bundles.size()+" bundles" + "\n\t" + "Placement: rt = "+(duration1/1.0E9)+", Total BBB Cost: "+bbbcc.calculateTotalCost(); writeToFile(line,logFile); } public static void writeToFile(String str, String filename){ try{ // Create file FileWriter fstream = new FileWriter(filename,true); BufferedWriter out = new BufferedWriter(fstream); out.write(str); //Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }
52687_6
package novi.nl.Les11BESpringbootmodelhuiswerk.models; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.util.List; @Entity @Table(name = "cimodules") public class CIModule { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String type; private Double price; // Een ManyToOne relatie tussen Television en CI-Module // @OneToMany(mappedBy = "cimodule") // private List<Television> televisions; // OneToMany relatie tussen Television en CI-Module @ManyToOne private Television television; //getters & setters........................................ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } // hoort bij ManyToOne public Television getTelevision() { return television; } public void setTelevision(Television television) { this.television = television; } // hoort bij OneToMany // public List<Television> getTelevisions() { // return televisions; // } // // public void setTelevisions(List<Television> televisions) { // this.televisions = televisions; // } }
Ellen-van-Duikeren/BE-spring-boot-model-huiswerk-Les11
src/main/java/novi/nl/Les11BESpringbootmodelhuiswerk/models/CIModule.java
493
// hoort bij OneToMany
line_comment
nl
package novi.nl.Les11BESpringbootmodelhuiswerk.models; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.util.List; @Entity @Table(name = "cimodules") public class CIModule { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String type; private Double price; // Een ManyToOne relatie tussen Television en CI-Module // @OneToMany(mappedBy = "cimodule") // private List<Television> televisions; // OneToMany relatie tussen Television en CI-Module @ManyToOne private Television television; //getters & setters........................................ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } // hoort bij ManyToOne public Television getTelevision() { return television; } public void setTelevision(Television television) { this.television = television; } // hoort bij<SUF> // public List<Television> getTelevisions() { // return televisions; // } // // public void setTelevisions(List<Television> televisions) { // this.televisions = televisions; // } }
67105_0
package org.destiny.client.messages.events; import org.destiny.client.Session; import org.destiny.client.backend.BattleManager; import org.destiny.client.messages.MessageEvent; import org.destiny.client.protocol.ClientMessage; import org.destiny.client.protocol.ServerMessage; public class BattleStartEvent implements MessageEvent { @Override public void parse(Session Session, ServerMessage Request, ClientMessage Message) { /* Dit heb ik veranderd van char naar bool! Want we kunnen nu bools lezen. */ BattleManager.getInstance().startBattle(Request.readBool(), Request.readInt()); } }
Elligent/destinyclient
src/org/destiny/client/messages/events/BattleStartEvent.java
168
/* Dit heb ik veranderd van char naar bool! Want we kunnen nu bools lezen. */
block_comment
nl
package org.destiny.client.messages.events; import org.destiny.client.Session; import org.destiny.client.backend.BattleManager; import org.destiny.client.messages.MessageEvent; import org.destiny.client.protocol.ClientMessage; import org.destiny.client.protocol.ServerMessage; public class BattleStartEvent implements MessageEvent { @Override public void parse(Session Session, ServerMessage Request, ClientMessage Message) { /* Dit heb ik<SUF>*/ BattleManager.getInstance().startBattle(Request.readBool(), Request.readInt()); } }
90550_0
package nl.han.ica.icss.checker; import nl.han.ica.datastructures.ISymbolTable; import nl.han.ica.datastructures.SymbolTableImpl; import nl.han.ica.icss.ast.*; import nl.han.ica.icss.ast.types.ExpressionType; import java.util.LinkedList; import java.util.List; public class Checker { public ISymbolTable<String, ExpressionType> symbolTable; private List<BaseCheck> checks; public Checker() { checks = new LinkedList<>(); checks.add(new VariableReferenceCheck(this)); checks.add(new DeclerationCheck(this)); checks.add(new IfCheck(this)); checks.add(new OperationCheck(this)); checks.add(new BooleanExpressionChecker(this)); checks.add(new VariableAssignmentCheck(this)); } public void check(AST ast) { symbolTable = new SymbolTableImpl(); checkNodes(ast.root); } private void checkNodes (ASTNode node) { for (ASTNode childNode: node.getChildren() ) { constructsymboltable(childNode); checkNode(childNode); checkNodes(childNode); aftersymboltable(childNode); } } private void aftersymboltable(ASTNode childNode) { if(childNode instanceof VariableAssignment) { VariableAssignment var = (VariableAssignment) childNode; symbolTable.assignSymbol(var.name.name, resolve_type_of_lit_op_varreference(var.expression)); } if(childNode instanceof Stylerule || childNode instanceof IfClause) { symbolTable.removeScope(); } } // Heb net door mijn refactor de else clause scope regelen geborked. private void constructsymboltable(ASTNode childNode) { if(childNode instanceof Stylerule || childNode instanceof IfClause) { symbolTable.newScope(); } if(childNode instanceof ElseClause) { symbolTable.removeScope(); symbolTable.newScope(); } } public ExpressionType resolve_type_of_lit_op_varreference(Expression ex) { // Literal direct if (ex instanceof Literal) { return ((Literal) ex).GetExpressionType(); } // Expression check soort expression else if (ex instanceof Operation) { Operation op = (Operation) ex; ExpressionType type; type = resolve_type_of_lit_op_varreference(op.lhs); ExpressionType typerhs = resolve_type_of_lit_op_varreference(op.rhs); if (typerhs == ExpressionType.PERCENTAGE) { type = ExpressionType.PERCENTAGE; } else if (typerhs == ExpressionType.PIXEL) { type = ExpressionType.PIXEL; } return type; } // Var pak uit symbol table else if (ex instanceof VariableReference) { return symbolTable.getValue(((VariableReference) ex).name); } else if (ex instanceof BooleanExpression) { return ExpressionType.BOOL; } return ExpressionType.UNDEFINED; } private void checkNode(ASTNode childNode) { for (BaseCheck bc: checks) { bc.checkRule(childNode); } } }
Elmar-Wiese/APP_Compiler_ICSS_to_CSS
startcode/src/main/java/nl/han/ica/icss/checker/Checker.java
879
// Heb net door mijn refactor de else clause scope regelen geborked.
line_comment
nl
package nl.han.ica.icss.checker; import nl.han.ica.datastructures.ISymbolTable; import nl.han.ica.datastructures.SymbolTableImpl; import nl.han.ica.icss.ast.*; import nl.han.ica.icss.ast.types.ExpressionType; import java.util.LinkedList; import java.util.List; public class Checker { public ISymbolTable<String, ExpressionType> symbolTable; private List<BaseCheck> checks; public Checker() { checks = new LinkedList<>(); checks.add(new VariableReferenceCheck(this)); checks.add(new DeclerationCheck(this)); checks.add(new IfCheck(this)); checks.add(new OperationCheck(this)); checks.add(new BooleanExpressionChecker(this)); checks.add(new VariableAssignmentCheck(this)); } public void check(AST ast) { symbolTable = new SymbolTableImpl(); checkNodes(ast.root); } private void checkNodes (ASTNode node) { for (ASTNode childNode: node.getChildren() ) { constructsymboltable(childNode); checkNode(childNode); checkNodes(childNode); aftersymboltable(childNode); } } private void aftersymboltable(ASTNode childNode) { if(childNode instanceof VariableAssignment) { VariableAssignment var = (VariableAssignment) childNode; symbolTable.assignSymbol(var.name.name, resolve_type_of_lit_op_varreference(var.expression)); } if(childNode instanceof Stylerule || childNode instanceof IfClause) { symbolTable.removeScope(); } } // Heb net<SUF> private void constructsymboltable(ASTNode childNode) { if(childNode instanceof Stylerule || childNode instanceof IfClause) { symbolTable.newScope(); } if(childNode instanceof ElseClause) { symbolTable.removeScope(); symbolTable.newScope(); } } public ExpressionType resolve_type_of_lit_op_varreference(Expression ex) { // Literal direct if (ex instanceof Literal) { return ((Literal) ex).GetExpressionType(); } // Expression check soort expression else if (ex instanceof Operation) { Operation op = (Operation) ex; ExpressionType type; type = resolve_type_of_lit_op_varreference(op.lhs); ExpressionType typerhs = resolve_type_of_lit_op_varreference(op.rhs); if (typerhs == ExpressionType.PERCENTAGE) { type = ExpressionType.PERCENTAGE; } else if (typerhs == ExpressionType.PIXEL) { type = ExpressionType.PIXEL; } return type; } // Var pak uit symbol table else if (ex instanceof VariableReference) { return symbolTable.getValue(((VariableReference) ex).name); } else if (ex instanceof BooleanExpression) { return ExpressionType.BOOL; } return ExpressionType.UNDEFINED; } private void checkNode(ASTNode childNode) { for (BaseCheck bc: checks) { bc.checkRule(childNode); } } }
125358_1
package bibliotheek.mensen; /** * Representeert een lid van de bibliotheek. */ public class Lid { public String naam; int geboorteJaar; int leeftijd; public Pas pas; /** * Constructor om een nieuw Lid-object aan te maken. * * @param naam Naam van de nieuwe lid. * @param geboorteJaar Geboortejaar van de nieuwe lid. */ public Lid(String naam, int geboorteJaar) { this.naam = naam; this.geboorteJaar = geboorteJaar; this.pas = new Pas(); } /** * Constructor om een nieuw Lid-object aan te maken met geen argumenten. */ public Lid(){ this.pas = new Pas(); } }
Eloise-es/java-foundations-exam-prep
2-Basic-Java-Elements/library-project/bibliotheek/mensen/Lid.java
228
/** * Constructor om een nieuw Lid-object aan te maken. * * @param naam Naam van de nieuwe lid. * @param geboorteJaar Geboortejaar van de nieuwe lid. */
block_comment
nl
package bibliotheek.mensen; /** * Representeert een lid van de bibliotheek. */ public class Lid { public String naam; int geboorteJaar; int leeftijd; public Pas pas; /** * Constructor om een<SUF>*/ public Lid(String naam, int geboorteJaar) { this.naam = naam; this.geboorteJaar = geboorteJaar; this.pas = new Pas(); } /** * Constructor om een nieuw Lid-object aan te maken met geen argumenten. */ public Lid(){ this.pas = new Pas(); } }
79337_10
package si.ijs.kt.clus.heuristic.hierarchical; import si.ijs.kt.clus.data.attweights.ClusAttributeWeights; import si.ijs.kt.clus.data.type.ClusAttrType.AttributeUseType; import si.ijs.kt.clus.heuristic.ClusHeuristic; import si.ijs.kt.clus.main.ClusStatManager; import si.ijs.kt.clus.main.settings.Settings; import si.ijs.kt.clus.main.settings.section.SettingsTree; import si.ijs.kt.clus.statistic.ClusStatistic; public class ClusRuleHeuristicHierarchical extends ClusHeuristic { protected ClusStatManager m_StatManager; public ClusRuleHeuristicHierarchical(ClusStatManager stat_mgr, ClusAttributeWeights prod, Settings sett) { super(sett); m_StatManager = stat_mgr; m_ClusteringWeights = prod; } /** * This heuristic calculates: * ( |S|.Var(S) - |Sr|.Var(Sr) ) . Coverage(r) */ @Override public double calcHeuristic(ClusStatistic c_tstat, ClusStatistic c_pstat, ClusStatistic missing) { double n_pos = c_pstat.getTotalWeight(); if (n_pos - SettingsTree.MINIMAL_WEIGHT < 1e-6) { // (n_pos < Settings.MINIMAL_WEIGHT) return Double.NEGATIVE_INFINITY; } // Calculate |S|.Var(S) - |Sr|.Var(Sr) // WHTDStatistic tstat = (WHTDStatistic) m_StatManager.getTrainSetStat(); // Geeft classcastexception (is // blijkbaar een CombStat) // WHTDStatistic tstat = (WHTDStatistic) m_StatManager.getStatistic(AttributeUseType.Target); // (is altijd // 0...) // WHTDStatistic tstat = (WHTDStatistic) m_StatManager.getTrainSetStat(ClusAttrType.ATTR_USE_CLUSTERING); // double totalValue = tstat.getSS(m_TargetWeights); double totalValue = getTrainDataHeurValue(); // optimization of the previous two lines double ruleValue = c_pstat.getSVarS(m_ClusteringWeights); double value = totalValue - ruleValue; // ClusLogger.info("Difference made by rule: " + totalValue + " - " + ruleValue); // Coverage(r) part double train_sum_w = m_StatManager.getTrainSetStat(AttributeUseType.Clustering).getTotalWeight(); double coverage = (n_pos / train_sum_w); double cov_par = m_StatManager.getSettings().getRules().getHeurCoveragePar(); coverage = Math.pow(coverage, cov_par); value = value * coverage; // ClusLogger.info("Totale Heuristiek: " + value + " Coverage: " + coverage); return value; } @Override public String getName() { return "RuleHeuristicHierarchical"; } }
ElsevierSoftwareX/SOFTX-D-23-00369
ClusProject/src/main/java/si/ijs/kt/clus/heuristic/hierarchical/ClusRuleHeuristicHierarchical.java
849
// ClusLogger.info("Totale Heuristiek: " + value + " Coverage: " + coverage);
line_comment
nl
package si.ijs.kt.clus.heuristic.hierarchical; import si.ijs.kt.clus.data.attweights.ClusAttributeWeights; import si.ijs.kt.clus.data.type.ClusAttrType.AttributeUseType; import si.ijs.kt.clus.heuristic.ClusHeuristic; import si.ijs.kt.clus.main.ClusStatManager; import si.ijs.kt.clus.main.settings.Settings; import si.ijs.kt.clus.main.settings.section.SettingsTree; import si.ijs.kt.clus.statistic.ClusStatistic; public class ClusRuleHeuristicHierarchical extends ClusHeuristic { protected ClusStatManager m_StatManager; public ClusRuleHeuristicHierarchical(ClusStatManager stat_mgr, ClusAttributeWeights prod, Settings sett) { super(sett); m_StatManager = stat_mgr; m_ClusteringWeights = prod; } /** * This heuristic calculates: * ( |S|.Var(S) - |Sr|.Var(Sr) ) . Coverage(r) */ @Override public double calcHeuristic(ClusStatistic c_tstat, ClusStatistic c_pstat, ClusStatistic missing) { double n_pos = c_pstat.getTotalWeight(); if (n_pos - SettingsTree.MINIMAL_WEIGHT < 1e-6) { // (n_pos < Settings.MINIMAL_WEIGHT) return Double.NEGATIVE_INFINITY; } // Calculate |S|.Var(S) - |Sr|.Var(Sr) // WHTDStatistic tstat = (WHTDStatistic) m_StatManager.getTrainSetStat(); // Geeft classcastexception (is // blijkbaar een CombStat) // WHTDStatistic tstat = (WHTDStatistic) m_StatManager.getStatistic(AttributeUseType.Target); // (is altijd // 0...) // WHTDStatistic tstat = (WHTDStatistic) m_StatManager.getTrainSetStat(ClusAttrType.ATTR_USE_CLUSTERING); // double totalValue = tstat.getSS(m_TargetWeights); double totalValue = getTrainDataHeurValue(); // optimization of the previous two lines double ruleValue = c_pstat.getSVarS(m_ClusteringWeights); double value = totalValue - ruleValue; // ClusLogger.info("Difference made by rule: " + totalValue + " - " + ruleValue); // Coverage(r) part double train_sum_w = m_StatManager.getTrainSetStat(AttributeUseType.Clustering).getTotalWeight(); double coverage = (n_pos / train_sum_w); double cov_par = m_StatManager.getSettings().getRules().getHeurCoveragePar(); coverage = Math.pow(coverage, cov_par); value = value * coverage; // ClusLogger.info("Totale Heuristiek:<SUF> return value; } @Override public String getName() { return "RuleHeuristicHierarchical"; } }
22188_0
/* ***************************** * Author: ELvira van der Ven * * Date: 13/11/2023 * * *******************************/ /* Bouw een programma wat: - Een getal aan de gebruiker kan vragen - Het gegeven getal gebruikt om letters uit het alfabet op het scherm te printen in regels o Per regel komt er steeds 1 letter bij, totdat er net zoveel letters op de regel staan als het getal wat opgegeven is o Bij ‘5’, print je 5 rijen, bij ‘6’ 6, enz. o Voorbeeldoutput bij input ‘5’: A A B A B C A B C D A B C D E - Bij input > 26 kom je na de ‘Z’ weer uit bij ‘A’ en ga je opnieuw het alfabet af. - Zorg dat het programma niet kan crashen! */ package week1; import java.util.Scanner; public class AlphabetSequence { public static void main(String[] args) { String alphabet = "abcdefghijklmnopqrstuwvxyz"; Scanner inputScanner = new Scanner(System.in); int gebruikers_input = 0; String run = "ja"; while (run.equalsIgnoreCase("ja")) { System.out.println("Voer een positief, geheel getal in:"); gebruikers_input = inputScanner.nextInt(); //System.out.println("U hebt " + gebruikers_input + " ingetyped."); if(gebruikers_input < 0){ System.out.println(""" Wat is niet te begrijpen aan positief?! Probeer het opnieuw."""); } for (int i = 0; i < gebruikers_input; i++) { for(int j = 0; j < i+1; j++) { System.out.print(alphabet.charAt(j % alphabet.length()) + " "); } System.out.println(); } //String literals System.out.println(""" Wilt u nog een getal invoeren? Type dan "Ja" Wilt u afsluiten? Type dan "Nee"."""); run = inputScanner.next(); } } }
ElviravdVen/TINPRO04-2_2324
hw_opdrachten/src/week1/AlphabetSequence.java
621
/* ***************************** * Author: ELvira van der Ven * * Date: 13/11/2023 * * *******************************/
block_comment
nl
/* ***************************** * Author: ELvira van<SUF>*/ /* Bouw een programma wat: - Een getal aan de gebruiker kan vragen - Het gegeven getal gebruikt om letters uit het alfabet op het scherm te printen in regels o Per regel komt er steeds 1 letter bij, totdat er net zoveel letters op de regel staan als het getal wat opgegeven is o Bij ‘5’, print je 5 rijen, bij ‘6’ 6, enz. o Voorbeeldoutput bij input ‘5’: A A B A B C A B C D A B C D E - Bij input > 26 kom je na de ‘Z’ weer uit bij ‘A’ en ga je opnieuw het alfabet af. - Zorg dat het programma niet kan crashen! */ package week1; import java.util.Scanner; public class AlphabetSequence { public static void main(String[] args) { String alphabet = "abcdefghijklmnopqrstuwvxyz"; Scanner inputScanner = new Scanner(System.in); int gebruikers_input = 0; String run = "ja"; while (run.equalsIgnoreCase("ja")) { System.out.println("Voer een positief, geheel getal in:"); gebruikers_input = inputScanner.nextInt(); //System.out.println("U hebt " + gebruikers_input + " ingetyped."); if(gebruikers_input < 0){ System.out.println(""" Wat is niet te begrijpen aan positief?! Probeer het opnieuw."""); } for (int i = 0; i < gebruikers_input; i++) { for(int j = 0; j < i+1; j++) { System.out.print(alphabet.charAt(j % alphabet.length()) + " "); } System.out.println(); } //String literals System.out.println(""" Wilt u nog een getal invoeren? Type dan "Ja" Wilt u afsluiten? Type dan "Nee"."""); run = inputScanner.next(); } } }
102998_82
/****************************************************************************** * Product: ADempiere ERP & CRM Smart Business Solution * * Copyright (C) 2006-2017 ADempiere Foundation, All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * or (at your option) any later version. * * by the Free Software Foundation. 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. * * For the text or an alternative of this public license, you may reach us * * or via [email protected] or http://www.adempiere.net/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.util.KeyNamePair; /** Generated Interface for PA_DashboardContent * @author Adempiere (generated) * @version Release 3.9.2 */ public interface I_PA_DashboardContent { /** TableName=PA_DashboardContent */ public static final String Table_Name = "PA_DashboardContent"; /** AD_Table_ID=50010 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 6 - System - Client */ BigDecimal accessLevel = BigDecimal.valueOf(6); /** Load Meta Data */ /** Column name AD_Browse_ID */ public static final String COLUMNNAME_AD_Browse_ID = "AD_Browse_ID"; /** Set Smart Browse */ public void setAD_Browse_ID (int AD_Browse_ID); /** Get Smart Browse */ public int getAD_Browse_ID(); public org.adempiere.model.I_AD_Browse getAD_Browse() throws RuntimeException; /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name AD_Window_ID */ public static final String COLUMNNAME_AD_Window_ID = "AD_Window_ID"; /** Set Window. * Data entry or display window */ public void setAD_Window_ID (int AD_Window_ID); /** Get Window. * Data entry or display window */ public int getAD_Window_ID(); public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException; /** Column name AccessLevel */ public static final String COLUMNNAME_AccessLevel = "AccessLevel"; /** Set Data Access Level. * Access Level required */ public void setAccessLevel (String AccessLevel); /** Get Data Access Level. * Access Level required */ public String getAccessLevel(); /** Column name ColumnNo */ public static final String COLUMNNAME_ColumnNo = "ColumnNo"; /** Set Column No. * Dashboard content column number */ public void setColumnNo (int ColumnNo); /** Get Column No. * Dashboard content column number */ public int getColumnNo(); /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name Description */ public static final String COLUMNNAME_Description = "Description"; /** Set Description. * Optional short description of the record */ public void setDescription (String Description); /** Get Description. * Optional short description of the record */ public String getDescription(); /** Column name GoalDisplay */ public static final String COLUMNNAME_GoalDisplay = "GoalDisplay"; /** Set Goal Display. * Type of goal display on dashboard */ public void setGoalDisplay (String GoalDisplay); /** Get Goal Display. * Type of goal display on dashboard */ public String getGoalDisplay(); /** Column name HTML */ public static final String COLUMNNAME_HTML = "HTML"; /** Set HTML */ public void setHTML (String HTML); /** Get HTML */ public String getHTML(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name IsCollapsible */ public static final String COLUMNNAME_IsCollapsible = "IsCollapsible"; /** Set Collapsible. * Flag to indicate the state of the dashboard panel */ public void setIsCollapsible (boolean IsCollapsible); /** Get Collapsible. * Flag to indicate the state of the dashboard panel */ public boolean isCollapsible(); /** Column name IsEventRequired */ public static final String COLUMNNAME_IsEventRequired = "IsEventRequired"; /** Set IsEventRequired */ public void setIsEventRequired (boolean IsEventRequired); /** Get IsEventRequired */ public boolean isEventRequired(); /** Column name IsOpenByDefault */ public static final String COLUMNNAME_IsOpenByDefault = "IsOpenByDefault"; /** Set Open By Default */ public void setIsOpenByDefault (boolean IsOpenByDefault); /** Get Open By Default */ public boolean isOpenByDefault(); /** Column name Line */ public static final String COLUMNNAME_Line = "Line"; /** Set Line No. * Unique line for this document */ public void setLine (int Line); /** Get Line No. * Unique line for this document */ public int getLine(); /** Column name Name */ public static final String COLUMNNAME_Name = "Name"; /** Set Name. * Alphanumeric identifier of the entity */ public void setName (String Name); /** Get Name. * Alphanumeric identifier of the entity */ public String getName(); /** Column name PA_DashboardContent_ID */ public static final String COLUMNNAME_PA_DashboardContent_ID = "PA_DashboardContent_ID"; /** Set Dashboard Content */ public void setPA_DashboardContent_ID (int PA_DashboardContent_ID); /** Get Dashboard Content */ public int getPA_DashboardContent_ID(); /** Column name PA_Goal_ID */ public static final String COLUMNNAME_PA_Goal_ID = "PA_Goal_ID"; /** Set Goal. * Performance Goal */ public void setPA_Goal_ID (int PA_Goal_ID); /** Get Goal. * Performance Goal */ public int getPA_Goal_ID(); public org.compiere.model.I_PA_Goal getPA_Goal() throws RuntimeException; /** Column name PageSize */ public static final String COLUMNNAME_PageSize = "PageSize"; /** Set PageSize */ public void setPageSize (BigDecimal PageSize); /** Get PageSize */ public BigDecimal getPageSize(); /** Column name UUID */ public static final String COLUMNNAME_UUID = "UUID"; /** Set Immutable Universally Unique Identifier. * Immutable Universally Unique Identifier */ public void setUUID (String UUID); /** Get Immutable Universally Unique Identifier. * Immutable Universally Unique Identifier */ public String getUUID(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); /** Column name Zoom_Field_ID */ public static final String COLUMNNAME_Zoom_Field_ID = "Zoom_Field_ID"; /** Set Zoom_Field_ID */ public void setZoom_Field_ID (int Zoom_Field_ID); /** Get Zoom_Field_ID */ public int getZoom_Field_ID(); public org.adempiere.model.I_AD_Browse_Field getZoom_Field() throws RuntimeException; /** Column name Zoom_Tab_ID */ public static final String COLUMNNAME_Zoom_Tab_ID = "Zoom_Tab_ID"; /** Set Zoom_Tab_ID */ public void setZoom_Tab_ID (int Zoom_Tab_ID); /** Get Zoom_Tab_ID */ public int getZoom_Tab_ID(); public org.compiere.model.I_AD_Tab getZoom_Tab() throws RuntimeException; /** Column name Zoom_Window_ID */ public static final String COLUMNNAME_Zoom_Window_ID = "Zoom_Window_ID"; /** Set Zoom_Window_ID */ public void setZoom_Window_ID (int Zoom_Window_ID); /** Get Zoom_Window_ID */ public int getZoom_Window_ID(); public org.compiere.model.I_AD_Window getZoom_Window() throws RuntimeException; /** Column name ZulFilePath */ public static final String COLUMNNAME_ZulFilePath = "ZulFilePath"; /** Set ZUL File Path. * Absolute path to zul file */ public void setZulFilePath (String ZulFilePath); /** Get ZUL File Path. * Absolute path to zul file */ public String getZulFilePath(); /** Column name onevent */ public static final String COLUMNNAME_onevent = "onevent"; /** Set onevent */ public void setonevent (String onevent); /** Get onevent */ public String getonevent(); }
EmerisScala/adempiere
base/src/org/compiere/model/I_PA_DashboardContent.java
3,029
/** Get onevent */
block_comment
nl
/****************************************************************************** * Product: ADempiere ERP & CRM Smart Business Solution * * Copyright (C) 2006-2017 ADempiere Foundation, All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * or (at your option) any later version. * * by the Free Software Foundation. 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. * * For the text or an alternative of this public license, you may reach us * * or via [email protected] or http://www.adempiere.net/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.util.KeyNamePair; /** Generated Interface for PA_DashboardContent * @author Adempiere (generated) * @version Release 3.9.2 */ public interface I_PA_DashboardContent { /** TableName=PA_DashboardContent */ public static final String Table_Name = "PA_DashboardContent"; /** AD_Table_ID=50010 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 6 - System - Client */ BigDecimal accessLevel = BigDecimal.valueOf(6); /** Load Meta Data */ /** Column name AD_Browse_ID */ public static final String COLUMNNAME_AD_Browse_ID = "AD_Browse_ID"; /** Set Smart Browse */ public void setAD_Browse_ID (int AD_Browse_ID); /** Get Smart Browse */ public int getAD_Browse_ID(); public org.adempiere.model.I_AD_Browse getAD_Browse() throws RuntimeException; /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name AD_Window_ID */ public static final String COLUMNNAME_AD_Window_ID = "AD_Window_ID"; /** Set Window. * Data entry or display window */ public void setAD_Window_ID (int AD_Window_ID); /** Get Window. * Data entry or display window */ public int getAD_Window_ID(); public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException; /** Column name AccessLevel */ public static final String COLUMNNAME_AccessLevel = "AccessLevel"; /** Set Data Access Level. * Access Level required */ public void setAccessLevel (String AccessLevel); /** Get Data Access Level. * Access Level required */ public String getAccessLevel(); /** Column name ColumnNo */ public static final String COLUMNNAME_ColumnNo = "ColumnNo"; /** Set Column No. * Dashboard content column number */ public void setColumnNo (int ColumnNo); /** Get Column No. * Dashboard content column number */ public int getColumnNo(); /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name Description */ public static final String COLUMNNAME_Description = "Description"; /** Set Description. * Optional short description of the record */ public void setDescription (String Description); /** Get Description. * Optional short description of the record */ public String getDescription(); /** Column name GoalDisplay */ public static final String COLUMNNAME_GoalDisplay = "GoalDisplay"; /** Set Goal Display. * Type of goal display on dashboard */ public void setGoalDisplay (String GoalDisplay); /** Get Goal Display. * Type of goal display on dashboard */ public String getGoalDisplay(); /** Column name HTML */ public static final String COLUMNNAME_HTML = "HTML"; /** Set HTML */ public void setHTML (String HTML); /** Get HTML */ public String getHTML(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name IsCollapsible */ public static final String COLUMNNAME_IsCollapsible = "IsCollapsible"; /** Set Collapsible. * Flag to indicate the state of the dashboard panel */ public void setIsCollapsible (boolean IsCollapsible); /** Get Collapsible. * Flag to indicate the state of the dashboard panel */ public boolean isCollapsible(); /** Column name IsEventRequired */ public static final String COLUMNNAME_IsEventRequired = "IsEventRequired"; /** Set IsEventRequired */ public void setIsEventRequired (boolean IsEventRequired); /** Get IsEventRequired */ public boolean isEventRequired(); /** Column name IsOpenByDefault */ public static final String COLUMNNAME_IsOpenByDefault = "IsOpenByDefault"; /** Set Open By Default */ public void setIsOpenByDefault (boolean IsOpenByDefault); /** Get Open By Default */ public boolean isOpenByDefault(); /** Column name Line */ public static final String COLUMNNAME_Line = "Line"; /** Set Line No. * Unique line for this document */ public void setLine (int Line); /** Get Line No. * Unique line for this document */ public int getLine(); /** Column name Name */ public static final String COLUMNNAME_Name = "Name"; /** Set Name. * Alphanumeric identifier of the entity */ public void setName (String Name); /** Get Name. * Alphanumeric identifier of the entity */ public String getName(); /** Column name PA_DashboardContent_ID */ public static final String COLUMNNAME_PA_DashboardContent_ID = "PA_DashboardContent_ID"; /** Set Dashboard Content */ public void setPA_DashboardContent_ID (int PA_DashboardContent_ID); /** Get Dashboard Content */ public int getPA_DashboardContent_ID(); /** Column name PA_Goal_ID */ public static final String COLUMNNAME_PA_Goal_ID = "PA_Goal_ID"; /** Set Goal. * Performance Goal */ public void setPA_Goal_ID (int PA_Goal_ID); /** Get Goal. * Performance Goal */ public int getPA_Goal_ID(); public org.compiere.model.I_PA_Goal getPA_Goal() throws RuntimeException; /** Column name PageSize */ public static final String COLUMNNAME_PageSize = "PageSize"; /** Set PageSize */ public void setPageSize (BigDecimal PageSize); /** Get PageSize */ public BigDecimal getPageSize(); /** Column name UUID */ public static final String COLUMNNAME_UUID = "UUID"; /** Set Immutable Universally Unique Identifier. * Immutable Universally Unique Identifier */ public void setUUID (String UUID); /** Get Immutable Universally Unique Identifier. * Immutable Universally Unique Identifier */ public String getUUID(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); /** Column name Zoom_Field_ID */ public static final String COLUMNNAME_Zoom_Field_ID = "Zoom_Field_ID"; /** Set Zoom_Field_ID */ public void setZoom_Field_ID (int Zoom_Field_ID); /** Get Zoom_Field_ID */ public int getZoom_Field_ID(); public org.adempiere.model.I_AD_Browse_Field getZoom_Field() throws RuntimeException; /** Column name Zoom_Tab_ID */ public static final String COLUMNNAME_Zoom_Tab_ID = "Zoom_Tab_ID"; /** Set Zoom_Tab_ID */ public void setZoom_Tab_ID (int Zoom_Tab_ID); /** Get Zoom_Tab_ID */ public int getZoom_Tab_ID(); public org.compiere.model.I_AD_Tab getZoom_Tab() throws RuntimeException; /** Column name Zoom_Window_ID */ public static final String COLUMNNAME_Zoom_Window_ID = "Zoom_Window_ID"; /** Set Zoom_Window_ID */ public void setZoom_Window_ID (int Zoom_Window_ID); /** Get Zoom_Window_ID */ public int getZoom_Window_ID(); public org.compiere.model.I_AD_Window getZoom_Window() throws RuntimeException; /** Column name ZulFilePath */ public static final String COLUMNNAME_ZulFilePath = "ZulFilePath"; /** Set ZUL File Path. * Absolute path to zul file */ public void setZulFilePath (String ZulFilePath); /** Get ZUL File Path. * Absolute path to zul file */ public String getZulFilePath(); /** Column name onevent */ public static final String COLUMNNAME_onevent = "onevent"; /** Set onevent */ public void setonevent (String onevent); /** Get onevent <SUF>*/ public String getonevent(); }
117226_0
package nl.belastingdienst.autogarage.service; import nl.belastingdienst.autogarage.dto.AppointmentDto; import nl.belastingdienst.autogarage.model.Appointment; import nl.belastingdienst.autogarage.repository.AppointmentRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; @ExtendWith(MockitoExtension.class) class AppointmentServiceTest { @Mock AppointmentRepository appointmentRepository; @InjectMocks AppointmentService appointmentService; @Mock Appointment appointment1; @Mock Appointment appointment2; @Mock AppointmentDto appointmentDto1; @Mock AppointmentDto appointmentDto2; @BeforeEach public void setup(){ appointment1 = new Appointment(LocalDateTime.of(2020,10,6,10,00), LocalDateTime.of(2020, 10,6,11,00)); appointment1.setId(1L); appointment2 = new Appointment(LocalDateTime.of(2020,10,6,11,30), LocalDateTime.of(2020,10,6,12,00)); appointment2.setId(2L); appointmentDto1 = new AppointmentDto(LocalDateTime.of(2020,10,6,10,00), LocalDateTime.of(2020, 10,6,11,00)); appointmentDto1.setId(1L); appointmentDto2 = new AppointmentDto(LocalDateTime.of(2020,10,6,11,30), LocalDateTime.of(2020,10,6,12,00)); appointmentDto2.setId(2L); //Id wordt in het programma geregeld door springboot //om de test te laten slagen worden ze hier handmatig overschreven } @Test void allAppointments(){ List<Appointment> appointmentList = new ArrayList<>(); appointmentList.add(appointment1); appointmentList.add(appointment2); List<AppointmentDto> expected = new ArrayList<>(); expected.add(appointmentDto1); expected.add(appointmentDto2); Mockito .when(appointmentRepository.findAll()) .thenReturn(appointmentList); List<AppointmentDto> actual = appointmentService.allAppointments(); assertEquals(expected.get(0).getId(), actual.get(0).getId()); assertEquals(expected.get(0).getStartAppointment(), actual.get(0).getStartAppointment()); assertEquals(expected.get(0).getEndAppointment(), actual.get(0).getEndAppointment()); assertEquals(expected.get(1).getId(), actual.get(1).getId()); assertEquals(expected.get(1).getStartAppointment(), actual.get(1).getStartAppointment()); assertEquals(expected.get(1).getEndAppointment(), actual.get(1).getEndAppointment()); } @Test void appointmentById(){ AppointmentDto expected = appointmentDto1; Mockito .when(appointmentRepository.findById(appointment1.getId())) .thenReturn(Optional.of(appointment1)); AppointmentDto actual = appointmentService.appointmentById(appointment1.getId()); assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getStartAppointment(), actual.getStartAppointment()); assertEquals(expected.getEndAppointment(), actual.getEndAppointment()); } @Test void newAppointment(){ AppointmentDto expected = appointmentDto1; Mockito .when(appointmentRepository.save(Mockito.any())) .thenReturn(appointment1); AppointmentDto actual = appointmentService.newAppointment(appointmentDto1); assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getStartAppointment(), actual.getStartAppointment()); assertEquals(expected.getEndAppointment(), actual.getEndAppointment()); } @Test void updateAppointment(){ AppointmentDto newAppointmentDto = appointmentDto2; Mockito .when(appointmentRepository.findById(appointment1.getId())) .thenReturn(Optional.of(appointment1)); Mockito .when(appointmentRepository.save(appointment1)) .thenReturn(appointment1); appointmentService.updateAppointment(appointment1.getId(), newAppointmentDto); Mockito.verify(appointmentRepository, Mockito.times(1)).findById(appointment1.getId()); Mockito.verify(appointmentRepository, Mockito.times(1)).save(appointment1); } @Test void deleteAppointment(){ appointmentService.deleteAppointment(appointment1.getId()); Mockito.verify(appointmentRepository, Mockito.times(1)).deleteById(appointment1.getId()); } }
EmperorJuul/AutoGarage
src/test/java/nl/belastingdienst/autogarage/service/AppointmentServiceTest.java
1,453
//Id wordt in het programma geregeld door springboot
line_comment
nl
package nl.belastingdienst.autogarage.service; import nl.belastingdienst.autogarage.dto.AppointmentDto; import nl.belastingdienst.autogarage.model.Appointment; import nl.belastingdienst.autogarage.repository.AppointmentRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; @ExtendWith(MockitoExtension.class) class AppointmentServiceTest { @Mock AppointmentRepository appointmentRepository; @InjectMocks AppointmentService appointmentService; @Mock Appointment appointment1; @Mock Appointment appointment2; @Mock AppointmentDto appointmentDto1; @Mock AppointmentDto appointmentDto2; @BeforeEach public void setup(){ appointment1 = new Appointment(LocalDateTime.of(2020,10,6,10,00), LocalDateTime.of(2020, 10,6,11,00)); appointment1.setId(1L); appointment2 = new Appointment(LocalDateTime.of(2020,10,6,11,30), LocalDateTime.of(2020,10,6,12,00)); appointment2.setId(2L); appointmentDto1 = new AppointmentDto(LocalDateTime.of(2020,10,6,10,00), LocalDateTime.of(2020, 10,6,11,00)); appointmentDto1.setId(1L); appointmentDto2 = new AppointmentDto(LocalDateTime.of(2020,10,6,11,30), LocalDateTime.of(2020,10,6,12,00)); appointmentDto2.setId(2L); //Id wordt<SUF> //om de test te laten slagen worden ze hier handmatig overschreven } @Test void allAppointments(){ List<Appointment> appointmentList = new ArrayList<>(); appointmentList.add(appointment1); appointmentList.add(appointment2); List<AppointmentDto> expected = new ArrayList<>(); expected.add(appointmentDto1); expected.add(appointmentDto2); Mockito .when(appointmentRepository.findAll()) .thenReturn(appointmentList); List<AppointmentDto> actual = appointmentService.allAppointments(); assertEquals(expected.get(0).getId(), actual.get(0).getId()); assertEquals(expected.get(0).getStartAppointment(), actual.get(0).getStartAppointment()); assertEquals(expected.get(0).getEndAppointment(), actual.get(0).getEndAppointment()); assertEquals(expected.get(1).getId(), actual.get(1).getId()); assertEquals(expected.get(1).getStartAppointment(), actual.get(1).getStartAppointment()); assertEquals(expected.get(1).getEndAppointment(), actual.get(1).getEndAppointment()); } @Test void appointmentById(){ AppointmentDto expected = appointmentDto1; Mockito .when(appointmentRepository.findById(appointment1.getId())) .thenReturn(Optional.of(appointment1)); AppointmentDto actual = appointmentService.appointmentById(appointment1.getId()); assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getStartAppointment(), actual.getStartAppointment()); assertEquals(expected.getEndAppointment(), actual.getEndAppointment()); } @Test void newAppointment(){ AppointmentDto expected = appointmentDto1; Mockito .when(appointmentRepository.save(Mockito.any())) .thenReturn(appointment1); AppointmentDto actual = appointmentService.newAppointment(appointmentDto1); assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getStartAppointment(), actual.getStartAppointment()); assertEquals(expected.getEndAppointment(), actual.getEndAppointment()); } @Test void updateAppointment(){ AppointmentDto newAppointmentDto = appointmentDto2; Mockito .when(appointmentRepository.findById(appointment1.getId())) .thenReturn(Optional.of(appointment1)); Mockito .when(appointmentRepository.save(appointment1)) .thenReturn(appointment1); appointmentService.updateAppointment(appointment1.getId(), newAppointmentDto); Mockito.verify(appointmentRepository, Mockito.times(1)).findById(appointment1.getId()); Mockito.verify(appointmentRepository, Mockito.times(1)).save(appointment1); } @Test void deleteAppointment(){ appointmentService.deleteAppointment(appointment1.getId()); Mockito.verify(appointmentRepository, Mockito.times(1)).deleteById(appointment1.getId()); } }
73380_15
package be.kuleuven.candycrush; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.*; import java.util.stream.Stream; import java.util.stream.Collectors; public class CandyCrushModel { public String playerName; public int score; public BoardSize boardSize; public Board<Candy> candyBoard; public int maxScore; public List<List<Position>> bestSequence; public CandyCrushModel(BoardSize boardSize) { this.boardSize = boardSize; this.candyBoard = new Board<>(boardSize); this.playerName = "Player1"; this.score = 0; generateRandomGrid(); } public String getPlayerName() { return playerName; } public void setPlayerName(String playerName) { this.playerName = playerName; } public int getScore() { return score; } public void updateScore(int value) { score += value; } public Board<Candy> getCandyBoard() { return candyBoard; } public void generateRandomGrid() { candyBoard.fill(this::createRandomCandy); } public Candy getCandyAt(Position position) { return candyBoard.getCellAt(position); } public void updateCandyAt(Position position, Candy candy) { candyBoard.replaceCellAt(position, candy); } // Method to create a random Candy object public Candy createRandomCandy(Position position) { Random random = new Random(); int candyType = random.nextInt(8); // 0-3 for NormalCandy, 4-7 for special candies return switch (candyType) { case 0, 1, 2, 3 -> // Create a NormalCandy with a random color (0, 1, 2, or 3) new NormalCandy(random.nextInt(4)); case 4 -> new ChocoCrunch(); case 5 -> new CaramelBlast(); case 6 -> new LemonDrop(); case 7 -> new BerryBurst(); default -> throw new IllegalStateException("Unexpected candy type: " + candyType); }; } // Methode om dezelfde buurposities op te halen voor een gegeven positie public Iterable<Position> getSameNeighbourPositions(Position position) { List<Position> result = new ArrayList<>(); // Iterate over the neighbor positions of the given position for (Position neighborPosition : position.neighborPositions()) { // Retrieve the candy at the neighbor position Candy neighborCandy = candyBoard.getCellAt(neighborPosition); // Add the neighbor position to the result if it's valid and has the same candy if (isValidPosition(neighborPosition.row(), neighborPosition.column()) && compareCandyAtPosition(neighborCandy, candyBoard.getCellAt(position))) { result.add(neighborPosition); } } return result; } public boolean compareCandyAtPosition(Candy candy, Candy neighborCandy) { // Als beide snoepjes null zijn, beschouwen we ze als gelijk if (candy == null && neighborCandy == null) return false; // Als slechts één van de snoepjes null is, beschouwen we ze als verschillend if (candy == null || neighborCandy == null) return false; // Vergelijk de snoepjes normaal als ze beide niet null zijn return candy.equals(neighborCandy); } private boolean isValidPosition(int row, int col) { return row >= 0 && row < boardSize.rows() && col >= 0 && col < boardSize.columns(); } public boolean firstTwoHaveCandy(Candy candy, Stream<Position> positions) { return positions.limit(2).allMatch(pos -> compareCandyAtPosition(candy, getCandyAt(pos))); } public Stream<Position> horizontalStartingPositions() { return boardSize.positions().stream() .filter(pos -> !firstTwoHaveCandy(getCandyAt(pos), pos.walkLeft())||pos.column()==0); } public Stream<Position> verticalStartingPositions() { return boardSize.positions().stream() .filter(pos -> !firstTwoHaveCandy(getCandyAt(pos), pos.walkUp())||pos.row()==0); } public List<Position> longestMatchToRight(Position pos) { return pos.walkRight().takeWhile(nextPos -> compareCandyAtPosition(getCandyAt(nextPos), getCandyAt(pos))) .collect(Collectors.toList()); } public List<Position> longestMatchDown(Position pos) { return pos.walkDown().takeWhile(nextPos -> compareCandyAtPosition(getCandyAt(nextPos), getCandyAt(pos))) .collect(Collectors.toList()); } public Set<List<Position>> findAllMatches() { Set<List<Position>> matches = new HashSet<>(); // Horizontale matches Stream<Position> horizontalStartingPositions = horizontalStartingPositions(); Stream<List<Position>> horizontalMatches = horizontalStartingPositions .map(this::longestMatchToRight) .filter(match -> match.size() >= 3); // filter matches with more than 3 candies matches.addAll(horizontalMatches.collect(Collectors.toSet())); // Verticale matches Stream<Position> verticalStartingPositions = verticalStartingPositions(); Stream<List<Position>> verticalMatches = verticalStartingPositions .map(this::longestMatchDown) .filter(match -> match.size() >= 3); // filter matches with more than 3 candies matches.addAll(verticalMatches.collect(Collectors.toSet())); return matches; } public void clearMatch(List<Position> match) { for (Position pos : match) { // Verwijder het snoepje op de huidige positie updateCandyAt(pos, null); // Loop door de buurposities en roep de methode recursief aan voor elke buurpositie for (Position neighbor : pos.neighborPositions()) { // Controleer of de buurpositie een snoepje bevat en of het overeenkomt met het snoepje op de huidige positie if (neighbor != null && getCandyAt(neighbor) != null && compareCandyAtPosition(getCandyAt(neighbor), getCandyAt(pos))) { // Roep de methode recursief aan voor de buurpositie clearMatch(List.of(neighbor)); } } } } public void fallDownTo(Position pos) { int row = pos.row(); int col = pos.column(); // Check if we are on the top row, in which case we cannot fall down further if (row == 0) { return; } // Get the candy at the current position Candy candy = candyBoard.getCellAt(pos); // Check if the cell above is empty if (candy == null) { // Move the candy from the cell above, if it exists for (int r = row - 1; r >= 0; r--) { Candy candyAbove = candyBoard.getCellAt(new Position(r, col, boardSize)); if (candyAbove != null) { candyBoard.replaceCellAt(new Position(r, col, boardSize), null); candyBoard.replaceCellAt(new Position(row, col, boardSize), candyAbove); break; } } } // Recursively call fallDownTo for the cell above fallDownTo(new Position(row - 1, col, boardSize)); } private Position selectedPosition; // New member to store the selected position public Position getSelectedPosition() { return selectedPosition; } public void setSelectedPosition(Position selectedPosition) { this.selectedPosition = selectedPosition; } public boolean updateBoard() { boolean matchRemoved = false; // Find all matches on the board Set<List<Position>> matches = findAllMatches(); // If there are matches, clear them and let the candies fall down if (!matches.isEmpty()) { matchRemoved = true; for (List<Position> match : matches) { // Calculate the score gained from the current match int matchScore = calculateMatchScore(match); // Update the total score updateScore(matchScore); // Clear the current match clearMatch(match); } // After clearing matches, let candies fall down for (int col = 0; col < boardSize.columns(); col++) { for (int row = boardSize.rows() - 1; row >= 0; row--) { fallDownTo(new Position(row, col, boardSize)); } } // Recursively update the board until no more matches are found matchRemoved |= updateBoard(); } return matchRemoved; } private int calculateMatchScore(List<Position> match) { return match.size() ; } public void printBoard() { int rows = candyBoard.boardSize.rows(); int cols = candyBoard.boardSize.columns(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { Position currentPosition = new Position(i, j, boardSize); Candy currentCandy = candyBoard.getCellAt(currentPosition); switch (currentCandy) { case NormalCandy normalCandy -> System.out.print(normalCandy.color() + " "); case ChocoCrunch chocoCrunch -> System.out.print("5 "); case CaramelBlast caramelBlast -> System.out.print("6 "); case LemonDrop lemonDrop -> System.out.print("7 "); case BerryBurst berryBurst -> System.out.print("8 "); case null, default -> System.out.print("n "); } } System.out.println(); } } public List<List<Position>> maximizeScore() { maxScore = 0; bestSequence = new ArrayList<>(); List<List<Position>> currentSequence = new ArrayList<>(); updateBoard(); // Update the board initially backtrack(currentSequence); return bestSequence; } private void backtrack(List<List<Position>> currentSequence) { //printBoard(); //System.out.println(); // Base case: If there are no more valid switches or the board is empty after updates, return if ((noValidSwitches()&& findAllMatches().isEmpty()) || boardIsEmpty()) { int currentScore = getScore(); if (currentScore > maxScore) { maxScore = currentScore; bestSequence = currentSequence; //System.out.println("New best sequence found: " + bestSequence); } return; } // For horizontal swaps for (int row = 0; row < boardSize.rows(); row++) { for (int col = 0; col < boardSize.columns() - 1; col++) { if(matchAfterSwitch(row, col, row, col + 1)) { // Perform the horizontal swap swapCandies(row, col, row, col + 1); currentSequence.add(List.of(new Position(row, col, boardSize), new Position(row, col + 1, boardSize))); // Recursively call backtrack //System.out.println("Performing horizontal swap: (" + row + "," + col + ") <-> (" + row + "," + (col + 1) + ")"); // Create a copy of the model CandyCrushModel copyModel = new CandyCrushModel(boardSize); candyBoard.copyTo(copyModel.candyBoard); copyModel.score = score; updateBoard(); // Update the board after the swap backtrack(new ArrayList<>(currentSequence)); copyModel.candyBoard.copyTo(this.candyBoard); score = copyModel.score; // Undo the horizontal swap swapCandies(row, col, row, col + 1); currentSequence.removeLast(); //currentSequence.removeLast(); } } } // For vertical swaps for (int row = 0; row < boardSize.rows() - 1; row++) { for (int col = 0; col < boardSize.columns(); col++) { if(matchAfterSwitch(row, col, row + 1, col)) { // Perform the vertical swap swapCandies(row, col, row + 1, col); currentSequence.add(List.of(new Position(row, col, boardSize), new Position(row + 1, col, boardSize))); // Recursively call backtrack // Create a copy of the model CandyCrushModel copyModel = new CandyCrushModel(boardSize); candyBoard.copyTo(copyModel.candyBoard); copyModel.score = score; updateBoard(); // Update the board after the swap backtrack(new ArrayList<>(currentSequence)); copyModel.candyBoard.copyTo(this.candyBoard); score = copyModel.score; // Undo the vertical swap swapCandies(row, col, row + 1, col); currentSequence.removeLast(); //currentSequence.removeLast(); } } } } private boolean boardIsEmpty() { for (int row = 0; row < boardSize.rows(); row++) { for (int col = 0; col < boardSize.columns(); col++) { if (getCandyAt(new Position(row, col, boardSize)) != null) { return false; // Found a candy, board is not empty } } } return true; // No candies found, board is empty } boolean noValidSwitches() { for (int row = 0; row < boardSize.rows(); row++) { for (int col = 0; col < boardSize.columns()-1; col++){ if (matchAfterSwitch(row,col,row,col+1)) { return false; } } } for (int row = 0; row < boardSize.rows()-1; row++) { for (int col = 0; col < boardSize.columns(); col++){ if (matchAfterSwitch(row,col,row+1,col)) { return false; } } } // If no match is found after all possible swaps, return true indicating no valid switches return true; } private boolean matchAfterSwitch(int row1, int col1, int row2, int col2) { // Create a copy of the model CandyCrushModel copyModel = new CandyCrushModel(boardSize); candyBoard.copyTo(copyModel.candyBoard); copyModel.score = score; // Perform the swap in the copied model copyModel.swapCandies(row1, col1, row2, col2); // Find matches on the current board state Set<List<Position>> matches = copyModel.findAllMatches(); // Return true if matches are found after the swap, false otherwise return !matches.isEmpty(); } public void swapCandies(int row1, int col1, int row2, int col2) { // Check if the positions are valid if (!isValidPosition(row1, col1) || !isValidPosition(row2, col2)) { return; } // Get the candies from the specified positions Candy candy1 = getCandyAt(new Position(row1, col1, boardSize)); Candy candy2 = getCandyAt(new Position(row2, col2, boardSize)); // Swap the candies by replacing them at their positions updateCandyAt(new Position(row1, col1, boardSize), candy2); updateCandyAt(new Position(row2, col2, boardSize), candy1); } }
Emre-Dag/ses_opdracht
candycrush/src/main/java/be/kuleuven/candycrush/CandyCrushModel.java
4,257
// Roep de methode recursief aan voor de buurpositie
line_comment
nl
package be.kuleuven.candycrush; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.*; import java.util.stream.Stream; import java.util.stream.Collectors; public class CandyCrushModel { public String playerName; public int score; public BoardSize boardSize; public Board<Candy> candyBoard; public int maxScore; public List<List<Position>> bestSequence; public CandyCrushModel(BoardSize boardSize) { this.boardSize = boardSize; this.candyBoard = new Board<>(boardSize); this.playerName = "Player1"; this.score = 0; generateRandomGrid(); } public String getPlayerName() { return playerName; } public void setPlayerName(String playerName) { this.playerName = playerName; } public int getScore() { return score; } public void updateScore(int value) { score += value; } public Board<Candy> getCandyBoard() { return candyBoard; } public void generateRandomGrid() { candyBoard.fill(this::createRandomCandy); } public Candy getCandyAt(Position position) { return candyBoard.getCellAt(position); } public void updateCandyAt(Position position, Candy candy) { candyBoard.replaceCellAt(position, candy); } // Method to create a random Candy object public Candy createRandomCandy(Position position) { Random random = new Random(); int candyType = random.nextInt(8); // 0-3 for NormalCandy, 4-7 for special candies return switch (candyType) { case 0, 1, 2, 3 -> // Create a NormalCandy with a random color (0, 1, 2, or 3) new NormalCandy(random.nextInt(4)); case 4 -> new ChocoCrunch(); case 5 -> new CaramelBlast(); case 6 -> new LemonDrop(); case 7 -> new BerryBurst(); default -> throw new IllegalStateException("Unexpected candy type: " + candyType); }; } // Methode om dezelfde buurposities op te halen voor een gegeven positie public Iterable<Position> getSameNeighbourPositions(Position position) { List<Position> result = new ArrayList<>(); // Iterate over the neighbor positions of the given position for (Position neighborPosition : position.neighborPositions()) { // Retrieve the candy at the neighbor position Candy neighborCandy = candyBoard.getCellAt(neighborPosition); // Add the neighbor position to the result if it's valid and has the same candy if (isValidPosition(neighborPosition.row(), neighborPosition.column()) && compareCandyAtPosition(neighborCandy, candyBoard.getCellAt(position))) { result.add(neighborPosition); } } return result; } public boolean compareCandyAtPosition(Candy candy, Candy neighborCandy) { // Als beide snoepjes null zijn, beschouwen we ze als gelijk if (candy == null && neighborCandy == null) return false; // Als slechts één van de snoepjes null is, beschouwen we ze als verschillend if (candy == null || neighborCandy == null) return false; // Vergelijk de snoepjes normaal als ze beide niet null zijn return candy.equals(neighborCandy); } private boolean isValidPosition(int row, int col) { return row >= 0 && row < boardSize.rows() && col >= 0 && col < boardSize.columns(); } public boolean firstTwoHaveCandy(Candy candy, Stream<Position> positions) { return positions.limit(2).allMatch(pos -> compareCandyAtPosition(candy, getCandyAt(pos))); } public Stream<Position> horizontalStartingPositions() { return boardSize.positions().stream() .filter(pos -> !firstTwoHaveCandy(getCandyAt(pos), pos.walkLeft())||pos.column()==0); } public Stream<Position> verticalStartingPositions() { return boardSize.positions().stream() .filter(pos -> !firstTwoHaveCandy(getCandyAt(pos), pos.walkUp())||pos.row()==0); } public List<Position> longestMatchToRight(Position pos) { return pos.walkRight().takeWhile(nextPos -> compareCandyAtPosition(getCandyAt(nextPos), getCandyAt(pos))) .collect(Collectors.toList()); } public List<Position> longestMatchDown(Position pos) { return pos.walkDown().takeWhile(nextPos -> compareCandyAtPosition(getCandyAt(nextPos), getCandyAt(pos))) .collect(Collectors.toList()); } public Set<List<Position>> findAllMatches() { Set<List<Position>> matches = new HashSet<>(); // Horizontale matches Stream<Position> horizontalStartingPositions = horizontalStartingPositions(); Stream<List<Position>> horizontalMatches = horizontalStartingPositions .map(this::longestMatchToRight) .filter(match -> match.size() >= 3); // filter matches with more than 3 candies matches.addAll(horizontalMatches.collect(Collectors.toSet())); // Verticale matches Stream<Position> verticalStartingPositions = verticalStartingPositions(); Stream<List<Position>> verticalMatches = verticalStartingPositions .map(this::longestMatchDown) .filter(match -> match.size() >= 3); // filter matches with more than 3 candies matches.addAll(verticalMatches.collect(Collectors.toSet())); return matches; } public void clearMatch(List<Position> match) { for (Position pos : match) { // Verwijder het snoepje op de huidige positie updateCandyAt(pos, null); // Loop door de buurposities en roep de methode recursief aan voor elke buurpositie for (Position neighbor : pos.neighborPositions()) { // Controleer of de buurpositie een snoepje bevat en of het overeenkomt met het snoepje op de huidige positie if (neighbor != null && getCandyAt(neighbor) != null && compareCandyAtPosition(getCandyAt(neighbor), getCandyAt(pos))) { // Roep de<SUF> clearMatch(List.of(neighbor)); } } } } public void fallDownTo(Position pos) { int row = pos.row(); int col = pos.column(); // Check if we are on the top row, in which case we cannot fall down further if (row == 0) { return; } // Get the candy at the current position Candy candy = candyBoard.getCellAt(pos); // Check if the cell above is empty if (candy == null) { // Move the candy from the cell above, if it exists for (int r = row - 1; r >= 0; r--) { Candy candyAbove = candyBoard.getCellAt(new Position(r, col, boardSize)); if (candyAbove != null) { candyBoard.replaceCellAt(new Position(r, col, boardSize), null); candyBoard.replaceCellAt(new Position(row, col, boardSize), candyAbove); break; } } } // Recursively call fallDownTo for the cell above fallDownTo(new Position(row - 1, col, boardSize)); } private Position selectedPosition; // New member to store the selected position public Position getSelectedPosition() { return selectedPosition; } public void setSelectedPosition(Position selectedPosition) { this.selectedPosition = selectedPosition; } public boolean updateBoard() { boolean matchRemoved = false; // Find all matches on the board Set<List<Position>> matches = findAllMatches(); // If there are matches, clear them and let the candies fall down if (!matches.isEmpty()) { matchRemoved = true; for (List<Position> match : matches) { // Calculate the score gained from the current match int matchScore = calculateMatchScore(match); // Update the total score updateScore(matchScore); // Clear the current match clearMatch(match); } // After clearing matches, let candies fall down for (int col = 0; col < boardSize.columns(); col++) { for (int row = boardSize.rows() - 1; row >= 0; row--) { fallDownTo(new Position(row, col, boardSize)); } } // Recursively update the board until no more matches are found matchRemoved |= updateBoard(); } return matchRemoved; } private int calculateMatchScore(List<Position> match) { return match.size() ; } public void printBoard() { int rows = candyBoard.boardSize.rows(); int cols = candyBoard.boardSize.columns(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { Position currentPosition = new Position(i, j, boardSize); Candy currentCandy = candyBoard.getCellAt(currentPosition); switch (currentCandy) { case NormalCandy normalCandy -> System.out.print(normalCandy.color() + " "); case ChocoCrunch chocoCrunch -> System.out.print("5 "); case CaramelBlast caramelBlast -> System.out.print("6 "); case LemonDrop lemonDrop -> System.out.print("7 "); case BerryBurst berryBurst -> System.out.print("8 "); case null, default -> System.out.print("n "); } } System.out.println(); } } public List<List<Position>> maximizeScore() { maxScore = 0; bestSequence = new ArrayList<>(); List<List<Position>> currentSequence = new ArrayList<>(); updateBoard(); // Update the board initially backtrack(currentSequence); return bestSequence; } private void backtrack(List<List<Position>> currentSequence) { //printBoard(); //System.out.println(); // Base case: If there are no more valid switches or the board is empty after updates, return if ((noValidSwitches()&& findAllMatches().isEmpty()) || boardIsEmpty()) { int currentScore = getScore(); if (currentScore > maxScore) { maxScore = currentScore; bestSequence = currentSequence; //System.out.println("New best sequence found: " + bestSequence); } return; } // For horizontal swaps for (int row = 0; row < boardSize.rows(); row++) { for (int col = 0; col < boardSize.columns() - 1; col++) { if(matchAfterSwitch(row, col, row, col + 1)) { // Perform the horizontal swap swapCandies(row, col, row, col + 1); currentSequence.add(List.of(new Position(row, col, boardSize), new Position(row, col + 1, boardSize))); // Recursively call backtrack //System.out.println("Performing horizontal swap: (" + row + "," + col + ") <-> (" + row + "," + (col + 1) + ")"); // Create a copy of the model CandyCrushModel copyModel = new CandyCrushModel(boardSize); candyBoard.copyTo(copyModel.candyBoard); copyModel.score = score; updateBoard(); // Update the board after the swap backtrack(new ArrayList<>(currentSequence)); copyModel.candyBoard.copyTo(this.candyBoard); score = copyModel.score; // Undo the horizontal swap swapCandies(row, col, row, col + 1); currentSequence.removeLast(); //currentSequence.removeLast(); } } } // For vertical swaps for (int row = 0; row < boardSize.rows() - 1; row++) { for (int col = 0; col < boardSize.columns(); col++) { if(matchAfterSwitch(row, col, row + 1, col)) { // Perform the vertical swap swapCandies(row, col, row + 1, col); currentSequence.add(List.of(new Position(row, col, boardSize), new Position(row + 1, col, boardSize))); // Recursively call backtrack // Create a copy of the model CandyCrushModel copyModel = new CandyCrushModel(boardSize); candyBoard.copyTo(copyModel.candyBoard); copyModel.score = score; updateBoard(); // Update the board after the swap backtrack(new ArrayList<>(currentSequence)); copyModel.candyBoard.copyTo(this.candyBoard); score = copyModel.score; // Undo the vertical swap swapCandies(row, col, row + 1, col); currentSequence.removeLast(); //currentSequence.removeLast(); } } } } private boolean boardIsEmpty() { for (int row = 0; row < boardSize.rows(); row++) { for (int col = 0; col < boardSize.columns(); col++) { if (getCandyAt(new Position(row, col, boardSize)) != null) { return false; // Found a candy, board is not empty } } } return true; // No candies found, board is empty } boolean noValidSwitches() { for (int row = 0; row < boardSize.rows(); row++) { for (int col = 0; col < boardSize.columns()-1; col++){ if (matchAfterSwitch(row,col,row,col+1)) { return false; } } } for (int row = 0; row < boardSize.rows()-1; row++) { for (int col = 0; col < boardSize.columns(); col++){ if (matchAfterSwitch(row,col,row+1,col)) { return false; } } } // If no match is found after all possible swaps, return true indicating no valid switches return true; } private boolean matchAfterSwitch(int row1, int col1, int row2, int col2) { // Create a copy of the model CandyCrushModel copyModel = new CandyCrushModel(boardSize); candyBoard.copyTo(copyModel.candyBoard); copyModel.score = score; // Perform the swap in the copied model copyModel.swapCandies(row1, col1, row2, col2); // Find matches on the current board state Set<List<Position>> matches = copyModel.findAllMatches(); // Return true if matches are found after the swap, false otherwise return !matches.isEmpty(); } public void swapCandies(int row1, int col1, int row2, int col2) { // Check if the positions are valid if (!isValidPosition(row1, col1) || !isValidPosition(row2, col2)) { return; } // Get the candies from the specified positions Candy candy1 = getCandyAt(new Position(row1, col1, boardSize)); Candy candy2 = getCandyAt(new Position(row2, col2, boardSize)); // Swap the candies by replacing them at their positions updateCandyAt(new Position(row1, col1, boardSize), candy2); updateCandyAt(new Position(row2, col2, boardSize), candy1); } }
98435_11
package jerklib.events.impl; import jerklib.Session; import jerklib.events.IRCEvent; import jerklib.events.WhoEvent; /** * Created: Jan 31, 2008 6:31:31 PM * * @author <a href="mailto:[email protected]">Robert O'Connor</a> * @see WhoEvent */ public class WhoEventImpl implements WhoEvent { private final String nick, userName, realName, hostName, channel, rawEventData; private final String serverName; private final boolean isAway; private final int hopCount; private final Type type = IRCEvent.Type.WHO_EVENT; private final Session session; public WhoEventImpl( String channel, int hopCount, String hostName, boolean away, String nick, String rawEventData, String realName, String serverName, Session session, String userName ) { this.channel = channel; this.hopCount = hopCount; this.hostName = hostName; isAway = away; this.nick = nick; this.rawEventData = rawEventData; this.realName = realName; this.serverName = serverName; this.session = session; this.userName = userName; } /** * Get the nick of the user * * @return the nick of the user. */ public String getNick() { return nick; } /** * Get the username of the user * * @return the username */ public String getUserName() { return userName; } /** * Get the hostname of the user * * @return the hostname */ public String getHostName() { return hostName; } /** * Get the real name of the user. * * @return the real name */ public String getRealName() { return realName; } /** * Retrieve the channel (for when you WHO a channel) * * @return the channel or an empty String */ public String getChannel() { return channel.equals("*") ? "" : channel; } /** * Get whether or not the user is away. * * @return whether or not the user is away. */ public boolean isAway() { return isAway; } /** * Used to find out the exact type of event the IRCEvent object * is. The IRCEvent object can be cast into a more specific event object to * get access to convience methods for the specific event types. * * @return Type of event */ public Type getType() { return type; } /** * Returns the raw IRC data that makes up this event * * @return Raw IRC event text. */ public String getRawEventData() { return rawEventData; } /* (non-Javadoc) * @see jerklib.events.WhoEvent#getHopCount() */ public int getHopCount() { return hopCount; } /** * Gets session for connection * * @return Session */ public Session getSession() { return session; } /* (non-Javadoc) * @see jerklib.events.WhoEvent#getServerName() */ public String getServerName() { return serverName; } }
EnderWiggin/Haven-and-Hearth-client-modified-by-Ender
src/jerklib/events/impl/WhoEventImpl.java
934
/* (non-Javadoc) * @see jerklib.events.WhoEvent#getServerName() */
block_comment
nl
package jerklib.events.impl; import jerklib.Session; import jerklib.events.IRCEvent; import jerklib.events.WhoEvent; /** * Created: Jan 31, 2008 6:31:31 PM * * @author <a href="mailto:[email protected]">Robert O'Connor</a> * @see WhoEvent */ public class WhoEventImpl implements WhoEvent { private final String nick, userName, realName, hostName, channel, rawEventData; private final String serverName; private final boolean isAway; private final int hopCount; private final Type type = IRCEvent.Type.WHO_EVENT; private final Session session; public WhoEventImpl( String channel, int hopCount, String hostName, boolean away, String nick, String rawEventData, String realName, String serverName, Session session, String userName ) { this.channel = channel; this.hopCount = hopCount; this.hostName = hostName; isAway = away; this.nick = nick; this.rawEventData = rawEventData; this.realName = realName; this.serverName = serverName; this.session = session; this.userName = userName; } /** * Get the nick of the user * * @return the nick of the user. */ public String getNick() { return nick; } /** * Get the username of the user * * @return the username */ public String getUserName() { return userName; } /** * Get the hostname of the user * * @return the hostname */ public String getHostName() { return hostName; } /** * Get the real name of the user. * * @return the real name */ public String getRealName() { return realName; } /** * Retrieve the channel (for when you WHO a channel) * * @return the channel or an empty String */ public String getChannel() { return channel.equals("*") ? "" : channel; } /** * Get whether or not the user is away. * * @return whether or not the user is away. */ public boolean isAway() { return isAway; } /** * Used to find out the exact type of event the IRCEvent object * is. The IRCEvent object can be cast into a more specific event object to * get access to convience methods for the specific event types. * * @return Type of event */ public Type getType() { return type; } /** * Returns the raw IRC data that makes up this event * * @return Raw IRC event text. */ public String getRawEventData() { return rawEventData; } /* (non-Javadoc) * @see jerklib.events.WhoEvent#getHopCount() */ public int getHopCount() { return hopCount; } /** * Gets session for connection * * @return Session */ public Session getSession() { return session; } /* (non-Javadoc) <SUF>*/ public String getServerName() { return serverName; } }
23306_1
package nl.tudelft.jpacman.level; import nl.tudelft.jpacman.board.Unit; /** * Een tabel met alle (relevante) botsingen tussen verschillende typen * eenheden. * * @auteur Jeroen Roosen */ public interface CollisionMap { /** * Laat de twee eenheden in botsing komen en handelt het resultaat van de botsing af, wat mogelijk is * helemaal niets zijn. * * @param <C1> Het botstype. * @param <C2> Het botsende type (eenheid waarin is verplaatst). * @param botser De eenheid die de botsing veroorzaakt door een veld te bezetten * er staat al een ander apparaat op. * @param botst De eenheid die zich al op het veld bevindt dat wordt binnengevallen. */ <C1 extends Unit, C2 extends Unit> void collide(C1 botser, C2 botst); }
Eragon6080/examVVPackman
src/main/java/nl/tudelft/jpacman/level/CollisionMap.java
277
/** * Laat de twee eenheden in botsing komen en handelt het resultaat van de botsing af, wat mogelijk is * helemaal niets zijn. * * @param <C1> Het botstype. * @param <C2> Het botsende type (eenheid waarin is verplaatst). * @param botser De eenheid die de botsing veroorzaakt door een veld te bezetten * er staat al een ander apparaat op. * @param botst De eenheid die zich al op het veld bevindt dat wordt binnengevallen. */
block_comment
nl
package nl.tudelft.jpacman.level; import nl.tudelft.jpacman.board.Unit; /** * Een tabel met alle (relevante) botsingen tussen verschillende typen * eenheden. * * @auteur Jeroen Roosen */ public interface CollisionMap { /** * Laat de twee<SUF>*/ <C1 extends Unit, C2 extends Unit> void collide(C1 botser, C2 botst); }
87425_9
/* Copyright (c) 2008-2023, Nathan Sweet * 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 Esoteric Software nor the names of its 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 HOLDER 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 com.esotericsoftware.kryo.util; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Random; /** An unordered map. This implementation is a cuckoo hash map using 3 hashes (if table size is less than 2^16) or 4 hashes (if * table size is greater than or equal to 2^16), random walking, and a small stash for problematic keys Null keys are not allowed. * Null values are allowed. No allocation is done except when growing the table size. <br> * <br> * This map performs very fast get, containsKey, and remove (typically O(1), worst case O(log(n))). Put may be a bit slower, * depending on hash collisions. Load factors greater than 0.91 greatly increase the chances the map will have to rehash to the * next higher POT size. * @author Nathan Sweet */ @Deprecated public class CuckooObjectMap<K, V> { // primes for hash functions 2, 3, and 4 private static final int PRIME2 = 0xbe1f14b1; private static final int PRIME3 = 0xb4b82e39; private static final int PRIME4 = 0xced1c241; static Random random = new Random(); public int size; K[] keyTable; V[] valueTable; int capacity, stashSize; private float loadFactor; private int hashShift, mask, threshold; private int stashCapacity; private int pushIterations; private boolean isBigTable; /** Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the * backing table. */ public CuckooObjectMap () { this(32, 0.8f); } /** Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing * table. */ public CuckooObjectMap (int initialCapacity) { this(initialCapacity, 0.8f); } /** Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor * items before growing the backing table. */ public CuckooObjectMap (int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be >= 0: " + initialCapacity); if (initialCapacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large: " + initialCapacity); capacity = nextPowerOfTwo(initialCapacity); if (loadFactor <= 0) throw new IllegalArgumentException("loadFactor must be > 0: " + loadFactor); this.loadFactor = loadFactor; // big table is when capacity >= 2^16 isBigTable = (capacity >>> 16) != 0 ? true : false; threshold = (int)(capacity * loadFactor); mask = capacity - 1; hashShift = 31 - Integer.numberOfTrailingZeros(capacity); stashCapacity = Math.max(3, (int)Math.ceil(Math.log(capacity)) * 2); pushIterations = Math.max(Math.min(capacity, 8), (int)Math.sqrt(capacity) / 8); keyTable = (K[])new Object[capacity + stashCapacity]; valueTable = (V[])new Object[keyTable.length]; } /** Creates a new map identical to the specified map. */ public CuckooObjectMap (CuckooObjectMap<? extends K, ? extends V> map) { this(map.capacity, map.loadFactor); stashSize = map.stashSize; System.arraycopy(map.keyTable, 0, keyTable, 0, map.keyTable.length); System.arraycopy(map.valueTable, 0, valueTable, 0, map.valueTable.length); size = map.size; } /** Returns the old value associated with the specified key, or null. */ public V put (K key, V value) { if (key == null) throw new IllegalArgumentException("key cannot be null."); return put_internal(key, value); } private V put_internal (K key, V value) { // avoid getfield opcode K[] keyTable = this.keyTable; int mask = this.mask; boolean isBigTable = this.isBigTable; // Check for existing keys. int hashCode = key.hashCode(); int index1 = hashCode & mask; K key1 = keyTable[index1]; if (key.equals(key1)) { V oldValue = valueTable[index1]; valueTable[index1] = value; return oldValue; } int index2 = hash2(hashCode); K key2 = keyTable[index2]; if (key.equals(key2)) { V oldValue = valueTable[index2]; valueTable[index2] = value; return oldValue; } int index3 = hash3(hashCode); K key3 = keyTable[index3]; if (key.equals(key3)) { V oldValue = valueTable[index3]; valueTable[index3] = value; return oldValue; } int index4 = -1; K key4 = null; if (isBigTable) { index4 = hash4(hashCode); key4 = keyTable[index4]; if (key.equals(key4)) { V oldValue = valueTable[index4]; valueTable[index4] = value; return oldValue; } } // Update key in the stash. for (int i = capacity, n = i + stashSize; i < n; i++) { if (key.equals(keyTable[i])) { V oldValue = valueTable[i]; valueTable[i] = value; return oldValue; } } // Check for empty buckets. if (key1 == null) { keyTable[index1] = key; valueTable[index1] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (key2 == null) { keyTable[index2] = key; valueTable[index2] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (key3 == null) { keyTable[index3] = key; valueTable[index3] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (isBigTable && key4 == null) { keyTable[index4] = key; valueTable[index4] = value; if (size++ >= threshold) resize(capacity << 1); return null; } push(key, value, index1, key1, index2, key2, index3, key3, index4, key4); return null; } public void putAll (CuckooObjectMap<K, V> map) { ensureCapacity(map.size); for (Entry<K, V> entry : map.entries()) put(entry.key, entry.value); } /** Skips checks for existing keys. */ private void putResize (K key, V value) { // Check for empty buckets. int hashCode = key.hashCode(); int index1 = hashCode & mask; K key1 = keyTable[index1]; if (key1 == null) { keyTable[index1] = key; valueTable[index1] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index2 = hash2(hashCode); K key2 = keyTable[index2]; if (key2 == null) { keyTable[index2] = key; valueTable[index2] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index3 = hash3(hashCode); K key3 = keyTable[index3]; if (key3 == null) { keyTable[index3] = key; valueTable[index3] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index4 = -1; K key4 = null; if (isBigTable) { index4 = hash4(hashCode); key4 = keyTable[index4]; if (key4 == null) { keyTable[index4] = key; valueTable[index4] = value; if (size++ >= threshold) resize(capacity << 1); return; } } push(key, value, index1, key1, index2, key2, index3, key3, index4, key4); } private void push (K insertKey, V insertValue, int index1, K key1, int index2, K key2, int index3, K key3, int index4, K key4) { // avoid getfield opcode K[] keyTable = this.keyTable; V[] valueTable = this.valueTable; int mask = this.mask; boolean isBigTable = this.isBigTable; // Push keys until an empty bucket is found. K evictedKey; V evictedValue; int i = 0, pushIterations = this.pushIterations; int n = isBigTable ? 4 : 3; do { // Replace the key and value for one of the hashes. switch (random.nextInt(n)) { case 0: evictedKey = key1; evictedValue = valueTable[index1]; keyTable[index1] = insertKey; valueTable[index1] = insertValue; break; case 1: evictedKey = key2; evictedValue = valueTable[index2]; keyTable[index2] = insertKey; valueTable[index2] = insertValue; break; case 2: evictedKey = key3; evictedValue = valueTable[index3]; keyTable[index3] = insertKey; valueTable[index3] = insertValue; break; default: evictedKey = key4; evictedValue = valueTable[index4]; keyTable[index4] = insertKey; valueTable[index4] = insertValue; break; } // If the evicted key hashes to an empty bucket, put it there and stop. int hashCode = evictedKey.hashCode(); index1 = hashCode & mask; key1 = keyTable[index1]; if (key1 == null) { keyTable[index1] = evictedKey; valueTable[index1] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } index2 = hash2(hashCode); key2 = keyTable[index2]; if (key2 == null) { keyTable[index2] = evictedKey; valueTable[index2] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } index3 = hash3(hashCode); key3 = keyTable[index3]; if (key3 == null) { keyTable[index3] = evictedKey; valueTable[index3] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } if (isBigTable) { index4 = hash4(hashCode); key4 = keyTable[index4]; if (key4 == null) { keyTable[index4] = evictedKey; valueTable[index4] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } } if (++i == pushIterations) break; insertKey = evictedKey; insertValue = evictedValue; } while (true); putStash(evictedKey, evictedValue); } private void putStash (K key, V value) { if (stashSize == stashCapacity) { // Too many pushes occurred and the stash is full, increase the table size. resize(capacity << 1); put_internal(key, value); return; } // Store key in the stash. int index = capacity + stashSize; keyTable[index] = key; valueTable[index] = value; stashSize++; size++; } public V get (K key) { int hashCode = key.hashCode(); int index = hashCode & mask; if (!key.equals(keyTable[index])) { index = hash2(hashCode); if (!key.equals(keyTable[index])) { index = hash3(hashCode); if (!key.equals(keyTable[index])) { if (isBigTable) { index = hash4(hashCode); if (!key.equals(keyTable[index])) return getStash(key); } else { return getStash(key); } } } } return valueTable[index]; } private V getStash (K key) { K[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (key.equals(keyTable[i])) return valueTable[i]; return null; } /** Returns the value for the specified key, or the default value if the key is not in the map. */ public V get (K key, V defaultValue) { int hashCode = key.hashCode(); int index = hashCode & mask; if (!key.equals(keyTable[index])) { index = hash2(hashCode); if (!key.equals(keyTable[index])) { index = hash3(hashCode); if (!key.equals(keyTable[index])) { if (isBigTable) { index = hash4(hashCode); if (!key.equals(keyTable[index])) return getStash(key, defaultValue); } else { return getStash(key, defaultValue); } } } } return valueTable[index]; } private V getStash (K key, V defaultValue) { K[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (key.equals(keyTable[i])) return valueTable[i]; return defaultValue; } public V remove (K key) { int hashCode = key.hashCode(); int index = hashCode & mask; if (key.equals(keyTable[index])) { keyTable[index] = null; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } index = hash2(hashCode); if (key.equals(keyTable[index])) { keyTable[index] = null; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } index = hash3(hashCode); if (key.equals(keyTable[index])) { keyTable[index] = null; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } if (isBigTable) { index = hash4(hashCode); if (key.equals(keyTable[index])) { keyTable[index] = null; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } } return removeStash(key); } V removeStash (K key) { K[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) { if (key.equals(keyTable[i])) { V oldValue = valueTable[i]; removeStashIndex(i); size--; return oldValue; } } return null; } void removeStashIndex (int index) { // If the removed location was not last, move the last tuple to the removed location. stashSize--; int lastIndex = capacity + stashSize; if (index < lastIndex) { keyTable[index] = keyTable[lastIndex]; valueTable[index] = valueTable[lastIndex]; valueTable[lastIndex] = null; } else valueTable[index] = null; } /** Reduces the size of the backing arrays to be the specified capacity or less. If the capacity is already less, nothing is * done. If the map contains more items than the specified capacity, the next highest power of two capacity is used instead. */ public void shrink (int maximumCapacity) { if (maximumCapacity < 0) throw new IllegalArgumentException("maximumCapacity must be >= 0: " + maximumCapacity); if (size > maximumCapacity) maximumCapacity = size; if (capacity <= maximumCapacity) return; maximumCapacity = nextPowerOfTwo(maximumCapacity); resize(maximumCapacity); } /** Clears the map and reduces the size of the backing arrays to be the specified capacity if they are larger. */ public void clear (int maximumCapacity) { if (capacity <= maximumCapacity) { clear(); return; } size = 0; resize(maximumCapacity); } public void clear () { K[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = capacity + stashSize; i-- > 0;) { keyTable[i] = null; valueTable[i] = null; } size = 0; stashSize = 0; } /** Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may * be an expensive operation. * @param identity If true, uses == to compare the specified value with values in the map. If false, uses * {@link #equals(Object)}. */ public boolean containsValue (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { K[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != null && valueTable[i] == null) return true; } else if (identity) { for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return true; } else { for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return true; } return false; } public boolean containsKey (K key) { int hashCode = key.hashCode(); int index = hashCode & mask; if (!key.equals(keyTable[index])) { index = hash2(hashCode); if (!key.equals(keyTable[index])) { index = hash3(hashCode); if (!key.equals(keyTable[index])) { if (isBigTable) { index = hash4(hashCode); if (!key.equals(keyTable[index])) return containsKeyStash(key); } else { return containsKeyStash(key); } } } } return true; } private boolean containsKeyStash (K key) { K[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (key.equals(keyTable[i])) return true; return false; } /** Returns the key for the specified value, or null if it is not in the map. Note this traverses the entire map and compares * every value, which may be an expensive operation. * @param identity If true, uses == to compare the specified value with values in the map. If false, uses * {@link #equals(Object)}. */ public K findKey (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { K[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != null && valueTable[i] == null) return keyTable[i]; } else if (identity) { for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return keyTable[i]; } else { for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return keyTable[i]; } return null; } /** Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many * items to avoid multiple backing array resizes. */ public void ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= threshold) resize(nextPowerOfTwo((int)(sizeNeeded / loadFactor))); } private void resize (int newSize) { int oldEndIndex = capacity + stashSize; capacity = newSize; threshold = (int)(newSize * loadFactor); mask = newSize - 1; hashShift = 31 - Integer.numberOfTrailingZeros(newSize); stashCapacity = Math.max(3, (int)Math.ceil(Math.log(newSize)) * 2); pushIterations = Math.max(Math.min(newSize, 8), (int)Math.sqrt(newSize) / 8); // big table is when capacity >= 2^16 isBigTable = (capacity >>> 16) != 0 ? true : false; K[] oldKeyTable = keyTable; V[] oldValueTable = valueTable; keyTable = (K[])new Object[newSize + stashCapacity]; valueTable = (V[])new Object[newSize + stashCapacity]; int oldSize = size; size = 0; stashSize = 0; if (oldSize > 0) { for (int i = 0; i < oldEndIndex; i++) { K key = oldKeyTable[i]; if (key != null) putResize(key, oldValueTable[i]); } } } private int hash2 (int h) { h *= PRIME2; return (h ^ h >>> hashShift) & mask; } private int hash3 (int h) { h *= PRIME3; return (h ^ h >>> hashShift) & mask; } private int hash4 (int h) { h *= PRIME4; return (h ^ h >>> hashShift) & mask; } public String toString () { if (size == 0) return "{}"; StringBuilder buffer = new StringBuilder(32); buffer.append('{'); K[] keyTable = this.keyTable; V[] valueTable = this.valueTable; int i = keyTable.length; while (i-- > 0) { K key = keyTable[i]; if (key == null) continue; buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); break; } while (i-- > 0) { K key = keyTable[i]; if (key == null) continue; buffer.append(", "); buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); } buffer.append('}'); return buffer.toString(); } /** Returns an iterator for the entries in the map. Remove is supported. */ public Entries<K, V> entries () { return new Entries(this); } /** Returns an iterator for the values in the map. Remove is supported. */ public Values<V> values () { return new Values(this); } /** Returns an iterator for the keys in the map. Remove is supported. */ public Keys<K> keys () { return new Keys(this); } static public class Entry<K, V> { public K key; public V value; public String toString () { return key + "=" + value; } } static private class MapIterator<K, V> { public boolean hasNext; final CuckooObjectMap<K, V> map; int nextIndex, currentIndex; public MapIterator (CuckooObjectMap<K, V> map) { this.map = map; reset(); } public void reset () { currentIndex = -1; nextIndex = -1; advance(); } void advance () { hasNext = false; K[] keyTable = map.keyTable; for (int n = map.capacity + map.stashSize; ++nextIndex < n;) { if (keyTable[nextIndex] != null) { hasNext = true; break; } } } public void remove () { if (currentIndex < 0) throw new IllegalStateException("next must be called before remove."); if (currentIndex >= map.capacity) { map.removeStashIndex(currentIndex); nextIndex = currentIndex - 1; advance(); } else { map.keyTable[currentIndex] = null; map.valueTable[currentIndex] = null; } currentIndex = -1; map.size--; } } static public class Entries<K, V> extends MapIterator<K, V> implements Iterable<Entry<K, V>>, Iterator<Entry<K, V>> { Entry<K, V> entry = new Entry(); public Entries (CuckooObjectMap<K, V> map) { super(map); } /** Note the same entry instance is returned each time this method is called. */ public Entry<K, V> next () { if (!hasNext) throw new NoSuchElementException(); K[] keyTable = map.keyTable; entry.key = keyTable[nextIndex]; entry.value = map.valueTable[nextIndex]; currentIndex = nextIndex; advance(); return entry; } public boolean hasNext () { return hasNext; } public Iterator<Entry<K, V>> iterator () { return this; } } static public class Values<V> extends MapIterator<Object, V> implements Iterable<V>, Iterator<V> { public Values (CuckooObjectMap<?, V> map) { super((CuckooObjectMap<Object, V>)map); } public boolean hasNext () { return hasNext; } public V next () { if (!hasNext) throw new NoSuchElementException(); V value = map.valueTable[nextIndex]; currentIndex = nextIndex; advance(); return value; } public Iterator<V> iterator () { return this; } /** Returns a new array containing the remaining values. */ public ArrayList<V> toArray () { ArrayList array = new ArrayList(map.size); while (hasNext) array.add(next()); return array; } /** Adds the remaining values to the specified array. */ public void toArray (ArrayList<V> array) { while (hasNext) array.add(next()); } } static public class Keys<K> extends MapIterator<K, Object> implements Iterable<K>, Iterator<K> { public Keys (CuckooObjectMap<K, ?> map) { super((CuckooObjectMap<K, Object>)map); } public boolean hasNext () { return hasNext; } public K next () { if (!hasNext) throw new NoSuchElementException(); K key = map.keyTable[nextIndex]; currentIndex = nextIndex; advance(); return key; } public Iterator<K> iterator () { return this; } /** Returns a new array containing the remaining keys. */ public ArrayList<K> toArray () { ArrayList array = new ArrayList(map.size); while (hasNext) array.add(next()); return array; } } static public int nextPowerOfTwo (int value) { if (value == 0) return 1; value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return value + 1; } }
EsotericSoftware/kryo
src/com/esotericsoftware/kryo/util/CuckooObjectMap.java
8,124
// avoid getfield opcode
line_comment
nl
/* Copyright (c) 2008-2023, Nathan Sweet * 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 Esoteric Software nor the names of its 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 HOLDER 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 com.esotericsoftware.kryo.util; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Random; /** An unordered map. This implementation is a cuckoo hash map using 3 hashes (if table size is less than 2^16) or 4 hashes (if * table size is greater than or equal to 2^16), random walking, and a small stash for problematic keys Null keys are not allowed. * Null values are allowed. No allocation is done except when growing the table size. <br> * <br> * This map performs very fast get, containsKey, and remove (typically O(1), worst case O(log(n))). Put may be a bit slower, * depending on hash collisions. Load factors greater than 0.91 greatly increase the chances the map will have to rehash to the * next higher POT size. * @author Nathan Sweet */ @Deprecated public class CuckooObjectMap<K, V> { // primes for hash functions 2, 3, and 4 private static final int PRIME2 = 0xbe1f14b1; private static final int PRIME3 = 0xb4b82e39; private static final int PRIME4 = 0xced1c241; static Random random = new Random(); public int size; K[] keyTable; V[] valueTable; int capacity, stashSize; private float loadFactor; private int hashShift, mask, threshold; private int stashCapacity; private int pushIterations; private boolean isBigTable; /** Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the * backing table. */ public CuckooObjectMap () { this(32, 0.8f); } /** Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing * table. */ public CuckooObjectMap (int initialCapacity) { this(initialCapacity, 0.8f); } /** Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor * items before growing the backing table. */ public CuckooObjectMap (int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be >= 0: " + initialCapacity); if (initialCapacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large: " + initialCapacity); capacity = nextPowerOfTwo(initialCapacity); if (loadFactor <= 0) throw new IllegalArgumentException("loadFactor must be > 0: " + loadFactor); this.loadFactor = loadFactor; // big table is when capacity >= 2^16 isBigTable = (capacity >>> 16) != 0 ? true : false; threshold = (int)(capacity * loadFactor); mask = capacity - 1; hashShift = 31 - Integer.numberOfTrailingZeros(capacity); stashCapacity = Math.max(3, (int)Math.ceil(Math.log(capacity)) * 2); pushIterations = Math.max(Math.min(capacity, 8), (int)Math.sqrt(capacity) / 8); keyTable = (K[])new Object[capacity + stashCapacity]; valueTable = (V[])new Object[keyTable.length]; } /** Creates a new map identical to the specified map. */ public CuckooObjectMap (CuckooObjectMap<? extends K, ? extends V> map) { this(map.capacity, map.loadFactor); stashSize = map.stashSize; System.arraycopy(map.keyTable, 0, keyTable, 0, map.keyTable.length); System.arraycopy(map.valueTable, 0, valueTable, 0, map.valueTable.length); size = map.size; } /** Returns the old value associated with the specified key, or null. */ public V put (K key, V value) { if (key == null) throw new IllegalArgumentException("key cannot be null."); return put_internal(key, value); } private V put_internal (K key, V value) { // avoid getfield<SUF> K[] keyTable = this.keyTable; int mask = this.mask; boolean isBigTable = this.isBigTable; // Check for existing keys. int hashCode = key.hashCode(); int index1 = hashCode & mask; K key1 = keyTable[index1]; if (key.equals(key1)) { V oldValue = valueTable[index1]; valueTable[index1] = value; return oldValue; } int index2 = hash2(hashCode); K key2 = keyTable[index2]; if (key.equals(key2)) { V oldValue = valueTable[index2]; valueTable[index2] = value; return oldValue; } int index3 = hash3(hashCode); K key3 = keyTable[index3]; if (key.equals(key3)) { V oldValue = valueTable[index3]; valueTable[index3] = value; return oldValue; } int index4 = -1; K key4 = null; if (isBigTable) { index4 = hash4(hashCode); key4 = keyTable[index4]; if (key.equals(key4)) { V oldValue = valueTable[index4]; valueTable[index4] = value; return oldValue; } } // Update key in the stash. for (int i = capacity, n = i + stashSize; i < n; i++) { if (key.equals(keyTable[i])) { V oldValue = valueTable[i]; valueTable[i] = value; return oldValue; } } // Check for empty buckets. if (key1 == null) { keyTable[index1] = key; valueTable[index1] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (key2 == null) { keyTable[index2] = key; valueTable[index2] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (key3 == null) { keyTable[index3] = key; valueTable[index3] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (isBigTable && key4 == null) { keyTable[index4] = key; valueTable[index4] = value; if (size++ >= threshold) resize(capacity << 1); return null; } push(key, value, index1, key1, index2, key2, index3, key3, index4, key4); return null; } public void putAll (CuckooObjectMap<K, V> map) { ensureCapacity(map.size); for (Entry<K, V> entry : map.entries()) put(entry.key, entry.value); } /** Skips checks for existing keys. */ private void putResize (K key, V value) { // Check for empty buckets. int hashCode = key.hashCode(); int index1 = hashCode & mask; K key1 = keyTable[index1]; if (key1 == null) { keyTable[index1] = key; valueTable[index1] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index2 = hash2(hashCode); K key2 = keyTable[index2]; if (key2 == null) { keyTable[index2] = key; valueTable[index2] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index3 = hash3(hashCode); K key3 = keyTable[index3]; if (key3 == null) { keyTable[index3] = key; valueTable[index3] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index4 = -1; K key4 = null; if (isBigTable) { index4 = hash4(hashCode); key4 = keyTable[index4]; if (key4 == null) { keyTable[index4] = key; valueTable[index4] = value; if (size++ >= threshold) resize(capacity << 1); return; } } push(key, value, index1, key1, index2, key2, index3, key3, index4, key4); } private void push (K insertKey, V insertValue, int index1, K key1, int index2, K key2, int index3, K key3, int index4, K key4) { // avoid getfield opcode K[] keyTable = this.keyTable; V[] valueTable = this.valueTable; int mask = this.mask; boolean isBigTable = this.isBigTable; // Push keys until an empty bucket is found. K evictedKey; V evictedValue; int i = 0, pushIterations = this.pushIterations; int n = isBigTable ? 4 : 3; do { // Replace the key and value for one of the hashes. switch (random.nextInt(n)) { case 0: evictedKey = key1; evictedValue = valueTable[index1]; keyTable[index1] = insertKey; valueTable[index1] = insertValue; break; case 1: evictedKey = key2; evictedValue = valueTable[index2]; keyTable[index2] = insertKey; valueTable[index2] = insertValue; break; case 2: evictedKey = key3; evictedValue = valueTable[index3]; keyTable[index3] = insertKey; valueTable[index3] = insertValue; break; default: evictedKey = key4; evictedValue = valueTable[index4]; keyTable[index4] = insertKey; valueTable[index4] = insertValue; break; } // If the evicted key hashes to an empty bucket, put it there and stop. int hashCode = evictedKey.hashCode(); index1 = hashCode & mask; key1 = keyTable[index1]; if (key1 == null) { keyTable[index1] = evictedKey; valueTable[index1] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } index2 = hash2(hashCode); key2 = keyTable[index2]; if (key2 == null) { keyTable[index2] = evictedKey; valueTable[index2] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } index3 = hash3(hashCode); key3 = keyTable[index3]; if (key3 == null) { keyTable[index3] = evictedKey; valueTable[index3] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } if (isBigTable) { index4 = hash4(hashCode); key4 = keyTable[index4]; if (key4 == null) { keyTable[index4] = evictedKey; valueTable[index4] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } } if (++i == pushIterations) break; insertKey = evictedKey; insertValue = evictedValue; } while (true); putStash(evictedKey, evictedValue); } private void putStash (K key, V value) { if (stashSize == stashCapacity) { // Too many pushes occurred and the stash is full, increase the table size. resize(capacity << 1); put_internal(key, value); return; } // Store key in the stash. int index = capacity + stashSize; keyTable[index] = key; valueTable[index] = value; stashSize++; size++; } public V get (K key) { int hashCode = key.hashCode(); int index = hashCode & mask; if (!key.equals(keyTable[index])) { index = hash2(hashCode); if (!key.equals(keyTable[index])) { index = hash3(hashCode); if (!key.equals(keyTable[index])) { if (isBigTable) { index = hash4(hashCode); if (!key.equals(keyTable[index])) return getStash(key); } else { return getStash(key); } } } } return valueTable[index]; } private V getStash (K key) { K[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (key.equals(keyTable[i])) return valueTable[i]; return null; } /** Returns the value for the specified key, or the default value if the key is not in the map. */ public V get (K key, V defaultValue) { int hashCode = key.hashCode(); int index = hashCode & mask; if (!key.equals(keyTable[index])) { index = hash2(hashCode); if (!key.equals(keyTable[index])) { index = hash3(hashCode); if (!key.equals(keyTable[index])) { if (isBigTable) { index = hash4(hashCode); if (!key.equals(keyTable[index])) return getStash(key, defaultValue); } else { return getStash(key, defaultValue); } } } } return valueTable[index]; } private V getStash (K key, V defaultValue) { K[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (key.equals(keyTable[i])) return valueTable[i]; return defaultValue; } public V remove (K key) { int hashCode = key.hashCode(); int index = hashCode & mask; if (key.equals(keyTable[index])) { keyTable[index] = null; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } index = hash2(hashCode); if (key.equals(keyTable[index])) { keyTable[index] = null; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } index = hash3(hashCode); if (key.equals(keyTable[index])) { keyTable[index] = null; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } if (isBigTable) { index = hash4(hashCode); if (key.equals(keyTable[index])) { keyTable[index] = null; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } } return removeStash(key); } V removeStash (K key) { K[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) { if (key.equals(keyTable[i])) { V oldValue = valueTable[i]; removeStashIndex(i); size--; return oldValue; } } return null; } void removeStashIndex (int index) { // If the removed location was not last, move the last tuple to the removed location. stashSize--; int lastIndex = capacity + stashSize; if (index < lastIndex) { keyTable[index] = keyTable[lastIndex]; valueTable[index] = valueTable[lastIndex]; valueTable[lastIndex] = null; } else valueTable[index] = null; } /** Reduces the size of the backing arrays to be the specified capacity or less. If the capacity is already less, nothing is * done. If the map contains more items than the specified capacity, the next highest power of two capacity is used instead. */ public void shrink (int maximumCapacity) { if (maximumCapacity < 0) throw new IllegalArgumentException("maximumCapacity must be >= 0: " + maximumCapacity); if (size > maximumCapacity) maximumCapacity = size; if (capacity <= maximumCapacity) return; maximumCapacity = nextPowerOfTwo(maximumCapacity); resize(maximumCapacity); } /** Clears the map and reduces the size of the backing arrays to be the specified capacity if they are larger. */ public void clear (int maximumCapacity) { if (capacity <= maximumCapacity) { clear(); return; } size = 0; resize(maximumCapacity); } public void clear () { K[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = capacity + stashSize; i-- > 0;) { keyTable[i] = null; valueTable[i] = null; } size = 0; stashSize = 0; } /** Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may * be an expensive operation. * @param identity If true, uses == to compare the specified value with values in the map. If false, uses * {@link #equals(Object)}. */ public boolean containsValue (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { K[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != null && valueTable[i] == null) return true; } else if (identity) { for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return true; } else { for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return true; } return false; } public boolean containsKey (K key) { int hashCode = key.hashCode(); int index = hashCode & mask; if (!key.equals(keyTable[index])) { index = hash2(hashCode); if (!key.equals(keyTable[index])) { index = hash3(hashCode); if (!key.equals(keyTable[index])) { if (isBigTable) { index = hash4(hashCode); if (!key.equals(keyTable[index])) return containsKeyStash(key); } else { return containsKeyStash(key); } } } } return true; } private boolean containsKeyStash (K key) { K[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (key.equals(keyTable[i])) return true; return false; } /** Returns the key for the specified value, or null if it is not in the map. Note this traverses the entire map and compares * every value, which may be an expensive operation. * @param identity If true, uses == to compare the specified value with values in the map. If false, uses * {@link #equals(Object)}. */ public K findKey (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { K[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != null && valueTable[i] == null) return keyTable[i]; } else if (identity) { for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return keyTable[i]; } else { for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return keyTable[i]; } return null; } /** Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many * items to avoid multiple backing array resizes. */ public void ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= threshold) resize(nextPowerOfTwo((int)(sizeNeeded / loadFactor))); } private void resize (int newSize) { int oldEndIndex = capacity + stashSize; capacity = newSize; threshold = (int)(newSize * loadFactor); mask = newSize - 1; hashShift = 31 - Integer.numberOfTrailingZeros(newSize); stashCapacity = Math.max(3, (int)Math.ceil(Math.log(newSize)) * 2); pushIterations = Math.max(Math.min(newSize, 8), (int)Math.sqrt(newSize) / 8); // big table is when capacity >= 2^16 isBigTable = (capacity >>> 16) != 0 ? true : false; K[] oldKeyTable = keyTable; V[] oldValueTable = valueTable; keyTable = (K[])new Object[newSize + stashCapacity]; valueTable = (V[])new Object[newSize + stashCapacity]; int oldSize = size; size = 0; stashSize = 0; if (oldSize > 0) { for (int i = 0; i < oldEndIndex; i++) { K key = oldKeyTable[i]; if (key != null) putResize(key, oldValueTable[i]); } } } private int hash2 (int h) { h *= PRIME2; return (h ^ h >>> hashShift) & mask; } private int hash3 (int h) { h *= PRIME3; return (h ^ h >>> hashShift) & mask; } private int hash4 (int h) { h *= PRIME4; return (h ^ h >>> hashShift) & mask; } public String toString () { if (size == 0) return "{}"; StringBuilder buffer = new StringBuilder(32); buffer.append('{'); K[] keyTable = this.keyTable; V[] valueTable = this.valueTable; int i = keyTable.length; while (i-- > 0) { K key = keyTable[i]; if (key == null) continue; buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); break; } while (i-- > 0) { K key = keyTable[i]; if (key == null) continue; buffer.append(", "); buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); } buffer.append('}'); return buffer.toString(); } /** Returns an iterator for the entries in the map. Remove is supported. */ public Entries<K, V> entries () { return new Entries(this); } /** Returns an iterator for the values in the map. Remove is supported. */ public Values<V> values () { return new Values(this); } /** Returns an iterator for the keys in the map. Remove is supported. */ public Keys<K> keys () { return new Keys(this); } static public class Entry<K, V> { public K key; public V value; public String toString () { return key + "=" + value; } } static private class MapIterator<K, V> { public boolean hasNext; final CuckooObjectMap<K, V> map; int nextIndex, currentIndex; public MapIterator (CuckooObjectMap<K, V> map) { this.map = map; reset(); } public void reset () { currentIndex = -1; nextIndex = -1; advance(); } void advance () { hasNext = false; K[] keyTable = map.keyTable; for (int n = map.capacity + map.stashSize; ++nextIndex < n;) { if (keyTable[nextIndex] != null) { hasNext = true; break; } } } public void remove () { if (currentIndex < 0) throw new IllegalStateException("next must be called before remove."); if (currentIndex >= map.capacity) { map.removeStashIndex(currentIndex); nextIndex = currentIndex - 1; advance(); } else { map.keyTable[currentIndex] = null; map.valueTable[currentIndex] = null; } currentIndex = -1; map.size--; } } static public class Entries<K, V> extends MapIterator<K, V> implements Iterable<Entry<K, V>>, Iterator<Entry<K, V>> { Entry<K, V> entry = new Entry(); public Entries (CuckooObjectMap<K, V> map) { super(map); } /** Note the same entry instance is returned each time this method is called. */ public Entry<K, V> next () { if (!hasNext) throw new NoSuchElementException(); K[] keyTable = map.keyTable; entry.key = keyTable[nextIndex]; entry.value = map.valueTable[nextIndex]; currentIndex = nextIndex; advance(); return entry; } public boolean hasNext () { return hasNext; } public Iterator<Entry<K, V>> iterator () { return this; } } static public class Values<V> extends MapIterator<Object, V> implements Iterable<V>, Iterator<V> { public Values (CuckooObjectMap<?, V> map) { super((CuckooObjectMap<Object, V>)map); } public boolean hasNext () { return hasNext; } public V next () { if (!hasNext) throw new NoSuchElementException(); V value = map.valueTable[nextIndex]; currentIndex = nextIndex; advance(); return value; } public Iterator<V> iterator () { return this; } /** Returns a new array containing the remaining values. */ public ArrayList<V> toArray () { ArrayList array = new ArrayList(map.size); while (hasNext) array.add(next()); return array; } /** Adds the remaining values to the specified array. */ public void toArray (ArrayList<V> array) { while (hasNext) array.add(next()); } } static public class Keys<K> extends MapIterator<K, Object> implements Iterable<K>, Iterator<K> { public Keys (CuckooObjectMap<K, ?> map) { super((CuckooObjectMap<K, Object>)map); } public boolean hasNext () { return hasNext; } public K next () { if (!hasNext) throw new NoSuchElementException(); K key = map.keyTable[nextIndex]; currentIndex = nextIndex; advance(); return key; } public Iterator<K> iterator () { return this; } /** Returns a new array containing the remaining keys. */ public ArrayList<K> toArray () { ArrayList array = new ArrayList(map.size); while (hasNext) array.add(next()); return array; } } static public int nextPowerOfTwo (int value) { if (value == 0) return 1; value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return value + 1; } }
98520_11
package com.esri.geoevent.solutions.transport.irc.jerklib.events.impl; import com.esri.geoevent.solutions.transport.irc.jerklib.Session; import com.esri.geoevent.solutions.transport.irc.jerklib.events.IRCEvent; import com.esri.geoevent.solutions.transport.irc.jerklib.events.WhoEvent; /** * Created: Jan 31, 2008 6:31:31 PM * * @author <a href="mailto:[email protected]">Robert O'Connor</a> * @see WhoEvent */ public class WhoEventImpl implements WhoEvent { private final String nick, userName, realName, hostName, channel, rawEventData; private final String serverName; private final boolean isAway; private final int hopCount; private final Type type = IRCEvent.Type.WHO_EVENT; private final Session session; public WhoEventImpl( String channel, int hopCount, String hostName, boolean away, String nick, String rawEventData, String realName, String serverName, Session session, String userName ) { this.channel = channel; this.hopCount = hopCount; this.hostName = hostName; isAway = away; this.nick = nick; this.rawEventData = rawEventData; this.realName = realName; this.serverName = serverName; this.session = session; this.userName = userName; } /** * Get the nick of the user * * @return the nick of the user. */ public String getNick() { return nick; } /** * Get the username of the user * * @return the username */ public String getUserName() { return userName; } /** * Get the hostname of the user * * @return the hostname */ public String getHostName() { return hostName; } /** * Get the real name of the user. * * @return the real name */ public String getRealName() { return realName; } /** * Retrieve the channel (for when you WHO a channel) * * @return the channel or an empty String */ public String getChannel() { return channel.equals("*") ? "" : channel; } /** * Get whether or not the user is away. * * @return whether or not the user is away. */ public boolean isAway() { return isAway; } /** * Used to find out the exact type of event the IRCEvent object * is. The IRCEvent object can be cast into a more specific event object to * get access to convience methods for the specific event types. * * @return Type of event */ public Type getType() { return type; } /** * Returns the raw IRC data that makes up this event * * @return Raw IRC event text. */ public String getRawEventData() { return rawEventData; } /* (non-Javadoc) * @see com.esri.ges.transport.Irc.jerklib.events.WhoEvent#getHopCount() */ public int getHopCount() { return hopCount; } /** * Gets session for connection * * @return Session */ public Session getSession() { return session; } /* (non-Javadoc) * @see com.esri.ges.transport.Irc.jerklib.events.WhoEvent#getServerName() */ public String getServerName() { return serverName; } }
Esri/solutions-geoevent-java
solutions-geoevent/transports/irc-transport/src/main/java/com/esri/geoevent/solutions/transport/irc/jerklib/events/impl/WhoEventImpl.java
1,028
/* (non-Javadoc) * @see com.esri.ges.transport.Irc.jerklib.events.WhoEvent#getServerName() */
block_comment
nl
package com.esri.geoevent.solutions.transport.irc.jerklib.events.impl; import com.esri.geoevent.solutions.transport.irc.jerklib.Session; import com.esri.geoevent.solutions.transport.irc.jerklib.events.IRCEvent; import com.esri.geoevent.solutions.transport.irc.jerklib.events.WhoEvent; /** * Created: Jan 31, 2008 6:31:31 PM * * @author <a href="mailto:[email protected]">Robert O'Connor</a> * @see WhoEvent */ public class WhoEventImpl implements WhoEvent { private final String nick, userName, realName, hostName, channel, rawEventData; private final String serverName; private final boolean isAway; private final int hopCount; private final Type type = IRCEvent.Type.WHO_EVENT; private final Session session; public WhoEventImpl( String channel, int hopCount, String hostName, boolean away, String nick, String rawEventData, String realName, String serverName, Session session, String userName ) { this.channel = channel; this.hopCount = hopCount; this.hostName = hostName; isAway = away; this.nick = nick; this.rawEventData = rawEventData; this.realName = realName; this.serverName = serverName; this.session = session; this.userName = userName; } /** * Get the nick of the user * * @return the nick of the user. */ public String getNick() { return nick; } /** * Get the username of the user * * @return the username */ public String getUserName() { return userName; } /** * Get the hostname of the user * * @return the hostname */ public String getHostName() { return hostName; } /** * Get the real name of the user. * * @return the real name */ public String getRealName() { return realName; } /** * Retrieve the channel (for when you WHO a channel) * * @return the channel or an empty String */ public String getChannel() { return channel.equals("*") ? "" : channel; } /** * Get whether or not the user is away. * * @return whether or not the user is away. */ public boolean isAway() { return isAway; } /** * Used to find out the exact type of event the IRCEvent object * is. The IRCEvent object can be cast into a more specific event object to * get access to convience methods for the specific event types. * * @return Type of event */ public Type getType() { return type; } /** * Returns the raw IRC data that makes up this event * * @return Raw IRC event text. */ public String getRawEventData() { return rawEventData; } /* (non-Javadoc) * @see com.esri.ges.transport.Irc.jerklib.events.WhoEvent#getHopCount() */ public int getHopCount() { return hopCount; } /** * Gets session for connection * * @return Session */ public Session getSession() { return session; } /* (non-Javadoc) <SUF>*/ public String getServerName() { return serverName; } }
110818_8
package tracks.levelGeneration; import java.util.Random; public class TestLevelGeneration { public static void main(String[] args) { // Available Level Generators String randomLevelGenerator = "tracks.levelGeneration.randomLevelGenerator.LevelGenerator"; String geneticGenerator = "tracks.levelGeneration.geneticLevelGenerator.LevelGenerator"; String constructiveLevelGenerator = "tracks.levelGeneration.constructiveLevelGenerator.LevelGenerator"; String gamesPath = "examples/gridphysics/"; String physicsGamesPath = "examples/contphysics/"; String generateLevelPath = gamesPath; String games[] = new String[] { "aliens", "angelsdemons", "assemblyline", "avoidgeorge", "bait", // 0-4 "beltmanager", "blacksmoke", "boloadventures", "bomber", "bomberman", // 5-9 "boulderchase", "boulderdash", "brainman", "butterflies", "cakybaky", // 10-14 "camelRace", "catapults", "chainreaction", "chase", "chipschallenge", // 15-19 "clusters", "colourescape", "chopper", "cookmepasta", "cops", // 20-24 "crossfire", "defem", "defender", "digdug", "dungeon", // 25-29 "eighthpassenger", "eggomania", "enemycitadel", "escape", "factorymanager", // 30-34 "firecaster", "fireman", "firestorms", "freeway", "frogs", // 35-39 "garbagecollector", "gymkhana", "hungrybirds", "iceandfire", "ikaruga", // 40-44 "infection", "intersection", "islands", "jaws", "killBillVol1", // 45-49 "labyrinth", "labyrinthdual", "lasers", "lasers2", "lemmings", // 50-54 "missilecommand", "modality", "overload", "pacman", "painter", // 55-59 "pokemon", "plants", "plaqueattack", "portals", "raceBet", // 60-64 "raceBet2", "realportals", "realsokoban", "rivers", "roadfighter", // 65-69 "roguelike", "run", "seaquest", "sheriff", "shipwreck", // 70-74 "sokoban", "solarfox", "superman", "surround", "survivezombies", // 75-79 "tercio", "thecitadel", "thesnowman", "waitforbreakfast", "watergame", // 80-84 "waves", "whackamole", "wildgunman", "witnessprotection", "wrapsokoban", // 85-89 "zelda", "zenpuzzle" }; // 90, 91 String recordActionsFile = null;// "actions_" + games[gameIdx] + "_lvl" // + levelIdx + "_" + seed + ".txt"; // where to record the actions // executed. null if not to save. // Other settings int seed = new Random().nextInt(); int gameIdx = 0; String recordLevelFile = generateLevelPath + games[gameIdx] + "_glvl.txt"; String game = generateLevelPath + games[gameIdx] + ".txt"; // 1. This starts a game, in a generated level created by a specific level generator if(LevelGenMachine.generateOneLevel(game, constructiveLevelGenerator, recordLevelFile)){ LevelGenMachine.playOneGeneratedLevel(game, recordActionsFile, recordLevelFile, seed); } // 2. This generates numberOfLevels levels. // String levelGenerator = "tracks.levelGeneration." + args[0] + ".LevelGenerator"; // int numberOfLevels = 5; // tracks.levelGeneration.randomLevelGenerator.LevelGenerator.includeBorders = true; // String[] folderName = levelGenerator.split("\\."); // generateLevelPath = "examples/generatedLevels/" + folderName[1] + "/"; // game = gamesPath + args[1] + ".txt"; // for (int i = 0; i < numberOfLevels; i++) { // recordLevelFile = generateLevelPath + args[1] + "_lvl" + i + ".txt"; // LevelGenMachine.generateOneLevel(game, levelGenerator, recordLevelFile); //} } }
EssexUniversityMCTS/gvgai
src/tracks/levelGeneration/TestLevelGeneration.java
1,203
// int numberOfLevels = 5;
line_comment
nl
package tracks.levelGeneration; import java.util.Random; public class TestLevelGeneration { public static void main(String[] args) { // Available Level Generators String randomLevelGenerator = "tracks.levelGeneration.randomLevelGenerator.LevelGenerator"; String geneticGenerator = "tracks.levelGeneration.geneticLevelGenerator.LevelGenerator"; String constructiveLevelGenerator = "tracks.levelGeneration.constructiveLevelGenerator.LevelGenerator"; String gamesPath = "examples/gridphysics/"; String physicsGamesPath = "examples/contphysics/"; String generateLevelPath = gamesPath; String games[] = new String[] { "aliens", "angelsdemons", "assemblyline", "avoidgeorge", "bait", // 0-4 "beltmanager", "blacksmoke", "boloadventures", "bomber", "bomberman", // 5-9 "boulderchase", "boulderdash", "brainman", "butterflies", "cakybaky", // 10-14 "camelRace", "catapults", "chainreaction", "chase", "chipschallenge", // 15-19 "clusters", "colourescape", "chopper", "cookmepasta", "cops", // 20-24 "crossfire", "defem", "defender", "digdug", "dungeon", // 25-29 "eighthpassenger", "eggomania", "enemycitadel", "escape", "factorymanager", // 30-34 "firecaster", "fireman", "firestorms", "freeway", "frogs", // 35-39 "garbagecollector", "gymkhana", "hungrybirds", "iceandfire", "ikaruga", // 40-44 "infection", "intersection", "islands", "jaws", "killBillVol1", // 45-49 "labyrinth", "labyrinthdual", "lasers", "lasers2", "lemmings", // 50-54 "missilecommand", "modality", "overload", "pacman", "painter", // 55-59 "pokemon", "plants", "plaqueattack", "portals", "raceBet", // 60-64 "raceBet2", "realportals", "realsokoban", "rivers", "roadfighter", // 65-69 "roguelike", "run", "seaquest", "sheriff", "shipwreck", // 70-74 "sokoban", "solarfox", "superman", "surround", "survivezombies", // 75-79 "tercio", "thecitadel", "thesnowman", "waitforbreakfast", "watergame", // 80-84 "waves", "whackamole", "wildgunman", "witnessprotection", "wrapsokoban", // 85-89 "zelda", "zenpuzzle" }; // 90, 91 String recordActionsFile = null;// "actions_" + games[gameIdx] + "_lvl" // + levelIdx + "_" + seed + ".txt"; // where to record the actions // executed. null if not to save. // Other settings int seed = new Random().nextInt(); int gameIdx = 0; String recordLevelFile = generateLevelPath + games[gameIdx] + "_glvl.txt"; String game = generateLevelPath + games[gameIdx] + ".txt"; // 1. This starts a game, in a generated level created by a specific level generator if(LevelGenMachine.generateOneLevel(game, constructiveLevelGenerator, recordLevelFile)){ LevelGenMachine.playOneGeneratedLevel(game, recordActionsFile, recordLevelFile, seed); } // 2. This generates numberOfLevels levels. // String levelGenerator = "tracks.levelGeneration." + args[0] + ".LevelGenerator"; // int numberOfLevels<SUF> // tracks.levelGeneration.randomLevelGenerator.LevelGenerator.includeBorders = true; // String[] folderName = levelGenerator.split("\\."); // generateLevelPath = "examples/generatedLevels/" + folderName[1] + "/"; // game = gamesPath + args[1] + ".txt"; // for (int i = 0; i < numberOfLevels; i++) { // recordLevelFile = generateLevelPath + args[1] + "_lvl" + i + ".txt"; // LevelGenMachine.generateOneLevel(game, levelGenerator, recordLevelFile); //} } }
36472_10
/** * @author mchyzer * $Id: GrouperUiTextConfig.java,v 1.2 2013/06/20 06:02:51 mchyzer Exp $ */ package edu.internet2.middleware.grouperClient.config; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import edu.internet2.middleware.grouper.grouperUi.beans.ui.TextContainer; import edu.internet2.middleware.grouper.ui.GrouperUiFilter; import edu.internet2.middleware.grouper.ui.tags.GrouperMessageTag; import edu.internet2.middleware.grouper.ui.text.TextBundleBean; import edu.internet2.middleware.grouper.ui.util.GrouperUiConfig; import edu.internet2.middleware.grouper.util.GrouperUtil; /** * save the text bundle for the session. Determine it based on * the language and locale of the browser */ public class GrouperUiTextConfig extends ConfigPropertiesCascadeBase { /** * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //some code to print out accented chars, just put institutionName to have accented char //make a grouper.text.fr.fr.base.properties and grouper.text.fr.fr.properties //config new locale in grouper-ui.properties // grouper.text.bundle.1.language = fr // grouper.text.bundle.1.country = fr // grouper.text.bundle.1.fileNamePrefix = grouperText/grouper.text.fr.fr Locale locale = new Locale("fr", "FR"); GrouperUiTextConfig grouperUiTextConfig = GrouperUiTextConfig.retrieveText(locale); System.out.println("1: " + grouperUiTextConfig.propertyValueString("institutionName")); Properties properties = GrouperUtil.propertiesFromResourceName("grouperText/grouper.text.fr.fr.properties"); System.out.println("2: " + properties.get("institutionName")); URL url = ConfigPropertiesCascadeUtils.computeUrl("grouperText/grouper.text.fr.fr.properties", true); InputStream inputStream = url.openStream(); String contents = ConfigPropertiesCascadeUtils.toString(inputStream, "UTF-8"); System.out.println("3: " + contents); File file = new File("C:\\Users\\mchyzer\\Documents\\GitHub\\grouper_v2_2\\grouper-ui\\conf\\grouperText\\grouper.text.fr.fr.properties"); contents = GrouperUtil.readFileIntoString(file); System.out.println("4: " + contents); System.out.println("5: " + new String(contents.getBytes("UTF-8"), "ISO-8859-1")); InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8"); StringWriter writer = new StringWriter(); IOUtils.copy(inputStreamReader, writer); contents = writer.toString(); System.out.println("6: " + contents); } /** * the name of the file on classpath, e.g. grouperText/grouper.text.en.us.properties */ private String mainConfigClasspath; /** * e.g. en_us */ private String languageCountry; /** * the name of the file on classpath, e.g. grouperText/grouper.text.en.us.base.properties */ private String mainExampleConfigClasspath; /** tooltip keys */ private List<String> tooltipKeys = null; /** tooltip values in order of keys */ private List<String> tooltipValues = null; /** in the text file, terms must start with this prefix. multiple terms can exist for one tooltip */ public static final String TERM_PREFIX = "term."; /** in the text file, tooltips must start with this prefix. there should be one and only one tooltip for a term. * tooltips and terms are linked by the common name, which is the suffix of the text file key. * e.g. tooltip.group=A group is a collection * term.group=Group * term.group=group * * these are linked because they all end in "group" */ public static final String TOOLTIP_PREFIX = "tooltip."; /** * target a tooltip on a certain message */ public static final String TOOLTIP_TARGETTED_PREFIX = "tooltipTargetted."; /** * target a tooltip on a certain message, and make the value of the tooltip * a reference to another tooltip */ public static final String TOOLTIP_TARGETTED_REF_PREFIX = "tooltipTargettedRef."; /** logger */ private static final Log LOG = GrouperUtil.getLog(GrouperUiTextConfig.class); /** * constructor with the correct files * @param theMainConfigClasspath * @param theMainExampleConfigClasspath * @param theLanguageCountry e.g. en_us */ private GrouperUiTextConfig(String theMainConfigClasspath, String theMainExampleConfigClasspath, String theLanguageCountry) { this.mainConfigClasspath = theMainConfigClasspath; this.mainExampleConfigClasspath = theMainExampleConfigClasspath; this.languageCountry = theLanguageCountry; } /** * */ public GrouperUiTextConfig() { } /** * text config for this user's locale * @return the config for this user's locale */ public static GrouperUiTextConfig retrieveTextConfig() { HttpServletRequest httpServletRequest = GrouperUiFilter.retrieveHttpServletRequest(); //cache this in the request GrouperUiTextConfig grouperUiTextConfig = (GrouperUiTextConfig)httpServletRequest.getAttribute("grouperUiTextConfig"); if (grouperUiTextConfig == null) { synchronized(httpServletRequest) { grouperUiTextConfig = (GrouperUiTextConfig)httpServletRequest.getAttribute("grouperUiTextConfig"); if (grouperUiTextConfig == null) { Locale locale = httpServletRequest.getLocale(); grouperUiTextConfig = retrieveText(locale); httpServletRequest.setAttribute("grouperUiTextConfig", grouperUiTextConfig); } } } return grouperUiTextConfig; } /** * text config for a certain locale * @param locale * @return the config for this user's locale */ public static GrouperUiTextConfig retrieveText(Locale locale) { TextBundleBean textBundleBean = retrieveTextBundleBean(locale); GrouperUiTextConfig grouperTextConfig = new GrouperUiTextConfig(textBundleBean.getFileNamePrefix() + ".properties", textBundleBean.getFileNamePrefix() + ".base.properties", textBundleBean.getLanguage() + "_" + textBundleBean.getCountry()); grouperTextConfig = (GrouperUiTextConfig)grouperTextConfig.retrieveFromConfigFileOrCache(); return grouperTextConfig; } /** * text config for a certain locale * @param locale * @return the config for this user's locale */ private static TextBundleBean retrieveTextBundleBean(Locale locale) { if (locale == null) { //return the default return GrouperUiConfig.retrieveConfig().textBundleDefault(); } String language = StringUtils.defaultString(locale.getLanguage()).toLowerCase(); String country = StringUtils.defaultString(locale.getCountry()).toLowerCase(); //see if there is a match by language and country TextBundleBean textBundleBean = GrouperUiConfig.retrieveConfig() .textBundleFromLanguageAndCountry().get(language + "_" + country); if (textBundleBean != null) { return textBundleBean; } //see if there is a match by language textBundleBean = GrouperUiConfig.retrieveConfig() .textBundleFromLanguage().get(language); if (textBundleBean != null) { return textBundleBean; } //see if there is a match by country textBundleBean = GrouperUiConfig.retrieveConfig() .textBundleFromCountry().get(country); if (textBundleBean != null) { return textBundleBean; } //do the default return GrouperUiConfig.retrieveConfig().textBundleDefault(); } /** * @see edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase#clearCachedCalculatedValues() */ @Override public void clearCachedCalculatedValues() { } /** * @see edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase#getHierarchyConfigKey() */ @Override protected String getHierarchyConfigKey() { //"grouperServer.config.hierarchy" return "text.config.hierarchy"; } /** * @see edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase#getMainConfigClasspath() */ @Override protected String getMainConfigClasspath() { //"grouper.server.properties" return this.mainConfigClasspath; } /** * @see edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase#getMainExampleConfigClasspath() */ @Override protected String getMainExampleConfigClasspath() { //"grouper.server.base.properties" return this.mainExampleConfigClasspath; } /** * @see edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase#getSecondsToCheckConfigKey() */ @Override protected String getSecondsToCheckConfigKey() { //"grouperServer.config.secondsBetweenUpdateChecks" return "text.config.secondsBetweenUpdateChecks"; } /** * config file cache */ private static Map<String, ConfigPropertiesCascadeBase> configFileCache = null; /** * pattern to find where the variables are in the textm, e.g. $$something$$ */ private static Pattern substitutePattern = Pattern.compile("\\$\\$([^\\s\\$]+?)\\$\\$"); /** * @see edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase#retrieveFromConfigFiles() */ @Override protected ConfigPropertiesCascadeBase retrieveFromConfigFiles() { ConfigPropertiesCascadeBase configPropertiesCascadeBase = super.retrieveFromConfigFiles(); Properties properties = configPropertiesCascadeBase.internalProperties(); Set<String> propertyNamesToCheck = new LinkedHashSet<String>(); for (Object propertyName : properties.keySet()) { propertyNamesToCheck.add((String)propertyName); } Set<String> nextPropertyNamesToCheck = new LinkedHashSet<String>(); //lets resolve variables for (int i=0;i<20;i++) { boolean foundVariable = false; for (Object propertyNameObject : properties.keySet()) { String propertyName = (String)propertyNameObject; String value = properties.getProperty(propertyName); String newValue = substituteVariables(properties, value); //next run, dont do the ones that dont change... if (!StringUtils.equals(value, newValue)) { nextPropertyNamesToCheck.add(value); foundVariable = true; properties.put(propertyName, newValue); } } if (!foundVariable) { break; } //keep track of ones to check propertyNamesToCheck = nextPropertyNamesToCheck; nextPropertyNamesToCheck = new LinkedHashSet<String>(); } return configPropertiesCascadeBase; } /** * * @param properties to get data from * @param value * @return the subsituted string */ protected String substituteVariables(Properties properties, String value) { Matcher matcher = substitutePattern.matcher(value); StringBuilder result = new StringBuilder(); int index = 0; //loop through and find each script while(matcher.find()) { result.append(value.substring(index, matcher.start())); //here is the script inside the dollars String variable = matcher.group(1); index = matcher.end(); String variableText = properties.getProperty(variable); if (StringUtils.isBlank(variableText)) { LOG.error("Cant find text for variable: '" + variable + "'"); variableText = "$$not found: " + variable + "$$"; } result.append(variableText); } result.append(value.substring(index, value.length())); return result.toString(); } /** * see if there is one in cache, if so, use it, if not, get from config files * @return the config from file or cache */ @Override protected ConfigPropertiesCascadeBase retrieveFromConfigFileOrCache() { if (configFileCache == null) { configFileCache = new HashMap<String, ConfigPropertiesCascadeBase>(); } ConfigPropertiesCascadeBase configObject = configFileCache.get(this.languageCountry); if (configObject == null) { if (LOG != null && LOG.isDebugEnabled()) { LOG.debug("Config file has not be created yet, will create now: " + this.getMainConfigClasspath()); } configObject = retrieveFromConfigFiles(); configFileCache.put(this.languageCountry, configObject); } else { //see if that much time has passed if (configObject.needToCheckIfFilesNeedReloading()) { synchronized (configObject) { configObject = configFileCache.get(this.languageCountry); //check again in case another thread did it if (configObject.needToCheckIfFilesNeedReloading()) { if (configObject.filesNeedReloadingBasedOnContents()) { configObject = retrieveFromConfigFiles(); configFileCache.put(this.languageCountry, configObject); } } } } } return configObject; } /** * init and return the tooltip keys * @return the list of keys */ public List<String> tooltipKeys() { if (this.tooltipKeys == null) { //add properties to map Properties propertiesFromConfig = properties(); Set<Object> propertiesKeys = propertiesFromConfig.keySet(); Map<String, String> propertiesMap = null; //loop through the tooltips if (propertiesKeys != null) { propertiesMap = new HashMap<String, String>(); for (Object propertiesKeyObject : propertiesKeys) { String propertiesKey = (String)propertiesKeyObject; //see if a key boolean isTerm = propertiesKey.startsWith(TERM_PREFIX); //if isValue, continue on if (!isTerm) { continue; } //if term then get the term String term = propertiesFromConfig.getProperty(propertiesKey); String termId = propertiesKey.substring(TERM_PREFIX.length()); //strip off the .1, .2, etc if it exists if (termId.matches("^.*\\.[0-9]+$")) { int lastDot = termId.lastIndexOf('.'); termId = termId.substring(0,lastDot); } String tooltipKey = GrouperMessageTag.TOOLTIP_PREFIX + termId; String tooltip = propertiesFromConfig.getProperty(tooltipKey); //tooltipKeys.add(term); tooltip = TextContainer.convertTooltipTextToHtml(tooltip, term, false); //tooltipValues.add(tooltip); propertiesMap.put(term, tooltip); } propertiesMap = sortMapBySubstringFirst(propertiesMap); //convert back to lists this.tooltipKeys = new ArrayList<String>(propertiesMap.keySet()); this.tooltipValues = new ArrayList<String>(propertiesMap.values()); } } return this.tooltipKeys; } /** * convert the properties configuration object to a map object (tree map) * @param inputMap * @return the */ static Map<String, String> sortMapBySubstringFirst(Map<String, String> inputMap) { if (inputMap == null) { return null; } Map<String, String> resultMap = new TreeMap<String, String>(new Comparator<String>() { /** * comparator that puts substrings last * @param o1 * @param o2 * @return comparison */ public int compare(String o1, String o2) { if (o1 == o2) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } if (o1.equals(o2)) { return 0; } if (o1.contains(o2)) { return -1; } if (o2.contains(o1)) { return 1; } return o1.compareTo(o2); } }); resultMap.putAll(inputMap); return resultMap; } /** * init and return the tooltip keys * @return the list of keys */ public List<String> tooltipValues() { //init everything tooltipKeys(); return this.tooltipValues; } }
EsupPortail/grouper-esup
grouper-ui/java/src/edu/internet2/middleware/grouperClient/config/GrouperUiTextConfig.java
5,534
/** * e.g. en_us */
block_comment
nl
/** * @author mchyzer * $Id: GrouperUiTextConfig.java,v 1.2 2013/06/20 06:02:51 mchyzer Exp $ */ package edu.internet2.middleware.grouperClient.config; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import edu.internet2.middleware.grouper.grouperUi.beans.ui.TextContainer; import edu.internet2.middleware.grouper.ui.GrouperUiFilter; import edu.internet2.middleware.grouper.ui.tags.GrouperMessageTag; import edu.internet2.middleware.grouper.ui.text.TextBundleBean; import edu.internet2.middleware.grouper.ui.util.GrouperUiConfig; import edu.internet2.middleware.grouper.util.GrouperUtil; /** * save the text bundle for the session. Determine it based on * the language and locale of the browser */ public class GrouperUiTextConfig extends ConfigPropertiesCascadeBase { /** * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //some code to print out accented chars, just put institutionName to have accented char //make a grouper.text.fr.fr.base.properties and grouper.text.fr.fr.properties //config new locale in grouper-ui.properties // grouper.text.bundle.1.language = fr // grouper.text.bundle.1.country = fr // grouper.text.bundle.1.fileNamePrefix = grouperText/grouper.text.fr.fr Locale locale = new Locale("fr", "FR"); GrouperUiTextConfig grouperUiTextConfig = GrouperUiTextConfig.retrieveText(locale); System.out.println("1: " + grouperUiTextConfig.propertyValueString("institutionName")); Properties properties = GrouperUtil.propertiesFromResourceName("grouperText/grouper.text.fr.fr.properties"); System.out.println("2: " + properties.get("institutionName")); URL url = ConfigPropertiesCascadeUtils.computeUrl("grouperText/grouper.text.fr.fr.properties", true); InputStream inputStream = url.openStream(); String contents = ConfigPropertiesCascadeUtils.toString(inputStream, "UTF-8"); System.out.println("3: " + contents); File file = new File("C:\\Users\\mchyzer\\Documents\\GitHub\\grouper_v2_2\\grouper-ui\\conf\\grouperText\\grouper.text.fr.fr.properties"); contents = GrouperUtil.readFileIntoString(file); System.out.println("4: " + contents); System.out.println("5: " + new String(contents.getBytes("UTF-8"), "ISO-8859-1")); InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8"); StringWriter writer = new StringWriter(); IOUtils.copy(inputStreamReader, writer); contents = writer.toString(); System.out.println("6: " + contents); } /** * the name of the file on classpath, e.g. grouperText/grouper.text.en.us.properties */ private String mainConfigClasspath; /** * e.g. en_us <SUF>*/ private String languageCountry; /** * the name of the file on classpath, e.g. grouperText/grouper.text.en.us.base.properties */ private String mainExampleConfigClasspath; /** tooltip keys */ private List<String> tooltipKeys = null; /** tooltip values in order of keys */ private List<String> tooltipValues = null; /** in the text file, terms must start with this prefix. multiple terms can exist for one tooltip */ public static final String TERM_PREFIX = "term."; /** in the text file, tooltips must start with this prefix. there should be one and only one tooltip for a term. * tooltips and terms are linked by the common name, which is the suffix of the text file key. * e.g. tooltip.group=A group is a collection * term.group=Group * term.group=group * * these are linked because they all end in "group" */ public static final String TOOLTIP_PREFIX = "tooltip."; /** * target a tooltip on a certain message */ public static final String TOOLTIP_TARGETTED_PREFIX = "tooltipTargetted."; /** * target a tooltip on a certain message, and make the value of the tooltip * a reference to another tooltip */ public static final String TOOLTIP_TARGETTED_REF_PREFIX = "tooltipTargettedRef."; /** logger */ private static final Log LOG = GrouperUtil.getLog(GrouperUiTextConfig.class); /** * constructor with the correct files * @param theMainConfigClasspath * @param theMainExampleConfigClasspath * @param theLanguageCountry e.g. en_us */ private GrouperUiTextConfig(String theMainConfigClasspath, String theMainExampleConfigClasspath, String theLanguageCountry) { this.mainConfigClasspath = theMainConfigClasspath; this.mainExampleConfigClasspath = theMainExampleConfigClasspath; this.languageCountry = theLanguageCountry; } /** * */ public GrouperUiTextConfig() { } /** * text config for this user's locale * @return the config for this user's locale */ public static GrouperUiTextConfig retrieveTextConfig() { HttpServletRequest httpServletRequest = GrouperUiFilter.retrieveHttpServletRequest(); //cache this in the request GrouperUiTextConfig grouperUiTextConfig = (GrouperUiTextConfig)httpServletRequest.getAttribute("grouperUiTextConfig"); if (grouperUiTextConfig == null) { synchronized(httpServletRequest) { grouperUiTextConfig = (GrouperUiTextConfig)httpServletRequest.getAttribute("grouperUiTextConfig"); if (grouperUiTextConfig == null) { Locale locale = httpServletRequest.getLocale(); grouperUiTextConfig = retrieveText(locale); httpServletRequest.setAttribute("grouperUiTextConfig", grouperUiTextConfig); } } } return grouperUiTextConfig; } /** * text config for a certain locale * @param locale * @return the config for this user's locale */ public static GrouperUiTextConfig retrieveText(Locale locale) { TextBundleBean textBundleBean = retrieveTextBundleBean(locale); GrouperUiTextConfig grouperTextConfig = new GrouperUiTextConfig(textBundleBean.getFileNamePrefix() + ".properties", textBundleBean.getFileNamePrefix() + ".base.properties", textBundleBean.getLanguage() + "_" + textBundleBean.getCountry()); grouperTextConfig = (GrouperUiTextConfig)grouperTextConfig.retrieveFromConfigFileOrCache(); return grouperTextConfig; } /** * text config for a certain locale * @param locale * @return the config for this user's locale */ private static TextBundleBean retrieveTextBundleBean(Locale locale) { if (locale == null) { //return the default return GrouperUiConfig.retrieveConfig().textBundleDefault(); } String language = StringUtils.defaultString(locale.getLanguage()).toLowerCase(); String country = StringUtils.defaultString(locale.getCountry()).toLowerCase(); //see if there is a match by language and country TextBundleBean textBundleBean = GrouperUiConfig.retrieveConfig() .textBundleFromLanguageAndCountry().get(language + "_" + country); if (textBundleBean != null) { return textBundleBean; } //see if there is a match by language textBundleBean = GrouperUiConfig.retrieveConfig() .textBundleFromLanguage().get(language); if (textBundleBean != null) { return textBundleBean; } //see if there is a match by country textBundleBean = GrouperUiConfig.retrieveConfig() .textBundleFromCountry().get(country); if (textBundleBean != null) { return textBundleBean; } //do the default return GrouperUiConfig.retrieveConfig().textBundleDefault(); } /** * @see edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase#clearCachedCalculatedValues() */ @Override public void clearCachedCalculatedValues() { } /** * @see edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase#getHierarchyConfigKey() */ @Override protected String getHierarchyConfigKey() { //"grouperServer.config.hierarchy" return "text.config.hierarchy"; } /** * @see edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase#getMainConfigClasspath() */ @Override protected String getMainConfigClasspath() { //"grouper.server.properties" return this.mainConfigClasspath; } /** * @see edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase#getMainExampleConfigClasspath() */ @Override protected String getMainExampleConfigClasspath() { //"grouper.server.base.properties" return this.mainExampleConfigClasspath; } /** * @see edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase#getSecondsToCheckConfigKey() */ @Override protected String getSecondsToCheckConfigKey() { //"grouperServer.config.secondsBetweenUpdateChecks" return "text.config.secondsBetweenUpdateChecks"; } /** * config file cache */ private static Map<String, ConfigPropertiesCascadeBase> configFileCache = null; /** * pattern to find where the variables are in the textm, e.g. $$something$$ */ private static Pattern substitutePattern = Pattern.compile("\\$\\$([^\\s\\$]+?)\\$\\$"); /** * @see edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase#retrieveFromConfigFiles() */ @Override protected ConfigPropertiesCascadeBase retrieveFromConfigFiles() { ConfigPropertiesCascadeBase configPropertiesCascadeBase = super.retrieveFromConfigFiles(); Properties properties = configPropertiesCascadeBase.internalProperties(); Set<String> propertyNamesToCheck = new LinkedHashSet<String>(); for (Object propertyName : properties.keySet()) { propertyNamesToCheck.add((String)propertyName); } Set<String> nextPropertyNamesToCheck = new LinkedHashSet<String>(); //lets resolve variables for (int i=0;i<20;i++) { boolean foundVariable = false; for (Object propertyNameObject : properties.keySet()) { String propertyName = (String)propertyNameObject; String value = properties.getProperty(propertyName); String newValue = substituteVariables(properties, value); //next run, dont do the ones that dont change... if (!StringUtils.equals(value, newValue)) { nextPropertyNamesToCheck.add(value); foundVariable = true; properties.put(propertyName, newValue); } } if (!foundVariable) { break; } //keep track of ones to check propertyNamesToCheck = nextPropertyNamesToCheck; nextPropertyNamesToCheck = new LinkedHashSet<String>(); } return configPropertiesCascadeBase; } /** * * @param properties to get data from * @param value * @return the subsituted string */ protected String substituteVariables(Properties properties, String value) { Matcher matcher = substitutePattern.matcher(value); StringBuilder result = new StringBuilder(); int index = 0; //loop through and find each script while(matcher.find()) { result.append(value.substring(index, matcher.start())); //here is the script inside the dollars String variable = matcher.group(1); index = matcher.end(); String variableText = properties.getProperty(variable); if (StringUtils.isBlank(variableText)) { LOG.error("Cant find text for variable: '" + variable + "'"); variableText = "$$not found: " + variable + "$$"; } result.append(variableText); } result.append(value.substring(index, value.length())); return result.toString(); } /** * see if there is one in cache, if so, use it, if not, get from config files * @return the config from file or cache */ @Override protected ConfigPropertiesCascadeBase retrieveFromConfigFileOrCache() { if (configFileCache == null) { configFileCache = new HashMap<String, ConfigPropertiesCascadeBase>(); } ConfigPropertiesCascadeBase configObject = configFileCache.get(this.languageCountry); if (configObject == null) { if (LOG != null && LOG.isDebugEnabled()) { LOG.debug("Config file has not be created yet, will create now: " + this.getMainConfigClasspath()); } configObject = retrieveFromConfigFiles(); configFileCache.put(this.languageCountry, configObject); } else { //see if that much time has passed if (configObject.needToCheckIfFilesNeedReloading()) { synchronized (configObject) { configObject = configFileCache.get(this.languageCountry); //check again in case another thread did it if (configObject.needToCheckIfFilesNeedReloading()) { if (configObject.filesNeedReloadingBasedOnContents()) { configObject = retrieveFromConfigFiles(); configFileCache.put(this.languageCountry, configObject); } } } } } return configObject; } /** * init and return the tooltip keys * @return the list of keys */ public List<String> tooltipKeys() { if (this.tooltipKeys == null) { //add properties to map Properties propertiesFromConfig = properties(); Set<Object> propertiesKeys = propertiesFromConfig.keySet(); Map<String, String> propertiesMap = null; //loop through the tooltips if (propertiesKeys != null) { propertiesMap = new HashMap<String, String>(); for (Object propertiesKeyObject : propertiesKeys) { String propertiesKey = (String)propertiesKeyObject; //see if a key boolean isTerm = propertiesKey.startsWith(TERM_PREFIX); //if isValue, continue on if (!isTerm) { continue; } //if term then get the term String term = propertiesFromConfig.getProperty(propertiesKey); String termId = propertiesKey.substring(TERM_PREFIX.length()); //strip off the .1, .2, etc if it exists if (termId.matches("^.*\\.[0-9]+$")) { int lastDot = termId.lastIndexOf('.'); termId = termId.substring(0,lastDot); } String tooltipKey = GrouperMessageTag.TOOLTIP_PREFIX + termId; String tooltip = propertiesFromConfig.getProperty(tooltipKey); //tooltipKeys.add(term); tooltip = TextContainer.convertTooltipTextToHtml(tooltip, term, false); //tooltipValues.add(tooltip); propertiesMap.put(term, tooltip); } propertiesMap = sortMapBySubstringFirst(propertiesMap); //convert back to lists this.tooltipKeys = new ArrayList<String>(propertiesMap.keySet()); this.tooltipValues = new ArrayList<String>(propertiesMap.values()); } } return this.tooltipKeys; } /** * convert the properties configuration object to a map object (tree map) * @param inputMap * @return the */ static Map<String, String> sortMapBySubstringFirst(Map<String, String> inputMap) { if (inputMap == null) { return null; } Map<String, String> resultMap = new TreeMap<String, String>(new Comparator<String>() { /** * comparator that puts substrings last * @param o1 * @param o2 * @return comparison */ public int compare(String o1, String o2) { if (o1 == o2) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } if (o1.equals(o2)) { return 0; } if (o1.contains(o2)) { return -1; } if (o2.contains(o1)) { return 1; } return o1.compareTo(o2); } }); resultMap.putAll(inputMap); return resultMap; } /** * init and return the tooltip keys * @return the list of keys */ public List<String> tooltipValues() { //init everything tooltipKeys(); return this.tooltipValues; } }
189486_21
/* * Copyright (C) 2014-2016 The CyanogenMod Project * * 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.android.calendar.icalendar; import java.util.HashMap; import java.util.LinkedList; import java.util.ListIterator; import java.util.UUID; /** * Models the Event/VEvent component of the iCalendar format */ public class VEvent { // Valid property identifiers for an event component // TODO: only a partial list of attributes has been implemented, implement the rest public static String CLASS = "CLASS"; public static String CREATED = "CREATED"; public static String LOCATION = "LOCATION"; public static String ORGANIZER = "ORGANIZER"; public static String PRIORITY = "PRIORITY"; public static String SEQ = "SEQ"; public static String STATUS = "STATUS"; public static String UID = "UID"; public static String URL = "URL"; public static String DTSTART = "DTSTART"; public static String DTEND = "DTEND"; public static String DURATION = "DURATION"; public static String DTSTAMP = "DTSTAMP"; public static String SUMMARY = "SUMMARY"; public static String DESCRIPTION = "DESCRIPTION"; public static String ATTENDEE = "ATTENDEE"; public static String CATEGORIES = "CATEGORIES"; // Stores the -arity of the attributes that this component can have private static HashMap<String, Integer> sPropertyList = new HashMap<String, Integer>(); // Initialize the approved list of mProperties for a calendar event static { sPropertyList.put(CLASS,1); sPropertyList.put(CREATED,1); sPropertyList.put(LOCATION,1); sPropertyList.put(ORGANIZER,1); sPropertyList.put(PRIORITY,1); sPropertyList.put(SEQ,1); sPropertyList.put(STATUS,1); sPropertyList.put(UID,1); sPropertyList.put(URL,1); sPropertyList.put(DTSTART,1); sPropertyList.put(DTEND,1); sPropertyList.put(DURATION, 1); sPropertyList.put(DTSTAMP,1); sPropertyList.put(SUMMARY,1); sPropertyList.put(DESCRIPTION,1); sPropertyList.put(ATTENDEE, Integer.MAX_VALUE); sPropertyList.put(CATEGORIES, Integer.MAX_VALUE); sPropertyList.put(CATEGORIES, Integer.MAX_VALUE); } // Stores attributes and their corresponding values belonging to the Event component public HashMap<String, String> mProperties; public HashMap<String, String> mPropertyParameters; public LinkedList<Attendee> mAttendees; public Organizer mOrganizer; /** * Constructor */ public VEvent() { mProperties = new HashMap<String, String>(); mPropertyParameters = new HashMap<String, String>(); mAttendees = new LinkedList<Attendee>(); // Generate and add a unique identifier to this event - iCal requisite addProperty(UID , UUID.randomUUID().toString() + "@ws.xsoh.etar"); addTimeStamp(); } /** * For adding unary properties. For adding other property attributes , use the respective * component methods to create and add these special components. * @param property * @param value * @return */ public boolean addProperty(String property, String value) { // Only unary-properties for now if (sPropertyList.containsKey(property) && sPropertyList.get(property) == 1 && value != null) { mProperties.put(property, IcalendarUtils.cleanseString(value)); return true; } return false; } /** * Returns the value of the requested event property or null if there isn't one */ public String getProperty(String property) { return mProperties.get(property); } /** * Returns the parameters of the requested event property or null if there isn't one */ public String getPropertyParameters(String property) { return mPropertyParameters.get(property); } /** * Add attendees to the event * @param attendee */ public void addAttendee(Attendee attendee) { if(attendee != null) mAttendees.add(attendee); } /** * Add an Organizer to the Event * @param organizer */ public void addOrganizer(Organizer organizer) { if (organizer != null) mOrganizer = organizer; } /** * Add an start date-time to the event */ public void addEventStart(long startMillis, String timeZone) { if (startMillis < 0) return; String formattedDateTime = IcalendarUtils.getICalFormattedDateTime(startMillis, timeZone); addProperty(DTSTART, formattedDateTime); } /** * Add an end date-time for event */ public void addEventEnd(long endMillis, String timeZone) { if (endMillis < 0) return; String formattedDateTime = IcalendarUtils.getICalFormattedDateTime(endMillis, timeZone); addProperty(DTEND, formattedDateTime); } /** * Timestamps the events with the current date-time */ private void addTimeStamp() { String formattedDateTime = IcalendarUtils.getICalFormattedDateTime( System.currentTimeMillis(), "UTC"); addProperty(DTSTAMP, formattedDateTime); } /** * Returns the iCal representation of the Event component */ public String getICalFormattedString() { StringBuilder sb = new StringBuilder(); // Add Event properties sb.append("BEGIN:VEVENT\n"); for (String property : mProperties.keySet() ) { sb.append(property + ":" + mProperties.get(property) + "\n"); } // Enforce line length requirements sb = IcalendarUtils.enforceICalLineLength(sb); sb.append(mOrganizer.getICalFormattedString()); // Add event Attendees for (Attendee attendee : mAttendees) { sb.append(attendee.getICalFormattedString()); } sb.append("END:VEVENT\n"); return sb.toString(); } public void populateFromEntries(ListIterator<String> iter) { while (iter.hasNext()) { String line = iter.next(); if (line.contains("BEGIN:VEVENT")) { // Continue } else if (line.startsWith("END:VEVENT")) { break; } else if (line.startsWith("ORGANIZER")) { String entry = parseTillNextAttribute(iter, line); mOrganizer = Organizer.populateFromICalString(entry); } else if (line.startsWith("ATTENDEE")) { // Go one previous, so VEvent, parses current line iter.previous(); // Offload to Attendee for parsing Attendee attendee = new Attendee(); attendee.populateFromEntries(iter); mAttendees.add(attendee); } else if (line.contains(":")) { String entry = parseTillNextAttribute(iter, line); int indexOfFirstColon = entry.indexOf(":"); int indexOfFirstParamDelimiter = entry.indexOf(";"); String key; if (indexOfFirstParamDelimiter != -1 && indexOfFirstParamDelimiter < indexOfFirstColon) { key = entry.substring(0, indexOfFirstParamDelimiter); String params = entry.substring(indexOfFirstParamDelimiter + 1, indexOfFirstColon); mPropertyParameters.put(key, params); } else { key = entry.substring(0, indexOfFirstColon); } String value = entry.substring(indexOfFirstColon + 1); mProperties.put(key, value); } } } public static String parseTillNextAttribute(ListIterator<String> iter, String currentLine) { StringBuilder parse = new StringBuilder(); parse.append(currentLine); while (iter.hasNext()) { String line = iter.next(); if (line.startsWith(" ")) { parse.append(line.replaceFirst(" ", "")); } else { iter.previous(); break; } } return parse.toString(); } }
Etar-Group/Etar-Calendar
app/src/main/java/com/android/calendar/icalendar/VEvent.java
2,413
// Add event Attendees
line_comment
nl
/* * Copyright (C) 2014-2016 The CyanogenMod Project * * 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.android.calendar.icalendar; import java.util.HashMap; import java.util.LinkedList; import java.util.ListIterator; import java.util.UUID; /** * Models the Event/VEvent component of the iCalendar format */ public class VEvent { // Valid property identifiers for an event component // TODO: only a partial list of attributes has been implemented, implement the rest public static String CLASS = "CLASS"; public static String CREATED = "CREATED"; public static String LOCATION = "LOCATION"; public static String ORGANIZER = "ORGANIZER"; public static String PRIORITY = "PRIORITY"; public static String SEQ = "SEQ"; public static String STATUS = "STATUS"; public static String UID = "UID"; public static String URL = "URL"; public static String DTSTART = "DTSTART"; public static String DTEND = "DTEND"; public static String DURATION = "DURATION"; public static String DTSTAMP = "DTSTAMP"; public static String SUMMARY = "SUMMARY"; public static String DESCRIPTION = "DESCRIPTION"; public static String ATTENDEE = "ATTENDEE"; public static String CATEGORIES = "CATEGORIES"; // Stores the -arity of the attributes that this component can have private static HashMap<String, Integer> sPropertyList = new HashMap<String, Integer>(); // Initialize the approved list of mProperties for a calendar event static { sPropertyList.put(CLASS,1); sPropertyList.put(CREATED,1); sPropertyList.put(LOCATION,1); sPropertyList.put(ORGANIZER,1); sPropertyList.put(PRIORITY,1); sPropertyList.put(SEQ,1); sPropertyList.put(STATUS,1); sPropertyList.put(UID,1); sPropertyList.put(URL,1); sPropertyList.put(DTSTART,1); sPropertyList.put(DTEND,1); sPropertyList.put(DURATION, 1); sPropertyList.put(DTSTAMP,1); sPropertyList.put(SUMMARY,1); sPropertyList.put(DESCRIPTION,1); sPropertyList.put(ATTENDEE, Integer.MAX_VALUE); sPropertyList.put(CATEGORIES, Integer.MAX_VALUE); sPropertyList.put(CATEGORIES, Integer.MAX_VALUE); } // Stores attributes and their corresponding values belonging to the Event component public HashMap<String, String> mProperties; public HashMap<String, String> mPropertyParameters; public LinkedList<Attendee> mAttendees; public Organizer mOrganizer; /** * Constructor */ public VEvent() { mProperties = new HashMap<String, String>(); mPropertyParameters = new HashMap<String, String>(); mAttendees = new LinkedList<Attendee>(); // Generate and add a unique identifier to this event - iCal requisite addProperty(UID , UUID.randomUUID().toString() + "@ws.xsoh.etar"); addTimeStamp(); } /** * For adding unary properties. For adding other property attributes , use the respective * component methods to create and add these special components. * @param property * @param value * @return */ public boolean addProperty(String property, String value) { // Only unary-properties for now if (sPropertyList.containsKey(property) && sPropertyList.get(property) == 1 && value != null) { mProperties.put(property, IcalendarUtils.cleanseString(value)); return true; } return false; } /** * Returns the value of the requested event property or null if there isn't one */ public String getProperty(String property) { return mProperties.get(property); } /** * Returns the parameters of the requested event property or null if there isn't one */ public String getPropertyParameters(String property) { return mPropertyParameters.get(property); } /** * Add attendees to the event * @param attendee */ public void addAttendee(Attendee attendee) { if(attendee != null) mAttendees.add(attendee); } /** * Add an Organizer to the Event * @param organizer */ public void addOrganizer(Organizer organizer) { if (organizer != null) mOrganizer = organizer; } /** * Add an start date-time to the event */ public void addEventStart(long startMillis, String timeZone) { if (startMillis < 0) return; String formattedDateTime = IcalendarUtils.getICalFormattedDateTime(startMillis, timeZone); addProperty(DTSTART, formattedDateTime); } /** * Add an end date-time for event */ public void addEventEnd(long endMillis, String timeZone) { if (endMillis < 0) return; String formattedDateTime = IcalendarUtils.getICalFormattedDateTime(endMillis, timeZone); addProperty(DTEND, formattedDateTime); } /** * Timestamps the events with the current date-time */ private void addTimeStamp() { String formattedDateTime = IcalendarUtils.getICalFormattedDateTime( System.currentTimeMillis(), "UTC"); addProperty(DTSTAMP, formattedDateTime); } /** * Returns the iCal representation of the Event component */ public String getICalFormattedString() { StringBuilder sb = new StringBuilder(); // Add Event properties sb.append("BEGIN:VEVENT\n"); for (String property : mProperties.keySet() ) { sb.append(property + ":" + mProperties.get(property) + "\n"); } // Enforce line length requirements sb = IcalendarUtils.enforceICalLineLength(sb); sb.append(mOrganizer.getICalFormattedString()); // Add event<SUF> for (Attendee attendee : mAttendees) { sb.append(attendee.getICalFormattedString()); } sb.append("END:VEVENT\n"); return sb.toString(); } public void populateFromEntries(ListIterator<String> iter) { while (iter.hasNext()) { String line = iter.next(); if (line.contains("BEGIN:VEVENT")) { // Continue } else if (line.startsWith("END:VEVENT")) { break; } else if (line.startsWith("ORGANIZER")) { String entry = parseTillNextAttribute(iter, line); mOrganizer = Organizer.populateFromICalString(entry); } else if (line.startsWith("ATTENDEE")) { // Go one previous, so VEvent, parses current line iter.previous(); // Offload to Attendee for parsing Attendee attendee = new Attendee(); attendee.populateFromEntries(iter); mAttendees.add(attendee); } else if (line.contains(":")) { String entry = parseTillNextAttribute(iter, line); int indexOfFirstColon = entry.indexOf(":"); int indexOfFirstParamDelimiter = entry.indexOf(";"); String key; if (indexOfFirstParamDelimiter != -1 && indexOfFirstParamDelimiter < indexOfFirstColon) { key = entry.substring(0, indexOfFirstParamDelimiter); String params = entry.substring(indexOfFirstParamDelimiter + 1, indexOfFirstColon); mPropertyParameters.put(key, params); } else { key = entry.substring(0, indexOfFirstColon); } String value = entry.substring(indexOfFirstColon + 1); mProperties.put(key, value); } } } public static String parseTillNextAttribute(ListIterator<String> iter, String currentLine) { StringBuilder parse = new StringBuilder(); parse.append(currentLine); while (iter.hasNext()) { String line = iter.next(); if (line.startsWith(" ")) { parse.append(line.replaceFirst(" ", "")); } else { iter.previous(); break; } } return parse.toString(); } }
57133_24
/* * Copyright 2017 Google Inc. 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 com.xrengine.xr.rendering; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.GLUtils; import android.opengl.Matrix; import com.google.ar.core.Camera; import com.google.ar.core.Plane; import com.google.ar.core.Pose; import com.google.ar.core.Trackable.*; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Renders the detected AR planes. */ public class PlaneRenderer { private static final String TAG = PlaneRenderer.class.getSimpleName(); private static final int BYTES_PER_FLOAT = Float.SIZE / 8; private static final int BYTES_PER_SHORT = Short.SIZE / 8; private static final int COORDS_PER_VERTEX = 3; // x, z, alpha private static final int VERTS_PER_BOUNDARY_VERT = 2; private static final int INDICES_PER_BOUNDARY_VERT = 3; private static final int INITIAL_BUFFER_BOUNDARY_VERTS = 64; private static final int INITIAL_VERTEX_BUFFER_SIZE_BYTES = BYTES_PER_FLOAT * COORDS_PER_VERTEX * VERTS_PER_BOUNDARY_VERT * INITIAL_BUFFER_BOUNDARY_VERTS; private static final int INITIAL_INDEX_BUFFER_SIZE_BYTES = BYTES_PER_SHORT * INDICES_PER_BOUNDARY_VERT * INDICES_PER_BOUNDARY_VERT * INITIAL_BUFFER_BOUNDARY_VERTS; private static final float FADE_RADIUS_M = 0.25f; private static final float DOTS_PER_METER = 10.0f; private static final float EQUILATERAL_TRIANGLE_SCALE = (float) (1 / Math.sqrt(3)); // Using the "signed distance field" approach to render sharp lines and circles. // {dotThreshold, lineThreshold, lineFadeSpeed, occlusionScale} // dotThreshold/lineThreshold: red/green intensity above which dots/lines are present // lineFadeShrink: lines will fade in between alpha = 1-(1/lineFadeShrink) and 1.0 // occlusionShrink: occluded planes will fade out between alpha = 0 and 1/occlusionShrink private static final float[] GRID_CONTROL = {0.2f, 0.4f, 2.0f, 1.5f}; private int mPlaneProgram; private int[] mTextures = new int[1]; private int mPlaneXZPositionAlphaAttribute; private int mPlaneModelUniform; private int mPlaneModelViewProjectionUniform; private int mTextureUniform; private int mLineColorUniform; private int mDotColorUniform; private int mGridControlUniform; private int mPlaneUvMatrixUniform; private FloatBuffer mVertexBuffer = ByteBuffer.allocateDirect(INITIAL_VERTEX_BUFFER_SIZE_BYTES) .order(ByteOrder.nativeOrder()).asFloatBuffer(); private ShortBuffer mIndexBuffer = ByteBuffer.allocateDirect(INITIAL_INDEX_BUFFER_SIZE_BYTES) .order(ByteOrder.nativeOrder()).asShortBuffer(); // Temporary lists/matrices allocated here to reduce number of allocations for each frame. private float[] mModelMatrix = new float[16]; private float[] mModelViewMatrix = new float[16]; private float[] mModelViewProjectionMatrix = new float[16]; private float[] mPlaneColor = new float[4]; private float[] mPlaneAngleUvMatrix = new float[4]; // 2x2 rotation matrix applied to uv coords. private Map<Plane, Integer> mPlaneIndexMap = new HashMap<Plane, Integer>(); public PlaneRenderer() { } /** * Allocates and initializes OpenGL resources needed by the plane renderer. Must be * called on the OpenGL thread, typically in * {@link GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig)}. * * @param context Needed to access shader source and texture PNG. * @param gridDistanceTextureName Name of the PNG file containing the grid texture. */ public void createOnGlThread(Context context, String gridDistanceTextureName) throws IOException { // TODO: UNCOMMENT instead of = 0 int vertexShader = 0; // ShaderUtil.loadGLShader(TAG, context, // GLES20.GL_VERTEX_SHADER, R.raw.plane_vertex); int passthroughShader = 0; // ShaderUtil.loadGLShader(TAG, context, // GLES20.GL_FRAGMENT_SHADER, R.raw.plane_fragment); mPlaneProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(mPlaneProgram, vertexShader); GLES20.glAttachShader(mPlaneProgram, passthroughShader); GLES20.glLinkProgram(mPlaneProgram); GLES20.glUseProgram(mPlaneProgram); ShaderUtil.checkGLError(TAG, "Program creation"); // Read the texture. Bitmap textureBitmap = BitmapFactory.decodeStream( context.getAssets().open(gridDistanceTextureName)); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glGenTextures(mTextures.length, mTextures, 0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextures[0]); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, textureBitmap, 0); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); ShaderUtil.checkGLError(TAG, "Texture loading"); mPlaneXZPositionAlphaAttribute = GLES20.glGetAttribLocation(mPlaneProgram, "a_XZPositionAlpha"); mPlaneModelUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_Model"); mPlaneModelViewProjectionUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_ModelViewProjection"); mTextureUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_Texture"); mLineColorUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_lineColor"); mDotColorUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_dotColor"); mGridControlUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_gridControl"); mPlaneUvMatrixUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_PlaneUvMatrix"); ShaderUtil.checkGLError(TAG, "Program parameters"); } /** * Updates the plane model transform matrix and extents. */ private void updatePlaneParameters(float[] planeMatrix, float extentX, float extentZ, FloatBuffer boundary) { System.arraycopy(planeMatrix, 0, mModelMatrix, 0, 16); if (boundary == null) { mVertexBuffer.limit(0); mIndexBuffer.limit(0); return; } // Generate a new set of vertices and a corresponding triangle strip index set so that // the plane boundary polygon has a fading edge. This is done by making a copy of the // boundary polygon vertices and scaling it down around center to push it inwards. Then // the index buffer is setup accordingly. boundary.rewind(); int boundaryVertices = boundary.limit() / 2; int numVertices; int numIndices; numVertices = boundaryVertices * VERTS_PER_BOUNDARY_VERT; // drawn as GL_TRIANGLE_STRIP with 3n-2 triangles (n-2 for fill, 2n for perimeter). numIndices = boundaryVertices * INDICES_PER_BOUNDARY_VERT; if (mVertexBuffer.capacity() < numVertices * COORDS_PER_VERTEX) { int size = mVertexBuffer.capacity(); while (size < numVertices * COORDS_PER_VERTEX) { size *= 2; } mVertexBuffer = ByteBuffer.allocateDirect(BYTES_PER_FLOAT * size) .order(ByteOrder.nativeOrder()).asFloatBuffer(); } mVertexBuffer.rewind(); mVertexBuffer.limit(numVertices * COORDS_PER_VERTEX); if (mIndexBuffer.capacity() < numIndices) { int size = mIndexBuffer.capacity(); while (size < numIndices) { size *= 2; } mIndexBuffer = ByteBuffer.allocateDirect(BYTES_PER_SHORT * size) .order(ByteOrder.nativeOrder()).asShortBuffer(); } mIndexBuffer.rewind(); mIndexBuffer.limit(numIndices); // Note: when either dimension of the bounding box is smaller than 2*FADE_RADIUS_M we // generate a bunch of 0-area triangles. These don't get rendered though so it works // out ok. float xScale = Math.max((extentX - 2 * FADE_RADIUS_M) / extentX, 0.0f); float zScale = Math.max((extentZ - 2 * FADE_RADIUS_M) / extentZ, 0.0f); while (boundary.hasRemaining()) { float x = boundary.get(); float z = boundary.get(); mVertexBuffer.put(x); mVertexBuffer.put(z); mVertexBuffer.put(0.0f); mVertexBuffer.put(x * xScale); mVertexBuffer.put(z * zScale); mVertexBuffer.put(1.0f); } // step 1, perimeter mIndexBuffer.put((short) ((boundaryVertices - 1) * 2)); for (int i = 0; i < boundaryVertices; ++i) { mIndexBuffer.put((short) (i * 2)); mIndexBuffer.put((short) (i * 2 + 1)); } mIndexBuffer.put((short) 1); // This leaves us on the interior edge of the perimeter between the inset vertices // for boundary verts n-1 and 0. // step 2, interior: for (int i = 1; i < boundaryVertices / 2; ++i) { mIndexBuffer.put((short) ((boundaryVertices - 1 - i) * 2 + 1)); mIndexBuffer.put((short) (i * 2 + 1)); } if (boundaryVertices % 2 != 0) { mIndexBuffer.put((short) ((boundaryVertices / 2) * 2 + 1)); } } private void draw(float[] cameraView, float[] cameraPerspective) { // Build the ModelView and ModelViewProjection matrices // for calculating cube position and light. Matrix.multiplyMM(mModelViewMatrix, 0, cameraView, 0, mModelMatrix, 0); Matrix.multiplyMM(mModelViewProjectionMatrix, 0, cameraPerspective, 0, mModelViewMatrix, 0); // Set the position of the plane mVertexBuffer.rewind(); GLES20.glVertexAttribPointer( mPlaneXZPositionAlphaAttribute, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, BYTES_PER_FLOAT * COORDS_PER_VERTEX, mVertexBuffer); // Set the Model and ModelViewProjection matrices in the shader. GLES20.glUniformMatrix4fv(mPlaneModelUniform, 1, false, mModelMatrix, 0); GLES20.glUniformMatrix4fv( mPlaneModelViewProjectionUniform, 1, false, mModelViewProjectionMatrix, 0); mIndexBuffer.rewind(); GLES20.glDrawElements(GLES20.GL_TRIANGLE_STRIP, mIndexBuffer.limit(), GLES20.GL_UNSIGNED_SHORT, mIndexBuffer); ShaderUtil.checkGLError(TAG, "Drawing plane"); } static class SortablePlane { final float mDistance; final Plane mPlane; SortablePlane(float distance, Plane plane) { this.mDistance = distance; this.mPlane = plane; } } /** * Draws the collection of tracked planes, with closer planes hiding more distant ones. * * @param allPlanes The collection of planes to draw. * @param cameraPose The pose of the camera, as returned by {@link Camera#getPose()} * @param cameraPerspective The projection matrix, as returned by * {@link Camera#getProjectionMatrix(float[], int, float, float)} */ public void drawPlanes(Collection<Plane> allPlanes, Pose cameraPose, float[] cameraPerspective) { // Planes must be sorted by distance from camera so that we draw closer planes first, and // they occlude the farther planes. List<SortablePlane> sortedPlanes = new ArrayList<SortablePlane>(); float[] normal = new float[3]; float cameraX = cameraPose.tx(); float cameraY = cameraPose.ty(); float cameraZ = cameraPose.tz(); for (Plane plane : allPlanes) { // if (plane.getTrackingState() != TrackingState.TRACKING // || plane.getSubsumedBy() != null) { // continue; // } Pose center = plane.getCenterPose(); // Get transformed Y axis of plane's coordinate system. center.getTransformedAxis(1, 1.0f, normal, 0); // Compute dot product of plane's normal with vector from camera to plane center. float distance = (cameraX - center.tx()) * normal[0] + (cameraY - center.ty()) * normal[1] + (cameraZ - center.tz()) * normal[2]; if (distance < 0) { // Plane is back-facing. continue; } sortedPlanes.add(new SortablePlane(distance, plane)); } Collections.sort(sortedPlanes, new Comparator<SortablePlane>() { @Override public int compare(SortablePlane a, SortablePlane b) { return Float.compare(a.mDistance, b.mDistance); } }); float[] cameraView = new float[16]; cameraPose.inverse().toMatrix(cameraView, 0); // Planes are drawn with additive blending, masked by the alpha channel for occlusion. // Start by clearing the alpha channel of the color buffer to 1.0. GLES20.glClearColor(1, 1, 1, 1); GLES20.glColorMask(false, false, false, true); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); GLES20.glColorMask(true, true, true, true); // Disable depth write. GLES20.glDepthMask(false); // Additive blending, masked by alpha channel, clearing alpha channel. GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFuncSeparate( GLES20.GL_DST_ALPHA, GLES20.GL_ONE, // RGB (src, dest) GLES20.GL_ZERO, GLES20.GL_ONE_MINUS_SRC_ALPHA); // ALPHA (src, dest) // Set up the shader. GLES20.glUseProgram(mPlaneProgram); // Attach the texture. GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextures[0]); GLES20.glUniform1i(mTextureUniform, 0); // Shared fragment uniforms. GLES20.glUniform4fv(mGridControlUniform, 1, GRID_CONTROL, 0); // Enable vertex arrays GLES20.glEnableVertexAttribArray(mPlaneXZPositionAlphaAttribute); ShaderUtil.checkGLError(TAG, "Setting up to draw planes"); for (SortablePlane sortedPlane : sortedPlanes) { Plane plane = sortedPlane.mPlane; float[] planeMatrix = new float[16]; plane.getCenterPose().toMatrix(planeMatrix, 0); updatePlaneParameters( planeMatrix, plane.getExtentX(), plane.getExtentZ(), plane.getPolygon()); // Get plane index. Keep a map to assign same indices to same planes. Integer planeIndex = mPlaneIndexMap.get(plane); if (planeIndex == null) { planeIndex = mPlaneIndexMap.size(); mPlaneIndexMap.put(plane, planeIndex); } // Set plane color. Computed deterministically from the Plane index. int colorIndex = planeIndex % PLANE_COLORS_RGBA.length; colorRgbaToFloat(mPlaneColor, PLANE_COLORS_RGBA[colorIndex]); GLES20.glUniform4fv(mLineColorUniform, 1, mPlaneColor, 0); GLES20.glUniform4fv(mDotColorUniform, 1, mPlaneColor, 0); // Each plane will have its own angle offset from others, to make them easier to // distinguish. Compute a 2x2 rotation matrix from the angle. float angleRadians = planeIndex * 0.144f; float uScale = DOTS_PER_METER; float vScale = DOTS_PER_METER * EQUILATERAL_TRIANGLE_SCALE; mPlaneAngleUvMatrix[0] = +(float) Math.cos(angleRadians) * uScale; mPlaneAngleUvMatrix[1] = -(float) Math.sin(angleRadians) * vScale; mPlaneAngleUvMatrix[2] = +(float) Math.sin(angleRadians) * uScale; mPlaneAngleUvMatrix[3] = +(float) Math.cos(angleRadians) * vScale; GLES20.glUniformMatrix2fv(mPlaneUvMatrixUniform, 1, false, mPlaneAngleUvMatrix, 0); draw(cameraView, cameraPerspective); } // Clean up the state we set GLES20.glDisableVertexAttribArray(mPlaneXZPositionAlphaAttribute); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); GLES20.glDisable(GLES20.GL_BLEND); GLES20.glDepthMask(true); ShaderUtil.checkGLError(TAG, "Cleaning up after drawing planes"); } private static void colorRgbaToFloat(float[] planeColor, int colorRgba) { planeColor[0] = ((float) ((colorRgba >> 24) & 0xff)) / 255.0f; planeColor[1] = ((float) ((colorRgba >> 16) & 0xff)) / 255.0f; planeColor[2] = ((float) ((colorRgba >> 8) & 0xff)) / 255.0f; planeColor[3] = ((float) ((colorRgba >> 0) & 0xff)) / 255.0f; } private static final int[] PLANE_COLORS_RGBA = { 0xFFFFFFFF, 0xF44336FF, 0xE91E63FF, 0x9C27B0FF, 0x673AB7FF, 0x3F51B5FF, 0x2196F3FF, 0x03A9F4FF, 0x00BCD4FF, 0x009688FF, 0x4CAF50FF, 0x8BC34AFF, 0xCDDC39FF, 0xFFEB3BFF, 0xFFC107FF, 0xFF9800FF, }; }
EtherealEngine/Native-XR-for-Web
android/src/main/java/com/xrengine/xr/rendering/PlaneRenderer.java
5,843
// step 2, interior:
line_comment
nl
/* * Copyright 2017 Google Inc. 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 com.xrengine.xr.rendering; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.GLUtils; import android.opengl.Matrix; import com.google.ar.core.Camera; import com.google.ar.core.Plane; import com.google.ar.core.Pose; import com.google.ar.core.Trackable.*; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Renders the detected AR planes. */ public class PlaneRenderer { private static final String TAG = PlaneRenderer.class.getSimpleName(); private static final int BYTES_PER_FLOAT = Float.SIZE / 8; private static final int BYTES_PER_SHORT = Short.SIZE / 8; private static final int COORDS_PER_VERTEX = 3; // x, z, alpha private static final int VERTS_PER_BOUNDARY_VERT = 2; private static final int INDICES_PER_BOUNDARY_VERT = 3; private static final int INITIAL_BUFFER_BOUNDARY_VERTS = 64; private static final int INITIAL_VERTEX_BUFFER_SIZE_BYTES = BYTES_PER_FLOAT * COORDS_PER_VERTEX * VERTS_PER_BOUNDARY_VERT * INITIAL_BUFFER_BOUNDARY_VERTS; private static final int INITIAL_INDEX_BUFFER_SIZE_BYTES = BYTES_PER_SHORT * INDICES_PER_BOUNDARY_VERT * INDICES_PER_BOUNDARY_VERT * INITIAL_BUFFER_BOUNDARY_VERTS; private static final float FADE_RADIUS_M = 0.25f; private static final float DOTS_PER_METER = 10.0f; private static final float EQUILATERAL_TRIANGLE_SCALE = (float) (1 / Math.sqrt(3)); // Using the "signed distance field" approach to render sharp lines and circles. // {dotThreshold, lineThreshold, lineFadeSpeed, occlusionScale} // dotThreshold/lineThreshold: red/green intensity above which dots/lines are present // lineFadeShrink: lines will fade in between alpha = 1-(1/lineFadeShrink) and 1.0 // occlusionShrink: occluded planes will fade out between alpha = 0 and 1/occlusionShrink private static final float[] GRID_CONTROL = {0.2f, 0.4f, 2.0f, 1.5f}; private int mPlaneProgram; private int[] mTextures = new int[1]; private int mPlaneXZPositionAlphaAttribute; private int mPlaneModelUniform; private int mPlaneModelViewProjectionUniform; private int mTextureUniform; private int mLineColorUniform; private int mDotColorUniform; private int mGridControlUniform; private int mPlaneUvMatrixUniform; private FloatBuffer mVertexBuffer = ByteBuffer.allocateDirect(INITIAL_VERTEX_BUFFER_SIZE_BYTES) .order(ByteOrder.nativeOrder()).asFloatBuffer(); private ShortBuffer mIndexBuffer = ByteBuffer.allocateDirect(INITIAL_INDEX_BUFFER_SIZE_BYTES) .order(ByteOrder.nativeOrder()).asShortBuffer(); // Temporary lists/matrices allocated here to reduce number of allocations for each frame. private float[] mModelMatrix = new float[16]; private float[] mModelViewMatrix = new float[16]; private float[] mModelViewProjectionMatrix = new float[16]; private float[] mPlaneColor = new float[4]; private float[] mPlaneAngleUvMatrix = new float[4]; // 2x2 rotation matrix applied to uv coords. private Map<Plane, Integer> mPlaneIndexMap = new HashMap<Plane, Integer>(); public PlaneRenderer() { } /** * Allocates and initializes OpenGL resources needed by the plane renderer. Must be * called on the OpenGL thread, typically in * {@link GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig)}. * * @param context Needed to access shader source and texture PNG. * @param gridDistanceTextureName Name of the PNG file containing the grid texture. */ public void createOnGlThread(Context context, String gridDistanceTextureName) throws IOException { // TODO: UNCOMMENT instead of = 0 int vertexShader = 0; // ShaderUtil.loadGLShader(TAG, context, // GLES20.GL_VERTEX_SHADER, R.raw.plane_vertex); int passthroughShader = 0; // ShaderUtil.loadGLShader(TAG, context, // GLES20.GL_FRAGMENT_SHADER, R.raw.plane_fragment); mPlaneProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(mPlaneProgram, vertexShader); GLES20.glAttachShader(mPlaneProgram, passthroughShader); GLES20.glLinkProgram(mPlaneProgram); GLES20.glUseProgram(mPlaneProgram); ShaderUtil.checkGLError(TAG, "Program creation"); // Read the texture. Bitmap textureBitmap = BitmapFactory.decodeStream( context.getAssets().open(gridDistanceTextureName)); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glGenTextures(mTextures.length, mTextures, 0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextures[0]); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, textureBitmap, 0); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); ShaderUtil.checkGLError(TAG, "Texture loading"); mPlaneXZPositionAlphaAttribute = GLES20.glGetAttribLocation(mPlaneProgram, "a_XZPositionAlpha"); mPlaneModelUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_Model"); mPlaneModelViewProjectionUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_ModelViewProjection"); mTextureUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_Texture"); mLineColorUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_lineColor"); mDotColorUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_dotColor"); mGridControlUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_gridControl"); mPlaneUvMatrixUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_PlaneUvMatrix"); ShaderUtil.checkGLError(TAG, "Program parameters"); } /** * Updates the plane model transform matrix and extents. */ private void updatePlaneParameters(float[] planeMatrix, float extentX, float extentZ, FloatBuffer boundary) { System.arraycopy(planeMatrix, 0, mModelMatrix, 0, 16); if (boundary == null) { mVertexBuffer.limit(0); mIndexBuffer.limit(0); return; } // Generate a new set of vertices and a corresponding triangle strip index set so that // the plane boundary polygon has a fading edge. This is done by making a copy of the // boundary polygon vertices and scaling it down around center to push it inwards. Then // the index buffer is setup accordingly. boundary.rewind(); int boundaryVertices = boundary.limit() / 2; int numVertices; int numIndices; numVertices = boundaryVertices * VERTS_PER_BOUNDARY_VERT; // drawn as GL_TRIANGLE_STRIP with 3n-2 triangles (n-2 for fill, 2n for perimeter). numIndices = boundaryVertices * INDICES_PER_BOUNDARY_VERT; if (mVertexBuffer.capacity() < numVertices * COORDS_PER_VERTEX) { int size = mVertexBuffer.capacity(); while (size < numVertices * COORDS_PER_VERTEX) { size *= 2; } mVertexBuffer = ByteBuffer.allocateDirect(BYTES_PER_FLOAT * size) .order(ByteOrder.nativeOrder()).asFloatBuffer(); } mVertexBuffer.rewind(); mVertexBuffer.limit(numVertices * COORDS_PER_VERTEX); if (mIndexBuffer.capacity() < numIndices) { int size = mIndexBuffer.capacity(); while (size < numIndices) { size *= 2; } mIndexBuffer = ByteBuffer.allocateDirect(BYTES_PER_SHORT * size) .order(ByteOrder.nativeOrder()).asShortBuffer(); } mIndexBuffer.rewind(); mIndexBuffer.limit(numIndices); // Note: when either dimension of the bounding box is smaller than 2*FADE_RADIUS_M we // generate a bunch of 0-area triangles. These don't get rendered though so it works // out ok. float xScale = Math.max((extentX - 2 * FADE_RADIUS_M) / extentX, 0.0f); float zScale = Math.max((extentZ - 2 * FADE_RADIUS_M) / extentZ, 0.0f); while (boundary.hasRemaining()) { float x = boundary.get(); float z = boundary.get(); mVertexBuffer.put(x); mVertexBuffer.put(z); mVertexBuffer.put(0.0f); mVertexBuffer.put(x * xScale); mVertexBuffer.put(z * zScale); mVertexBuffer.put(1.0f); } // step 1, perimeter mIndexBuffer.put((short) ((boundaryVertices - 1) * 2)); for (int i = 0; i < boundaryVertices; ++i) { mIndexBuffer.put((short) (i * 2)); mIndexBuffer.put((short) (i * 2 + 1)); } mIndexBuffer.put((short) 1); // This leaves us on the interior edge of the perimeter between the inset vertices // for boundary verts n-1 and 0. // step 2,<SUF> for (int i = 1; i < boundaryVertices / 2; ++i) { mIndexBuffer.put((short) ((boundaryVertices - 1 - i) * 2 + 1)); mIndexBuffer.put((short) (i * 2 + 1)); } if (boundaryVertices % 2 != 0) { mIndexBuffer.put((short) ((boundaryVertices / 2) * 2 + 1)); } } private void draw(float[] cameraView, float[] cameraPerspective) { // Build the ModelView and ModelViewProjection matrices // for calculating cube position and light. Matrix.multiplyMM(mModelViewMatrix, 0, cameraView, 0, mModelMatrix, 0); Matrix.multiplyMM(mModelViewProjectionMatrix, 0, cameraPerspective, 0, mModelViewMatrix, 0); // Set the position of the plane mVertexBuffer.rewind(); GLES20.glVertexAttribPointer( mPlaneXZPositionAlphaAttribute, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, BYTES_PER_FLOAT * COORDS_PER_VERTEX, mVertexBuffer); // Set the Model and ModelViewProjection matrices in the shader. GLES20.glUniformMatrix4fv(mPlaneModelUniform, 1, false, mModelMatrix, 0); GLES20.glUniformMatrix4fv( mPlaneModelViewProjectionUniform, 1, false, mModelViewProjectionMatrix, 0); mIndexBuffer.rewind(); GLES20.glDrawElements(GLES20.GL_TRIANGLE_STRIP, mIndexBuffer.limit(), GLES20.GL_UNSIGNED_SHORT, mIndexBuffer); ShaderUtil.checkGLError(TAG, "Drawing plane"); } static class SortablePlane { final float mDistance; final Plane mPlane; SortablePlane(float distance, Plane plane) { this.mDistance = distance; this.mPlane = plane; } } /** * Draws the collection of tracked planes, with closer planes hiding more distant ones. * * @param allPlanes The collection of planes to draw. * @param cameraPose The pose of the camera, as returned by {@link Camera#getPose()} * @param cameraPerspective The projection matrix, as returned by * {@link Camera#getProjectionMatrix(float[], int, float, float)} */ public void drawPlanes(Collection<Plane> allPlanes, Pose cameraPose, float[] cameraPerspective) { // Planes must be sorted by distance from camera so that we draw closer planes first, and // they occlude the farther planes. List<SortablePlane> sortedPlanes = new ArrayList<SortablePlane>(); float[] normal = new float[3]; float cameraX = cameraPose.tx(); float cameraY = cameraPose.ty(); float cameraZ = cameraPose.tz(); for (Plane plane : allPlanes) { // if (plane.getTrackingState() != TrackingState.TRACKING // || plane.getSubsumedBy() != null) { // continue; // } Pose center = plane.getCenterPose(); // Get transformed Y axis of plane's coordinate system. center.getTransformedAxis(1, 1.0f, normal, 0); // Compute dot product of plane's normal with vector from camera to plane center. float distance = (cameraX - center.tx()) * normal[0] + (cameraY - center.ty()) * normal[1] + (cameraZ - center.tz()) * normal[2]; if (distance < 0) { // Plane is back-facing. continue; } sortedPlanes.add(new SortablePlane(distance, plane)); } Collections.sort(sortedPlanes, new Comparator<SortablePlane>() { @Override public int compare(SortablePlane a, SortablePlane b) { return Float.compare(a.mDistance, b.mDistance); } }); float[] cameraView = new float[16]; cameraPose.inverse().toMatrix(cameraView, 0); // Planes are drawn with additive blending, masked by the alpha channel for occlusion. // Start by clearing the alpha channel of the color buffer to 1.0. GLES20.glClearColor(1, 1, 1, 1); GLES20.glColorMask(false, false, false, true); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); GLES20.glColorMask(true, true, true, true); // Disable depth write. GLES20.glDepthMask(false); // Additive blending, masked by alpha channel, clearing alpha channel. GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFuncSeparate( GLES20.GL_DST_ALPHA, GLES20.GL_ONE, // RGB (src, dest) GLES20.GL_ZERO, GLES20.GL_ONE_MINUS_SRC_ALPHA); // ALPHA (src, dest) // Set up the shader. GLES20.glUseProgram(mPlaneProgram); // Attach the texture. GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextures[0]); GLES20.glUniform1i(mTextureUniform, 0); // Shared fragment uniforms. GLES20.glUniform4fv(mGridControlUniform, 1, GRID_CONTROL, 0); // Enable vertex arrays GLES20.glEnableVertexAttribArray(mPlaneXZPositionAlphaAttribute); ShaderUtil.checkGLError(TAG, "Setting up to draw planes"); for (SortablePlane sortedPlane : sortedPlanes) { Plane plane = sortedPlane.mPlane; float[] planeMatrix = new float[16]; plane.getCenterPose().toMatrix(planeMatrix, 0); updatePlaneParameters( planeMatrix, plane.getExtentX(), plane.getExtentZ(), plane.getPolygon()); // Get plane index. Keep a map to assign same indices to same planes. Integer planeIndex = mPlaneIndexMap.get(plane); if (planeIndex == null) { planeIndex = mPlaneIndexMap.size(); mPlaneIndexMap.put(plane, planeIndex); } // Set plane color. Computed deterministically from the Plane index. int colorIndex = planeIndex % PLANE_COLORS_RGBA.length; colorRgbaToFloat(mPlaneColor, PLANE_COLORS_RGBA[colorIndex]); GLES20.glUniform4fv(mLineColorUniform, 1, mPlaneColor, 0); GLES20.glUniform4fv(mDotColorUniform, 1, mPlaneColor, 0); // Each plane will have its own angle offset from others, to make them easier to // distinguish. Compute a 2x2 rotation matrix from the angle. float angleRadians = planeIndex * 0.144f; float uScale = DOTS_PER_METER; float vScale = DOTS_PER_METER * EQUILATERAL_TRIANGLE_SCALE; mPlaneAngleUvMatrix[0] = +(float) Math.cos(angleRadians) * uScale; mPlaneAngleUvMatrix[1] = -(float) Math.sin(angleRadians) * vScale; mPlaneAngleUvMatrix[2] = +(float) Math.sin(angleRadians) * uScale; mPlaneAngleUvMatrix[3] = +(float) Math.cos(angleRadians) * vScale; GLES20.glUniformMatrix2fv(mPlaneUvMatrixUniform, 1, false, mPlaneAngleUvMatrix, 0); draw(cameraView, cameraPerspective); } // Clean up the state we set GLES20.glDisableVertexAttribArray(mPlaneXZPositionAlphaAttribute); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); GLES20.glDisable(GLES20.GL_BLEND); GLES20.glDepthMask(true); ShaderUtil.checkGLError(TAG, "Cleaning up after drawing planes"); } private static void colorRgbaToFloat(float[] planeColor, int colorRgba) { planeColor[0] = ((float) ((colorRgba >> 24) & 0xff)) / 255.0f; planeColor[1] = ((float) ((colorRgba >> 16) & 0xff)) / 255.0f; planeColor[2] = ((float) ((colorRgba >> 8) & 0xff)) / 255.0f; planeColor[3] = ((float) ((colorRgba >> 0) & 0xff)) / 255.0f; } private static final int[] PLANE_COLORS_RGBA = { 0xFFFFFFFF, 0xF44336FF, 0xE91E63FF, 0x9C27B0FF, 0x673AB7FF, 0x3F51B5FF, 0x2196F3FF, 0x03A9F4FF, 0x00BCD4FF, 0x009688FF, 0x4CAF50FF, 0x8BC34AFF, 0xCDDC39FF, 0xFFEB3BFF, 0xFFC107FF, 0xFF9800FF, }; }
124915_0
package nl.yurimeiburg.ondertekenen.dao; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import nl.yurimeiburg.ondertekenen.objects.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.ws.rs.core.MediaType; import java.io.*; import java.text.MessageFormat; import java.util.Properties; /** * {@inheritDoc} * <p> * REST implementation of OndertekenenClient * * @see OndertekenenClient */ public class OndertekenenClientRestImpl implements OndertekenenClient { private static final String API_PROPERTIES_LOCATION = "api.properties"; private static final String MEDIATYPE_APPLICATION_PDF = "application/pdf"; /* Urls for the REST Api */ private static String DOCUMENT_URL; private static String RECEIPT_URL; private static String TRANSACTION_URL; private static String FILE_URL; private static final Logger LOGGER = LogManager.getLogger(OndertekenenClientRestImpl.class); private RESTEngine restEngine = null; private Gson gson = new GsonBuilder().create(); /** * Create a DAO object for Ondertekenen using REST implementation. * * @param restEngine The RESTEngine object used for the REST requests */ public OndertekenenClientRestImpl(RESTEngine restEngine) { this.restEngine = restEngine; initProperties(); } /** * {@inheritDoc} */ @Override public Document getSignedDocument(String transactionID, String fileID, boolean sendSignedRequest) { WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(MessageFormat.format(FILE_URL, transactionID, fileID)); System.out.println(MessageFormat.format(FILE_URL, transactionID, fileID)); try { ClientResponse clientResponse = webResourceBuilder.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); return restEngine.handleBinaryResponse(clientResponse, Document.class); } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice, returning empty document.", ce); return null; } } /** * {@inheritDoc} */ @Override public Receipt getReceipt(String documentID, boolean sendSignedRequest) { WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(RECEIPT_URL + documentID); try { ClientResponse clientResponse = webResourceBuilder.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); return restEngine.handleBinaryResponse(clientResponse, Receipt.class); } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice, returning empty document.", ce); return null; } } /** * {@inheritDoc} */ @Override public Transaction getTransaction(String transactionId) { WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(TRANSACTION_URL + transactionId); try { ClientResponse clientResponse = webResourceBuilder.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); return restEngine.handleJSONResponse(clientResponse, Transaction.class); } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice, returning empty document.", ce); return null; } } /** * {@inheritDoc} */ @Override public Transaction deleteTransaction(Transaction transaction, boolean sendNotification, String reason) { if (transaction == null) { return null; } return deleteTransaction(transaction.getId(), sendNotification, reason); } /** * {@inheritDoc} */ @Override public Transaction deleteTransaction(String transactionId, boolean sendNotification, String reason) { CancelTransaction cancelTransaction = new CancelTransaction(sendNotification, reason); WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(TRANSACTION_URL + transactionId); try { ClientResponse clientResponse = webResourceBuilder .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .delete(ClientResponse.class, gson.toJson(cancelTransaction)); return restEngine.handleJSONResponse(clientResponse, Transaction.class); } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice, returning empty document.", ce); return null; } } /** * {@inheritDoc} */ @Override public Transaction createTransaction(Transaction transaction) { WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(TRANSACTION_URL); try { ClientResponse clientResponse = webResourceBuilder .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .post(ClientResponse.class, gson.toJson(transaction)); return restEngine.handleJSONResponse(clientResponse, Transaction.class); } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice, returning empty document.", ce); return null; } } /** * {@inheritDoc} */ @Override public boolean uploadFile(Transaction transaction, File file) { LOGGER.info("Uploading PDF from: " + file.getName()); WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(MessageFormat.format(FILE_URL, transaction.getId(), file.getName())); try { InputStream inputStream = new FileInputStream(file); ClientResponse clientResponse = webResourceBuilder .type(MEDIATYPE_APPLICATION_PDF) .put(ClientResponse.class, inputStream); } catch (FileNotFoundException e) { LOGGER.error("Could not open PDF for uploading.", e); return false; } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice.", ce); return false; } return true; } /** * {@inheritDoc} */ @Override public boolean uploadFileMetaData(Transaction transaction, FileMetaData fileMetaData, String identifier) { LOGGER.info("Uploading File Metadata: " + fileMetaData + " for file: " + identifier); WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(MessageFormat.format(FILE_URL, transaction.getId(), identifier)); try { webResourceBuilder .type(MediaType.APPLICATION_JSON) .put(ClientResponse.class, gson.toJson(fileMetaData)); } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice.", ce); return false; } return true; } @Override public boolean startTransaction(String transactionId) { WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(TRANSACTION_URL + transactionId + "/start"); try { ClientResponse clientResponse = webResourceBuilder .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .put(ClientResponse.class, ""); return true; } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice, returning empty document.", ce); return false; } } /** * Read property files to get the API URI's */ private void initProperties() { try { Properties properties = new Properties(); properties.load(getClass().getClassLoader().getResourceAsStream(API_PROPERTIES_LOCATION)); RECEIPT_URL = properties.getProperty("receipt.url"); FILE_URL = properties.getProperty("file.url"); TRANSACTION_URL = properties.getProperty("transaction.url"); } catch (IOException e) { LOGGER.fatal("Could not read API locations from properties", e); } } }
Evidos/OndertekenenDemo-Java
Client/src/main/java/nl/yurimeiburg/ondertekenen/dao/OndertekenenClientRestImpl.java
2,238
/** * {@inheritDoc} * <p> * REST implementation of OndertekenenClient * * @see OndertekenenClient */
block_comment
nl
package nl.yurimeiburg.ondertekenen.dao; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import nl.yurimeiburg.ondertekenen.objects.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.ws.rs.core.MediaType; import java.io.*; import java.text.MessageFormat; import java.util.Properties; /** * {@inheritDoc} *<SUF>*/ public class OndertekenenClientRestImpl implements OndertekenenClient { private static final String API_PROPERTIES_LOCATION = "api.properties"; private static final String MEDIATYPE_APPLICATION_PDF = "application/pdf"; /* Urls for the REST Api */ private static String DOCUMENT_URL; private static String RECEIPT_URL; private static String TRANSACTION_URL; private static String FILE_URL; private static final Logger LOGGER = LogManager.getLogger(OndertekenenClientRestImpl.class); private RESTEngine restEngine = null; private Gson gson = new GsonBuilder().create(); /** * Create a DAO object for Ondertekenen using REST implementation. * * @param restEngine The RESTEngine object used for the REST requests */ public OndertekenenClientRestImpl(RESTEngine restEngine) { this.restEngine = restEngine; initProperties(); } /** * {@inheritDoc} */ @Override public Document getSignedDocument(String transactionID, String fileID, boolean sendSignedRequest) { WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(MessageFormat.format(FILE_URL, transactionID, fileID)); System.out.println(MessageFormat.format(FILE_URL, transactionID, fileID)); try { ClientResponse clientResponse = webResourceBuilder.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); return restEngine.handleBinaryResponse(clientResponse, Document.class); } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice, returning empty document.", ce); return null; } } /** * {@inheritDoc} */ @Override public Receipt getReceipt(String documentID, boolean sendSignedRequest) { WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(RECEIPT_URL + documentID); try { ClientResponse clientResponse = webResourceBuilder.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); return restEngine.handleBinaryResponse(clientResponse, Receipt.class); } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice, returning empty document.", ce); return null; } } /** * {@inheritDoc} */ @Override public Transaction getTransaction(String transactionId) { WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(TRANSACTION_URL + transactionId); try { ClientResponse clientResponse = webResourceBuilder.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); return restEngine.handleJSONResponse(clientResponse, Transaction.class); } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice, returning empty document.", ce); return null; } } /** * {@inheritDoc} */ @Override public Transaction deleteTransaction(Transaction transaction, boolean sendNotification, String reason) { if (transaction == null) { return null; } return deleteTransaction(transaction.getId(), sendNotification, reason); } /** * {@inheritDoc} */ @Override public Transaction deleteTransaction(String transactionId, boolean sendNotification, String reason) { CancelTransaction cancelTransaction = new CancelTransaction(sendNotification, reason); WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(TRANSACTION_URL + transactionId); try { ClientResponse clientResponse = webResourceBuilder .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .delete(ClientResponse.class, gson.toJson(cancelTransaction)); return restEngine.handleJSONResponse(clientResponse, Transaction.class); } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice, returning empty document.", ce); return null; } } /** * {@inheritDoc} */ @Override public Transaction createTransaction(Transaction transaction) { WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(TRANSACTION_URL); try { ClientResponse clientResponse = webResourceBuilder .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .post(ClientResponse.class, gson.toJson(transaction)); return restEngine.handleJSONResponse(clientResponse, Transaction.class); } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice, returning empty document.", ce); return null; } } /** * {@inheritDoc} */ @Override public boolean uploadFile(Transaction transaction, File file) { LOGGER.info("Uploading PDF from: " + file.getName()); WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(MessageFormat.format(FILE_URL, transaction.getId(), file.getName())); try { InputStream inputStream = new FileInputStream(file); ClientResponse clientResponse = webResourceBuilder .type(MEDIATYPE_APPLICATION_PDF) .put(ClientResponse.class, inputStream); } catch (FileNotFoundException e) { LOGGER.error("Could not open PDF for uploading.", e); return false; } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice.", ce); return false; } return true; } /** * {@inheritDoc} */ @Override public boolean uploadFileMetaData(Transaction transaction, FileMetaData fileMetaData, String identifier) { LOGGER.info("Uploading File Metadata: " + fileMetaData + " for file: " + identifier); WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(MessageFormat.format(FILE_URL, transaction.getId(), identifier)); try { webResourceBuilder .type(MediaType.APPLICATION_JSON) .put(ClientResponse.class, gson.toJson(fileMetaData)); } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice.", ce); return false; } return true; } @Override public boolean startTransaction(String transactionId) { WebResource.Builder webResourceBuilder = restEngine.getWebResourceBuilder(TRANSACTION_URL + transactionId + "/start"); try { ClientResponse clientResponse = webResourceBuilder .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .put(ClientResponse.class, ""); return true; } catch (ClientHandlerException ce) { LOGGER.error("Cannot connect to the webservice, returning empty document.", ce); return false; } } /** * Read property files to get the API URI's */ private void initProperties() { try { Properties properties = new Properties(); properties.load(getClass().getClassLoader().getResourceAsStream(API_PROPERTIES_LOCATION)); RECEIPT_URL = properties.getProperty("receipt.url"); FILE_URL = properties.getProperty("file.url"); TRANSACTION_URL = properties.getProperty("transaction.url"); } catch (IOException e) { LOGGER.fatal("Could not read API locations from properties", e); } } }
154456_26
/* * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite 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 * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.contracts; import org.evosuite.Properties; import org.evosuite.TestGenerationContext; import org.evosuite.testcase.TestCase; import org.evosuite.testcase.execution.ExecutionObserver; import org.evosuite.testcase.execution.ExecutionResult; import org.evosuite.testcase.execution.Scope; import org.evosuite.testcase.statements.Statement; import org.evosuite.utils.generic.GenericMethod; import org.junit.experimental.theories.Theory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; /** * <p> * ContractChecker class. * </p> * * @author Gordon Fraser */ public class ContractChecker extends ExecutionObserver { private static final Logger logger = LoggerFactory.getLogger(ContractChecker.class); private final Set<Contract> contracts = new HashSet<>(); /* * Maybe it was not a problem, but it all depends on when Properties.CHECK_CONTRACTS_END * is initialized. Maybe best to just call it directly */ //private static final boolean checkAtEnd = Properties.CHECK_CONTRACTS_END; private static final Set<Contract> invalid = new HashSet<>(); //private static boolean valid = true; private static boolean active = true; /** * <p> * Constructor for ContractChecker. * </p> */ public ContractChecker() { // Default from EvoSuite contracts.add(new UndeclaredExceptionContract()); contracts.add(new JCrasherExceptionContract()); // Defaults from Randoop paper contracts.add(new NullPointerExceptionContract()); contracts.add(new AssertionErrorContract()); contracts.add(new EqualsContract()); contracts.add(new ToStringReturnsNormallyContract()); contracts.add(new HashCodeReturnsNormallyContract()); // Further Randoop contracts, not in paper contracts.add(new EqualsHashcodeContract()); contracts.add(new EqualsNullContract()); contracts.add(new EqualsSymmetricContract()); loadJUnitTheories(); } private void loadJUnitTheories() { if (Properties.JUNIT_THEORIES.isEmpty()) return; for (String theoryName : Properties.JUNIT_THEORIES.split(":")) { try { Class<?> theory = TestGenerationContext.getInstance().getClassLoaderForSUT().loadClass(theoryName); Constructor<?> constructor = theory.getConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { logger.info("Theory class does not have public default constructor"); continue; } for (Method method : theory.getDeclaredMethods()) { if (method.isAnnotationPresent(Theory.class)) { logger.info("Found theory method: " + method.getName()); if (method.getParameterTypes().length != 1) { logger.info("Wrong number of arguments!"); continue; } try { GenericMethod gm = new GenericMethod(method, theory); JUnitTheoryContract contract = new JUnitTheoryContract(gm); contracts.add(contract); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } catch (ClassNotFoundException e) { logger.warn("Could not load theory " + theoryName + ": " + e); } catch (NoSuchMethodException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (SecurityException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } /** * <p> * Setter for the field <code>active</code>. * </p> * * @param isActive a boolean. */ public static void setActive(boolean isActive) { active = isActive; } /* (non-Javadoc) * @see org.evosuite.testcase.ExecutionObserver#output(int, java.lang.String) */ /** * {@inheritDoc} */ @Override public void output(int position, String output) { // TODO Auto-generated method stub } /** * Set the current test case, on which we check oracles while it is executed * * @param test a {@link org.evosuite.testcase.TestCase} object. */ public static void currentTest(TestCase test) { currentTest = test; //ContractChecker.valid = true; ContractChecker.invalid.clear(); // TODO: Keep track of objects that raised an exception, and exclude them from contract checking } /* (non-Javadoc) * @see org.evosuite.testcase.ExecutionObserver#statement(int, org.evosuite.testcase.Scope, org.evosuite.testcase.VariableReference) */ /** * {@inheritDoc} */ @Override public void afterStatement(Statement statement, Scope scope, Throwable exception) { //if (!ContractChecker.valid) { /* * once we get a contract that is violated, no point in checking the following statements, * because the internal state of the SUT is corrupted. * * TODO: at this point, for the fitness function we still consider the coverage given by the * following statements. Maybe that should be changed? At the moment, we only stop if exceptions */ // logger.debug("Not checking contracts for invalid test"); // return; //} if (!ContractChecker.active) { return; } if (Properties.CHECK_CONTRACTS_END && statement.getPosition() < (currentTest.size() - 1)) return; for (Contract contract : contracts) { if (invalid.contains(contract)) continue; try { logger.debug("Checking contract {}", contract); ContractViolation violation = contract.check(statement, scope, exception); if (violation != null) { logger.debug("Contract failed: {} {}", contract, statement.getCode()); FailingTestSet.addFailingTest(violation); /* FailingTestSet.addFailingTest(currentTest, contract, statement, exception); */ //ContractChecker.valid = false; invalid.add(contract); //break; } } catch (Throwable t) { logger.debug("Caught exception during contract checking: " + t); for (StackTraceElement e : t.getStackTrace()) logger.info(e.toString()); } } } /* (non-Javadoc) * @see org.evosuite.testcase.ExecutionObserver#beforeStatement(org.evosuite.testcase.StatementInterface, org.evosuite.testcase.Scope) */ @Override public void beforeStatement(Statement statement, Scope scope) { // Do nothing } /* (non-Javadoc) * @see org.evosuite.testcase.ExecutionObserver#clear() */ /** * {@inheritDoc} */ @Override public void clear() { ContractChecker.invalid.clear(); // ContractChecker.valid = true; } @Override public void testExecutionFinished(ExecutionResult r, Scope s) { // do nothing } }
EvoSuite/evosuite
client/src/main/java/org/evosuite/contracts/ContractChecker.java
2,354
//ContractChecker.valid = false;
line_comment
nl
/* * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite 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 * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.contracts; import org.evosuite.Properties; import org.evosuite.TestGenerationContext; import org.evosuite.testcase.TestCase; import org.evosuite.testcase.execution.ExecutionObserver; import org.evosuite.testcase.execution.ExecutionResult; import org.evosuite.testcase.execution.Scope; import org.evosuite.testcase.statements.Statement; import org.evosuite.utils.generic.GenericMethod; import org.junit.experimental.theories.Theory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; /** * <p> * ContractChecker class. * </p> * * @author Gordon Fraser */ public class ContractChecker extends ExecutionObserver { private static final Logger logger = LoggerFactory.getLogger(ContractChecker.class); private final Set<Contract> contracts = new HashSet<>(); /* * Maybe it was not a problem, but it all depends on when Properties.CHECK_CONTRACTS_END * is initialized. Maybe best to just call it directly */ //private static final boolean checkAtEnd = Properties.CHECK_CONTRACTS_END; private static final Set<Contract> invalid = new HashSet<>(); //private static boolean valid = true; private static boolean active = true; /** * <p> * Constructor for ContractChecker. * </p> */ public ContractChecker() { // Default from EvoSuite contracts.add(new UndeclaredExceptionContract()); contracts.add(new JCrasherExceptionContract()); // Defaults from Randoop paper contracts.add(new NullPointerExceptionContract()); contracts.add(new AssertionErrorContract()); contracts.add(new EqualsContract()); contracts.add(new ToStringReturnsNormallyContract()); contracts.add(new HashCodeReturnsNormallyContract()); // Further Randoop contracts, not in paper contracts.add(new EqualsHashcodeContract()); contracts.add(new EqualsNullContract()); contracts.add(new EqualsSymmetricContract()); loadJUnitTheories(); } private void loadJUnitTheories() { if (Properties.JUNIT_THEORIES.isEmpty()) return; for (String theoryName : Properties.JUNIT_THEORIES.split(":")) { try { Class<?> theory = TestGenerationContext.getInstance().getClassLoaderForSUT().loadClass(theoryName); Constructor<?> constructor = theory.getConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { logger.info("Theory class does not have public default constructor"); continue; } for (Method method : theory.getDeclaredMethods()) { if (method.isAnnotationPresent(Theory.class)) { logger.info("Found theory method: " + method.getName()); if (method.getParameterTypes().length != 1) { logger.info("Wrong number of arguments!"); continue; } try { GenericMethod gm = new GenericMethod(method, theory); JUnitTheoryContract contract = new JUnitTheoryContract(gm); contracts.add(contract); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } catch (ClassNotFoundException e) { logger.warn("Could not load theory " + theoryName + ": " + e); } catch (NoSuchMethodException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (SecurityException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } /** * <p> * Setter for the field <code>active</code>. * </p> * * @param isActive a boolean. */ public static void setActive(boolean isActive) { active = isActive; } /* (non-Javadoc) * @see org.evosuite.testcase.ExecutionObserver#output(int, java.lang.String) */ /** * {@inheritDoc} */ @Override public void output(int position, String output) { // TODO Auto-generated method stub } /** * Set the current test case, on which we check oracles while it is executed * * @param test a {@link org.evosuite.testcase.TestCase} object. */ public static void currentTest(TestCase test) { currentTest = test; //ContractChecker.valid = true; ContractChecker.invalid.clear(); // TODO: Keep track of objects that raised an exception, and exclude them from contract checking } /* (non-Javadoc) * @see org.evosuite.testcase.ExecutionObserver#statement(int, org.evosuite.testcase.Scope, org.evosuite.testcase.VariableReference) */ /** * {@inheritDoc} */ @Override public void afterStatement(Statement statement, Scope scope, Throwable exception) { //if (!ContractChecker.valid) { /* * once we get a contract that is violated, no point in checking the following statements, * because the internal state of the SUT is corrupted. * * TODO: at this point, for the fitness function we still consider the coverage given by the * following statements. Maybe that should be changed? At the moment, we only stop if exceptions */ // logger.debug("Not checking contracts for invalid test"); // return; //} if (!ContractChecker.active) { return; } if (Properties.CHECK_CONTRACTS_END && statement.getPosition() < (currentTest.size() - 1)) return; for (Contract contract : contracts) { if (invalid.contains(contract)) continue; try { logger.debug("Checking contract {}", contract); ContractViolation violation = contract.check(statement, scope, exception); if (violation != null) { logger.debug("Contract failed: {} {}", contract, statement.getCode()); FailingTestSet.addFailingTest(violation); /* FailingTestSet.addFailingTest(currentTest, contract, statement, exception); */ //ContractChecker.valid =<SUF> invalid.add(contract); //break; } } catch (Throwable t) { logger.debug("Caught exception during contract checking: " + t); for (StackTraceElement e : t.getStackTrace()) logger.info(e.toString()); } } } /* (non-Javadoc) * @see org.evosuite.testcase.ExecutionObserver#beforeStatement(org.evosuite.testcase.StatementInterface, org.evosuite.testcase.Scope) */ @Override public void beforeStatement(Statement statement, Scope scope) { // Do nothing } /* (non-Javadoc) * @see org.evosuite.testcase.ExecutionObserver#clear() */ /** * {@inheritDoc} */ @Override public void clear() { ContractChecker.invalid.clear(); // ContractChecker.valid = true; } @Override public void testExecutionFinished(ExecutionResult r, Scope s) { // do nothing } }
151568_2
/* * Copyright (C) 2020-2022 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.notifications.impl.events; import java.util.Collection; import java.util.List; import javax.xml.namespace.QName; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.evolveum.midpoint.model.api.ModelService; import com.evolveum.midpoint.model.api.expr.MidpointFunctions; import com.evolveum.midpoint.notifications.api.events.Event; import com.evolveum.midpoint.notifications.api.events.SimpleObjectRef; import com.evolveum.midpoint.notifications.impl.SimpleObjectRefImpl; import com.evolveum.midpoint.notifications.impl.formatters.TextFormatter; import com.evolveum.midpoint.notifications.impl.util.ApplicationContextHolder; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.ChangeType; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SchemaService; import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.constants.ExpressionConstants; import com.evolveum.midpoint.schema.expression.TypedValue; import com.evolveum.midpoint.schema.expression.VariablesMap; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.LightweightIdentifier; import com.evolveum.midpoint.task.api.LightweightIdentifierGenerator; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.ShortDumpable; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** * Base implementation of Event that contains the common functionality. */ public abstract class BaseEventImpl implements Event, DebugDumpable, ShortDumpable { private static final Trace LOGGER = TraceManager.getTrace(BaseEventImpl.class); @NotNull private final LightweightIdentifier id; private SimpleObjectRef requester; private SimpleObjectRef requestee; private transient MidpointFunctions midpointFunctions; private transient TextFormatter textFormatter; private transient PrismContext prismContext; private String channel; BaseEventImpl() { this(ApplicationContextHolder.getBean(LightweightIdentifierGenerator.class)); } BaseEventImpl(@NotNull LightweightIdentifierGenerator lightweightIdentifierGenerator) { id = lightweightIdentifierGenerator.generate(); } @NotNull public LightweightIdentifier getId() { return id; } boolean changeTypeMatchesOperationType(ChangeType changeType, EventOperationType eventOperationType) { return switch (eventOperationType) { case ADD -> changeType == ChangeType.ADD; case MODIFY -> changeType == ChangeType.MODIFY; case DELETE -> changeType == ChangeType.DELETE; }; } abstract public boolean isCategoryType(EventCategoryType eventCategory); public boolean isUserRelated() { return false; // overridden in ModelEvent } public SimpleObjectRef getRequester() { return requester; } // TODO make requester final and remove this method public void setRequester(SimpleObjectRef requester) { this.requester = requester; } public SimpleObjectRef getRequestee() { return requestee; } // TODO we need the operation result parent here @Nullable private ObjectType resolveObject(SimpleObjectRef ref) { if (ref == null) { return null; } return ref.resolveObjectType(new OperationResult(BaseEventImpl.class + ".resolveObject"), true); } @Override public ObjectType getRequesteeObject() { return resolveObject(requestee); } @SuppressWarnings("WeakerAccess") public ObjectType getRequesterObject() { return resolveObject(requester); } @Override public PolyStringType getRequesteeDisplayName() { return getDisplayName(getRequesteeObject()); } @SuppressWarnings("unused") public PolyStringType getRequesterDisplayName() { return getDisplayName(getRequesterObject()); } @Nullable private PolyStringType getDisplayName(ObjectType object) { if (object == null) { return null; } if (object instanceof UserType) { return ((UserType) object).getFullName(); } else if (object instanceof AbstractRoleType) { return ((AbstractRoleType) object).getDisplayName(); } else { return object.getName(); } } @Nullable private PolyStringType getName(ObjectType object) { return object != null ? object.getName() : null; } @SuppressWarnings("unused") public PolyStringType getRequesteeName() { return getName(getRequesteeObject()); } @SuppressWarnings("unused") public PolyStringType getRequesterName() { return getName(getRequesterObject()); } public void setRequestee(SimpleObjectRef requestee) { this.requestee = requestee; } public void createVariablesMap(VariablesMap variables, OperationResult result) { variables.put(ExpressionConstants.VAR_EVENT, this, Event.class); variables.put(ExpressionConstants.VAR_REQUESTER, resolveTypedObject(requester, false, result)); variables.put(ExpressionConstants.VAR_REQUESTEE, resolveTypedObject(requestee, true, result)); } TypedValue<ObjectType> resolveTypedObject(SimpleObjectRef ref, boolean allowNotFound, OperationResult result) { ObjectType resolved = ref != null ? ref.resolveObjectType(result, allowNotFound) : null; if (resolved != null) { return new TypedValue<>(resolved, resolved.asPrismObject().getDefinition()); } else { PrismObjectDefinition<ObjectType> def = getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ObjectType.class); return new TypedValue<>(null, def); } } // Finding items in deltas/objects // this is similar to delta.hasItemDelta but much, much more relaxed (we completely ignore ID path segments and we take sub-paths into account) // // Very experimental implementation. Needs a bit of time to clean up and test adequately. @SuppressWarnings("WeakerAccess") public boolean containsItem(ObjectDelta<?> delta, ItemPath itemPath) { if (delta.getChangeType() == ChangeType.ADD) { return containsItem(delta.getObjectToAdd(), itemPath); } else //noinspection SimplifiableIfStatement if (delta.getChangeType() == ChangeType.MODIFY) { return containsItemInModifications(delta.getModifications(), itemPath); } else { return false; } } private boolean containsItemInModifications(Collection<? extends ItemDelta<?, ?>> modifications, ItemPath itemPath) { for (ItemDelta<?, ?> itemDelta : modifications) { if (containsItem(itemDelta, itemPath)) { return true; } } return false; } private boolean containsItem(ItemDelta<?, ?> itemDelta, ItemPath itemPath) { ItemPath namesOnlyPathTested = itemPath.namedSegmentsOnly(); ItemPath namesOnlyPathInDelta = itemDelta.getPath().namedSegmentsOnly(); if (namesOnlyPathTested.isSubPathOrEquivalent(namesOnlyPathInDelta)) { return true; } // however, we can add/delete whole container (containing part of the path) // e.g. we can test for activation/administrativeStatus, and the delta is: // ADD activation VALUE (administrativeStatus=ENABLED) if (!namesOnlyPathInDelta.isSubPath(namesOnlyPathTested)) { return false; } // for ADD values we know // for REPLACE values we know - for values being added, but NOT for values being left behind // for DELETE we have a problem if we are deleting "by ID" - we just don't know if the value being deleted contains the path in question or not ItemPath remainder = namesOnlyPathTested.remainder(namesOnlyPathInDelta); return containsItemInValues(itemDelta.getValuesToAdd(), remainder) || containsItemInValues(itemDelta.getValuesToReplace(), remainder) || containsItemInValues(itemDelta.getValuesToDelete(), remainder); } // remainder contains only named segments and is not empty private boolean containsItemInValues(Collection<?> values, ItemPath remainder) { if (values == null) { return false; } for (Object value : values) { if (value instanceof PrismContainerValue) { // we do not want to look inside references nor primitive values if (containsItem((PrismContainerValue<?>) value, remainder)) { return true; } } } return false; } boolean containsItem(List<ObjectDelta<AssignmentHolderType>> deltas, ItemPath itemPath) { for (ObjectDelta<?> objectDelta : deltas) { if (containsItem(objectDelta, itemPath)) { return true; } } return false; } // itemPath is empty or starts with named item path segment private boolean containsItem(PrismContainer<?> container, ItemPath itemPath) { if (container.size() == 0) { return false; // there is a container, but no values } if (itemPath.isEmpty()) { return true; } for (PrismContainerValue<?> o : container.getValues()) { if (containsItem(o, itemPath)) { return true; } } return false; } // path starts with named item path segment private boolean containsItem(PrismContainerValue<?> prismContainerValue, ItemPath itemPath) { ItemName first = ItemPath.toName(itemPath.first()); Item<?, ?> item = prismContainerValue.findItem(first); if (item == null) { return false; } ItemPath pathTail = stripFirstIds(itemPath); if (item instanceof PrismContainer) { return containsItem((PrismContainer<?>) item, pathTail); } else if (item instanceof PrismReference) { return pathTail.isEmpty(); // we do not want to look inside references } else //noinspection SimplifiableIfStatement if (item instanceof PrismProperty) { return pathTail.isEmpty(); // ...neither inside atomic values } else { return false; // should not occur anyway } } private ItemPath stripFirstIds(ItemPath itemPath) { while (!itemPath.isEmpty() && itemPath.startsWithId()) { itemPath = itemPath.rest(); } return itemPath; } @Override public String getChannel() { return channel; } public void setChannel(String channel) { this.channel = channel; } @Override public String getStatusAsText() { if (isSuccess()) { return "SUCCESS"; } else if (isOnlyFailure()) { return "FAILURE"; } else if (isFailure()) { return "PARTIAL FAILURE"; } else if (isInProgress()) { return "IN PROGRESS"; } else { return "UNKNOWN"; } } protected void debugDumpCommon(StringBuilder sb, int indent) { DebugUtil.debugDumpWithLabelToStringLn(sb, "id", getId(), indent + 1); DebugUtil.debugDumpWithLabelLn(sb, "requester", getRequester(), indent + 1); DebugUtil.debugDumpWithLabelLn(sb, "requestee", getRequestee(), indent + 1); } @Override public void shortDump(StringBuilder sb) { sb.append(this.getClass().getSimpleName()).append("(").append(getId()).append(")"); } MidpointFunctions getMidpointFunctions() { if (midpointFunctions == null) { midpointFunctions = ApplicationContextHolder.getBean(MidpointFunctions.class); } return midpointFunctions; } private ModelService getModelService() { return ApplicationContextHolder.getBean(ModelService.class); } PrismContext getPrismContext() { if (prismContext == null) { prismContext = ApplicationContextHolder.getBean(PrismContext.class); } return prismContext; } TextFormatter getTextFormatter() { if (textFormatter == null) { textFormatter = ApplicationContextHolder.getBean(TextFormatter.class); } return textFormatter; } /** * As {@link MidpointFunctions#resolveReferenceIfExists(ObjectReferenceType)} but a bit more intelligent * (e.g. it stores resolved object right in the reference). */ @Nullable ObjectType resolveReferenceIfExists(@Nullable ObjectReferenceType reference) { if (reference == null) { return null; } if (reference.getObject() != null) { return (ObjectType) reference.getObject().asObjectable(); } QName type = reference.getType(); // TODO what about implicitly specified types, like in resourceRef? PrismObjectDefinition<ObjectType> objectDefinition = PrismContext.get().getSchemaRegistry().findObjectDefinitionByType(reference.getType()); try { if (objectDefinition == null) { throw new SchemaException("No definition for type " + type); } Collection<SelectorOptions<GetOperationOptions>> options = SchemaService.get().getOperationOptionsBuilder() .executionPhase() .allowNotFound(true) .build(); PrismObject<ObjectType> object = getModelService().getObject( objectDefinition.getCompileTimeClass(), reference.getOid(), options, getCurrentTask(), getCurrentResult()); if (!reference.asReferenceValue().isImmutable()) { reference.asReferenceValue().setObject(object); } return object.asObjectable(); } catch (ObjectNotFoundException e) { LoggingUtils.logException(LOGGER, "Couldn't resolve object from reference: {}", e, reference); return null; } catch (Exception e) { LoggingUtils.logUnexpectedException(LOGGER, "Couldn't resolve object from reference: {}", e, reference); return null; } } @Nullable PolyStringType getNameFromReference(@Nullable ObjectReferenceType reference) { if (reference == null) { return null; } else if (reference.getTargetName() != null) { return reference.getTargetName(); } else if (reference.getObject() != null) { return reference.getObject().asObjectable().getName(); } else { ObjectType resolved = resolveReferenceIfExists(reference); if (resolved != null) { return resolved.getName(); } else { return PolyStringType.fromOrig( reference.getOid()); // At least something } } } protected @Nullable PolyStringType getDisplayNameFromReference(@Nullable ObjectReferenceType reference) { if (reference == null) { return null; } else if (reference.getObject() != null) { return getDisplayName((ObjectType) reference.getObject().asObjectable()); } else { ObjectType resolved = resolveReferenceIfExists(reference); if (resolved != null) { return getDisplayName(resolved); } else { return PolyStringType.fromOrig( reference.getOid()); // At least something } } } private Task getCurrentTask() { return getMidpointFunctions().getCurrentTask(); } private OperationResult getCurrentResult() { return getMidpointFunctions().getCurrentResult(); } public void setRequesterAndRequesteeAsTaskOwner(@NotNull Task task, @NotNull OperationResult result) { PrismObject<? extends FocusType> ownerObject = task.getOwner(result); if (ownerObject != null) { FocusType owner = ownerObject.asObjectable(); setRequester(new SimpleObjectRefImpl(owner)); setRequestee(new SimpleObjectRefImpl(owner)); } else { LOGGER.debug("No owner for {}, therefore no requester and requestee will be set for event {}", task, getId()); } } @Override public String toString() { return toStringPrefix() + '}'; } /** * Prefix for {@link #toString()} after which other attributes can be added; final `}` needs be added too. * Useful for event subclasses. */ @NotNull protected String toStringPrefix() { return getClass().getSimpleName() + "{" + "id=" + id + ",requester=" + requester + ",requestee=" + requestee; } }
Evolveum/midpoint
model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/events/BaseEventImpl.java
4,687
// overridden in ModelEvent
line_comment
nl
/* * Copyright (C) 2020-2022 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.notifications.impl.events; import java.util.Collection; import java.util.List; import javax.xml.namespace.QName; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.evolveum.midpoint.model.api.ModelService; import com.evolveum.midpoint.model.api.expr.MidpointFunctions; import com.evolveum.midpoint.notifications.api.events.Event; import com.evolveum.midpoint.notifications.api.events.SimpleObjectRef; import com.evolveum.midpoint.notifications.impl.SimpleObjectRefImpl; import com.evolveum.midpoint.notifications.impl.formatters.TextFormatter; import com.evolveum.midpoint.notifications.impl.util.ApplicationContextHolder; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.ChangeType; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SchemaService; import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.constants.ExpressionConstants; import com.evolveum.midpoint.schema.expression.TypedValue; import com.evolveum.midpoint.schema.expression.VariablesMap; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.LightweightIdentifier; import com.evolveum.midpoint.task.api.LightweightIdentifierGenerator; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.ShortDumpable; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** * Base implementation of Event that contains the common functionality. */ public abstract class BaseEventImpl implements Event, DebugDumpable, ShortDumpable { private static final Trace LOGGER = TraceManager.getTrace(BaseEventImpl.class); @NotNull private final LightweightIdentifier id; private SimpleObjectRef requester; private SimpleObjectRef requestee; private transient MidpointFunctions midpointFunctions; private transient TextFormatter textFormatter; private transient PrismContext prismContext; private String channel; BaseEventImpl() { this(ApplicationContextHolder.getBean(LightweightIdentifierGenerator.class)); } BaseEventImpl(@NotNull LightweightIdentifierGenerator lightweightIdentifierGenerator) { id = lightweightIdentifierGenerator.generate(); } @NotNull public LightweightIdentifier getId() { return id; } boolean changeTypeMatchesOperationType(ChangeType changeType, EventOperationType eventOperationType) { return switch (eventOperationType) { case ADD -> changeType == ChangeType.ADD; case MODIFY -> changeType == ChangeType.MODIFY; case DELETE -> changeType == ChangeType.DELETE; }; } abstract public boolean isCategoryType(EventCategoryType eventCategory); public boolean isUserRelated() { return false; // overridden in<SUF> } public SimpleObjectRef getRequester() { return requester; } // TODO make requester final and remove this method public void setRequester(SimpleObjectRef requester) { this.requester = requester; } public SimpleObjectRef getRequestee() { return requestee; } // TODO we need the operation result parent here @Nullable private ObjectType resolveObject(SimpleObjectRef ref) { if (ref == null) { return null; } return ref.resolveObjectType(new OperationResult(BaseEventImpl.class + ".resolveObject"), true); } @Override public ObjectType getRequesteeObject() { return resolveObject(requestee); } @SuppressWarnings("WeakerAccess") public ObjectType getRequesterObject() { return resolveObject(requester); } @Override public PolyStringType getRequesteeDisplayName() { return getDisplayName(getRequesteeObject()); } @SuppressWarnings("unused") public PolyStringType getRequesterDisplayName() { return getDisplayName(getRequesterObject()); } @Nullable private PolyStringType getDisplayName(ObjectType object) { if (object == null) { return null; } if (object instanceof UserType) { return ((UserType) object).getFullName(); } else if (object instanceof AbstractRoleType) { return ((AbstractRoleType) object).getDisplayName(); } else { return object.getName(); } } @Nullable private PolyStringType getName(ObjectType object) { return object != null ? object.getName() : null; } @SuppressWarnings("unused") public PolyStringType getRequesteeName() { return getName(getRequesteeObject()); } @SuppressWarnings("unused") public PolyStringType getRequesterName() { return getName(getRequesterObject()); } public void setRequestee(SimpleObjectRef requestee) { this.requestee = requestee; } public void createVariablesMap(VariablesMap variables, OperationResult result) { variables.put(ExpressionConstants.VAR_EVENT, this, Event.class); variables.put(ExpressionConstants.VAR_REQUESTER, resolveTypedObject(requester, false, result)); variables.put(ExpressionConstants.VAR_REQUESTEE, resolveTypedObject(requestee, true, result)); } TypedValue<ObjectType> resolveTypedObject(SimpleObjectRef ref, boolean allowNotFound, OperationResult result) { ObjectType resolved = ref != null ? ref.resolveObjectType(result, allowNotFound) : null; if (resolved != null) { return new TypedValue<>(resolved, resolved.asPrismObject().getDefinition()); } else { PrismObjectDefinition<ObjectType> def = getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ObjectType.class); return new TypedValue<>(null, def); } } // Finding items in deltas/objects // this is similar to delta.hasItemDelta but much, much more relaxed (we completely ignore ID path segments and we take sub-paths into account) // // Very experimental implementation. Needs a bit of time to clean up and test adequately. @SuppressWarnings("WeakerAccess") public boolean containsItem(ObjectDelta<?> delta, ItemPath itemPath) { if (delta.getChangeType() == ChangeType.ADD) { return containsItem(delta.getObjectToAdd(), itemPath); } else //noinspection SimplifiableIfStatement if (delta.getChangeType() == ChangeType.MODIFY) { return containsItemInModifications(delta.getModifications(), itemPath); } else { return false; } } private boolean containsItemInModifications(Collection<? extends ItemDelta<?, ?>> modifications, ItemPath itemPath) { for (ItemDelta<?, ?> itemDelta : modifications) { if (containsItem(itemDelta, itemPath)) { return true; } } return false; } private boolean containsItem(ItemDelta<?, ?> itemDelta, ItemPath itemPath) { ItemPath namesOnlyPathTested = itemPath.namedSegmentsOnly(); ItemPath namesOnlyPathInDelta = itemDelta.getPath().namedSegmentsOnly(); if (namesOnlyPathTested.isSubPathOrEquivalent(namesOnlyPathInDelta)) { return true; } // however, we can add/delete whole container (containing part of the path) // e.g. we can test for activation/administrativeStatus, and the delta is: // ADD activation VALUE (administrativeStatus=ENABLED) if (!namesOnlyPathInDelta.isSubPath(namesOnlyPathTested)) { return false; } // for ADD values we know // for REPLACE values we know - for values being added, but NOT for values being left behind // for DELETE we have a problem if we are deleting "by ID" - we just don't know if the value being deleted contains the path in question or not ItemPath remainder = namesOnlyPathTested.remainder(namesOnlyPathInDelta); return containsItemInValues(itemDelta.getValuesToAdd(), remainder) || containsItemInValues(itemDelta.getValuesToReplace(), remainder) || containsItemInValues(itemDelta.getValuesToDelete(), remainder); } // remainder contains only named segments and is not empty private boolean containsItemInValues(Collection<?> values, ItemPath remainder) { if (values == null) { return false; } for (Object value : values) { if (value instanceof PrismContainerValue) { // we do not want to look inside references nor primitive values if (containsItem((PrismContainerValue<?>) value, remainder)) { return true; } } } return false; } boolean containsItem(List<ObjectDelta<AssignmentHolderType>> deltas, ItemPath itemPath) { for (ObjectDelta<?> objectDelta : deltas) { if (containsItem(objectDelta, itemPath)) { return true; } } return false; } // itemPath is empty or starts with named item path segment private boolean containsItem(PrismContainer<?> container, ItemPath itemPath) { if (container.size() == 0) { return false; // there is a container, but no values } if (itemPath.isEmpty()) { return true; } for (PrismContainerValue<?> o : container.getValues()) { if (containsItem(o, itemPath)) { return true; } } return false; } // path starts with named item path segment private boolean containsItem(PrismContainerValue<?> prismContainerValue, ItemPath itemPath) { ItemName first = ItemPath.toName(itemPath.first()); Item<?, ?> item = prismContainerValue.findItem(first); if (item == null) { return false; } ItemPath pathTail = stripFirstIds(itemPath); if (item instanceof PrismContainer) { return containsItem((PrismContainer<?>) item, pathTail); } else if (item instanceof PrismReference) { return pathTail.isEmpty(); // we do not want to look inside references } else //noinspection SimplifiableIfStatement if (item instanceof PrismProperty) { return pathTail.isEmpty(); // ...neither inside atomic values } else { return false; // should not occur anyway } } private ItemPath stripFirstIds(ItemPath itemPath) { while (!itemPath.isEmpty() && itemPath.startsWithId()) { itemPath = itemPath.rest(); } return itemPath; } @Override public String getChannel() { return channel; } public void setChannel(String channel) { this.channel = channel; } @Override public String getStatusAsText() { if (isSuccess()) { return "SUCCESS"; } else if (isOnlyFailure()) { return "FAILURE"; } else if (isFailure()) { return "PARTIAL FAILURE"; } else if (isInProgress()) { return "IN PROGRESS"; } else { return "UNKNOWN"; } } protected void debugDumpCommon(StringBuilder sb, int indent) { DebugUtil.debugDumpWithLabelToStringLn(sb, "id", getId(), indent + 1); DebugUtil.debugDumpWithLabelLn(sb, "requester", getRequester(), indent + 1); DebugUtil.debugDumpWithLabelLn(sb, "requestee", getRequestee(), indent + 1); } @Override public void shortDump(StringBuilder sb) { sb.append(this.getClass().getSimpleName()).append("(").append(getId()).append(")"); } MidpointFunctions getMidpointFunctions() { if (midpointFunctions == null) { midpointFunctions = ApplicationContextHolder.getBean(MidpointFunctions.class); } return midpointFunctions; } private ModelService getModelService() { return ApplicationContextHolder.getBean(ModelService.class); } PrismContext getPrismContext() { if (prismContext == null) { prismContext = ApplicationContextHolder.getBean(PrismContext.class); } return prismContext; } TextFormatter getTextFormatter() { if (textFormatter == null) { textFormatter = ApplicationContextHolder.getBean(TextFormatter.class); } return textFormatter; } /** * As {@link MidpointFunctions#resolveReferenceIfExists(ObjectReferenceType)} but a bit more intelligent * (e.g. it stores resolved object right in the reference). */ @Nullable ObjectType resolveReferenceIfExists(@Nullable ObjectReferenceType reference) { if (reference == null) { return null; } if (reference.getObject() != null) { return (ObjectType) reference.getObject().asObjectable(); } QName type = reference.getType(); // TODO what about implicitly specified types, like in resourceRef? PrismObjectDefinition<ObjectType> objectDefinition = PrismContext.get().getSchemaRegistry().findObjectDefinitionByType(reference.getType()); try { if (objectDefinition == null) { throw new SchemaException("No definition for type " + type); } Collection<SelectorOptions<GetOperationOptions>> options = SchemaService.get().getOperationOptionsBuilder() .executionPhase() .allowNotFound(true) .build(); PrismObject<ObjectType> object = getModelService().getObject( objectDefinition.getCompileTimeClass(), reference.getOid(), options, getCurrentTask(), getCurrentResult()); if (!reference.asReferenceValue().isImmutable()) { reference.asReferenceValue().setObject(object); } return object.asObjectable(); } catch (ObjectNotFoundException e) { LoggingUtils.logException(LOGGER, "Couldn't resolve object from reference: {}", e, reference); return null; } catch (Exception e) { LoggingUtils.logUnexpectedException(LOGGER, "Couldn't resolve object from reference: {}", e, reference); return null; } } @Nullable PolyStringType getNameFromReference(@Nullable ObjectReferenceType reference) { if (reference == null) { return null; } else if (reference.getTargetName() != null) { return reference.getTargetName(); } else if (reference.getObject() != null) { return reference.getObject().asObjectable().getName(); } else { ObjectType resolved = resolveReferenceIfExists(reference); if (resolved != null) { return resolved.getName(); } else { return PolyStringType.fromOrig( reference.getOid()); // At least something } } } protected @Nullable PolyStringType getDisplayNameFromReference(@Nullable ObjectReferenceType reference) { if (reference == null) { return null; } else if (reference.getObject() != null) { return getDisplayName((ObjectType) reference.getObject().asObjectable()); } else { ObjectType resolved = resolveReferenceIfExists(reference); if (resolved != null) { return getDisplayName(resolved); } else { return PolyStringType.fromOrig( reference.getOid()); // At least something } } } private Task getCurrentTask() { return getMidpointFunctions().getCurrentTask(); } private OperationResult getCurrentResult() { return getMidpointFunctions().getCurrentResult(); } public void setRequesterAndRequesteeAsTaskOwner(@NotNull Task task, @NotNull OperationResult result) { PrismObject<? extends FocusType> ownerObject = task.getOwner(result); if (ownerObject != null) { FocusType owner = ownerObject.asObjectable(); setRequester(new SimpleObjectRefImpl(owner)); setRequestee(new SimpleObjectRefImpl(owner)); } else { LOGGER.debug("No owner for {}, therefore no requester and requestee will be set for event {}", task, getId()); } } @Override public String toString() { return toStringPrefix() + '}'; } /** * Prefix for {@link #toString()} after which other attributes can be added; final `}` needs be added too. * Useful for event subclasses. */ @NotNull protected String toStringPrefix() { return getClass().getSimpleName() + "{" + "id=" + id + ",requester=" + requester + ",requestee=" + requestee; } }
8789_9
/** * Dies ist ein Git-Test! */ package org.exmaralda.coma.root; import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import java.util.prefs.Preferences; import org.exmaralda.coma.datatypes.ComaDatatype; import org.exmaralda.coma.datatypes.ComaTemplate; import org.exmaralda.coma.filters.ComaFilter; import org.exmaralda.coma.helpers.ComaTemplates; import org.jdom.Attribute; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.xpath.XPath; /** @author woerner */ public class ComaData { private static final int MAX_RECENT_FILES = 5; public static final String[] TRANSCRIPTION_FORMATS = new String[] { "xml", "exb", "exs", "tei", "exa" }; public static Preferences prefs = Ui.prefs; HashMap<String, ComaTemplate> oldTemplates; private HashSet<Element> basket; private HashSet<String> roleTypes; private HashMap<String, ComaFilter> cfilters; private HashMap<String, ComaFilter> pfilters; private HashMap<String, ComaFilter> cFilterPresets; private HashMap<String, ComaFilter> sFilterPresets; private HashMap<String, String> hiddenKeys; private Vector<File> recentFiles; // private Element selectedCorpus; String defaultTemplateName = ""; private Element dataElement; private Document document; private Element rootElement; private File openFile = new File(""); private String uniqueSpeakerDistinction; private int schemaVersion = 0; private ComaTemplates templates; private File templateFile; private String searchTerm; private HashMap<String, Element> selectedCommunications = new HashMap<String, Element>(); private HashMap<String, Element> selectedPersons = new HashMap<String, Element>(); // waren Element-Vektoren private Coma coma; private String filterChanged; public ComaData(Coma c) { coma = c; oldTemplates = new HashMap<String, ComaTemplate>(); basket = new HashSet<Element>(); cfilters = new HashMap<String, ComaFilter>(); pfilters = new HashMap<String, ComaFilter>(); templates = new ComaTemplates(); uniqueSpeakerDistinction = ""; openFile = new File(""); initPresets(); createRecentFiles(); } private void initPresets() { cFilterPresets = new HashMap<String, ComaFilter>(); cFilterPresets.put(Ui.getText("filter.emptyFilter"), new ComaFilter( coma, "//Corpus/CorpusData/Communication[1>0]")); cFilterPresets .put(Ui.getText("filter.commsWithTranscriptions"), new ComaFilter(coma, "//Corpus/CorpusData/Communication[count(Transcription)>0]")); cFilterPresets .put(Ui.getText("filter.commsWithRecordings"), new ComaFilter( coma, "//Corpus/CorpusData/Communication[count(Recording)>0]")); sFilterPresets = new HashMap<String, ComaFilter>(); sFilterPresets.put(Ui.getText("filter.emptyFilter"), new ComaFilter( coma, "//Corpus/CorpusData/Speaker[1>0]")); } private void createRecentFiles() { recentFiles = new Vector<File>(); String allFiles = prefs.get("recentFiles", ""); String[] files = allFiles.split("\n"); for (String s : files) { if (s.length() > 0) { if (recentFiles.size() < MAX_RECENT_FILES) { recentFiles.add(new File(s)); } } } } // RECENT FILES (moved from coma.helpers.RecentFiles.java) public Vector<File> getRecentFiles() { return recentFiles; } public void removeRecentFile(File f) { recentFiles.remove(f); recentFilesChanged(); } private void recentFilesChanged() { String filesString = ""; for (File f : recentFiles) { filesString += f.getAbsolutePath() + "\n"; } prefs.put("recentFiles", filesString); } public void clearRecentFiles() { recentFiles.clear(); recentFilesChanged(); } private void setRecentFile(File f) { if (f != null) if (f.exists()) { prefs.put("recentDir", f.getParent()); if (recentFiles.contains(f)) { recentFiles.remove(f); } recentFiles.add(0, f); } if (recentFiles.size() > MAX_RECENT_FILES) { recentFiles.remove(recentFiles.size() - 1); } recentFilesChanged(); } // templates for description-panels public ComaTemplates getTemplates() { return templates; } public void setDefaultTemplateName(String t) { if (oldTemplates.containsKey(t)) defaultTemplateName = t; } public ComaTemplate getTemplate(String s) { String key = (s == null ? defaultTemplateName : s); return oldTemplates.get(key); } /** * @param text * @param keys */ public void addTemplate(String name, Vector<String> keys) { oldTemplates.put(name, new ComaTemplate(name, null, keys)); } public HashMap<String, ComaFilter> getCfilters() { return cfilters; } public void setCfilters(HashMap<String, ComaFilter> cfilters) { this.cfilters = cfilters; } public HashMap<String, ComaFilter> getPfilters() { return pfilters; } public void addRawCFilter(String xpath) { ComaFilter filter = new ComaFilter(coma, xpath); cfilters.put(filter.getXPath(), filter); } public void addRawPFilter(String xpath) { ComaFilter filter = new ComaFilter(coma, xpath); pfilters.put(filter.getXPath(), filter); } public void addcfilter(String xpath) { String newXPath = xpath.substring(0, xpath.indexOf("Communication") + 13) + "[" + xpath.substring((xpath.indexOf("Communication") + 14)) + "]"; System.out.println("-->" + newXPath); ComaFilter filter = new ComaFilter(coma, (newXPath)); cfilters.put(filter.getXPath(), filter); } public void addpfilter(String xpath) { String newXPath = xpath.substring(0, xpath.indexOf("Speaker") + 7) + "[" + xpath.substring((xpath.indexOf("Speaker") + 8)) + "]"; ComaFilter filter = new ComaFilter(coma, (newXPath)); pfilters.put(filter.getXPath(), filter); } public void removepfilter(String xpath) { if (xpath == null) { pfilters.clear(); } else { pfilters.remove(xpath); } } public void removecfilter(String xpath) { if (xpath == null) { cfilters.clear(); } else { cfilters.remove(xpath); } } public void removeSearchFilters() { for (String xp : cfilters.keySet()) { if (xp.contains(searchTerm)) { removecfilter(xp); } } for (String xp : pfilters.keySet()) { if (xp.contains(searchTerm)) { removepfilter(xp); } } } /** @param string */ /** * Returns a java.util.list of Communications for a Speaker * * @param speakerElmt * @return */ public HashSet<String> getSpeakerIDs(Vector<Element> speakers) { HashSet<String> ids = new HashSet<String>(); for (Element speaker : speakers) { ids.add(speaker.getAttributeValue("Id")); } return ids; } /** * Returns a java.util.list of Communications for a Speaker * * @param speakerElmt * @return */ public List<Element> getCommunicationsForSpeaker(Element speakerElmt, boolean filtered) { HashSet<Element> commlist = new HashSet<Element>(); String speakerId = speakerElmt.getAttributeValue("Id"); List<Element> allComms = (filtered ? filterComms() : dataElement .getChildren("Communication")); for (Element el : allComms) { List<Element> spks = el.getChild("Setting").getChildren("Person"); HashMap<String, Element> spkTmp = new HashMap<String, Element>(); for (Element sp : spks) { if (sp.getText().equals(speakerId)) { commlist.add(el); } } } return (new Vector<Element>(commlist).subList(0, commlist.size())); // return List.(commList); } public List<Element> filterComms() { List<Element> allComms = dataElement.getChildren("Communication"); Vector<Element> independentList = new Vector<Element>(); independentList.addAll(allComms); int fcount = 0; for (ComaFilter filter : getCfilters().values()) { if (filter.isEnabled()) { try { XPath xp = XPath.newInstance(filter.isInverted() ? filter .getXPathInverted() : filter.getXPath()); List nl = xp.selectNodes(dataElement); if ((filter.isIncluding()) && (fcount > 0)) { independentList.addAll(nl); } else { independentList.retainAll(nl); } } catch (JDOMException err) { err.printStackTrace(); } } fcount++; } return independentList; } public List<Element> filterSpeakers() { List<Element> allComms = dataElement.getChildren("Speaker"); Vector<Element> independentList = new Vector<Element>(); independentList.addAll(allComms); int fcount = 0; for (ComaFilter filter : getPfilters().values()) { if (filter.isEnabled()) { try { XPath xp = XPath.newInstance(filter.isInverted() ? filter .getXPathInverted() : filter.getXPath()); List nl = xp.selectNodes(dataElement); if ((filter.isIncluding()) && (fcount > 0)) { independentList.addAll(nl); } else { independentList.retainAll(nl); } } catch (JDOMException err) { err.printStackTrace(); } } fcount++; } return independentList; } public HashMap<String, Element> getAssignedSpeakers( Element communicationElement) { HashMap<String, Element> spks = new HashMap<String, Element>(); XPath idx; try { idx = XPath.newInstance("//Speaker[role/@target='" + communicationElement.getAttributeValue("Id") + "']"); List<Element> roleElements = idx.selectNodes(getDataElement()); for (Element e : roleElements) { spks.put(e.getAttributeValue("Id"), e); } } catch (JDOMException err) { err.printStackTrace(); } return spks; } /** @param elmt */ // public void setSelectedCorpus(Element elmt) { // selectedCorpus = elmt; // dataElement = selectedCorpus.getChild("CorpusData"); // } public Element getDataElement() { return dataElement; } // public Element getSelectedCorpus() { // return selectedCorpus; // } /** * sets all communication-filters inactive so a new communication gets * displayed in any case */ public void disableCommFilters() { for (ComaFilter f : getCfilters().values()) { f.setEnabled(false); } } /** * sets all speaker-filters inactive so a new communication gets displayed * in any case */ public void disableSpeakerFilters() { for (ComaFilter f : getPfilters().values()) { f.setEnabled(false); } } /** @return */ public String getUniqueSpeakerDistinction() { return uniqueSpeakerDistinction; } /** @param attributeValue */ public void setUniqueSpeakerDistinction(String attributeValue) { uniqueSpeakerDistinction = attributeValue; } /** @param e */ public void setDataElement(Element e) { dataElement = e; } public File getOpenFile() { return (openFile == null) ? new File("") : openFile; } public void setOpenFile(File openFile) { this.openFile = openFile; setRecentFile(openFile); } /** @param selectedFile */ public void setTemplateFile(File f) { templates.setFile(f); templateFile = f; } // public String getSelectedCorpusName() { // return ((getSelectedCorpus() == null) // ? "no corpus selected" // : getSelectedCorpus().getAttributeValue("Name")); // } public Element getRootElement() { return document.getRootElement(); } public Document getDocument() { return document; } public void setDocument(Document d) { document = d; setSchemaVersion(0); } public HashMap<String, String> getHiddenKeys() { if (hiddenKeys == null) { hiddenKeys = new HashMap<String, String>(); if (getRootElement().getChildren("coma").size() > 0) { for (Element e : (List<Element>) getRootElement() .getChild("coma").getChild("hidden").getChildren()) { hiddenKeys.put(e.getAttributeValue("Name"), e.getValue()); } } } return hiddenKeys; } public void setRootElement(Element re) { document.setRootElement(re); } public String getCorpusName() { return document.getRootElement().getAttributeValue("Name"); } public void removeSubcorpora() { System.out.print("removing subcorpora..."); XPath spx; Document newDoc = new Document(); Element cd = new Element("CorpusData"); newDoc.setRootElement(new Element("Corpus").addContent(cd)); newDoc.getRootElement().addContent(new Element("Description")); for (Attribute a : (List<Attribute>) getRootElement().getAttributes()) { newDoc.getRootElement().setAttribute(a.getName(), a.getValue()); } if (getRootElement().getChild("Description") != null) { for (Element delm : (List<Element>) getRootElement().getChild( "Description").getChildren()) { Element dk = new Element("Key"); dk.setAttribute("Name", delm.getAttributeValue("Name")); dk.setText(delm.getText()); newDoc.getRootElement().getChild("Description").addContent(dk); } } try { XPath xpsc = XPath.newInstance("//Communication|//Speaker"); List<Element> elements = xpsc.selectNodes(getRootElement()); for (Element sce : elements) { if (sce.getChild("Description") == null) { sce.addContent(new Element("Description")); } Element d = sce.getChild("Description"); d.addContent(new Element("Key").setAttribute("Name", "@Coma-Corpus").setText( sce.getParentElement().getParentElement() .getAttributeValue("Name"))); cd.addContent((Element) sce.clone()); } document = newDoc; System.out.println("removed."); // setRootElement(newDoc.getRootElement()); } catch (JDOMException e) { System.out.println("failed."); } } public void addSpeakers(HashSet<Element> speakers) { for (Element e : speakers) { dataElement.addContent((Element) e.clone()); } } public String getSearchTerm() { if ((cfilters.size()) + (pfilters.size()) > 0) { return searchTerm; } else { return ""; } } public void setSearchTerm(String text) { searchTerm = text; // TODO Auto-generated method stub } /* * clears the basket */ public void clearBasket() { basket.clear(); } /* * adds a transcription to the basket */ public void addToBasket(Element transcription) { basket.add(transcription); } public HashSet<Element> getBasket() { return basket; } // // public void setSelectedCommunications(Vector<Element> // selectedCommunications) { // this.selectedCommunications = selectedCommunications; // } public HashMap<String, Element> getSelectedCommunications() { return selectedCommunications; } // public void setSelectedPersons(Vector<Element> selectedPersons) { // this.selectedPersons = selectedPersons; // } public HashMap<String, Element> getSelectedPersons() { return selectedPersons; } public Element getElementById(String target) { XPath xp; try { xp = XPath.newInstance("//.[@Id=\"" + target + "\"]"); // System.out.println("XPath:" + ".[@Id=\"" + target + "\"]"); // System.out.println("FOUND " // + ((Element) xp.selectSingleNode(dataElement))); return (Element) xp.selectSingleNode(dataElement); } catch (JDOMException e) { e.printStackTrace(); } return null; } public void setcFilterPresets(HashMap<String, ComaFilter> cFilterPresets) { this.cFilterPresets = cFilterPresets; } public HashMap<String, ComaFilter> getcFilterPresets() { System.out.println(cFilterPresets.size()); return cFilterPresets; } public void setsFilterPresets(HashMap<String, ComaFilter> sFilterPresets) { this.sFilterPresets = sFilterPresets; } public HashMap<String, ComaFilter> getsFilterPresets() { System.out.println(sFilterPresets.size()); return sFilterPresets; } public void setSchemaVersion(int schemaVersion) { this.schemaVersion = schemaVersion; } public void setSchemaVersion(String versionString) { this.schemaVersion = Integer.parseInt(versionString); } public int getSchemaVersion() { return schemaVersion; } public Set<String> getCommIdsForSelectedSpeakers() { HashSet<String> ids = new HashSet<String>(); for (String s : selectedPersons.keySet()) { Element person = selectedPersons.get(s); if (person.getChild("role") != null) { for (Element role : (List<Element>) person.getChildren("role")) { ids.add(role.getAttributeValue("target")); } } } return ids; } public String getSelectedCorpusName() { return getCorpusName(); } public HashSet<String> getRoleTypes() { return roleTypes; } public void setRoleTypes(HashSet<String> roleTypes) { this.roleTypes = roleTypes; } public HashSet<String> addRoleType(String rt) { if (roleTypes == null) { roleTypes = new HashSet<String>(); } roleTypes.add(rt); return roleTypes; } public void setFilterChanged(String string) { filterChanged=string; } public String getFilterChanged() { return filterChanged; } }
Exmaralda-Org/exmaralda
src/org/exmaralda/coma/root/ComaData.java
5,605
// dataElement = selectedCorpus.getChild("CorpusData");
line_comment
nl
/** * Dies ist ein Git-Test! */ package org.exmaralda.coma.root; import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import java.util.prefs.Preferences; import org.exmaralda.coma.datatypes.ComaDatatype; import org.exmaralda.coma.datatypes.ComaTemplate; import org.exmaralda.coma.filters.ComaFilter; import org.exmaralda.coma.helpers.ComaTemplates; import org.jdom.Attribute; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.xpath.XPath; /** @author woerner */ public class ComaData { private static final int MAX_RECENT_FILES = 5; public static final String[] TRANSCRIPTION_FORMATS = new String[] { "xml", "exb", "exs", "tei", "exa" }; public static Preferences prefs = Ui.prefs; HashMap<String, ComaTemplate> oldTemplates; private HashSet<Element> basket; private HashSet<String> roleTypes; private HashMap<String, ComaFilter> cfilters; private HashMap<String, ComaFilter> pfilters; private HashMap<String, ComaFilter> cFilterPresets; private HashMap<String, ComaFilter> sFilterPresets; private HashMap<String, String> hiddenKeys; private Vector<File> recentFiles; // private Element selectedCorpus; String defaultTemplateName = ""; private Element dataElement; private Document document; private Element rootElement; private File openFile = new File(""); private String uniqueSpeakerDistinction; private int schemaVersion = 0; private ComaTemplates templates; private File templateFile; private String searchTerm; private HashMap<String, Element> selectedCommunications = new HashMap<String, Element>(); private HashMap<String, Element> selectedPersons = new HashMap<String, Element>(); // waren Element-Vektoren private Coma coma; private String filterChanged; public ComaData(Coma c) { coma = c; oldTemplates = new HashMap<String, ComaTemplate>(); basket = new HashSet<Element>(); cfilters = new HashMap<String, ComaFilter>(); pfilters = new HashMap<String, ComaFilter>(); templates = new ComaTemplates(); uniqueSpeakerDistinction = ""; openFile = new File(""); initPresets(); createRecentFiles(); } private void initPresets() { cFilterPresets = new HashMap<String, ComaFilter>(); cFilterPresets.put(Ui.getText("filter.emptyFilter"), new ComaFilter( coma, "//Corpus/CorpusData/Communication[1>0]")); cFilterPresets .put(Ui.getText("filter.commsWithTranscriptions"), new ComaFilter(coma, "//Corpus/CorpusData/Communication[count(Transcription)>0]")); cFilterPresets .put(Ui.getText("filter.commsWithRecordings"), new ComaFilter( coma, "//Corpus/CorpusData/Communication[count(Recording)>0]")); sFilterPresets = new HashMap<String, ComaFilter>(); sFilterPresets.put(Ui.getText("filter.emptyFilter"), new ComaFilter( coma, "//Corpus/CorpusData/Speaker[1>0]")); } private void createRecentFiles() { recentFiles = new Vector<File>(); String allFiles = prefs.get("recentFiles", ""); String[] files = allFiles.split("\n"); for (String s : files) { if (s.length() > 0) { if (recentFiles.size() < MAX_RECENT_FILES) { recentFiles.add(new File(s)); } } } } // RECENT FILES (moved from coma.helpers.RecentFiles.java) public Vector<File> getRecentFiles() { return recentFiles; } public void removeRecentFile(File f) { recentFiles.remove(f); recentFilesChanged(); } private void recentFilesChanged() { String filesString = ""; for (File f : recentFiles) { filesString += f.getAbsolutePath() + "\n"; } prefs.put("recentFiles", filesString); } public void clearRecentFiles() { recentFiles.clear(); recentFilesChanged(); } private void setRecentFile(File f) { if (f != null) if (f.exists()) { prefs.put("recentDir", f.getParent()); if (recentFiles.contains(f)) { recentFiles.remove(f); } recentFiles.add(0, f); } if (recentFiles.size() > MAX_RECENT_FILES) { recentFiles.remove(recentFiles.size() - 1); } recentFilesChanged(); } // templates for description-panels public ComaTemplates getTemplates() { return templates; } public void setDefaultTemplateName(String t) { if (oldTemplates.containsKey(t)) defaultTemplateName = t; } public ComaTemplate getTemplate(String s) { String key = (s == null ? defaultTemplateName : s); return oldTemplates.get(key); } /** * @param text * @param keys */ public void addTemplate(String name, Vector<String> keys) { oldTemplates.put(name, new ComaTemplate(name, null, keys)); } public HashMap<String, ComaFilter> getCfilters() { return cfilters; } public void setCfilters(HashMap<String, ComaFilter> cfilters) { this.cfilters = cfilters; } public HashMap<String, ComaFilter> getPfilters() { return pfilters; } public void addRawCFilter(String xpath) { ComaFilter filter = new ComaFilter(coma, xpath); cfilters.put(filter.getXPath(), filter); } public void addRawPFilter(String xpath) { ComaFilter filter = new ComaFilter(coma, xpath); pfilters.put(filter.getXPath(), filter); } public void addcfilter(String xpath) { String newXPath = xpath.substring(0, xpath.indexOf("Communication") + 13) + "[" + xpath.substring((xpath.indexOf("Communication") + 14)) + "]"; System.out.println("-->" + newXPath); ComaFilter filter = new ComaFilter(coma, (newXPath)); cfilters.put(filter.getXPath(), filter); } public void addpfilter(String xpath) { String newXPath = xpath.substring(0, xpath.indexOf("Speaker") + 7) + "[" + xpath.substring((xpath.indexOf("Speaker") + 8)) + "]"; ComaFilter filter = new ComaFilter(coma, (newXPath)); pfilters.put(filter.getXPath(), filter); } public void removepfilter(String xpath) { if (xpath == null) { pfilters.clear(); } else { pfilters.remove(xpath); } } public void removecfilter(String xpath) { if (xpath == null) { cfilters.clear(); } else { cfilters.remove(xpath); } } public void removeSearchFilters() { for (String xp : cfilters.keySet()) { if (xp.contains(searchTerm)) { removecfilter(xp); } } for (String xp : pfilters.keySet()) { if (xp.contains(searchTerm)) { removepfilter(xp); } } } /** @param string */ /** * Returns a java.util.list of Communications for a Speaker * * @param speakerElmt * @return */ public HashSet<String> getSpeakerIDs(Vector<Element> speakers) { HashSet<String> ids = new HashSet<String>(); for (Element speaker : speakers) { ids.add(speaker.getAttributeValue("Id")); } return ids; } /** * Returns a java.util.list of Communications for a Speaker * * @param speakerElmt * @return */ public List<Element> getCommunicationsForSpeaker(Element speakerElmt, boolean filtered) { HashSet<Element> commlist = new HashSet<Element>(); String speakerId = speakerElmt.getAttributeValue("Id"); List<Element> allComms = (filtered ? filterComms() : dataElement .getChildren("Communication")); for (Element el : allComms) { List<Element> spks = el.getChild("Setting").getChildren("Person"); HashMap<String, Element> spkTmp = new HashMap<String, Element>(); for (Element sp : spks) { if (sp.getText().equals(speakerId)) { commlist.add(el); } } } return (new Vector<Element>(commlist).subList(0, commlist.size())); // return List.(commList); } public List<Element> filterComms() { List<Element> allComms = dataElement.getChildren("Communication"); Vector<Element> independentList = new Vector<Element>(); independentList.addAll(allComms); int fcount = 0; for (ComaFilter filter : getCfilters().values()) { if (filter.isEnabled()) { try { XPath xp = XPath.newInstance(filter.isInverted() ? filter .getXPathInverted() : filter.getXPath()); List nl = xp.selectNodes(dataElement); if ((filter.isIncluding()) && (fcount > 0)) { independentList.addAll(nl); } else { independentList.retainAll(nl); } } catch (JDOMException err) { err.printStackTrace(); } } fcount++; } return independentList; } public List<Element> filterSpeakers() { List<Element> allComms = dataElement.getChildren("Speaker"); Vector<Element> independentList = new Vector<Element>(); independentList.addAll(allComms); int fcount = 0; for (ComaFilter filter : getPfilters().values()) { if (filter.isEnabled()) { try { XPath xp = XPath.newInstance(filter.isInverted() ? filter .getXPathInverted() : filter.getXPath()); List nl = xp.selectNodes(dataElement); if ((filter.isIncluding()) && (fcount > 0)) { independentList.addAll(nl); } else { independentList.retainAll(nl); } } catch (JDOMException err) { err.printStackTrace(); } } fcount++; } return independentList; } public HashMap<String, Element> getAssignedSpeakers( Element communicationElement) { HashMap<String, Element> spks = new HashMap<String, Element>(); XPath idx; try { idx = XPath.newInstance("//Speaker[role/@target='" + communicationElement.getAttributeValue("Id") + "']"); List<Element> roleElements = idx.selectNodes(getDataElement()); for (Element e : roleElements) { spks.put(e.getAttributeValue("Id"), e); } } catch (JDOMException err) { err.printStackTrace(); } return spks; } /** @param elmt */ // public void setSelectedCorpus(Element elmt) { // selectedCorpus = elmt; // dataElement =<SUF> // } public Element getDataElement() { return dataElement; } // public Element getSelectedCorpus() { // return selectedCorpus; // } /** * sets all communication-filters inactive so a new communication gets * displayed in any case */ public void disableCommFilters() { for (ComaFilter f : getCfilters().values()) { f.setEnabled(false); } } /** * sets all speaker-filters inactive so a new communication gets displayed * in any case */ public void disableSpeakerFilters() { for (ComaFilter f : getPfilters().values()) { f.setEnabled(false); } } /** @return */ public String getUniqueSpeakerDistinction() { return uniqueSpeakerDistinction; } /** @param attributeValue */ public void setUniqueSpeakerDistinction(String attributeValue) { uniqueSpeakerDistinction = attributeValue; } /** @param e */ public void setDataElement(Element e) { dataElement = e; } public File getOpenFile() { return (openFile == null) ? new File("") : openFile; } public void setOpenFile(File openFile) { this.openFile = openFile; setRecentFile(openFile); } /** @param selectedFile */ public void setTemplateFile(File f) { templates.setFile(f); templateFile = f; } // public String getSelectedCorpusName() { // return ((getSelectedCorpus() == null) // ? "no corpus selected" // : getSelectedCorpus().getAttributeValue("Name")); // } public Element getRootElement() { return document.getRootElement(); } public Document getDocument() { return document; } public void setDocument(Document d) { document = d; setSchemaVersion(0); } public HashMap<String, String> getHiddenKeys() { if (hiddenKeys == null) { hiddenKeys = new HashMap<String, String>(); if (getRootElement().getChildren("coma").size() > 0) { for (Element e : (List<Element>) getRootElement() .getChild("coma").getChild("hidden").getChildren()) { hiddenKeys.put(e.getAttributeValue("Name"), e.getValue()); } } } return hiddenKeys; } public void setRootElement(Element re) { document.setRootElement(re); } public String getCorpusName() { return document.getRootElement().getAttributeValue("Name"); } public void removeSubcorpora() { System.out.print("removing subcorpora..."); XPath spx; Document newDoc = new Document(); Element cd = new Element("CorpusData"); newDoc.setRootElement(new Element("Corpus").addContent(cd)); newDoc.getRootElement().addContent(new Element("Description")); for (Attribute a : (List<Attribute>) getRootElement().getAttributes()) { newDoc.getRootElement().setAttribute(a.getName(), a.getValue()); } if (getRootElement().getChild("Description") != null) { for (Element delm : (List<Element>) getRootElement().getChild( "Description").getChildren()) { Element dk = new Element("Key"); dk.setAttribute("Name", delm.getAttributeValue("Name")); dk.setText(delm.getText()); newDoc.getRootElement().getChild("Description").addContent(dk); } } try { XPath xpsc = XPath.newInstance("//Communication|//Speaker"); List<Element> elements = xpsc.selectNodes(getRootElement()); for (Element sce : elements) { if (sce.getChild("Description") == null) { sce.addContent(new Element("Description")); } Element d = sce.getChild("Description"); d.addContent(new Element("Key").setAttribute("Name", "@Coma-Corpus").setText( sce.getParentElement().getParentElement() .getAttributeValue("Name"))); cd.addContent((Element) sce.clone()); } document = newDoc; System.out.println("removed."); // setRootElement(newDoc.getRootElement()); } catch (JDOMException e) { System.out.println("failed."); } } public void addSpeakers(HashSet<Element> speakers) { for (Element e : speakers) { dataElement.addContent((Element) e.clone()); } } public String getSearchTerm() { if ((cfilters.size()) + (pfilters.size()) > 0) { return searchTerm; } else { return ""; } } public void setSearchTerm(String text) { searchTerm = text; // TODO Auto-generated method stub } /* * clears the basket */ public void clearBasket() { basket.clear(); } /* * adds a transcription to the basket */ public void addToBasket(Element transcription) { basket.add(transcription); } public HashSet<Element> getBasket() { return basket; } // // public void setSelectedCommunications(Vector<Element> // selectedCommunications) { // this.selectedCommunications = selectedCommunications; // } public HashMap<String, Element> getSelectedCommunications() { return selectedCommunications; } // public void setSelectedPersons(Vector<Element> selectedPersons) { // this.selectedPersons = selectedPersons; // } public HashMap<String, Element> getSelectedPersons() { return selectedPersons; } public Element getElementById(String target) { XPath xp; try { xp = XPath.newInstance("//.[@Id=\"" + target + "\"]"); // System.out.println("XPath:" + ".[@Id=\"" + target + "\"]"); // System.out.println("FOUND " // + ((Element) xp.selectSingleNode(dataElement))); return (Element) xp.selectSingleNode(dataElement); } catch (JDOMException e) { e.printStackTrace(); } return null; } public void setcFilterPresets(HashMap<String, ComaFilter> cFilterPresets) { this.cFilterPresets = cFilterPresets; } public HashMap<String, ComaFilter> getcFilterPresets() { System.out.println(cFilterPresets.size()); return cFilterPresets; } public void setsFilterPresets(HashMap<String, ComaFilter> sFilterPresets) { this.sFilterPresets = sFilterPresets; } public HashMap<String, ComaFilter> getsFilterPresets() { System.out.println(sFilterPresets.size()); return sFilterPresets; } public void setSchemaVersion(int schemaVersion) { this.schemaVersion = schemaVersion; } public void setSchemaVersion(String versionString) { this.schemaVersion = Integer.parseInt(versionString); } public int getSchemaVersion() { return schemaVersion; } public Set<String> getCommIdsForSelectedSpeakers() { HashSet<String> ids = new HashSet<String>(); for (String s : selectedPersons.keySet()) { Element person = selectedPersons.get(s); if (person.getChild("role") != null) { for (Element role : (List<Element>) person.getChildren("role")) { ids.add(role.getAttributeValue("target")); } } } return ids; } public String getSelectedCorpusName() { return getCorpusName(); } public HashSet<String> getRoleTypes() { return roleTypes; } public void setRoleTypes(HashSet<String> roleTypes) { this.roleTypes = roleTypes; } public HashSet<String> addRoleType(String rt) { if (roleTypes == null) { roleTypes = new HashSet<String>(); } roleTypes.add(rt); return roleTypes; } public void setFilterChanged(String string) { filterChanged=string; } public String getFilterChanged() { return filterChanged; } }
140631_32
/* * Copyright 2013-2024 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.s3.internal.crypto.v2; import static com.amazonaws.services.s3.model.CryptoMode.AuthenticatedEncryption; import static com.amazonaws.services.s3.model.CryptoMode.StrictAuthenticatedEncryption; import static com.amazonaws.services.s3.model.ExtraMaterialsDescription.NONE; import static com.amazonaws.util.IOUtils.closeQuietly; import com.amazonaws.services.s3.model.CryptoRangeGetMode; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Collections; import java.util.Map; import com.amazonaws.SdkClientException; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.internal.SdkFilterInputStream; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.s3.internal.S3Direct; import com.amazonaws.services.s3.internal.crypto.AdjustedRangeInputStream; import com.amazonaws.services.s3.internal.crypto.CipherLite; import com.amazonaws.services.s3.internal.crypto.CipherLiteInputStream; import com.amazonaws.services.s3.internal.crypto.ContentCryptoScheme; import com.amazonaws.services.s3.internal.crypto.CryptoRuntime; import com.amazonaws.services.s3.model.CryptoConfigurationV2; import com.amazonaws.services.s3.model.CryptoMode; import com.amazonaws.services.s3.model.EncryptedGetObjectRequest; import com.amazonaws.services.s3.model.EncryptionMaterialsProvider; import com.amazonaws.services.s3.model.ExtraMaterialsDescription; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectId; import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.util.json.Jackson; /** * Authenticated encryption (AE) cryptographic module for the S3 encryption client. */ public class S3CryptoModuleAE extends S3CryptoModuleBase<MultipartUploadCryptoContext> { static { // Enable bouncy castle if available CryptoRuntime.enableBouncyCastle(); } /** * @param cryptoConfig a read-only copy of the crypto configuration. */ public S3CryptoModuleAE(AWSKMS kms, S3Direct s3, AWSCredentialsProvider credentialsProvider, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfigurationV2 cryptoConfig) { super(kms, s3, encryptionMaterialsProvider, cryptoConfig); CryptoMode mode = cryptoConfig.getCryptoMode(); if (mode != StrictAuthenticatedEncryption && mode != AuthenticatedEncryption) { throw new IllegalArgumentException(); } } /** * Used for testing purposes only. */ S3CryptoModuleAE(S3Direct s3, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfigurationV2 cryptoConfig) { this(null, s3, new DefaultAWSCredentialsProviderChain(), encryptionMaterialsProvider, cryptoConfig); } /** * Used for testing purposes only. */ S3CryptoModuleAE(AWSKMS kms, S3Direct s3, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfigurationV2 cryptoConfig) { this(kms, s3, new DefaultAWSCredentialsProviderChain(), encryptionMaterialsProvider, cryptoConfig); } /** * Returns true if a strict encryption mode is in use in the current crypto * module; false otherwise. */ protected boolean isStrict() { return false; } @Override public S3Object getObjectSecurely(GetObjectRequest req) { // Adjust the crypto range to retrieve all of the cipher blocks needed to contain the user's desired // range of bytes. long[] desiredRange = req.getRange(); boolean isPartialObject = desiredRange != null || req.getPartNumber() != null; if (isPartialObject) { assertCanGetPartialObject(); } long[] adjustedCryptoRange = getAdjustedCryptoRange(desiredRange); if (adjustedCryptoRange != null) req.setRange(adjustedCryptoRange[0], adjustedCryptoRange[1]); // Get the object from S3 S3Object retrieved = s3.getObject(req); // If the caller has specified constraints, it's possible that super.getObject(...) // would return null, so we simply return null as well. if (retrieved == null) return null; String suffix = null; if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; suffix = ereq.getInstructionFileSuffix(); } try { return suffix == null || suffix.trim().isEmpty() ? decipher(req, desiredRange, adjustedCryptoRange, retrieved) : decipherWithInstFileSuffix(req, desiredRange, adjustedCryptoRange, retrieved, suffix) ; } catch (RuntimeException ex) { // If we're unable to set up the decryption, make sure we close the // HTTP connection closeQuietly(retrieved, log); throw ex; } catch (Error error) { closeQuietly(retrieved, log); throw error; } } private S3Object decipher(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3Object retrieved) { S3ObjectWrapper wrapped = new S3ObjectWrapper(retrieved, req.getS3ObjectId()); // Check if encryption info is in object metadata if (wrapped.hasEncryptionInfo()) return decipherWithMetadata(req, desiredRange, cryptoRange, wrapped); // Check if encrypted info is in an instruction file S3ObjectWrapper ifile = fetchInstructionFile(req.getS3ObjectId(), null); if (ifile != null) { try { return decipherWithInstructionFile(req, desiredRange, cryptoRange, wrapped, ifile); } finally { closeQuietly(ifile, log); } } if (isStrict()) { closeQuietly(wrapped, log); throw new SecurityException("Unencrypted object found, cannot be decrypted in mode " + StrictAuthenticatedEncryption + "; bucket name: " + retrieved.getBucketName() + ", key: " + retrieved.getKey()); } if (cryptoConfig.isUnsafeUndecryptableObjectPassthrough()) { log.warn(String.format( "Unable to detect encryption information for object '%s' in bucket '%s'. " + "Returning object without decryption.", retrieved.getKey(), retrieved.getBucketName())); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange(wrapped, desiredRange, null); return adjusted.getS3Object(); } else { closeQuietly(wrapped, log); throw new SecurityException("Instruction file not found for S3 object with bucket name: " + retrieved.getBucketName() + ", key: " + retrieved.getKey()); } } /** * Same as {@link #decipher(GetObjectRequest, long[], long[], S3Object)} * but makes use of an instruction file with the specified suffix. * @param instFileSuffix never null or empty (which is assumed to have been * sanitized upstream.) */ private S3Object decipherWithInstFileSuffix(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3Object retrieved, String instFileSuffix) { final S3ObjectId id = req.getS3ObjectId(); // Check if encrypted info is in an instruction file final S3ObjectWrapper ifile = fetchInstructionFile(id, instFileSuffix); if (ifile == null) { throw new SdkClientException("Instruction file with suffix " + instFileSuffix + " is not found for " + retrieved); } try { return decipherWithInstructionFile(req, desiredRange, cryptoRange, new S3ObjectWrapper(retrieved, id), ifile); } finally { closeQuietly(ifile, log); } } private S3Object decipherWithInstructionFile(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3ObjectWrapper retrieved, S3ObjectWrapper instructionFile) { ExtraMaterialsDescription extraMatDesc = NONE; boolean keyWrapExpected = isStrict(); if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; extraMatDesc = ereq.getExtraMaterialDescription(); if (!keyWrapExpected) keyWrapExpected = ereq.isKeyWrapExpected(); } String json = instructionFile.toJsonString(); Map<String, String> matdesc = Collections.unmodifiableMap(Jackson.stringMapFromJsonString(json)); ContentCryptoMaterial cekMaterial = ContentCryptoMaterial.fromInstructionFile( matdesc, kekMaterialsProvider, cryptoConfig, cryptoRange, // range is sometimes necessary to compute the adjusted IV extraMatDesc, keyWrapExpected, kms ); boolean isRangeGet = desiredRange != null; securityCheck(cekMaterial, retrieved.getS3ObjectId(), isRangeGet); S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange( decrypted, desiredRange, matdesc); return adjusted.getS3Object(); } private S3Object decipherWithMetadata(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3ObjectWrapper retrieved) { ExtraMaterialsDescription extraMatDesc = NONE; boolean keyWrapExpected = isStrict(); if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; extraMatDesc = ereq.getExtraMaterialDescription(); if (!keyWrapExpected) keyWrapExpected = ereq.isKeyWrapExpected(); } ContentCryptoMaterial cekMaterial = ContentCryptoMaterial .fromObjectMetadata(retrieved.getObjectMetadata().getUserMetadata(), kekMaterialsProvider, cryptoConfig, // range is sometimes necessary to compute the adjusted IV cryptoRange, extraMatDesc, keyWrapExpected, kms ); boolean isRangeGet = desiredRange != null; securityCheck(cekMaterial, retrieved.getS3ObjectId(), isRangeGet); S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange( decrypted, desiredRange, null); return adjusted.getS3Object(); } /** * Adjusts the retrieved S3Object so that the object contents contain only the range of bytes * desired by the user. Since encrypted contents can only be retrieved in CIPHER_BLOCK_SIZE * (16 bytes) chunks, the S3Object potentially contains more bytes than desired, so this method * adjusts the contents range. * * @param s3object * The S3Object retrieved from S3 that could possibly contain more bytes than desired * by the user. * @param range * A two-element array of longs corresponding to the start and finish (inclusive) of a desired * range of bytes. * @param instruction * Instruction file in JSON or null if no instruction file is involved * @return * The S3Object with adjusted object contents containing only the range desired by the user. * If the range specified is invalid, then the S3Object is returned without any modifications. */ protected final S3ObjectWrapper adjustToDesiredRange(S3ObjectWrapper s3object, long[] range, Map<String,String> instruction) { if (range == null) return s3object; // Figure out the original encryption scheme used, which can be // different from the crypto scheme used for decryption. ContentCryptoScheme encryptionScheme = s3object.encryptionSchemeOf(instruction); // range get on data encrypted using AES_GCM final long instanceLen = s3object.getObjectMetadata().getInstanceLength(); final long maxOffset = instanceLen - encryptionScheme.getTagLengthInBits() / 8 - 1; if (range[1] > maxOffset) { range[1] = maxOffset; if (range[0] > range[1]) { // Return empty content // First let's close the existing input stream to avoid resource // leakage closeQuietly(s3object.getObjectContent(), log); s3object.setObjectContent(new ByteArrayInputStream(new byte[0])); return s3object; } } if (range[0] > range[1]) { // Make no modifications if range is invalid. return s3object; } try { S3ObjectInputStream objectContent = s3object.getObjectContent(); InputStream adjustedRangeContents = new AdjustedRangeInputStream(objectContent, range[0], range[1]); s3object.setObjectContent(new S3ObjectInputStream(adjustedRangeContents, objectContent.getHttpRequest())); return s3object; } catch (IOException e) { throw new SdkClientException("Error adjusting output to desired byte range: " + e.getMessage()); } } @Override public ObjectMetadata getObjectSecurely(GetObjectRequest getObjectRequest, File destinationFile) { assertParameterNotNull(destinationFile, "The destination file parameter must be specified when downloading an object directly to a file"); S3Object s3Object = getObjectSecurely(getObjectRequest); // getObject can return null if constraints were specified but not met if (s3Object == null) return null; OutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(destinationFile)); byte[] buffer = new byte[1024*10]; int bytesRead; while ((bytesRead = s3Object.getObjectContent().read(buffer)) > -1) { outputStream.write(buffer, 0, bytesRead); } } catch (IOException e) { throw new SdkClientException( "Unable to store object contents to disk: " + e.getMessage(), e); } finally { closeQuietly(outputStream, log); closeQuietly(s3Object.getObjectContent(), log); } /* * Unlike the standard Amazon S3 Client, the Amazon S3 Encryption Client does not do an MD5 check * here because the contents stored in S3 and the contents we just retrieved are different. In * S3, the stored contents are encrypted, and locally, the retrieved contents are decrypted. */ return s3Object.getObjectMetadata(); } @Override final MultipartUploadCryptoContext newUploadContext( InitiateMultipartUploadRequest req, ContentCryptoMaterial cekMaterial) { return new MultipartUploadCryptoContext( req.getBucketName(), req.getKey(), cekMaterial); } //// specific overrides for uploading parts. @Override final CipherLite cipherLiteForNextPart( MultipartUploadCryptoContext uploadContext) { return uploadContext.getCipherLite(); } @Override final SdkFilterInputStream wrapForMultipart( CipherLiteInputStream is, long partSize) { return is; } @Override final long computeLastPartSize(UploadPartRequest req) { return req.getPartSize() + (contentCryptoScheme.getTagLengthInBits() / 8); } @Override final void updateUploadContext(MultipartUploadCryptoContext uploadContext, SdkFilterInputStream is) { } /* * Private helper methods */ /** * Returns an updated object where the object content input stream contains the decrypted contents. * * @param wrapper * The object whose contents are to be decrypted. * @param cekMaterial * The instruction that will be used to decrypt the object data. * @return * The updated object where the object content input stream contains the decrypted contents. */ private S3ObjectWrapper decrypt(S3ObjectWrapper wrapper, ContentCryptoMaterial cekMaterial, long[] range) { S3ObjectInputStream objectContent = wrapper.getObjectContent(); wrapper.setObjectContent(new S3ObjectInputStream( new CipherLiteInputStream(objectContent, cekMaterial.getCipherLite(), DEFAULT_BUFFER_SIZE), objectContent.getHttpRequest())); return wrapper; } /** * Asserts that the specified parameter value is not null and if it is, * throws an IllegalArgumentException with the specified error message. * * @param parameterValue * The parameter value being checked. * @param errorMessage * The error message to include in the IllegalArgumentException * if the specified parameter is null. */ private void assertParameterNotNull(Object parameterValue, String errorMessage) { if (parameterValue == null) throw new IllegalArgumentException(errorMessage); } @Override protected final long ciphertextLength(long originalContentLength) { // Add 16 bytes for the 128-bit tag length using AES/GCM return originalContentLength + contentCryptoScheme.getTagLengthInBits()/8; } private void assertCanGetPartialObject() { if (!isRangeGetEnabled()) { String msg = "Unable to perform range get request: Range get support has been disabled. " + "See https://docs.aws.amazon.com/general/latest/gr/aws_sdk_cryptography.html"; throw new SecurityException(msg); } } protected boolean isRangeGetEnabled() { CryptoRangeGetMode rangeGetMode = cryptoConfig.getRangeGetMode(); switch (rangeGetMode) { case ALL: return true; case DISABLED: default: return false; } } }
Exnadella/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/v2/S3CryptoModuleAE.java
5,150
/* * Private helper methods */
block_comment
nl
/* * Copyright 2013-2024 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.s3.internal.crypto.v2; import static com.amazonaws.services.s3.model.CryptoMode.AuthenticatedEncryption; import static com.amazonaws.services.s3.model.CryptoMode.StrictAuthenticatedEncryption; import static com.amazonaws.services.s3.model.ExtraMaterialsDescription.NONE; import static com.amazonaws.util.IOUtils.closeQuietly; import com.amazonaws.services.s3.model.CryptoRangeGetMode; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Collections; import java.util.Map; import com.amazonaws.SdkClientException; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.internal.SdkFilterInputStream; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.s3.internal.S3Direct; import com.amazonaws.services.s3.internal.crypto.AdjustedRangeInputStream; import com.amazonaws.services.s3.internal.crypto.CipherLite; import com.amazonaws.services.s3.internal.crypto.CipherLiteInputStream; import com.amazonaws.services.s3.internal.crypto.ContentCryptoScheme; import com.amazonaws.services.s3.internal.crypto.CryptoRuntime; import com.amazonaws.services.s3.model.CryptoConfigurationV2; import com.amazonaws.services.s3.model.CryptoMode; import com.amazonaws.services.s3.model.EncryptedGetObjectRequest; import com.amazonaws.services.s3.model.EncryptionMaterialsProvider; import com.amazonaws.services.s3.model.ExtraMaterialsDescription; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectId; import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.util.json.Jackson; /** * Authenticated encryption (AE) cryptographic module for the S3 encryption client. */ public class S3CryptoModuleAE extends S3CryptoModuleBase<MultipartUploadCryptoContext> { static { // Enable bouncy castle if available CryptoRuntime.enableBouncyCastle(); } /** * @param cryptoConfig a read-only copy of the crypto configuration. */ public S3CryptoModuleAE(AWSKMS kms, S3Direct s3, AWSCredentialsProvider credentialsProvider, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfigurationV2 cryptoConfig) { super(kms, s3, encryptionMaterialsProvider, cryptoConfig); CryptoMode mode = cryptoConfig.getCryptoMode(); if (mode != StrictAuthenticatedEncryption && mode != AuthenticatedEncryption) { throw new IllegalArgumentException(); } } /** * Used for testing purposes only. */ S3CryptoModuleAE(S3Direct s3, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfigurationV2 cryptoConfig) { this(null, s3, new DefaultAWSCredentialsProviderChain(), encryptionMaterialsProvider, cryptoConfig); } /** * Used for testing purposes only. */ S3CryptoModuleAE(AWSKMS kms, S3Direct s3, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfigurationV2 cryptoConfig) { this(kms, s3, new DefaultAWSCredentialsProviderChain(), encryptionMaterialsProvider, cryptoConfig); } /** * Returns true if a strict encryption mode is in use in the current crypto * module; false otherwise. */ protected boolean isStrict() { return false; } @Override public S3Object getObjectSecurely(GetObjectRequest req) { // Adjust the crypto range to retrieve all of the cipher blocks needed to contain the user's desired // range of bytes. long[] desiredRange = req.getRange(); boolean isPartialObject = desiredRange != null || req.getPartNumber() != null; if (isPartialObject) { assertCanGetPartialObject(); } long[] adjustedCryptoRange = getAdjustedCryptoRange(desiredRange); if (adjustedCryptoRange != null) req.setRange(adjustedCryptoRange[0], adjustedCryptoRange[1]); // Get the object from S3 S3Object retrieved = s3.getObject(req); // If the caller has specified constraints, it's possible that super.getObject(...) // would return null, so we simply return null as well. if (retrieved == null) return null; String suffix = null; if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; suffix = ereq.getInstructionFileSuffix(); } try { return suffix == null || suffix.trim().isEmpty() ? decipher(req, desiredRange, adjustedCryptoRange, retrieved) : decipherWithInstFileSuffix(req, desiredRange, adjustedCryptoRange, retrieved, suffix) ; } catch (RuntimeException ex) { // If we're unable to set up the decryption, make sure we close the // HTTP connection closeQuietly(retrieved, log); throw ex; } catch (Error error) { closeQuietly(retrieved, log); throw error; } } private S3Object decipher(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3Object retrieved) { S3ObjectWrapper wrapped = new S3ObjectWrapper(retrieved, req.getS3ObjectId()); // Check if encryption info is in object metadata if (wrapped.hasEncryptionInfo()) return decipherWithMetadata(req, desiredRange, cryptoRange, wrapped); // Check if encrypted info is in an instruction file S3ObjectWrapper ifile = fetchInstructionFile(req.getS3ObjectId(), null); if (ifile != null) { try { return decipherWithInstructionFile(req, desiredRange, cryptoRange, wrapped, ifile); } finally { closeQuietly(ifile, log); } } if (isStrict()) { closeQuietly(wrapped, log); throw new SecurityException("Unencrypted object found, cannot be decrypted in mode " + StrictAuthenticatedEncryption + "; bucket name: " + retrieved.getBucketName() + ", key: " + retrieved.getKey()); } if (cryptoConfig.isUnsafeUndecryptableObjectPassthrough()) { log.warn(String.format( "Unable to detect encryption information for object '%s' in bucket '%s'. " + "Returning object without decryption.", retrieved.getKey(), retrieved.getBucketName())); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange(wrapped, desiredRange, null); return adjusted.getS3Object(); } else { closeQuietly(wrapped, log); throw new SecurityException("Instruction file not found for S3 object with bucket name: " + retrieved.getBucketName() + ", key: " + retrieved.getKey()); } } /** * Same as {@link #decipher(GetObjectRequest, long[], long[], S3Object)} * but makes use of an instruction file with the specified suffix. * @param instFileSuffix never null or empty (which is assumed to have been * sanitized upstream.) */ private S3Object decipherWithInstFileSuffix(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3Object retrieved, String instFileSuffix) { final S3ObjectId id = req.getS3ObjectId(); // Check if encrypted info is in an instruction file final S3ObjectWrapper ifile = fetchInstructionFile(id, instFileSuffix); if (ifile == null) { throw new SdkClientException("Instruction file with suffix " + instFileSuffix + " is not found for " + retrieved); } try { return decipherWithInstructionFile(req, desiredRange, cryptoRange, new S3ObjectWrapper(retrieved, id), ifile); } finally { closeQuietly(ifile, log); } } private S3Object decipherWithInstructionFile(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3ObjectWrapper retrieved, S3ObjectWrapper instructionFile) { ExtraMaterialsDescription extraMatDesc = NONE; boolean keyWrapExpected = isStrict(); if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; extraMatDesc = ereq.getExtraMaterialDescription(); if (!keyWrapExpected) keyWrapExpected = ereq.isKeyWrapExpected(); } String json = instructionFile.toJsonString(); Map<String, String> matdesc = Collections.unmodifiableMap(Jackson.stringMapFromJsonString(json)); ContentCryptoMaterial cekMaterial = ContentCryptoMaterial.fromInstructionFile( matdesc, kekMaterialsProvider, cryptoConfig, cryptoRange, // range is sometimes necessary to compute the adjusted IV extraMatDesc, keyWrapExpected, kms ); boolean isRangeGet = desiredRange != null; securityCheck(cekMaterial, retrieved.getS3ObjectId(), isRangeGet); S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange( decrypted, desiredRange, matdesc); return adjusted.getS3Object(); } private S3Object decipherWithMetadata(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3ObjectWrapper retrieved) { ExtraMaterialsDescription extraMatDesc = NONE; boolean keyWrapExpected = isStrict(); if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; extraMatDesc = ereq.getExtraMaterialDescription(); if (!keyWrapExpected) keyWrapExpected = ereq.isKeyWrapExpected(); } ContentCryptoMaterial cekMaterial = ContentCryptoMaterial .fromObjectMetadata(retrieved.getObjectMetadata().getUserMetadata(), kekMaterialsProvider, cryptoConfig, // range is sometimes necessary to compute the adjusted IV cryptoRange, extraMatDesc, keyWrapExpected, kms ); boolean isRangeGet = desiredRange != null; securityCheck(cekMaterial, retrieved.getS3ObjectId(), isRangeGet); S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange( decrypted, desiredRange, null); return adjusted.getS3Object(); } /** * Adjusts the retrieved S3Object so that the object contents contain only the range of bytes * desired by the user. Since encrypted contents can only be retrieved in CIPHER_BLOCK_SIZE * (16 bytes) chunks, the S3Object potentially contains more bytes than desired, so this method * adjusts the contents range. * * @param s3object * The S3Object retrieved from S3 that could possibly contain more bytes than desired * by the user. * @param range * A two-element array of longs corresponding to the start and finish (inclusive) of a desired * range of bytes. * @param instruction * Instruction file in JSON or null if no instruction file is involved * @return * The S3Object with adjusted object contents containing only the range desired by the user. * If the range specified is invalid, then the S3Object is returned without any modifications. */ protected final S3ObjectWrapper adjustToDesiredRange(S3ObjectWrapper s3object, long[] range, Map<String,String> instruction) { if (range == null) return s3object; // Figure out the original encryption scheme used, which can be // different from the crypto scheme used for decryption. ContentCryptoScheme encryptionScheme = s3object.encryptionSchemeOf(instruction); // range get on data encrypted using AES_GCM final long instanceLen = s3object.getObjectMetadata().getInstanceLength(); final long maxOffset = instanceLen - encryptionScheme.getTagLengthInBits() / 8 - 1; if (range[1] > maxOffset) { range[1] = maxOffset; if (range[0] > range[1]) { // Return empty content // First let's close the existing input stream to avoid resource // leakage closeQuietly(s3object.getObjectContent(), log); s3object.setObjectContent(new ByteArrayInputStream(new byte[0])); return s3object; } } if (range[0] > range[1]) { // Make no modifications if range is invalid. return s3object; } try { S3ObjectInputStream objectContent = s3object.getObjectContent(); InputStream adjustedRangeContents = new AdjustedRangeInputStream(objectContent, range[0], range[1]); s3object.setObjectContent(new S3ObjectInputStream(adjustedRangeContents, objectContent.getHttpRequest())); return s3object; } catch (IOException e) { throw new SdkClientException("Error adjusting output to desired byte range: " + e.getMessage()); } } @Override public ObjectMetadata getObjectSecurely(GetObjectRequest getObjectRequest, File destinationFile) { assertParameterNotNull(destinationFile, "The destination file parameter must be specified when downloading an object directly to a file"); S3Object s3Object = getObjectSecurely(getObjectRequest); // getObject can return null if constraints were specified but not met if (s3Object == null) return null; OutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(destinationFile)); byte[] buffer = new byte[1024*10]; int bytesRead; while ((bytesRead = s3Object.getObjectContent().read(buffer)) > -1) { outputStream.write(buffer, 0, bytesRead); } } catch (IOException e) { throw new SdkClientException( "Unable to store object contents to disk: " + e.getMessage(), e); } finally { closeQuietly(outputStream, log); closeQuietly(s3Object.getObjectContent(), log); } /* * Unlike the standard Amazon S3 Client, the Amazon S3 Encryption Client does not do an MD5 check * here because the contents stored in S3 and the contents we just retrieved are different. In * S3, the stored contents are encrypted, and locally, the retrieved contents are decrypted. */ return s3Object.getObjectMetadata(); } @Override final MultipartUploadCryptoContext newUploadContext( InitiateMultipartUploadRequest req, ContentCryptoMaterial cekMaterial) { return new MultipartUploadCryptoContext( req.getBucketName(), req.getKey(), cekMaterial); } //// specific overrides for uploading parts. @Override final CipherLite cipherLiteForNextPart( MultipartUploadCryptoContext uploadContext) { return uploadContext.getCipherLite(); } @Override final SdkFilterInputStream wrapForMultipart( CipherLiteInputStream is, long partSize) { return is; } @Override final long computeLastPartSize(UploadPartRequest req) { return req.getPartSize() + (contentCryptoScheme.getTagLengthInBits() / 8); } @Override final void updateUploadContext(MultipartUploadCryptoContext uploadContext, SdkFilterInputStream is) { } /* * Private helper methods<SUF>*/ /** * Returns an updated object where the object content input stream contains the decrypted contents. * * @param wrapper * The object whose contents are to be decrypted. * @param cekMaterial * The instruction that will be used to decrypt the object data. * @return * The updated object where the object content input stream contains the decrypted contents. */ private S3ObjectWrapper decrypt(S3ObjectWrapper wrapper, ContentCryptoMaterial cekMaterial, long[] range) { S3ObjectInputStream objectContent = wrapper.getObjectContent(); wrapper.setObjectContent(new S3ObjectInputStream( new CipherLiteInputStream(objectContent, cekMaterial.getCipherLite(), DEFAULT_BUFFER_SIZE), objectContent.getHttpRequest())); return wrapper; } /** * Asserts that the specified parameter value is not null and if it is, * throws an IllegalArgumentException with the specified error message. * * @param parameterValue * The parameter value being checked. * @param errorMessage * The error message to include in the IllegalArgumentException * if the specified parameter is null. */ private void assertParameterNotNull(Object parameterValue, String errorMessage) { if (parameterValue == null) throw new IllegalArgumentException(errorMessage); } @Override protected final long ciphertextLength(long originalContentLength) { // Add 16 bytes for the 128-bit tag length using AES/GCM return originalContentLength + contentCryptoScheme.getTagLengthInBits()/8; } private void assertCanGetPartialObject() { if (!isRangeGetEnabled()) { String msg = "Unable to perform range get request: Range get support has been disabled. " + "See https://docs.aws.amazon.com/general/latest/gr/aws_sdk_cryptography.html"; throw new SecurityException(msg); } } protected boolean isRangeGetEnabled() { CryptoRangeGetMode rangeGetMode = cryptoConfig.getRangeGetMode(); switch (rangeGetMode) { case ALL: return true; case DISABLED: default: return false; } } }
84274_6
package flame.effects; import arc.*; import arc.func.*; import arc.graphics.*; import arc.graphics.g2d.*; import arc.math.*; import arc.math.geom.*; import arc.struct.*; import arc.util.*; import arc.util.pooling.*; import arc.util.pooling.Pool.*; import flame.Utils.*; import flame.entities.*; import mindustry.entities.*; import mindustry.gen.*; import mindustry.graphics.*; /** * @author EyeOfDarkness */ public class Disintegration implements Poolable{ float[] xs, ys; int width, height; float drawWidth, drawHeight; TextureRegion region = new TextureRegion(); int uses = 0; public float z = Layer.flyingUnit; public Color drawnColor = Color.white.cpy(), scorchColor = Pal.rubble.cpy(); static Pool<Disintegration> pool = new BasicPool<>(Disintegration::new); static int maxDimension = 64; static Point2 tmpPoint = new Point2(); static FloatSeq fseq = new FloatSeq(); static int[] arr = { 0, 0, 1, 0, 1, 1, 0, 1 }; public Disintegration(){} public static Disintegration generate(TextureRegion region, float x, float y, float rotation, float width, float height, Cons<DisintegrationEntity> cons){ int modW = (int)((5f / 320f) * Math.abs(width / Draw.scl)); int modH = (int)((5f / 320f) * Math.abs(height / Draw.scl)); return generate(region, x, y, rotation, width, height, modW, modH, cons); } public static Disintegration generate(TextureRegion region, float x, float y, float rotation, float width, float height, int iwidth, int iheight, Cons<DisintegrationEntity> cons){ //int modW = (int)((20f / 320f) * Math.abs(width / Draw.scl)); //int modH = (int)((20f / 320f) * Math.abs(height / Draw.scl)); float cos = Mathf.cosDeg(rotation); float sin = Mathf.sinDeg(rotation); Disintegration dis = pool.obtain(); dis.set(iwidth, iheight); //dis.region = region; dis.region.set(region); dis.drawWidth = width; dis.drawHeight = height; dis.uses = 0; int w = dis.width, h = dis.height; for(int ix = 0; ix < w - 1; ix++){ for(int iy = 0; iy < h - 1; iy++){ float ox = 0f, oy = 0f; for(int i = 0; i < 8; i += 2){ int bx = ix + arr[i]; int by = iy + arr[i + 1]; int pos = dis.toPos(bx, by); ox += dis.xs[pos]; oy += dis.ys[pos]; } ox /= 4f; oy /= 4f; float rx = (ox - 0.5f) * width; float ry = (oy - 0.5f) * height; float wx = (rx * cos - ry * sin) + x; float wy = (rx * sin + ry * cos) + y; DisintegrationEntity de = DisintegrationEntity.create(); de.source = dis; de.x = wx; de.y = wy; de.rotation = rotation; de.idx = dis.toPos(ix, iy); de.offsetX = ox; de.offsetY = oy; de.lifetime = 6f * 60f; cons.get(de); de.add(); dis.uses++; } } return dis; } public void set(int width, int height){ width = Mathf.clamp(width, 3, maxDimension); height = Mathf.clamp(height, 3, maxDimension); int size = width * height; this.width = width; this.height = height; if(xs == null || xs.length != size) xs = new float[size]; if(ys == null || ys.length != size) ys = new float[size]; for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ float fx = x / (width - 1f); float fy = y / (height - 1f); int idx = x + y * width; if(x > 0 && x < (width - 1)){ fx += Mathf.range(0.1f, 0.4f) / (width - 1f); } if(y > 0 && y < (height - 1)){ fy += Mathf.range(0.1f, 0.4f) / (height - 1f); } xs[idx] = fx; ys[idx] = fy; } } } Point2 getPos(int pos){ tmpPoint.x = pos % width; tmpPoint.y = pos / width; return tmpPoint; } int toPos(int x, int y){ return x + y * width; } @Override public void reset(){ //xs = ys = null; width = height = 0; drawWidth = drawHeight = 0f; drawnColor.set(Color.white); scorchColor.set(Pal.rubble); //region = Core.atlas.white(); region.set(Core.atlas.white()); uses = 0; z = Layer.flyingUnit; } public static class DisintegrationEntity extends DrawEntity implements Poolable, Sized{ public Disintegration source; int idx = 0; float rotation = 0f; float offsetX, offsetY; public float vx, vy, vr, drag = 0.05f; public float time, lifetime; public float zOverride = -1f; public boolean disintegrating = false; static DisintegrationEntity create(){ return Pools.obtain(DisintegrationEntity.class, DisintegrationEntity::new); } public float getSize(){ return Math.max(source.drawWidth / (source.width - 1), source.drawHeight / (source.height - 1)) / 2f; } @Override public void update(){ x += vx * Time.delta; y += vy * Time.delta; rotation += vr * Time.delta; float dt = 1f - drag * Time.delta; vx *= dt; vy *= dt; //vr *= dt; if((time += Time.delta) >= lifetime){ remove(); } } @Override public float hitSize(){ return Math.min(Math.abs(source.drawWidth) / source.width, Math.abs(source.drawHeight) / source.height); } @Override public void draw(){ float cos = Mathf.cosDeg(rotation); float sin = Mathf.sinDeg(rotation); TextureRegion region = source.region; float[] xs = source.xs, ys = source.ys; float scl = 1f; Point2 pos = source.getPos(idx); if(disintegrating){ Tmp.c1.set(source.drawnColor).lerp(source.scorchColor, Mathf.curve(time / lifetime, 0f, 0.75f)); scl = Interp.pow5Out.apply(1f - Mathf.clamp(time / lifetime)); }else{ Tmp.c1.set(source.drawnColor).a(1f - Mathf.curve(time / lifetime, 0.7f, 1f)); } float color = Tmp.c1.toFloatBits(); float mcolr = Color.clearFloatBits; fseq.clear(); for(int i = 0; i < 8; i += 2){ int sx = pos.x + arr[i]; int sy = pos.y + arr[i + 1]; int ps = source.toPos(sx, sy); float fx = xs[ps]; float fy = ys[ps]; float ox = (fx - offsetX) * source.drawWidth * scl; float oy = (fy - offsetY) * source.drawHeight * scl; float tx = (ox * cos - oy * sin) + x; float ty = (ox * sin + oy * cos) + y; float u = Mathf.lerp(region.u, region.u2, xs[ps]); float v = Mathf.lerp(region.v2, region.v, ys[ps]); fseq.addAll(tx, ty, color, u, v, mcolr); } Draw.z(zOverride != -1f ? zOverride : source.z); Draw.vert(region.texture, fseq.items, 0, fseq.size); } @Override public void reset(){ idx = 0; time = 0f; lifetime = 0f; vx = vy = vr = 0f; zOverride = -1f; drag = 0.05f; source = null; disintegrating = false; } @Override protected void removeGroup(){ super.removeGroup(); Groups.queueFree(this); source.uses--; if(source.uses <= 0){ idx = -1; pool.free(source); } } } }
EyeOfDarkness/FlameOut
src/flame/effects/Disintegration.java
2,643
//vr *= dt;
line_comment
nl
package flame.effects; import arc.*; import arc.func.*; import arc.graphics.*; import arc.graphics.g2d.*; import arc.math.*; import arc.math.geom.*; import arc.struct.*; import arc.util.*; import arc.util.pooling.*; import arc.util.pooling.Pool.*; import flame.Utils.*; import flame.entities.*; import mindustry.entities.*; import mindustry.gen.*; import mindustry.graphics.*; /** * @author EyeOfDarkness */ public class Disintegration implements Poolable{ float[] xs, ys; int width, height; float drawWidth, drawHeight; TextureRegion region = new TextureRegion(); int uses = 0; public float z = Layer.flyingUnit; public Color drawnColor = Color.white.cpy(), scorchColor = Pal.rubble.cpy(); static Pool<Disintegration> pool = new BasicPool<>(Disintegration::new); static int maxDimension = 64; static Point2 tmpPoint = new Point2(); static FloatSeq fseq = new FloatSeq(); static int[] arr = { 0, 0, 1, 0, 1, 1, 0, 1 }; public Disintegration(){} public static Disintegration generate(TextureRegion region, float x, float y, float rotation, float width, float height, Cons<DisintegrationEntity> cons){ int modW = (int)((5f / 320f) * Math.abs(width / Draw.scl)); int modH = (int)((5f / 320f) * Math.abs(height / Draw.scl)); return generate(region, x, y, rotation, width, height, modW, modH, cons); } public static Disintegration generate(TextureRegion region, float x, float y, float rotation, float width, float height, int iwidth, int iheight, Cons<DisintegrationEntity> cons){ //int modW = (int)((20f / 320f) * Math.abs(width / Draw.scl)); //int modH = (int)((20f / 320f) * Math.abs(height / Draw.scl)); float cos = Mathf.cosDeg(rotation); float sin = Mathf.sinDeg(rotation); Disintegration dis = pool.obtain(); dis.set(iwidth, iheight); //dis.region = region; dis.region.set(region); dis.drawWidth = width; dis.drawHeight = height; dis.uses = 0; int w = dis.width, h = dis.height; for(int ix = 0; ix < w - 1; ix++){ for(int iy = 0; iy < h - 1; iy++){ float ox = 0f, oy = 0f; for(int i = 0; i < 8; i += 2){ int bx = ix + arr[i]; int by = iy + arr[i + 1]; int pos = dis.toPos(bx, by); ox += dis.xs[pos]; oy += dis.ys[pos]; } ox /= 4f; oy /= 4f; float rx = (ox - 0.5f) * width; float ry = (oy - 0.5f) * height; float wx = (rx * cos - ry * sin) + x; float wy = (rx * sin + ry * cos) + y; DisintegrationEntity de = DisintegrationEntity.create(); de.source = dis; de.x = wx; de.y = wy; de.rotation = rotation; de.idx = dis.toPos(ix, iy); de.offsetX = ox; de.offsetY = oy; de.lifetime = 6f * 60f; cons.get(de); de.add(); dis.uses++; } } return dis; } public void set(int width, int height){ width = Mathf.clamp(width, 3, maxDimension); height = Mathf.clamp(height, 3, maxDimension); int size = width * height; this.width = width; this.height = height; if(xs == null || xs.length != size) xs = new float[size]; if(ys == null || ys.length != size) ys = new float[size]; for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ float fx = x / (width - 1f); float fy = y / (height - 1f); int idx = x + y * width; if(x > 0 && x < (width - 1)){ fx += Mathf.range(0.1f, 0.4f) / (width - 1f); } if(y > 0 && y < (height - 1)){ fy += Mathf.range(0.1f, 0.4f) / (height - 1f); } xs[idx] = fx; ys[idx] = fy; } } } Point2 getPos(int pos){ tmpPoint.x = pos % width; tmpPoint.y = pos / width; return tmpPoint; } int toPos(int x, int y){ return x + y * width; } @Override public void reset(){ //xs = ys = null; width = height = 0; drawWidth = drawHeight = 0f; drawnColor.set(Color.white); scorchColor.set(Pal.rubble); //region = Core.atlas.white(); region.set(Core.atlas.white()); uses = 0; z = Layer.flyingUnit; } public static class DisintegrationEntity extends DrawEntity implements Poolable, Sized{ public Disintegration source; int idx = 0; float rotation = 0f; float offsetX, offsetY; public float vx, vy, vr, drag = 0.05f; public float time, lifetime; public float zOverride = -1f; public boolean disintegrating = false; static DisintegrationEntity create(){ return Pools.obtain(DisintegrationEntity.class, DisintegrationEntity::new); } public float getSize(){ return Math.max(source.drawWidth / (source.width - 1), source.drawHeight / (source.height - 1)) / 2f; } @Override public void update(){ x += vx * Time.delta; y += vy * Time.delta; rotation += vr * Time.delta; float dt = 1f - drag * Time.delta; vx *= dt; vy *= dt; //vr *=<SUF> if((time += Time.delta) >= lifetime){ remove(); } } @Override public float hitSize(){ return Math.min(Math.abs(source.drawWidth) / source.width, Math.abs(source.drawHeight) / source.height); } @Override public void draw(){ float cos = Mathf.cosDeg(rotation); float sin = Mathf.sinDeg(rotation); TextureRegion region = source.region; float[] xs = source.xs, ys = source.ys; float scl = 1f; Point2 pos = source.getPos(idx); if(disintegrating){ Tmp.c1.set(source.drawnColor).lerp(source.scorchColor, Mathf.curve(time / lifetime, 0f, 0.75f)); scl = Interp.pow5Out.apply(1f - Mathf.clamp(time / lifetime)); }else{ Tmp.c1.set(source.drawnColor).a(1f - Mathf.curve(time / lifetime, 0.7f, 1f)); } float color = Tmp.c1.toFloatBits(); float mcolr = Color.clearFloatBits; fseq.clear(); for(int i = 0; i < 8; i += 2){ int sx = pos.x + arr[i]; int sy = pos.y + arr[i + 1]; int ps = source.toPos(sx, sy); float fx = xs[ps]; float fy = ys[ps]; float ox = (fx - offsetX) * source.drawWidth * scl; float oy = (fy - offsetY) * source.drawHeight * scl; float tx = (ox * cos - oy * sin) + x; float ty = (ox * sin + oy * cos) + y; float u = Mathf.lerp(region.u, region.u2, xs[ps]); float v = Mathf.lerp(region.v2, region.v, ys[ps]); fseq.addAll(tx, ty, color, u, v, mcolr); } Draw.z(zOverride != -1f ? zOverride : source.z); Draw.vert(region.texture, fseq.items, 0, fseq.size); } @Override public void reset(){ idx = 0; time = 0f; lifetime = 0f; vx = vy = vr = 0f; zOverride = -1f; drag = 0.05f; source = null; disintegrating = false; } @Override protected void removeGroup(){ super.removeGroup(); Groups.queueFree(this); source.uses--; if(source.uses <= 0){ idx = -1; pool.free(source); } } } }
36373_12
/* * Copyright (c) 2002-2008 LWJGL Project * 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 'LWJGL' nor the names of * its 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. */ /* * Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. * All rights reserved. */ /* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** http://oss.sgi.com/projects/FreeB ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** NOTE: The Original Code (as defined below) has been licensed to Sun ** Microsystems, Inc. ("Sun") under the SGI Free Software License B ** (Version 1.1), shown above ("SGI License"). Pursuant to Section ** 3.2(3) of the SGI License, Sun is distributing the Covered Code to ** you under an alternative license ("Alternative License"). This ** Alternative License includes all of the provisions of the SGI License ** except that Section 2.2 and 11 are omitted. Any differences between ** the Alternative License and the SGI License are offered solely by Sun ** and not by SGI. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: The application programming interfaces ** established by SGI in conjunction with the Original Code are The ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X ** Window System(R) (Version 1.3), released October 19, 1998. This software ** was created using the OpenGL(R) version 1.2.1 Sample Implementation ** published by SGI, but has not been independently verified as being ** compliant with the OpenGL(R) version 1.2.1 Specification. ** ** Author: Eric Veach, July 1994 ** Java Port: Pepijn Van Eeckhoudt, July 2003 ** Java Port: Nathan Parker Burg, August 2003 */ package org.lwjgl.util.glu.tessellation; class Geom { private Geom() { } /* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w), * evaluates the t-coord of the edge uw at the s-coord of the vertex v. * Returns v->t - (uw)(v->s), ie. the signed distance from uw to v. * If uw is vertical (and thus passes thru v), the result is zero. * * The calculation is extremely accurate and stable, even when v * is very close to u or w. In particular if we set v->t = 0 and * let r be the negated result (this evaluates (uw)(v->s)), then * r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t). */ static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) { double gapL, gapR; assert (VertLeq(u, v) && VertLeq(v, w)); gapL = v.s - u.s; gapR = w.s - v.s; if (gapL + gapR > 0) { if (gapL < gapR) { return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR)); } else { return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR)); } } /* vertical line */ return 0; } static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) { double gapL, gapR; assert (VertLeq(u, v) && VertLeq(v, w)); gapL = v.s - u.s; gapR = w.s - v.s; if (gapL + gapR > 0) { return (v.t - w.t) * gapL + (v.t - u.t) * gapR; } /* vertical line */ return 0; } /*********************************************************************** * Define versions of EdgeSign, EdgeEval with s and t transposed. */ static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) { /* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w), * evaluates the t-coord of the edge uw at the s-coord of the vertex v. * Returns v->s - (uw)(v->t), ie. the signed distance from uw to v. * If uw is vertical (and thus passes thru v), the result is zero. * * The calculation is extremely accurate and stable, even when v * is very close to u or w. In particular if we set v->s = 0 and * let r be the negated result (this evaluates (uw)(v->t)), then * r is guaranteed to satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s). */ double gapL, gapR; assert (TransLeq(u, v) && TransLeq(v, w)); gapL = v.t - u.t; gapR = w.t - v.t; if (gapL + gapR > 0) { if (gapL < gapR) { return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR)); } else { return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR)); } } /* vertical line */ return 0; } static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) { /* Returns a number whose sign matches TransEval(u,v,w) but which * is cheaper to evaluate. Returns > 0, == 0 , or < 0 * as v is above, on, or below the edge uw. */ double gapL, gapR; assert (TransLeq(u, v) && TransLeq(v, w)); gapL = v.t - u.t; gapR = w.t - v.t; if (gapL + gapR > 0) { return (v.s - w.s) * gapL + (v.s - u.s) * gapR; } /* vertical line */ return 0; } static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) { /* For almost-degenerate situations, the results are not reliable. * Unless the floating-point arithmetic can be performed without * rounding errors, *any* implementation will give incorrect results * on some degenerate inputs, so the client must have some way to * handle this situation. */ return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0; } /* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b), * or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces * this in the rare case that one argument is slightly negative. * The implementation is extremely stable numerically. * In particular it guarantees that the result r satisfies * MIN(x,y) <= r <= MAX(x,y), and the results are very accurate * even when a and b differ greatly in magnitude. */ static double Interpolate(double a, double x, double b, double y) { a = (a < 0) ? 0 : a; b = (b < 0) ? 0 : b; if (a <= b) { if (b == 0) { return (x + y) / 2.0; } else { return (x + (y - x) * (a / (a + b))); } } else { return (y + (x - y) * (b / (a + b))); } } static void EdgeIntersect(GLUvertex o1, GLUvertex d1, GLUvertex o2, GLUvertex d2, GLUvertex v) /* Given edges (o1,d1) and (o2,d2), compute their point of intersection. * The computed point is guaranteed to lie in the intersection of the * bounding rectangles defined by each edge. */ { double z1, z2; /* This is certainly not the most efficient way to find the intersection * of two line segments, but it is very numerically stable. * * Strategy: find the two middle vertices in the VertLeq ordering, * and interpolate the intersection s-value from these. Then repeat * using the TransLeq ordering to find the intersection t-value. */ if (!VertLeq(o1, d1)) { GLUvertex temp = o1; o1 = d1; d1 = temp; } if (!VertLeq(o2, d2)) { GLUvertex temp = o2; o2 = d2; d2 = temp; } if (!VertLeq(o1, o2)) { GLUvertex temp = o1; o1 = o2; o2 = temp; temp = d1; d1 = d2; d2 = temp; } if (!VertLeq(o2, d1)) { /* Technically, no intersection -- do our best */ v.s = (o2.s + d1.s) / 2.0; } else if (VertLeq(d1, d2)) { /* Interpolate between o2 and d1 */ z1 = EdgeEval(o1, o2, d1); z2 = EdgeEval(o2, d1, d2); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.s = Interpolate(z1, o2.s, z2, d1.s); } else { /* Interpolate between o2 and d2 */ z1 = EdgeSign(o1, o2, d1); z2 = -EdgeSign(o1, d2, d1); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.s = Interpolate(z1, o2.s, z2, d2.s); } /* Now repeat the process for t */ if (!TransLeq(o1, d1)) { GLUvertex temp = o1; o1 = d1; d1 = temp; } if (!TransLeq(o2, d2)) { GLUvertex temp = o2; o2 = d2; d2 = temp; } if (!TransLeq(o1, o2)) { GLUvertex temp = o2; o2 = o1; o1 = temp; temp = d2; d2 = d1; d1 = temp; } if (!TransLeq(o2, d1)) { /* Technically, no intersection -- do our best */ v.t = (o2.t + d1.t) / 2.0; } else if (TransLeq(d1, d2)) { /* Interpolate between o2 and d1 */ z1 = TransEval(o1, o2, d1); z2 = TransEval(o2, d1, d2); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.t = Interpolate(z1, o2.t, z2, d1.t); } else { /* Interpolate between o2 and d2 */ z1 = TransSign(o1, o2, d1); z2 = -TransSign(o1, d2, d1); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.t = Interpolate(z1, o2.t, z2, d2.t); } } static boolean VertEq(GLUvertex u, GLUvertex v) { return u.s == v.s && u.t == v.t; } static boolean VertLeq(GLUvertex u, GLUvertex v) { return u.s < v.s || (u.s == v.s && u.t <= v.t); } /* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */ static boolean TransLeq(GLUvertex u, GLUvertex v) { return u.t < v.t || (u.t == v.t && u.s <= v.s); } static boolean EdgeGoesLeft(GLUhalfEdge e) { return VertLeq(e.Sym.Org, e.Org); } static boolean EdgeGoesRight(GLUhalfEdge e) { return VertLeq(e.Org, e.Sym.Org); } static double VertL1dist(GLUvertex u, GLUvertex v) { return Math.abs(u.s - v.s) + Math.abs(u.t - v.t); } }
FCL-Team/FoldCraftLauncher
LWJGL/src/main/java/org/lwjgl/util/glu/tessellation/Geom.java
4,277
/* Interpolate between o2 and d1 */
block_comment
nl
/* * Copyright (c) 2002-2008 LWJGL Project * 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 'LWJGL' nor the names of * its 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. */ /* * Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. * All rights reserved. */ /* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** http://oss.sgi.com/projects/FreeB ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** NOTE: The Original Code (as defined below) has been licensed to Sun ** Microsystems, Inc. ("Sun") under the SGI Free Software License B ** (Version 1.1), shown above ("SGI License"). Pursuant to Section ** 3.2(3) of the SGI License, Sun is distributing the Covered Code to ** you under an alternative license ("Alternative License"). This ** Alternative License includes all of the provisions of the SGI License ** except that Section 2.2 and 11 are omitted. Any differences between ** the Alternative License and the SGI License are offered solely by Sun ** and not by SGI. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: The application programming interfaces ** established by SGI in conjunction with the Original Code are The ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X ** Window System(R) (Version 1.3), released October 19, 1998. This software ** was created using the OpenGL(R) version 1.2.1 Sample Implementation ** published by SGI, but has not been independently verified as being ** compliant with the OpenGL(R) version 1.2.1 Specification. ** ** Author: Eric Veach, July 1994 ** Java Port: Pepijn Van Eeckhoudt, July 2003 ** Java Port: Nathan Parker Burg, August 2003 */ package org.lwjgl.util.glu.tessellation; class Geom { private Geom() { } /* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w), * evaluates the t-coord of the edge uw at the s-coord of the vertex v. * Returns v->t - (uw)(v->s), ie. the signed distance from uw to v. * If uw is vertical (and thus passes thru v), the result is zero. * * The calculation is extremely accurate and stable, even when v * is very close to u or w. In particular if we set v->t = 0 and * let r be the negated result (this evaluates (uw)(v->s)), then * r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t). */ static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) { double gapL, gapR; assert (VertLeq(u, v) && VertLeq(v, w)); gapL = v.s - u.s; gapR = w.s - v.s; if (gapL + gapR > 0) { if (gapL < gapR) { return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR)); } else { return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR)); } } /* vertical line */ return 0; } static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) { double gapL, gapR; assert (VertLeq(u, v) && VertLeq(v, w)); gapL = v.s - u.s; gapR = w.s - v.s; if (gapL + gapR > 0) { return (v.t - w.t) * gapL + (v.t - u.t) * gapR; } /* vertical line */ return 0; } /*********************************************************************** * Define versions of EdgeSign, EdgeEval with s and t transposed. */ static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) { /* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w), * evaluates the t-coord of the edge uw at the s-coord of the vertex v. * Returns v->s - (uw)(v->t), ie. the signed distance from uw to v. * If uw is vertical (and thus passes thru v), the result is zero. * * The calculation is extremely accurate and stable, even when v * is very close to u or w. In particular if we set v->s = 0 and * let r be the negated result (this evaluates (uw)(v->t)), then * r is guaranteed to satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s). */ double gapL, gapR; assert (TransLeq(u, v) && TransLeq(v, w)); gapL = v.t - u.t; gapR = w.t - v.t; if (gapL + gapR > 0) { if (gapL < gapR) { return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR)); } else { return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR)); } } /* vertical line */ return 0; } static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) { /* Returns a number whose sign matches TransEval(u,v,w) but which * is cheaper to evaluate. Returns > 0, == 0 , or < 0 * as v is above, on, or below the edge uw. */ double gapL, gapR; assert (TransLeq(u, v) && TransLeq(v, w)); gapL = v.t - u.t; gapR = w.t - v.t; if (gapL + gapR > 0) { return (v.s - w.s) * gapL + (v.s - u.s) * gapR; } /* vertical line */ return 0; } static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) { /* For almost-degenerate situations, the results are not reliable. * Unless the floating-point arithmetic can be performed without * rounding errors, *any* implementation will give incorrect results * on some degenerate inputs, so the client must have some way to * handle this situation. */ return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0; } /* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b), * or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces * this in the rare case that one argument is slightly negative. * The implementation is extremely stable numerically. * In particular it guarantees that the result r satisfies * MIN(x,y) <= r <= MAX(x,y), and the results are very accurate * even when a and b differ greatly in magnitude. */ static double Interpolate(double a, double x, double b, double y) { a = (a < 0) ? 0 : a; b = (b < 0) ? 0 : b; if (a <= b) { if (b == 0) { return (x + y) / 2.0; } else { return (x + (y - x) * (a / (a + b))); } } else { return (y + (x - y) * (b / (a + b))); } } static void EdgeIntersect(GLUvertex o1, GLUvertex d1, GLUvertex o2, GLUvertex d2, GLUvertex v) /* Given edges (o1,d1) and (o2,d2), compute their point of intersection. * The computed point is guaranteed to lie in the intersection of the * bounding rectangles defined by each edge. */ { double z1, z2; /* This is certainly not the most efficient way to find the intersection * of two line segments, but it is very numerically stable. * * Strategy: find the two middle vertices in the VertLeq ordering, * and interpolate the intersection s-value from these. Then repeat * using the TransLeq ordering to find the intersection t-value. */ if (!VertLeq(o1, d1)) { GLUvertex temp = o1; o1 = d1; d1 = temp; } if (!VertLeq(o2, d2)) { GLUvertex temp = o2; o2 = d2; d2 = temp; } if (!VertLeq(o1, o2)) { GLUvertex temp = o1; o1 = o2; o2 = temp; temp = d1; d1 = d2; d2 = temp; } if (!VertLeq(o2, d1)) { /* Technically, no intersection -- do our best */ v.s = (o2.s + d1.s) / 2.0; } else if (VertLeq(d1, d2)) { /* Interpolate between o2<SUF>*/ z1 = EdgeEval(o1, o2, d1); z2 = EdgeEval(o2, d1, d2); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.s = Interpolate(z1, o2.s, z2, d1.s); } else { /* Interpolate between o2 and d2 */ z1 = EdgeSign(o1, o2, d1); z2 = -EdgeSign(o1, d2, d1); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.s = Interpolate(z1, o2.s, z2, d2.s); } /* Now repeat the process for t */ if (!TransLeq(o1, d1)) { GLUvertex temp = o1; o1 = d1; d1 = temp; } if (!TransLeq(o2, d2)) { GLUvertex temp = o2; o2 = d2; d2 = temp; } if (!TransLeq(o1, o2)) { GLUvertex temp = o2; o2 = o1; o1 = temp; temp = d2; d2 = d1; d1 = temp; } if (!TransLeq(o2, d1)) { /* Technically, no intersection -- do our best */ v.t = (o2.t + d1.t) / 2.0; } else if (TransLeq(d1, d2)) { /* Interpolate between o2 and d1 */ z1 = TransEval(o1, o2, d1); z2 = TransEval(o2, d1, d2); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.t = Interpolate(z1, o2.t, z2, d1.t); } else { /* Interpolate between o2 and d2 */ z1 = TransSign(o1, o2, d1); z2 = -TransSign(o1, d2, d1); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.t = Interpolate(z1, o2.t, z2, d2.t); } } static boolean VertEq(GLUvertex u, GLUvertex v) { return u.s == v.s && u.t == v.t; } static boolean VertLeq(GLUvertex u, GLUvertex v) { return u.s < v.s || (u.s == v.s && u.t <= v.t); } /* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */ static boolean TransLeq(GLUvertex u, GLUvertex v) { return u.t < v.t || (u.t == v.t && u.s <= v.s); } static boolean EdgeGoesLeft(GLUhalfEdge e) { return VertLeq(e.Sym.Org, e.Org); } static boolean EdgeGoesRight(GLUhalfEdge e) { return VertLeq(e.Org, e.Sym.Org); } static double VertL1dist(GLUvertex u, GLUvertex v) { return Math.abs(u.s - v.s) + Math.abs(u.t - v.t); } }