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
|
---|---|---|---|---|---|---|---|---|
196611_16 | /*
* L2jOrion Project - www.l2jorion.com
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package l2jorion.game.managers;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Future;
import javolution.util.FastList;
import l2jorion.Config;
import l2jorion.game.datatables.sql.ItemTable;
import l2jorion.game.datatables.sql.NpcTable;
import l2jorion.game.datatables.sql.SpawnTable;
import l2jorion.game.idfactory.IdFactory;
import l2jorion.game.model.L2Attackable;
import l2jorion.game.model.L2Object;
import l2jorion.game.model.L2World;
import l2jorion.game.model.actor.instance.L2ItemInstance;
import l2jorion.game.model.actor.instance.L2NpcInstance;
import l2jorion.game.model.actor.instance.L2PcInstance;
import l2jorion.game.model.entity.Announcements;
import l2jorion.game.model.spawn.L2Spawn;
import l2jorion.game.network.SystemMessageId;
import l2jorion.game.network.serverpackets.CreatureSay;
import l2jorion.game.network.serverpackets.SystemMessage;
import l2jorion.game.templates.L2NpcTemplate;
import l2jorion.game.thread.ThreadPoolManager;
import l2jorion.logger.Logger;
import l2jorion.logger.LoggerFactory;
public class ChristmasManager
{
private static final Logger LOG = LoggerFactory.getLogger(ChristmasManager.class);
protected List<L2NpcInstance> objectQueue = new FastList<>();
protected Random rand = new Random();
// X-Mas message list
protected String[] message =
{
"Ho Ho Ho... Merry Christmas!",
"God is Love...",
"Christmas is all about love...",
"Christmas is thus about God and Love...",
"Love is the key to peace among all Lineage creature kind..",
"Love is the key to peace and happiness within all creation...",
"Love needs to be practiced - Love needs to flow - Love needs to make happy...",
"Love starts with your partner, children and family and expands to all world.",
"God bless all kind.",
"God bless Lineage.",
"Forgive all.",
"Ask for forgiveness even from all the \"past away\" ones.",
"Give love in many different ways to your family members, relatives, neighbors and \"foreigners\".",
"Enhance the feeling within yourself of being a member of a far larger family than your physical family",
"MOST important - Christmas is a feast of BLISS given to YOU from God and all beloved ones back home in God !!",
"Open yourself for all divine bliss, forgiveness and divine help that is offered TO YOU by many others AND GOD.",
"Take it easy. Relax these coming days.",
"Every day is Christmas day - it is UP TO YOU to create the proper inner attitude and opening for love toward others AND from others within YOUR SELF !",
"Peace and Silence. Reduced activities. More time for your most direct families. If possible NO other dates or travel may help you most to actually RECEIVE all offered bliss.",
"What ever is offered to you from God either enters YOUR heart and soul or is LOST for GOOD !!! or at least until another such day - next year Christmas or so !!",
"Divine bliss and love NEVER can be stored and received later.",
"There is year round a huge quantity of love and bliss available from God and your Guru and other loving souls, but Christmas days are an extended period FOR ALL PLANET",
"Please open your heart and accept all love and bliss - For your benefit as well as for the benefit of all your beloved ones.",
"Beloved children of God",
"Beyond Christmas days and beyond Christmas season - The Christmas love lives on, the Christmas bliss goes on, the Christmas feeling expands.",
"The holy spirit of Christmas is the holy spirit of God and God's love for all days.",
"When the Christmas spirit lives on and on...",
"When the power of love created during the pre-Christmas days is kept alive and growing.",
"Peace among all mankind is growing as well =)",
"The holy gift of love is an eternal gift of love put into your heart like a seed.",
"Dozens of millions of humans worldwide are changing in their hearts during weeks of pre-Christmas time and find their peak power of love on Christmas nights and Christmas days.",
"What is special during these days, to give all of you this very special power of love, the power to forgive, the power to make others happy, power to join the loved one on his or her path of loving life.",
"It only is your now decision that makes the difference !",
"It only is your now focus in life that makes all the changes. It is your shift from purely worldly matters toward the power of love from God that dwells within all of us that gave you the power to change your own behavior from your normal year long behavior.",
"The decision of love, peace and happiness is the right one.",
"Whatever you focus on is filling your mind and subsequently filling your heart.",
"No one else but you have change your focus these past Christmas days and the days of love you may have experienced in earlier Christmas seasons.",
"God's love is always present.",
"God's Love has always been in same power and purity and quantity available to all of you.",
"Expand the spirit of Christmas love and Christmas joy to span all year of your life...",
"Do all year long what is creating this special Christmas feeling of love joy and happiness.",
"Expand the true Christmas feeling, expand the love you have ever given at your maximum power of love days ... ",
"Expand the power of love over more and more days.",
"Re-focus on what has brought your love to its peak power and refocus on those objects and actions in your focus of mind and actions.",
"Remember the people and surrounding you had when feeling most happy, most loved, most magic",
"People of true loving spirit - who all was present, recall their names, recall the one who may have had the greatest impact in love those hours of magic moments of love...",
"The decoration of your surrounding - Decoration may help to focus on love - Or lack of decoration may make you drift away into darkness or business - away from love...",
"Love songs, songs full of living joy - any of the thousands of true touching love songs and happy songs do contribute to the establishment of an inner attitude perceptible of love.",
"Songs can fine tune and open our heart for love from God and our loved ones.",
"Your power of will and focus of mind can keep Christmas Love and Christmas joy alive beyond Christmas season for eternity",
"Enjoy your love for ever!",
"Christmas can be every day - As soon as you truly love every day =)",
"Christmas is when you love all and are loved by all.",
"Christmas is when you are truly happy by creating true happiness in others with love from the bottom of your heart.",
"Secret in God's creation is that no single person can truly love without ignition of his love.",
"You need another person to love and to receive love, a person to truly fall in love to ignite your own divine fire of love. ",
"God created many and all are made of love and all are made to love...",
"The miracle of love only works if you want to become a fully loving member of the family of divine love.",
"Once you have started to fall in love with the one God created for you - your entire eternal life will be a permanent fire of miracles of love ... Eternally !",
"May all have a happy time on Christmas each year. Merry Christmas!",
"Christmas day is a time for love. It is a time for showing our affection to our loved ones. It is all about love.",
"Have a wonderful Christmas. May god bless our family. I love you all.",
"Wish all living creatures a Happy X-mas and a Happy New Year! By the way I would like us to share a warm fellowship in all places.",
"Just as animals need peace of mind, poeple and also trees need peace of mind. This is why I say, all creatures are waiting upon the Lord for their salvation. May God bless you all creatures in the whole world.",
"Merry Xmas!",
"May the grace of Our Mighty Father be with you all during this eve of Christmas. Have a blessed Christmas and a happy New Year.",
"Merry Christmas my children. May this new year give all of the things you rightly deserve. And may peace finally be yours.",
"I wish everybody a Merry Christmas! May the Holy Spirit be with you all the time.",
"May you have the best of Christmas this year and all your dreams come true.",
"May the miracle of Christmas fill your heart with warmth and love. Merry Christmas!"
},
sender =
{
"Santa Claus",
"Papai Noel",
"Shengdan Laoren",
"Santa",
"Viejo Pascuero",
"Sinter Klaas",
"Father Christmas",
"Saint Nicholas",
"Joulupukki",
"Pere Noel",
"Saint Nikolaus",
"Kanakaloka",
"De Kerstman",
"Winter grandfather",
"Babbo Natale",
"Hoteiosho",
"Kaledu Senelis",
"Black Peter",
"Kerstman",
"Julenissen",
"Swiety Mikolaj",
"Ded Moroz",
"Julenisse",
"El Nino Jesus",
"Jultomten",
"Reindeer Dasher",
"Reindeer Dancer",
"Christmas Spirit",
"Reindeer Prancer",
"Reindeer Vixen",
"Reindeer Comet",
"Reindeer Cupid",
"Reindeer Donner",
"Reindeer Donder",
"Reindeer Dunder",
"Reindeer Blitzen",
"Reindeer Bliksem",
"Reindeer Blixem",
"Reindeer Rudolf",
"Christmas Elf"
};
// Presents List:
protected int[] presents =
{
5560,
5560,
5560,
5560,
5560, /* x-mas tree */
5560,
5560,
5560,
5560,
5560,
5561,
5561,
5561,
5561,
5561, /* special x-mas tree */
5562,
5562,
5562,
5562, /* 1st Carol */
5563,
5563,
5563,
5563, /* 2nd Carol */
5564,
5564,
5564,
5564, /* 3rd Carol */
5565,
5565,
5565,
5565, /* 4th Carol */
5566,
5566,
5566,
5566, /* 5th Carol */
5583,
5583, /* 6th Carol */
5584,
5584, /* 7th Carol */
5585,
5585, /* 8th Carol */
5586,
5586, /* 9th Carol */
5587,
5587, /* 10th Carol */
6403,
6403,
6403,
6403, /* Star Shard */
6403,
6403,
6403,
6403,
6406,
6406,
6406,
6406, /* FireWorks */
6407,
6407, /* Large FireWorks */
5555, /* Token of Love */
7836, /* Santa Hat #1 */
9138, /* Santa Hat #2 */
8936, /* Santa's Antlers Hat */
6394, /* Red Party Mask */
5808
/* Black Party Mask */
};
// The message task sent at fixed rate
protected Future<?> _XMasMessageTask = null, _XMasPresentsTask = null;
// Manager should only be Initialized once:
protected int isManagerInit = 0;
// Interval of Christmas actions:
protected long _IntervalOfChristmas = 600000; // 10 minutes
private final int first = 25000, last = 73099;
/************************************** Initial Functions **************************************/
/**
* Empty constructor Does nothing
*/
public ChristmasManager()
{
//
}
/**
* @return an instance of <b>this</b> InstanceManager.
*/
public static ChristmasManager getInstance()
{
return SingletonHolder._instance;
}
/**
* initialize <b>this</b> ChristmasManager
* @param activeChar
*/
public void init(final L2PcInstance activeChar)
{
if (isManagerInit > 0)
{
activeChar.sendMessage("Christmas Manager has already begun or is processing. Please be patient....");
return;
}
activeChar.sendMessage("Started!!!! This will take a 2-3 hours (in order to reduce system lags to a minimum), please be patient... The process is working in the background and will spawn npcs, give presents and messages at a fixed rate.");
// Tasks:
spawnTrees();
startFestiveMessagesAtFixedRate();
isManagerInit++;
givePresentsAtFixedRate();
isManagerInit++;
checkIfOkToAnnounce();
}
/**
* ends <b>this</b> ChristmasManager
* @param activeChar
*/
public void end(final L2PcInstance activeChar)
{
if (isManagerInit < 4)
{
if (activeChar != null)
{
activeChar.sendMessage("Christmas Manager is not activated yet. Already Ended or is now processing....");
}
return;
}
if (activeChar != null)
{
activeChar.sendMessage("Terminating! This may take a while, please be patient...");
}
// Tasks:
ThreadPoolManager.getInstance().executeTask(new DeleteSpawns());
endFestiveMessagesAtFixedRate();
isManagerInit--;
endPresentGivingAtFixedRate();
isManagerInit--;
checkIfOkToAnnounce();
}
/************************************ - Tree management - *************************************/
/**
* Main function - spawns all trees.
*/
public void spawnTrees()
{
GetTreePos gtp = new GetTreePos(first);
ThreadPoolManager.getInstance().executeTask(gtp);
gtp = null;
}
/**
* returns a random X-Mas tree Npc Id.
* @return int tree Npc Id.
*/
protected int getTreeId()
{
final int[] ids =
{
13006,
13007
};
return ids[rand.nextInt(ids.length)];
}
/**
* gets random world positions according to spawned world objects and spawns x-mas trees around them...
*/
public class GetTreePos implements Runnable
{
private int _iterator;
private Future<?> _task;
public GetTreePos(final int iter)
{
_iterator = iter;
}
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
try
{
L2Object obj = null;
while (obj == null)
{
obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn();
_iterator++;
if (obj != null && obj instanceof L2Attackable)
{
if (rand.nextInt(100) > 10)
{
obj = null;
}
}
}
if (rand.nextInt(100) > 50)
{
spawnOneTree(getTreeId(), obj.getX() + rand.nextInt(200) - 100, obj.getY() + rand.nextInt(200) - 100, obj.getZ());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
{
t.printStackTrace();
}
}
if (_iterator >= last)
{
isManagerInit++;
SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(first);
_task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300);
ssNPCs.setTask(_task);
ssNPCs = null;
return;
}
_iterator++;
GetTreePos gtp = new GetTreePos(_iterator);
_task = ThreadPoolManager.getInstance().scheduleGeneral(gtp, 300);
gtp.setTask(_task);
gtp = null;
}
}
/**
* Delete all x-mas spawned trees from the world. Delete all x-mas trees spawns, and clears the L2NpcInstance tree queue.
*/
public class DeleteSpawns implements Runnable
{
@Override
public void run()
{
if (objectQueue == null || objectQueue.isEmpty())
{
return;
}
for (final L2NpcInstance deleted : objectQueue)
{
if (deleted == null)
{
continue;
}
try
{
L2World.getInstance().removeObject(deleted);
deleted.decayMe();
deleted.deleteMe();
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
{
t.printStackTrace();
}
continue;
}
}
objectQueue.clear();
objectQueue = null;
isManagerInit = isManagerInit - 2;
checkIfOkToAnnounce();
}
}
/**
* Spawns one x-mas tree at a given location x,y,z
* @param id - int tree npc id.
* @param x - int loc x
* @param y - int loc y
* @param z - int loc z
*/
protected void spawnOneTree(final int id, final int x, final int y, final int z)
{
try
{
L2NpcTemplate template1 = NpcTable.getInstance().getTemplate(id);
L2Spawn spawn = new L2Spawn(template1);
template1 = null;
spawn.setId(IdFactory.getInstance().getNextId());
spawn.setLocx(x);
spawn.setLocy(y);
spawn.setLocz(z);
L2NpcInstance tree = spawn.spawnOne();
L2World.getInstance().storeObject(tree);
objectQueue.add(tree);
spawn = null;
tree = null;
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
{
t.printStackTrace();
}
}
}
/**************************** - send players festive messages - *****************************/
/**
* Ends X-Mas messages sent to players, and terminates the thread.
*/
private void endFestiveMessagesAtFixedRate()
{
if (_XMasMessageTask != null)
{
_XMasMessageTask.cancel(true);
_XMasMessageTask = null;
}
}
/**
* Starts X-Mas messages sent to all players, and initialize the thread.
*/
private void startFestiveMessagesAtFixedRate()
{
SendXMasMessage XMasMessage = new SendXMasMessage();
_XMasMessageTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasMessage, 60000, _IntervalOfChristmas);
}
class SendXMasMessage implements Runnable
{
@Override
public void run()
{
try
{
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers().values())
{
if (pc == null)
{
continue;
}
else if (pc.isOnline() == 0)
{
continue;
}
pc.sendPacket(getXMasMessage());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
{
t.printStackTrace();
}
}
}
}
/**
* Returns a random X-Mas message.
* @return CreatureSay message
*/
protected CreatureSay getXMasMessage()
{
final CreatureSay cs = new CreatureSay(0, 17, getRandomSender(), getRandomXMasMessage());
return cs;
}
/**
* Returns a random name of the X-Mas message sender, sent to players
* @return String of the message sender's name
*/
private String getRandomSender()
{
return sender[rand.nextInt(sender.length)];
}
/**
* Returns a random X-Mas message String
* @return String containing the random message.
*/
private String getRandomXMasMessage()
{
return message[rand.nextInt(message.length)];
}
private void givePresentsAtFixedRate()
{
final XMasPresentGivingTask XMasPresents = new XMasPresentGivingTask();
_XMasPresentsTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasPresents, _IntervalOfChristmas, _IntervalOfChristmas * 3);
}
class XMasPresentGivingTask implements Runnable
{
@Override
public void run()
{
try
{
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers().values())
{
if (pc == null)
{
continue;
}
else if (pc.isOnline() == 0)
{
continue;
}
else if (pc.getInventoryLimit() <= pc.getInventory().getSize())
{
pc.sendMessage("Santa wanted to give you a Present but your inventory was full :(");
continue;
}
else if (rand.nextInt(100) < 50)
{
final int itemId = getSantaRandomPresent();
L2ItemInstance item = ItemTable.getInstance().createItem("Christmas Event", itemId, 1, pc);
pc.getInventory().addItem("Christmas Event", item.getItemId(), 1, pc, pc);
String itemName = ItemTable.getInstance().getTemplate(itemId).getName();
item = null;
SystemMessage sm;
sm = new SystemMessage(SystemMessageId.EARNED_ITEM);
sm.addString(itemName + " from Santa's Present Bag...");
pc.broadcastPacket(sm);
itemName = null;
sm = null;
}
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
{
t.printStackTrace();
}
}
}
}
protected int getSantaRandomPresent()
{
return presents[rand.nextInt(presents.length)];
}
/**
* Ends X-Mas present giving to players, and terminates the thread.
*/
private void endPresentGivingAtFixedRate()
{
if (_XMasPresentsTask != null)
{
_XMasPresentsTask.cancel(true);
_XMasPresentsTask = null;
}
}
/************************************ - spawn NPCs in towns - ***************************************/
// NPC Ids: 31863 , 31864
public class SpawnSantaNPCs implements Runnable
{
private int _iterator;
private Future<?> _task;
public SpawnSantaNPCs(final int iter)
{
_iterator = iter;
}
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
try
{
L2Object obj = null;
while (obj == null)
{
obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn();
_iterator++;
if (obj != null && obj instanceof L2Attackable)
{
obj = null;
}
}
if (rand.nextInt(100) < 80 && obj instanceof L2NpcInstance)
{
spawnOneTree(getSantaId(), obj.getX() + rand.nextInt(500) - 250, obj.getY() + rand.nextInt(500) - 250, obj.getZ());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
{
t.printStackTrace();
}
}
if (_iterator >= last)
{
isManagerInit++;
checkIfOkToAnnounce();
return;
}
_iterator++;
SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(_iterator);
_task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300);
ssNPCs.setTask(_task);
ssNPCs = null;
}
}
protected int getSantaId()
{
return rand.nextInt(100) < 50 ? 31863 : 31864;
}
protected void checkIfOkToAnnounce()
{
if (isManagerInit == 4)
{
Announcements.getInstance().announceToAll("Christmas Event has begun, have a Merry Christmas and a Happy New Year.");
Announcements.getInstance().announceToAll("Christmas Event will end in 24 hours.");
LOG.info("ChristmasManager:Init ChristmasManager was started successfully, have a festive holiday.");
final EndEvent ee = new EndEvent();
Future<?> task = ThreadPoolManager.getInstance().scheduleGeneral(ee, 86400000);
ee.setTask(task);
task = null;
isManagerInit = 5;
}
if (isManagerInit == 0)
{
Announcements.getInstance().announceToAll("Christmas Event has ended... Hope you enjoyed the festivities.");
LOG.info("ChristmasManager:Terminated ChristmasManager.");
isManagerInit = -1;
}
}
public class EndEvent implements Runnable
{
private Future<?> _task;
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
end(null);
}
}
private static class SingletonHolder
{
protected static final ChristmasManager _instance = new ChristmasManager();
}
}
| Hl4p3x/L2jOrion_Interlude_C6 | L2jOrion_SourceCode/src/l2jorion/game/managers/ChristmasManager.java | 7,513 | /************************************ - Tree management - *************************************/ | block_comment | nl | /*
* L2jOrion Project - www.l2jorion.com
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package l2jorion.game.managers;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Future;
import javolution.util.FastList;
import l2jorion.Config;
import l2jorion.game.datatables.sql.ItemTable;
import l2jorion.game.datatables.sql.NpcTable;
import l2jorion.game.datatables.sql.SpawnTable;
import l2jorion.game.idfactory.IdFactory;
import l2jorion.game.model.L2Attackable;
import l2jorion.game.model.L2Object;
import l2jorion.game.model.L2World;
import l2jorion.game.model.actor.instance.L2ItemInstance;
import l2jorion.game.model.actor.instance.L2NpcInstance;
import l2jorion.game.model.actor.instance.L2PcInstance;
import l2jorion.game.model.entity.Announcements;
import l2jorion.game.model.spawn.L2Spawn;
import l2jorion.game.network.SystemMessageId;
import l2jorion.game.network.serverpackets.CreatureSay;
import l2jorion.game.network.serverpackets.SystemMessage;
import l2jorion.game.templates.L2NpcTemplate;
import l2jorion.game.thread.ThreadPoolManager;
import l2jorion.logger.Logger;
import l2jorion.logger.LoggerFactory;
public class ChristmasManager
{
private static final Logger LOG = LoggerFactory.getLogger(ChristmasManager.class);
protected List<L2NpcInstance> objectQueue = new FastList<>();
protected Random rand = new Random();
// X-Mas message list
protected String[] message =
{
"Ho Ho Ho... Merry Christmas!",
"God is Love...",
"Christmas is all about love...",
"Christmas is thus about God and Love...",
"Love is the key to peace among all Lineage creature kind..",
"Love is the key to peace and happiness within all creation...",
"Love needs to be practiced - Love needs to flow - Love needs to make happy...",
"Love starts with your partner, children and family and expands to all world.",
"God bless all kind.",
"God bless Lineage.",
"Forgive all.",
"Ask for forgiveness even from all the \"past away\" ones.",
"Give love in many different ways to your family members, relatives, neighbors and \"foreigners\".",
"Enhance the feeling within yourself of being a member of a far larger family than your physical family",
"MOST important - Christmas is a feast of BLISS given to YOU from God and all beloved ones back home in God !!",
"Open yourself for all divine bliss, forgiveness and divine help that is offered TO YOU by many others AND GOD.",
"Take it easy. Relax these coming days.",
"Every day is Christmas day - it is UP TO YOU to create the proper inner attitude and opening for love toward others AND from others within YOUR SELF !",
"Peace and Silence. Reduced activities. More time for your most direct families. If possible NO other dates or travel may help you most to actually RECEIVE all offered bliss.",
"What ever is offered to you from God either enters YOUR heart and soul or is LOST for GOOD !!! or at least until another such day - next year Christmas or so !!",
"Divine bliss and love NEVER can be stored and received later.",
"There is year round a huge quantity of love and bliss available from God and your Guru and other loving souls, but Christmas days are an extended period FOR ALL PLANET",
"Please open your heart and accept all love and bliss - For your benefit as well as for the benefit of all your beloved ones.",
"Beloved children of God",
"Beyond Christmas days and beyond Christmas season - The Christmas love lives on, the Christmas bliss goes on, the Christmas feeling expands.",
"The holy spirit of Christmas is the holy spirit of God and God's love for all days.",
"When the Christmas spirit lives on and on...",
"When the power of love created during the pre-Christmas days is kept alive and growing.",
"Peace among all mankind is growing as well =)",
"The holy gift of love is an eternal gift of love put into your heart like a seed.",
"Dozens of millions of humans worldwide are changing in their hearts during weeks of pre-Christmas time and find their peak power of love on Christmas nights and Christmas days.",
"What is special during these days, to give all of you this very special power of love, the power to forgive, the power to make others happy, power to join the loved one on his or her path of loving life.",
"It only is your now decision that makes the difference !",
"It only is your now focus in life that makes all the changes. It is your shift from purely worldly matters toward the power of love from God that dwells within all of us that gave you the power to change your own behavior from your normal year long behavior.",
"The decision of love, peace and happiness is the right one.",
"Whatever you focus on is filling your mind and subsequently filling your heart.",
"No one else but you have change your focus these past Christmas days and the days of love you may have experienced in earlier Christmas seasons.",
"God's love is always present.",
"God's Love has always been in same power and purity and quantity available to all of you.",
"Expand the spirit of Christmas love and Christmas joy to span all year of your life...",
"Do all year long what is creating this special Christmas feeling of love joy and happiness.",
"Expand the true Christmas feeling, expand the love you have ever given at your maximum power of love days ... ",
"Expand the power of love over more and more days.",
"Re-focus on what has brought your love to its peak power and refocus on those objects and actions in your focus of mind and actions.",
"Remember the people and surrounding you had when feeling most happy, most loved, most magic",
"People of true loving spirit - who all was present, recall their names, recall the one who may have had the greatest impact in love those hours of magic moments of love...",
"The decoration of your surrounding - Decoration may help to focus on love - Or lack of decoration may make you drift away into darkness or business - away from love...",
"Love songs, songs full of living joy - any of the thousands of true touching love songs and happy songs do contribute to the establishment of an inner attitude perceptible of love.",
"Songs can fine tune and open our heart for love from God and our loved ones.",
"Your power of will and focus of mind can keep Christmas Love and Christmas joy alive beyond Christmas season for eternity",
"Enjoy your love for ever!",
"Christmas can be every day - As soon as you truly love every day =)",
"Christmas is when you love all and are loved by all.",
"Christmas is when you are truly happy by creating true happiness in others with love from the bottom of your heart.",
"Secret in God's creation is that no single person can truly love without ignition of his love.",
"You need another person to love and to receive love, a person to truly fall in love to ignite your own divine fire of love. ",
"God created many and all are made of love and all are made to love...",
"The miracle of love only works if you want to become a fully loving member of the family of divine love.",
"Once you have started to fall in love with the one God created for you - your entire eternal life will be a permanent fire of miracles of love ... Eternally !",
"May all have a happy time on Christmas each year. Merry Christmas!",
"Christmas day is a time for love. It is a time for showing our affection to our loved ones. It is all about love.",
"Have a wonderful Christmas. May god bless our family. I love you all.",
"Wish all living creatures a Happy X-mas and a Happy New Year! By the way I would like us to share a warm fellowship in all places.",
"Just as animals need peace of mind, poeple and also trees need peace of mind. This is why I say, all creatures are waiting upon the Lord for their salvation. May God bless you all creatures in the whole world.",
"Merry Xmas!",
"May the grace of Our Mighty Father be with you all during this eve of Christmas. Have a blessed Christmas and a happy New Year.",
"Merry Christmas my children. May this new year give all of the things you rightly deserve. And may peace finally be yours.",
"I wish everybody a Merry Christmas! May the Holy Spirit be with you all the time.",
"May you have the best of Christmas this year and all your dreams come true.",
"May the miracle of Christmas fill your heart with warmth and love. Merry Christmas!"
},
sender =
{
"Santa Claus",
"Papai Noel",
"Shengdan Laoren",
"Santa",
"Viejo Pascuero",
"Sinter Klaas",
"Father Christmas",
"Saint Nicholas",
"Joulupukki",
"Pere Noel",
"Saint Nikolaus",
"Kanakaloka",
"De Kerstman",
"Winter grandfather",
"Babbo Natale",
"Hoteiosho",
"Kaledu Senelis",
"Black Peter",
"Kerstman",
"Julenissen",
"Swiety Mikolaj",
"Ded Moroz",
"Julenisse",
"El Nino Jesus",
"Jultomten",
"Reindeer Dasher",
"Reindeer Dancer",
"Christmas Spirit",
"Reindeer Prancer",
"Reindeer Vixen",
"Reindeer Comet",
"Reindeer Cupid",
"Reindeer Donner",
"Reindeer Donder",
"Reindeer Dunder",
"Reindeer Blitzen",
"Reindeer Bliksem",
"Reindeer Blixem",
"Reindeer Rudolf",
"Christmas Elf"
};
// Presents List:
protected int[] presents =
{
5560,
5560,
5560,
5560,
5560, /* x-mas tree */
5560,
5560,
5560,
5560,
5560,
5561,
5561,
5561,
5561,
5561, /* special x-mas tree */
5562,
5562,
5562,
5562, /* 1st Carol */
5563,
5563,
5563,
5563, /* 2nd Carol */
5564,
5564,
5564,
5564, /* 3rd Carol */
5565,
5565,
5565,
5565, /* 4th Carol */
5566,
5566,
5566,
5566, /* 5th Carol */
5583,
5583, /* 6th Carol */
5584,
5584, /* 7th Carol */
5585,
5585, /* 8th Carol */
5586,
5586, /* 9th Carol */
5587,
5587, /* 10th Carol */
6403,
6403,
6403,
6403, /* Star Shard */
6403,
6403,
6403,
6403,
6406,
6406,
6406,
6406, /* FireWorks */
6407,
6407, /* Large FireWorks */
5555, /* Token of Love */
7836, /* Santa Hat #1 */
9138, /* Santa Hat #2 */
8936, /* Santa's Antlers Hat */
6394, /* Red Party Mask */
5808
/* Black Party Mask */
};
// The message task sent at fixed rate
protected Future<?> _XMasMessageTask = null, _XMasPresentsTask = null;
// Manager should only be Initialized once:
protected int isManagerInit = 0;
// Interval of Christmas actions:
protected long _IntervalOfChristmas = 600000; // 10 minutes
private final int first = 25000, last = 73099;
/************************************** Initial Functions **************************************/
/**
* Empty constructor Does nothing
*/
public ChristmasManager()
{
//
}
/**
* @return an instance of <b>this</b> InstanceManager.
*/
public static ChristmasManager getInstance()
{
return SingletonHolder._instance;
}
/**
* initialize <b>this</b> ChristmasManager
* @param activeChar
*/
public void init(final L2PcInstance activeChar)
{
if (isManagerInit > 0)
{
activeChar.sendMessage("Christmas Manager has already begun or is processing. Please be patient....");
return;
}
activeChar.sendMessage("Started!!!! This will take a 2-3 hours (in order to reduce system lags to a minimum), please be patient... The process is working in the background and will spawn npcs, give presents and messages at a fixed rate.");
// Tasks:
spawnTrees();
startFestiveMessagesAtFixedRate();
isManagerInit++;
givePresentsAtFixedRate();
isManagerInit++;
checkIfOkToAnnounce();
}
/**
* ends <b>this</b> ChristmasManager
* @param activeChar
*/
public void end(final L2PcInstance activeChar)
{
if (isManagerInit < 4)
{
if (activeChar != null)
{
activeChar.sendMessage("Christmas Manager is not activated yet. Already Ended or is now processing....");
}
return;
}
if (activeChar != null)
{
activeChar.sendMessage("Terminating! This may take a while, please be patient...");
}
// Tasks:
ThreadPoolManager.getInstance().executeTask(new DeleteSpawns());
endFestiveMessagesAtFixedRate();
isManagerInit--;
endPresentGivingAtFixedRate();
isManagerInit--;
checkIfOkToAnnounce();
}
/************************************ - Tree management<SUF>*/
/**
* Main function - spawns all trees.
*/
public void spawnTrees()
{
GetTreePos gtp = new GetTreePos(first);
ThreadPoolManager.getInstance().executeTask(gtp);
gtp = null;
}
/**
* returns a random X-Mas tree Npc Id.
* @return int tree Npc Id.
*/
protected int getTreeId()
{
final int[] ids =
{
13006,
13007
};
return ids[rand.nextInt(ids.length)];
}
/**
* gets random world positions according to spawned world objects and spawns x-mas trees around them...
*/
public class GetTreePos implements Runnable
{
private int _iterator;
private Future<?> _task;
public GetTreePos(final int iter)
{
_iterator = iter;
}
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
try
{
L2Object obj = null;
while (obj == null)
{
obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn();
_iterator++;
if (obj != null && obj instanceof L2Attackable)
{
if (rand.nextInt(100) > 10)
{
obj = null;
}
}
}
if (rand.nextInt(100) > 50)
{
spawnOneTree(getTreeId(), obj.getX() + rand.nextInt(200) - 100, obj.getY() + rand.nextInt(200) - 100, obj.getZ());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
{
t.printStackTrace();
}
}
if (_iterator >= last)
{
isManagerInit++;
SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(first);
_task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300);
ssNPCs.setTask(_task);
ssNPCs = null;
return;
}
_iterator++;
GetTreePos gtp = new GetTreePos(_iterator);
_task = ThreadPoolManager.getInstance().scheduleGeneral(gtp, 300);
gtp.setTask(_task);
gtp = null;
}
}
/**
* Delete all x-mas spawned trees from the world. Delete all x-mas trees spawns, and clears the L2NpcInstance tree queue.
*/
public class DeleteSpawns implements Runnable
{
@Override
public void run()
{
if (objectQueue == null || objectQueue.isEmpty())
{
return;
}
for (final L2NpcInstance deleted : objectQueue)
{
if (deleted == null)
{
continue;
}
try
{
L2World.getInstance().removeObject(deleted);
deleted.decayMe();
deleted.deleteMe();
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
{
t.printStackTrace();
}
continue;
}
}
objectQueue.clear();
objectQueue = null;
isManagerInit = isManagerInit - 2;
checkIfOkToAnnounce();
}
}
/**
* Spawns one x-mas tree at a given location x,y,z
* @param id - int tree npc id.
* @param x - int loc x
* @param y - int loc y
* @param z - int loc z
*/
protected void spawnOneTree(final int id, final int x, final int y, final int z)
{
try
{
L2NpcTemplate template1 = NpcTable.getInstance().getTemplate(id);
L2Spawn spawn = new L2Spawn(template1);
template1 = null;
spawn.setId(IdFactory.getInstance().getNextId());
spawn.setLocx(x);
spawn.setLocy(y);
spawn.setLocz(z);
L2NpcInstance tree = spawn.spawnOne();
L2World.getInstance().storeObject(tree);
objectQueue.add(tree);
spawn = null;
tree = null;
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
{
t.printStackTrace();
}
}
}
/**************************** - send players festive messages - *****************************/
/**
* Ends X-Mas messages sent to players, and terminates the thread.
*/
private void endFestiveMessagesAtFixedRate()
{
if (_XMasMessageTask != null)
{
_XMasMessageTask.cancel(true);
_XMasMessageTask = null;
}
}
/**
* Starts X-Mas messages sent to all players, and initialize the thread.
*/
private void startFestiveMessagesAtFixedRate()
{
SendXMasMessage XMasMessage = new SendXMasMessage();
_XMasMessageTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasMessage, 60000, _IntervalOfChristmas);
}
class SendXMasMessage implements Runnable
{
@Override
public void run()
{
try
{
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers().values())
{
if (pc == null)
{
continue;
}
else if (pc.isOnline() == 0)
{
continue;
}
pc.sendPacket(getXMasMessage());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
{
t.printStackTrace();
}
}
}
}
/**
* Returns a random X-Mas message.
* @return CreatureSay message
*/
protected CreatureSay getXMasMessage()
{
final CreatureSay cs = new CreatureSay(0, 17, getRandomSender(), getRandomXMasMessage());
return cs;
}
/**
* Returns a random name of the X-Mas message sender, sent to players
* @return String of the message sender's name
*/
private String getRandomSender()
{
return sender[rand.nextInt(sender.length)];
}
/**
* Returns a random X-Mas message String
* @return String containing the random message.
*/
private String getRandomXMasMessage()
{
return message[rand.nextInt(message.length)];
}
private void givePresentsAtFixedRate()
{
final XMasPresentGivingTask XMasPresents = new XMasPresentGivingTask();
_XMasPresentsTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasPresents, _IntervalOfChristmas, _IntervalOfChristmas * 3);
}
class XMasPresentGivingTask implements Runnable
{
@Override
public void run()
{
try
{
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers().values())
{
if (pc == null)
{
continue;
}
else if (pc.isOnline() == 0)
{
continue;
}
else if (pc.getInventoryLimit() <= pc.getInventory().getSize())
{
pc.sendMessage("Santa wanted to give you a Present but your inventory was full :(");
continue;
}
else if (rand.nextInt(100) < 50)
{
final int itemId = getSantaRandomPresent();
L2ItemInstance item = ItemTable.getInstance().createItem("Christmas Event", itemId, 1, pc);
pc.getInventory().addItem("Christmas Event", item.getItemId(), 1, pc, pc);
String itemName = ItemTable.getInstance().getTemplate(itemId).getName();
item = null;
SystemMessage sm;
sm = new SystemMessage(SystemMessageId.EARNED_ITEM);
sm.addString(itemName + " from Santa's Present Bag...");
pc.broadcastPacket(sm);
itemName = null;
sm = null;
}
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
{
t.printStackTrace();
}
}
}
}
protected int getSantaRandomPresent()
{
return presents[rand.nextInt(presents.length)];
}
/**
* Ends X-Mas present giving to players, and terminates the thread.
*/
private void endPresentGivingAtFixedRate()
{
if (_XMasPresentsTask != null)
{
_XMasPresentsTask.cancel(true);
_XMasPresentsTask = null;
}
}
/************************************ - spawn NPCs in towns - ***************************************/
// NPC Ids: 31863 , 31864
public class SpawnSantaNPCs implements Runnable
{
private int _iterator;
private Future<?> _task;
public SpawnSantaNPCs(final int iter)
{
_iterator = iter;
}
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
try
{
L2Object obj = null;
while (obj == null)
{
obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn();
_iterator++;
if (obj != null && obj instanceof L2Attackable)
{
obj = null;
}
}
if (rand.nextInt(100) < 80 && obj instanceof L2NpcInstance)
{
spawnOneTree(getSantaId(), obj.getX() + rand.nextInt(500) - 250, obj.getY() + rand.nextInt(500) - 250, obj.getZ());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
{
t.printStackTrace();
}
}
if (_iterator >= last)
{
isManagerInit++;
checkIfOkToAnnounce();
return;
}
_iterator++;
SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(_iterator);
_task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300);
ssNPCs.setTask(_task);
ssNPCs = null;
}
}
protected int getSantaId()
{
return rand.nextInt(100) < 50 ? 31863 : 31864;
}
protected void checkIfOkToAnnounce()
{
if (isManagerInit == 4)
{
Announcements.getInstance().announceToAll("Christmas Event has begun, have a Merry Christmas and a Happy New Year.");
Announcements.getInstance().announceToAll("Christmas Event will end in 24 hours.");
LOG.info("ChristmasManager:Init ChristmasManager was started successfully, have a festive holiday.");
final EndEvent ee = new EndEvent();
Future<?> task = ThreadPoolManager.getInstance().scheduleGeneral(ee, 86400000);
ee.setTask(task);
task = null;
isManagerInit = 5;
}
if (isManagerInit == 0)
{
Announcements.getInstance().announceToAll("Christmas Event has ended... Hope you enjoyed the festivities.");
LOG.info("ChristmasManager:Terminated ChristmasManager.");
isManagerInit = -1;
}
}
public class EndEvent implements Runnable
{
private Future<?> _task;
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
end(null);
}
}
private static class SingletonHolder
{
protected static final ChristmasManager _instance = new ChristmasManager();
}
}
|
8349_7 | package nl.hsleiden.game;
import java.util.ArrayList;
/**
* Dit is een level. Hier kun je een aantal methoden aanroepen om informatie over het level te krijgen,
* of om tiles en/of elementen toe te voegen aan het spel.
* */
public class Level {
private Tile[][] tiles;
private ArrayList<Element> elements;
private Element focusedElement;
private ArrayList<Element> bufferedElements;
public Level() {
bufferedElements = new ArrayList<>();
}
/**
* @return het element dat door de camera gefocussed wordt.
* */
public Element getFocusedElement() {
return focusedElement;
}
/**
* Set het element dat door de camera gefocussed moet worden.
* @param focusedElement het element waarop gefocussed moet worden.
* */
public void setFocusedElement(Element focusedElement) {
this.focusedElement = focusedElement;
}
/**
* Met deze methode kun je de tiles van dit level opvragen.
* @return de tiles van dit level.
* */
public Tile[][] getTiles() {
return tiles;
}
/**
* Met deze methode kun je de elementen van dit level opvragen.
* @return de elementen van dit level.
* */
public ArrayList<Element> getElements() {
return elements;
}
/**
* @return de breedte van het level.
* */
public int getWidth() {
return tiles[0].length * 80;
}
/**
* @return de hoogte van het level.
* */
public int getHeigt() {
return tiles.length * 80;
}
/**
* Plaats de tiles in dit level.
* @param tiles de tiles die in dit level moeten.
* */
public void setTiles(Tile[][] tiles) {
this.tiles = tiles;
}
/**
* Plaats de elements in dit level.
* @param elements de tiles die in dit level moeten.
* */
public void setElements(ArrayList<Element> elements) {
this.elements = elements;
}
public void refreshElements(){
this.bufferedElements.clear();
this.bufferedElements.addAll(elements);
}
public ArrayList<Element> getBufferedElements() {
return bufferedElements;
}
}
| Hogeschool-Leiden/GameEngine | src/main/java/nl/hsleiden/game/Level.java | 622 | /**
* Plaats de tiles in dit level.
* @param tiles de tiles die in dit level moeten.
* */ | block_comment | nl | package nl.hsleiden.game;
import java.util.ArrayList;
/**
* Dit is een level. Hier kun je een aantal methoden aanroepen om informatie over het level te krijgen,
* of om tiles en/of elementen toe te voegen aan het spel.
* */
public class Level {
private Tile[][] tiles;
private ArrayList<Element> elements;
private Element focusedElement;
private ArrayList<Element> bufferedElements;
public Level() {
bufferedElements = new ArrayList<>();
}
/**
* @return het element dat door de camera gefocussed wordt.
* */
public Element getFocusedElement() {
return focusedElement;
}
/**
* Set het element dat door de camera gefocussed moet worden.
* @param focusedElement het element waarop gefocussed moet worden.
* */
public void setFocusedElement(Element focusedElement) {
this.focusedElement = focusedElement;
}
/**
* Met deze methode kun je de tiles van dit level opvragen.
* @return de tiles van dit level.
* */
public Tile[][] getTiles() {
return tiles;
}
/**
* Met deze methode kun je de elementen van dit level opvragen.
* @return de elementen van dit level.
* */
public ArrayList<Element> getElements() {
return elements;
}
/**
* @return de breedte van het level.
* */
public int getWidth() {
return tiles[0].length * 80;
}
/**
* @return de hoogte van het level.
* */
public int getHeigt() {
return tiles.length * 80;
}
/**
* Plaats de tiles<SUF>*/
public void setTiles(Tile[][] tiles) {
this.tiles = tiles;
}
/**
* Plaats de elements in dit level.
* @param elements de tiles die in dit level moeten.
* */
public void setElements(ArrayList<Element> elements) {
this.elements = elements;
}
public void refreshElements(){
this.bufferedElements.clear();
this.bufferedElements.addAll(elements);
}
public ArrayList<Element> getBufferedElements() {
return bufferedElements;
}
}
|
17401_64 | package testen;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import domein.Edele;
import domein.EdeleRepository;
import domein.Edelsteenfiche;
import domein.EdelsteenficheRepository;
import domein.Ontwikkelingskaart;
import domein.Spel;
import domein.Speler;
import exceptions.EdeleNietBeschikbaarException;
class SpelTest {
EdelsteenficheRepository edelsteenRepo = new EdelsteenficheRepository();
EdeleRepository edeleRepo = new EdeleRepository();
Spel sp, spel, geldigSpel, spelUC3;
Speler speler1;
Speler speler2;
Speler speler3;
Speler speler4;
Speler speler5;
Speler spelerUC3_1, spelerUC3_2;
Ontwikkelingskaart k0, k1, k2, k3;
Edele edele1, edele2, edele3;
List<Edele> edelen;
ArrayList<Edelsteenfiche> edelsteenfiches;
@BeforeEach
void setUp() {
sp = new Spel(new ArrayList<Edelsteenfiche>(), new ArrayList<Ontwikkelingskaart>(),
new ArrayList<Ontwikkelingskaart>(), new ArrayList<Ontwikkelingskaart>());
speler1 = new Speler("Jean Louis", 1980);
speler2 = new Speler("Jean Jacques", 1981);
speler3 = new Speler("Yean Jules", 1980);
speler4 = new Speler("Jean Pierre", 1980);
speler5 = new Speler("Jean Michel", 1980);
}
@Test
void maakSpel_TeWeinigSpelers_returntFalse() {
sp.voegSpelerToe(speler1);
assertFalse(sp.heeftGeldigAantalSpelers());
}
@Test
void maakSpel_TeVeelSpelers_returntFalse() {
sp.voegSpelerToe(speler1);
sp.voegSpelerToe(speler2);
sp.voegSpelerToe(speler3);
sp.voegSpelerToe(speler4);
sp.voegSpelerToe(speler5);
assertFalse(sp.heeftGeldigAantalSpelers());
}
@Test
void maakSpel_met2Spelers_returntTrue() {
sp.voegSpelerToe(speler1);
sp.voegSpelerToe(speler2);
assertTrue(sp.heeftGeldigAantalSpelers());
}
@Test
void maakSpel_met3Spelers_returntTrue() {
sp.voegSpelerToe(speler1);
sp.voegSpelerToe(speler2);
sp.voegSpelerToe(speler3);
assertTrue(sp.heeftGeldigAantalSpelers());
}
@Test
void maakSpel_met4Spelers_returntTrue() {
sp.voegSpelerToe(speler1);
sp.voegSpelerToe(speler2);
sp.voegSpelerToe(speler3);
sp.voegSpelerToe(speler4);
assertTrue(sp.heeftGeldigAantalSpelers());
}
@Test
void bepaalStartendeSpeler_met1SpelerJongste_returnJongste() {
sp.voegSpelerToe(speler1); // Jean Louis, 1980
sp.voegSpelerToe(speler2); // Jean Jacques, 1981
sp.bepaalStartendeSpeler();
var starter = sp.getHuidigeSpeler();
assertTrue(starter.getGebruikersnaam() == "Jean Jacques");
}
@Test
void bepaalStartendeSpeler_met2SpelersEvenJong_returnLangsteNaam() {
sp.voegSpelerToe(speler1); // Jean Louis, 1980
sp.voegSpelerToe(speler4); // Jean Pierre, 1980
sp.bepaalStartendeSpeler();
var starter = sp.getHuidigeSpeler();
assertTrue(starter.getGebruikersnaam() == "Jean Pierre");
}
@Test
void bepaalStartendeSpeler_met2SpelersEvenJongEnEvenLangeNaam_returnOmgekeerdAlfabetisch() {
sp.voegSpelerToe(speler1); // Jean Louis, 1980
sp.voegSpelerToe(speler3); // Yean Jules, 1980
sp.bepaalStartendeSpeler();
var starter = sp.getHuidigeSpeler();
assertTrue(starter.getGebruikersnaam() == "Yean Jules");
}
/** UC1 testen of correct aantal Edelen en correct aantal edelsteenfiches per type op spelbord ligt
* bij verschillend aantal spelers in spel
*/
@BeforeEach
void maakSpelOmAantalFichesEnEdelenTeTesten() {
List<Edelsteenfiche> fiches = new ArrayList<>();
fiches = edelsteenRepo.geefEdelsteenfiches();
spel = new Spel(fiches, new ArrayList<Ontwikkelingskaart>(),
new ArrayList<Ontwikkelingskaart>(), new ArrayList<Ontwikkelingskaart>());
edelen = new ArrayList<>();
edelen = edeleRepo.geefEdele();
}
@Test
void bepaalAantalEdelenEnFichesInSpel_spelMet2Spelers_Returnt3EdelenEn4EdelstenenPerType() {
spel.voegSpelerToe(speler1);
spel.voegSpelerToe(speler2);
spel.setEdelen(edelen);
assertEquals(2, spel.geefAantalSpelers());
assertEquals(3, spel.getEdelen().size()); //controle aantal edelen in spel: 2 spelers = 3 edelen
//controle of spel juiste aantal edelsteenfiches heeft
spel.bepaalAantalEdelsteenfiches();
HashMap<Edelsteenfiche, Integer> aantalPerEdelsteenfiche = spel.getEdelsteenfiches();
assertEquals(5, aantalPerEdelsteenfiche.size()); //test aantal verschillende soorten edelstenen
for(var e : aantalPerEdelsteenfiche.keySet()) { //test voor elke type edelsteenfiche het aantal fiches:
var aantal = aantalPerEdelsteenfiche.get(e);
assertEquals(4, aantal); //Spel met 2spelers heeft 4 fiches per type
}
}
@Test
void bepaalAantalEdelenenEnFichesInSpel_spelMet3Spelers_Returnt4EdelenEn5EdelstenenPerType() {
spel.voegSpelerToe(speler1);
spel.voegSpelerToe(speler2);
spel.voegSpelerToe(speler3);
spel.setEdelen(edelen);
assertEquals(3, spel.geefAantalSpelers());
assertEquals(4, spel.getEdelen().size()); //controle aantal edelen in spel: 3 spelers = 4 edelen
//controle of spel juiste aantal edelsteenfiches heeft
spel.bepaalAantalEdelsteenfiches();
HashMap<Edelsteenfiche, Integer> aantalPerEdelsteenfiche = spel.getEdelsteenfiches();
assertEquals(5, aantalPerEdelsteenfiche.size()); //test aantal verschillende soorten edelstenen
for(var e : aantalPerEdelsteenfiche.keySet()) { //test voor elke type edelsteenfiche het aantal fiches:
var aantal = aantalPerEdelsteenfiche.get(e);
assertEquals(5, aantal); //Spel met 3 spelers heeft 5 fiches per type
}
}
@Test
void bepaalAantalEdelenenEnFichesInSpel_spelMet4Spelers_Returnt5EdelenEn7EdelstenenPerType() {
spel.voegSpelerToe(speler1);
spel.voegSpelerToe(speler2);
spel.voegSpelerToe(speler3);
spel.voegSpelerToe(speler4);
spel.setEdelen(edelen);
assertEquals(4, spel.geefAantalSpelers());
assertEquals(5, spel.getEdelen().size()); //controle aantal edelen in spel: 4 spelers = 5 edelen
//controle of spel juiste aantal edelsteenfiches heeft
spel.bepaalAantalEdelsteenfiches();
HashMap<Edelsteenfiche, Integer> aantalPerEdelsteenfiche = spel.getEdelsteenfiches();
assertEquals(5, aantalPerEdelsteenfiche.size()); //test aantal verschillende soorten edelstenen
for(var e : aantalPerEdelsteenfiche.keySet()) { //test voor elke type edelsteenfiche het aantal fiches:
var aantal = aantalPerEdelsteenfiche.get(e);
assertEquals(7, aantal); //Spel met 4 spelers heeft 7 fiches per type
}
}
/** UC2 Testen: controleren of één of meerdere spelers aangeduid worden als winnaar bij behalen eindscore
*/
@BeforeEach
void maakGeldigSpel() {
geldigSpel = new Spel(new ArrayList<Edelsteenfiche>(), new ArrayList<Ontwikkelingskaart>(),
new ArrayList<Ontwikkelingskaart>(), new ArrayList<Ontwikkelingskaart>());
geldigSpel.voegSpelerToe(speler1);
geldigSpel.voegSpelerToe(speler2);
geldigSpel.voegSpelerToe(speler3);
}
@BeforeEach
void maakOntwikkelingskaarten() {
HashMap<String, Integer> aankoopprijs = new HashMap<String, Integer>();
k0 = new Ontwikkelingskaart(1, 1, 0, 1, aankoopprijs, ""); // kaart id1 niveau1 met 0 prestigepunten, String afbeelding
k1 = new Ontwikkelingskaart(2, 1, 2, 2, aankoopprijs, ""); // kaart id2 niveau1 met 2 prestigepunt
k2 = new Ontwikkelingskaart(3, 2, 3, 3, aankoopprijs, ""); // kaart id3 niveau2 met 3 prestigepunten
k3 = new Ontwikkelingskaart(4, 3, 6, 4, aankoopprijs, ""); // kaart id4 niveau3 met 6 prestigepunten
}
@BeforeEach
void geefSpelersNetNietVoldoendePrestigepuntenInBezit() {
// Speler1 krijgt 4 kaarten en één edele met een totaal aantal aan prestigepunten = 14
speler1.setKaartenInBezit(k0); // kaart met prestigepunten: 0
speler1.setKaartenInBezit(k1); // kaart met prestigepunten: 2
speler1.setKaartenInBezit(k2); // kaart met prestigepunten: 3
speler1.setKaartenInBezit(k3); // kaart met prestigepunten: 6
speler1.voegEdeleInBezitToe(new Edele(1, 3 , new HashMap<String, Integer>(), "")); // edele met prestigepunten: 3
// Speler2 krijgt 4 kaarten met een totaal aantal aan prestigepunten = 14
speler2.setKaartenInBezit(k1); // kaart met prestigepunten: 2
speler2.setKaartenInBezit(k2); // kaart met prestigepunten: 3
speler2.setKaartenInBezit(k2); // kaart met prestigepunten: 3
speler2.setKaartenInBezit(k3); // kaart met prestigepunten: 6
}
@Test
void bepaalScoreEnOfErWinnaarIs_spelersHebbenNetNietVoldoendePrestigepunten_returntGeenWinnaarEnScoreElkeSpeler() {
//controle of spelers kaarten en edelen die ze hebben meegekregen in bezit hebben
assertEquals(4,speler1.getKaartenInBezit().size());
assertEquals(1,speler1.getEdelenInBezit().size());
assertEquals(4,speler2.getKaartenInBezit().size());
assertEquals(0,speler2.getEdelenInBezit().size());
//controle van de score bij onze spelers
assertEquals(14, speler1.getScore()); // totaal aantal prestigepunten in bezit van speler1 = 14
assertEquals(14, speler2.getScore()); // totaal aantal prestigepunten in bezit van speler2 = 14
assertEquals(0, speler3.getScore());
assertFalse(geldigSpel.heeftWinnaars());
}
@Test
void bepaalScoreEnWinnaar_éénSpelerHeeftNetVoldoendePrestigepunten_returntScoreEnNaamWinnaar() {
System.out.println("\nTest bepaalScoreEnWinnaar_éénSpelerHeeftNetVoldoendePrestigepunten_returntScoreEnNaamWinnaar");
speler1.setKaartenInBezit(k1); // speler1 krijgt extra kaart met prestigepunten: 2 en haalt eindscore van 16
assertEquals(16, speler1.getScore());
assertTrue(geldigSpel.heeftWinnaars());
assertTrue(geldigSpel.geefNamenWinnaars().contains("Jean Louis"));
}
@Test
void bepaalScoreEnWinnaars_tweeSpelershebbenGelijkeMaxScoreEnGelijkAantalOntwikkelingskaarten_returntNamen2Winnaars() {
System.out.println("\nTest bepaalScoreEnWinnaars_tweeSpelershebbenGelijkeMaxScoreEnGelijkAantalOntwikkelingskaarten_returntNamen2Winnaars");
speler1.setKaartenInBezit(k2); // speler1 krijgt extra kaart met prestigepunten: 3
speler2.setKaartenInBezit(k2); // speler1 krijgt extra kaart met prestigepunten: 3
//twee spelers hebben een eindscore van 17 behaald en een gelijk aantal ontwikkelingskaarten in bezit
assertEquals(17, speler1.getScore());
assertEquals(17, speler2.getScore());
assertTrue(geldigSpel.heeftWinnaars());
assertTrue(geldigSpel.geefNamenWinnaars().contains("Jean Louis"));
assertTrue(geldigSpel.geefNamenWinnaars().contains("Jean Jacques"));
}
@Test
void bepaalScoreEnWinnaar_tweeSpelershebbenGelijkeMaxScoreMaarOngelijkAantalOntwikkelingskaarten_returntNaamVanEénWinnaar() {
System.out.println("\nTest bepaalScoreEnWinnaar_tweeSpelershebbenGelijkeMaxScoreMaarOngelijkAantalOntwikkelingskaarten_returntNaamVanEénWinnaar");
speler1.setKaartenInBezit(k3); // speler1 krijgt één extra kaart met prestigepunten: 6
speler2.setKaartenInBezit(k2);
speler2.setKaartenInBezit(k2); // speler2 krijgt twee extra kaarten met prestigepunten: 3
//controle of spelers correcte aantal kaarten en edelen die ze hebben meegekregen in bezit hebben
assertEquals(5,speler1.getKaartenInBezit().size());
assertEquals(1,speler1.getEdelenInBezit().size());
assertEquals(6,speler2.getKaartenInBezit().size());
assertEquals(0,speler2.getEdelenInBezit().size());
//beide spelers hebben een eindscore van 20 behaald
assertEquals(20, speler1.getScore());
assertEquals(20, speler2.getScore());
assertTrue(geldigSpel.heeftWinnaars());
//speler1("Jean Louis") heeft één ontwikkelingskaart minder in bezit dan speler2 ("Jean Jacques") en wint het spel
assertTrue(geldigSpel.geefNamenWinnaars().contains("Jean Louis"));
assertFalse(geldigSpel.geefNamenWinnaars().contains("Jean Jacques"));
}
/** UC3 testen: verkrijgen van een tegel (edele)
*/
@BeforeEach
void maakEdelenVoorTestUC3() {
//Aanmaken edele1, kostprijs samenstellen in een Hashmap:
HashMap<String, Integer> kost3Groen3Wit3Zwart = new HashMap<String, Integer>();
kost3Groen3Wit3Zwart.put("smaragd", 3); // instellen 3 groen
kost3Groen3Wit3Zwart.put("diamant", 3); // instellen 3 wit
kost3Groen3Wit3Zwart.put("onyx", 3); // instellen 3 zwart
kost3Groen3Wit3Zwart.put("saffier", 0);
kost3Groen3Wit3Zwart.put("robijn", 0);
// edele1 met idNr=1, 3 prestigepunten en zijn kostprijs
edele1 = new Edele(1, 3, kost3Groen3Wit3Zwart,"");
//Aanmaken edele2, kostprijs samenstellen in een Hashmap:
HashMap<String, Integer> kost3Groen3Wit3Rood = new HashMap<String, Integer>();
kost3Groen3Wit3Rood.put("smaragd", 3); // instellen 3 groen
kost3Groen3Wit3Rood.put("diamant", 3); // instellen 3 wit
kost3Groen3Wit3Rood.put("robijn", 3); // instellen 3 rood
kost3Groen3Wit3Rood.put("saffier", 0);
kost3Groen3Wit3Rood.put("onyx", 0);
// edele2 met idNr=2, 3 prestigepunten en zijn kostprijs
edele2 = new Edele(2, 3, kost3Groen3Wit3Rood,"");
//Aanmaken edele3, kostprijs samenstellen in een Hashmap:
HashMap<String, Integer> kost3Groen3Wit3Blauw = new HashMap<String, Integer>();
kost3Groen3Wit3Rood.put("smaragd", 3); // instellen 3 groen
kost3Groen3Wit3Rood.put("diamant", 3); // instellen 3 wit
kost3Groen3Wit3Rood.put("saffier", 3); // instellen 3 blauw
kost3Groen3Wit3Rood.put("onyx", 0);
kost3Groen3Wit3Rood.put("robijn", 0);
// edele met idNr=3, 3 prestigepunten en zijn kostprijs
edele3 = new Edele(3, 3, kost3Groen3Wit3Blauw,"");
}
@BeforeEach
void setUpUC3() {
spelUC3 = new Spel(new ArrayList<Edelsteenfiche>(), new ArrayList<Ontwikkelingskaart>(),
new ArrayList<Ontwikkelingskaart>(), new ArrayList<Ontwikkelingskaart>());
spelerUC3_1 = new Speler("speler 1", 1993);
spelerUC3_2 = new Speler("speler 2", 1993);
spelUC3.voegSpelerToe(spelerUC3_1);
spelUC3.voegSpelerToe(spelerUC3_2);
List<Edele> edelen_UC3 = new ArrayList<>();
edelen_UC3.add(edele1);
edelen_UC3.add(edele2);
edelen_UC3.add(edele3);
spelUC3.setEdelen(edelen_UC3);
spelUC3.bepaalVolgendeSpelerAanDeBeurt();
//speler1 (huidigeSpeler) wordt in het bezit gebracht van ontwikkelingskaarten:
// 3 kaarten met bonusficheId 1 en 3 kaarten met bonusficheId 2
for (int i = 1 ; i <= 3 ; i++) {
spelerUC3_1.setKaartenInBezit(new Ontwikkelingskaart(i , 1, 0, 1, new HashMap<String, Integer>(),""));
spelerUC3_1.setKaartenInBezit(new Ontwikkelingskaart(i+10, 1, 0, 2, new HashMap<String, Integer>(),""));
}
}
@Test
void bepaalHuidigeSpelerInSpelUC3EnZijnStatus_speler1WordtAangesteldAlsHuidigeSpeler() {
//spelUC3.bepaalVolgendeSpelerAanDeBeurt();
Speler huidigeSpeler = spelUC3.getHuidigeSpeler();
//speler1 wordt aangeduid als huidige speler
assertEquals("speler 1", huidigeSpeler.getGebruikersnaam());
//controle kaarten in bezit van speler1
assertEquals(6, spelerUC3_1.getKaartenInBezit().size());
}
@Test
void bepaalOfEdelenInSpelUC3_returntEdeleEnAantalEdelen() {
assertEquals(3, spelUC3.getEdelen().size());
assertTrue(spelUC3.getEdelen().contains(edele1));
}
@Test
void bepaalOfHuidigeSpelerTegelKrijgt_spelerHeeftOnvoldoendeBonusfiches_spelerKrijgtGeenTegel() {
//speler1 heeft edele1 nog niet in zijn bezit
assertFalse(spelerUC3_1.getEdelenInBezit().contains(edele1));
//speler1 wil edele aankopen maar krijgt exception te zien
assertThrows(EdeleNietBeschikbaarException.class, () -> spelUC3.kiesTegel(edele1));
//aangezien speler1 niet de benodigde bonusfiches heeft is aankoop edele niet gelukt
assertFalse(spelerUC3_1.getEdelenInBezit().contains(edele1));
}
@Test
void bepaalOfHuidigeSpelerTegelKrijgt_spelerHeeftVoldoendeBonusfichesVoorEénTegel_spelerKrijgtTegel() {
//speler1 heeft edele1 nog niet in zijn bezit
assertFalse(spelerUC3_1.getEdelenInBezit().contains(edele1));
//speler1 krijgt 3 extra kaarten met bonusficheId 3 zodat speler één tegel kan verkrijgen
for (int i = 1 ; i <= 3 ; i++) {
spelerUC3_1.setKaartenInBezit(new Ontwikkelingskaart(i+20, 1, 0, 4, new HashMap<String, Integer>(),""));
}
//speler1 wil edele aankopen
spelUC3.kiesTegel(edele1);
//speler1 heeft tegel succesvol in bezit genomen
assertTrue(spelerUC3_1.getEdelenInBezit().contains(edele1));
//controle of tegel (edele1) is verwijderd uit aanbod na aankoop
assertEquals(2, spelUC3.getEdelen().size());
assertFalse(spelUC3.getEdelen().contains(edele1));
}
}
| Holsbeeck/Splendor | src/testen/SpelTest.java | 6,876 | // instellen 3 wit | line_comment | nl | package testen;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import domein.Edele;
import domein.EdeleRepository;
import domein.Edelsteenfiche;
import domein.EdelsteenficheRepository;
import domein.Ontwikkelingskaart;
import domein.Spel;
import domein.Speler;
import exceptions.EdeleNietBeschikbaarException;
class SpelTest {
EdelsteenficheRepository edelsteenRepo = new EdelsteenficheRepository();
EdeleRepository edeleRepo = new EdeleRepository();
Spel sp, spel, geldigSpel, spelUC3;
Speler speler1;
Speler speler2;
Speler speler3;
Speler speler4;
Speler speler5;
Speler spelerUC3_1, spelerUC3_2;
Ontwikkelingskaart k0, k1, k2, k3;
Edele edele1, edele2, edele3;
List<Edele> edelen;
ArrayList<Edelsteenfiche> edelsteenfiches;
@BeforeEach
void setUp() {
sp = new Spel(new ArrayList<Edelsteenfiche>(), new ArrayList<Ontwikkelingskaart>(),
new ArrayList<Ontwikkelingskaart>(), new ArrayList<Ontwikkelingskaart>());
speler1 = new Speler("Jean Louis", 1980);
speler2 = new Speler("Jean Jacques", 1981);
speler3 = new Speler("Yean Jules", 1980);
speler4 = new Speler("Jean Pierre", 1980);
speler5 = new Speler("Jean Michel", 1980);
}
@Test
void maakSpel_TeWeinigSpelers_returntFalse() {
sp.voegSpelerToe(speler1);
assertFalse(sp.heeftGeldigAantalSpelers());
}
@Test
void maakSpel_TeVeelSpelers_returntFalse() {
sp.voegSpelerToe(speler1);
sp.voegSpelerToe(speler2);
sp.voegSpelerToe(speler3);
sp.voegSpelerToe(speler4);
sp.voegSpelerToe(speler5);
assertFalse(sp.heeftGeldigAantalSpelers());
}
@Test
void maakSpel_met2Spelers_returntTrue() {
sp.voegSpelerToe(speler1);
sp.voegSpelerToe(speler2);
assertTrue(sp.heeftGeldigAantalSpelers());
}
@Test
void maakSpel_met3Spelers_returntTrue() {
sp.voegSpelerToe(speler1);
sp.voegSpelerToe(speler2);
sp.voegSpelerToe(speler3);
assertTrue(sp.heeftGeldigAantalSpelers());
}
@Test
void maakSpel_met4Spelers_returntTrue() {
sp.voegSpelerToe(speler1);
sp.voegSpelerToe(speler2);
sp.voegSpelerToe(speler3);
sp.voegSpelerToe(speler4);
assertTrue(sp.heeftGeldigAantalSpelers());
}
@Test
void bepaalStartendeSpeler_met1SpelerJongste_returnJongste() {
sp.voegSpelerToe(speler1); // Jean Louis, 1980
sp.voegSpelerToe(speler2); // Jean Jacques, 1981
sp.bepaalStartendeSpeler();
var starter = sp.getHuidigeSpeler();
assertTrue(starter.getGebruikersnaam() == "Jean Jacques");
}
@Test
void bepaalStartendeSpeler_met2SpelersEvenJong_returnLangsteNaam() {
sp.voegSpelerToe(speler1); // Jean Louis, 1980
sp.voegSpelerToe(speler4); // Jean Pierre, 1980
sp.bepaalStartendeSpeler();
var starter = sp.getHuidigeSpeler();
assertTrue(starter.getGebruikersnaam() == "Jean Pierre");
}
@Test
void bepaalStartendeSpeler_met2SpelersEvenJongEnEvenLangeNaam_returnOmgekeerdAlfabetisch() {
sp.voegSpelerToe(speler1); // Jean Louis, 1980
sp.voegSpelerToe(speler3); // Yean Jules, 1980
sp.bepaalStartendeSpeler();
var starter = sp.getHuidigeSpeler();
assertTrue(starter.getGebruikersnaam() == "Yean Jules");
}
/** UC1 testen of correct aantal Edelen en correct aantal edelsteenfiches per type op spelbord ligt
* bij verschillend aantal spelers in spel
*/
@BeforeEach
void maakSpelOmAantalFichesEnEdelenTeTesten() {
List<Edelsteenfiche> fiches = new ArrayList<>();
fiches = edelsteenRepo.geefEdelsteenfiches();
spel = new Spel(fiches, new ArrayList<Ontwikkelingskaart>(),
new ArrayList<Ontwikkelingskaart>(), new ArrayList<Ontwikkelingskaart>());
edelen = new ArrayList<>();
edelen = edeleRepo.geefEdele();
}
@Test
void bepaalAantalEdelenEnFichesInSpel_spelMet2Spelers_Returnt3EdelenEn4EdelstenenPerType() {
spel.voegSpelerToe(speler1);
spel.voegSpelerToe(speler2);
spel.setEdelen(edelen);
assertEquals(2, spel.geefAantalSpelers());
assertEquals(3, spel.getEdelen().size()); //controle aantal edelen in spel: 2 spelers = 3 edelen
//controle of spel juiste aantal edelsteenfiches heeft
spel.bepaalAantalEdelsteenfiches();
HashMap<Edelsteenfiche, Integer> aantalPerEdelsteenfiche = spel.getEdelsteenfiches();
assertEquals(5, aantalPerEdelsteenfiche.size()); //test aantal verschillende soorten edelstenen
for(var e : aantalPerEdelsteenfiche.keySet()) { //test voor elke type edelsteenfiche het aantal fiches:
var aantal = aantalPerEdelsteenfiche.get(e);
assertEquals(4, aantal); //Spel met 2spelers heeft 4 fiches per type
}
}
@Test
void bepaalAantalEdelenenEnFichesInSpel_spelMet3Spelers_Returnt4EdelenEn5EdelstenenPerType() {
spel.voegSpelerToe(speler1);
spel.voegSpelerToe(speler2);
spel.voegSpelerToe(speler3);
spel.setEdelen(edelen);
assertEquals(3, spel.geefAantalSpelers());
assertEquals(4, spel.getEdelen().size()); //controle aantal edelen in spel: 3 spelers = 4 edelen
//controle of spel juiste aantal edelsteenfiches heeft
spel.bepaalAantalEdelsteenfiches();
HashMap<Edelsteenfiche, Integer> aantalPerEdelsteenfiche = spel.getEdelsteenfiches();
assertEquals(5, aantalPerEdelsteenfiche.size()); //test aantal verschillende soorten edelstenen
for(var e : aantalPerEdelsteenfiche.keySet()) { //test voor elke type edelsteenfiche het aantal fiches:
var aantal = aantalPerEdelsteenfiche.get(e);
assertEquals(5, aantal); //Spel met 3 spelers heeft 5 fiches per type
}
}
@Test
void bepaalAantalEdelenenEnFichesInSpel_spelMet4Spelers_Returnt5EdelenEn7EdelstenenPerType() {
spel.voegSpelerToe(speler1);
spel.voegSpelerToe(speler2);
spel.voegSpelerToe(speler3);
spel.voegSpelerToe(speler4);
spel.setEdelen(edelen);
assertEquals(4, spel.geefAantalSpelers());
assertEquals(5, spel.getEdelen().size()); //controle aantal edelen in spel: 4 spelers = 5 edelen
//controle of spel juiste aantal edelsteenfiches heeft
spel.bepaalAantalEdelsteenfiches();
HashMap<Edelsteenfiche, Integer> aantalPerEdelsteenfiche = spel.getEdelsteenfiches();
assertEquals(5, aantalPerEdelsteenfiche.size()); //test aantal verschillende soorten edelstenen
for(var e : aantalPerEdelsteenfiche.keySet()) { //test voor elke type edelsteenfiche het aantal fiches:
var aantal = aantalPerEdelsteenfiche.get(e);
assertEquals(7, aantal); //Spel met 4 spelers heeft 7 fiches per type
}
}
/** UC2 Testen: controleren of één of meerdere spelers aangeduid worden als winnaar bij behalen eindscore
*/
@BeforeEach
void maakGeldigSpel() {
geldigSpel = new Spel(new ArrayList<Edelsteenfiche>(), new ArrayList<Ontwikkelingskaart>(),
new ArrayList<Ontwikkelingskaart>(), new ArrayList<Ontwikkelingskaart>());
geldigSpel.voegSpelerToe(speler1);
geldigSpel.voegSpelerToe(speler2);
geldigSpel.voegSpelerToe(speler3);
}
@BeforeEach
void maakOntwikkelingskaarten() {
HashMap<String, Integer> aankoopprijs = new HashMap<String, Integer>();
k0 = new Ontwikkelingskaart(1, 1, 0, 1, aankoopprijs, ""); // kaart id1 niveau1 met 0 prestigepunten, String afbeelding
k1 = new Ontwikkelingskaart(2, 1, 2, 2, aankoopprijs, ""); // kaart id2 niveau1 met 2 prestigepunt
k2 = new Ontwikkelingskaart(3, 2, 3, 3, aankoopprijs, ""); // kaart id3 niveau2 met 3 prestigepunten
k3 = new Ontwikkelingskaart(4, 3, 6, 4, aankoopprijs, ""); // kaart id4 niveau3 met 6 prestigepunten
}
@BeforeEach
void geefSpelersNetNietVoldoendePrestigepuntenInBezit() {
// Speler1 krijgt 4 kaarten en één edele met een totaal aantal aan prestigepunten = 14
speler1.setKaartenInBezit(k0); // kaart met prestigepunten: 0
speler1.setKaartenInBezit(k1); // kaart met prestigepunten: 2
speler1.setKaartenInBezit(k2); // kaart met prestigepunten: 3
speler1.setKaartenInBezit(k3); // kaart met prestigepunten: 6
speler1.voegEdeleInBezitToe(new Edele(1, 3 , new HashMap<String, Integer>(), "")); // edele met prestigepunten: 3
// Speler2 krijgt 4 kaarten met een totaal aantal aan prestigepunten = 14
speler2.setKaartenInBezit(k1); // kaart met prestigepunten: 2
speler2.setKaartenInBezit(k2); // kaart met prestigepunten: 3
speler2.setKaartenInBezit(k2); // kaart met prestigepunten: 3
speler2.setKaartenInBezit(k3); // kaart met prestigepunten: 6
}
@Test
void bepaalScoreEnOfErWinnaarIs_spelersHebbenNetNietVoldoendePrestigepunten_returntGeenWinnaarEnScoreElkeSpeler() {
//controle of spelers kaarten en edelen die ze hebben meegekregen in bezit hebben
assertEquals(4,speler1.getKaartenInBezit().size());
assertEquals(1,speler1.getEdelenInBezit().size());
assertEquals(4,speler2.getKaartenInBezit().size());
assertEquals(0,speler2.getEdelenInBezit().size());
//controle van de score bij onze spelers
assertEquals(14, speler1.getScore()); // totaal aantal prestigepunten in bezit van speler1 = 14
assertEquals(14, speler2.getScore()); // totaal aantal prestigepunten in bezit van speler2 = 14
assertEquals(0, speler3.getScore());
assertFalse(geldigSpel.heeftWinnaars());
}
@Test
void bepaalScoreEnWinnaar_éénSpelerHeeftNetVoldoendePrestigepunten_returntScoreEnNaamWinnaar() {
System.out.println("\nTest bepaalScoreEnWinnaar_éénSpelerHeeftNetVoldoendePrestigepunten_returntScoreEnNaamWinnaar");
speler1.setKaartenInBezit(k1); // speler1 krijgt extra kaart met prestigepunten: 2 en haalt eindscore van 16
assertEquals(16, speler1.getScore());
assertTrue(geldigSpel.heeftWinnaars());
assertTrue(geldigSpel.geefNamenWinnaars().contains("Jean Louis"));
}
@Test
void bepaalScoreEnWinnaars_tweeSpelershebbenGelijkeMaxScoreEnGelijkAantalOntwikkelingskaarten_returntNamen2Winnaars() {
System.out.println("\nTest bepaalScoreEnWinnaars_tweeSpelershebbenGelijkeMaxScoreEnGelijkAantalOntwikkelingskaarten_returntNamen2Winnaars");
speler1.setKaartenInBezit(k2); // speler1 krijgt extra kaart met prestigepunten: 3
speler2.setKaartenInBezit(k2); // speler1 krijgt extra kaart met prestigepunten: 3
//twee spelers hebben een eindscore van 17 behaald en een gelijk aantal ontwikkelingskaarten in bezit
assertEquals(17, speler1.getScore());
assertEquals(17, speler2.getScore());
assertTrue(geldigSpel.heeftWinnaars());
assertTrue(geldigSpel.geefNamenWinnaars().contains("Jean Louis"));
assertTrue(geldigSpel.geefNamenWinnaars().contains("Jean Jacques"));
}
@Test
void bepaalScoreEnWinnaar_tweeSpelershebbenGelijkeMaxScoreMaarOngelijkAantalOntwikkelingskaarten_returntNaamVanEénWinnaar() {
System.out.println("\nTest bepaalScoreEnWinnaar_tweeSpelershebbenGelijkeMaxScoreMaarOngelijkAantalOntwikkelingskaarten_returntNaamVanEénWinnaar");
speler1.setKaartenInBezit(k3); // speler1 krijgt één extra kaart met prestigepunten: 6
speler2.setKaartenInBezit(k2);
speler2.setKaartenInBezit(k2); // speler2 krijgt twee extra kaarten met prestigepunten: 3
//controle of spelers correcte aantal kaarten en edelen die ze hebben meegekregen in bezit hebben
assertEquals(5,speler1.getKaartenInBezit().size());
assertEquals(1,speler1.getEdelenInBezit().size());
assertEquals(6,speler2.getKaartenInBezit().size());
assertEquals(0,speler2.getEdelenInBezit().size());
//beide spelers hebben een eindscore van 20 behaald
assertEquals(20, speler1.getScore());
assertEquals(20, speler2.getScore());
assertTrue(geldigSpel.heeftWinnaars());
//speler1("Jean Louis") heeft één ontwikkelingskaart minder in bezit dan speler2 ("Jean Jacques") en wint het spel
assertTrue(geldigSpel.geefNamenWinnaars().contains("Jean Louis"));
assertFalse(geldigSpel.geefNamenWinnaars().contains("Jean Jacques"));
}
/** UC3 testen: verkrijgen van een tegel (edele)
*/
@BeforeEach
void maakEdelenVoorTestUC3() {
//Aanmaken edele1, kostprijs samenstellen in een Hashmap:
HashMap<String, Integer> kost3Groen3Wit3Zwart = new HashMap<String, Integer>();
kost3Groen3Wit3Zwart.put("smaragd", 3); // instellen 3 groen
kost3Groen3Wit3Zwart.put("diamant", 3); // instellen 3 wit
kost3Groen3Wit3Zwart.put("onyx", 3); // instellen 3 zwart
kost3Groen3Wit3Zwart.put("saffier", 0);
kost3Groen3Wit3Zwart.put("robijn", 0);
// edele1 met idNr=1, 3 prestigepunten en zijn kostprijs
edele1 = new Edele(1, 3, kost3Groen3Wit3Zwart,"");
//Aanmaken edele2, kostprijs samenstellen in een Hashmap:
HashMap<String, Integer> kost3Groen3Wit3Rood = new HashMap<String, Integer>();
kost3Groen3Wit3Rood.put("smaragd", 3); // instellen 3 groen
kost3Groen3Wit3Rood.put("diamant", 3); // instellen 3 wit
kost3Groen3Wit3Rood.put("robijn", 3); // instellen 3 rood
kost3Groen3Wit3Rood.put("saffier", 0);
kost3Groen3Wit3Rood.put("onyx", 0);
// edele2 met idNr=2, 3 prestigepunten en zijn kostprijs
edele2 = new Edele(2, 3, kost3Groen3Wit3Rood,"");
//Aanmaken edele3, kostprijs samenstellen in een Hashmap:
HashMap<String, Integer> kost3Groen3Wit3Blauw = new HashMap<String, Integer>();
kost3Groen3Wit3Rood.put("smaragd", 3); // instellen 3 groen
kost3Groen3Wit3Rood.put("diamant", 3); // instellen 3<SUF>
kost3Groen3Wit3Rood.put("saffier", 3); // instellen 3 blauw
kost3Groen3Wit3Rood.put("onyx", 0);
kost3Groen3Wit3Rood.put("robijn", 0);
// edele met idNr=3, 3 prestigepunten en zijn kostprijs
edele3 = new Edele(3, 3, kost3Groen3Wit3Blauw,"");
}
@BeforeEach
void setUpUC3() {
spelUC3 = new Spel(new ArrayList<Edelsteenfiche>(), new ArrayList<Ontwikkelingskaart>(),
new ArrayList<Ontwikkelingskaart>(), new ArrayList<Ontwikkelingskaart>());
spelerUC3_1 = new Speler("speler 1", 1993);
spelerUC3_2 = new Speler("speler 2", 1993);
spelUC3.voegSpelerToe(spelerUC3_1);
spelUC3.voegSpelerToe(spelerUC3_2);
List<Edele> edelen_UC3 = new ArrayList<>();
edelen_UC3.add(edele1);
edelen_UC3.add(edele2);
edelen_UC3.add(edele3);
spelUC3.setEdelen(edelen_UC3);
spelUC3.bepaalVolgendeSpelerAanDeBeurt();
//speler1 (huidigeSpeler) wordt in het bezit gebracht van ontwikkelingskaarten:
// 3 kaarten met bonusficheId 1 en 3 kaarten met bonusficheId 2
for (int i = 1 ; i <= 3 ; i++) {
spelerUC3_1.setKaartenInBezit(new Ontwikkelingskaart(i , 1, 0, 1, new HashMap<String, Integer>(),""));
spelerUC3_1.setKaartenInBezit(new Ontwikkelingskaart(i+10, 1, 0, 2, new HashMap<String, Integer>(),""));
}
}
@Test
void bepaalHuidigeSpelerInSpelUC3EnZijnStatus_speler1WordtAangesteldAlsHuidigeSpeler() {
//spelUC3.bepaalVolgendeSpelerAanDeBeurt();
Speler huidigeSpeler = spelUC3.getHuidigeSpeler();
//speler1 wordt aangeduid als huidige speler
assertEquals("speler 1", huidigeSpeler.getGebruikersnaam());
//controle kaarten in bezit van speler1
assertEquals(6, spelerUC3_1.getKaartenInBezit().size());
}
@Test
void bepaalOfEdelenInSpelUC3_returntEdeleEnAantalEdelen() {
assertEquals(3, spelUC3.getEdelen().size());
assertTrue(spelUC3.getEdelen().contains(edele1));
}
@Test
void bepaalOfHuidigeSpelerTegelKrijgt_spelerHeeftOnvoldoendeBonusfiches_spelerKrijgtGeenTegel() {
//speler1 heeft edele1 nog niet in zijn bezit
assertFalse(spelerUC3_1.getEdelenInBezit().contains(edele1));
//speler1 wil edele aankopen maar krijgt exception te zien
assertThrows(EdeleNietBeschikbaarException.class, () -> spelUC3.kiesTegel(edele1));
//aangezien speler1 niet de benodigde bonusfiches heeft is aankoop edele niet gelukt
assertFalse(spelerUC3_1.getEdelenInBezit().contains(edele1));
}
@Test
void bepaalOfHuidigeSpelerTegelKrijgt_spelerHeeftVoldoendeBonusfichesVoorEénTegel_spelerKrijgtTegel() {
//speler1 heeft edele1 nog niet in zijn bezit
assertFalse(spelerUC3_1.getEdelenInBezit().contains(edele1));
//speler1 krijgt 3 extra kaarten met bonusficheId 3 zodat speler één tegel kan verkrijgen
for (int i = 1 ; i <= 3 ; i++) {
spelerUC3_1.setKaartenInBezit(new Ontwikkelingskaart(i+20, 1, 0, 4, new HashMap<String, Integer>(),""));
}
//speler1 wil edele aankopen
spelUC3.kiesTegel(edele1);
//speler1 heeft tegel succesvol in bezit genomen
assertTrue(spelerUC3_1.getEdelenInBezit().contains(edele1));
//controle of tegel (edele1) is verwijderd uit aanbod na aankoop
assertEquals(2, spelUC3.getEdelen().size());
assertFalse(spelUC3.getEdelen().contains(edele1));
}
}
|
199548_4 | package com.jstarcraft.core.cache.proxy;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import com.jstarcraft.core.cache.CacheInformation;
import com.jstarcraft.core.cache.annotation.CacheChange;
import com.jstarcraft.core.common.conversion.ConversionUtility;
import com.jstarcraft.core.utility.StringUtility;
import javassist.CtClass;
import javassist.CtMethod;
/**
* 实体代理
*
* @author Birdy
*
*/
public class JavassistEntityProxy extends JavassistProxy {
public JavassistEntityProxy(ProxyManager proxyManager, CacheInformation cacheInformation) {
super(proxyManager, cacheInformation);
}
/**
* 代理方法
*
* <pre>
* // TODO 索引变更部分
* CacheInformation cacheInformation = _manager.getCacheInformation();
* String[] values = _indexChange != null ? _indexChange.values() : new String[] {};
* TreeSet<String> indexNames = new TreeSet(Arrays.asList(values));
* LinkedList<Lock> locks = new LinkedList<Lock>();
* for (String name : indexNames) {
* locks.addLast(cacheInformation.getIndexWriteLock(name));
* }
* Object value = null;
* try {
* for (Lock lock : locks) {
* lock.lock();
* }
* Map<String, Object> oldIndexValues = cacheInformation.getIndexValues(_object, indexNames);
* value = method.invoke(_object);
* Map<String, Object> newIndexValues = cacheInformation.getIndexValues(_object, indexNames);
* boolean result = true;
* for (Entry<String, Object> entry : newIndexValues.entrySet()) {
* if (_manager.hasUnique(entry.getKey(), entry.getValue())) {
* result = false;
* break;
* }
* }
* if (result) {
* for (Entry<String, Object> entry : newIndexValues.entrySet()) {
* _manager.modifyUnique(_object.getId(), entry.getKey(), entry.getValue());
* }
* } else {
* cacheInformation.setIndexValues(_object, oldIndexValues);
* }
* } finally {
* for (Lock lock : locks) {
* lock.unlock();
* }
* }
* // TODO 数据变更部分
* if (_dataChange != null) {
* if (returnType == void.class) {
* _manager.modifyDatas(_object.getId(), _object);
* } else {
* TreeSet<String> resultValues = new TreeSet(Arrays.asList(_dataChange.values()));
* if (resultValues.contains(value.toString())) {
* _manager.modifyDatas(_object.getId(), _object);
* }
* }
* }
* // TODO 返回值部分
* if (returnType != void.class) {
* return value;
* }
* </pre>
*/
final void proxyMethod(Class<?> clazz, CtClass proxyClazz, Method method, CacheChange cacheChange) throws Exception {
Class<?> returnType = method.getReturnType();
CtMethod proxyMethod = new CtMethod(classPool.get(returnType.getName()), method.getName(), toProxyClasses(method.getParameterTypes()), proxyClazz);
proxyMethod.setModifiers(Modifier.PUBLIC);
if (method.getExceptionTypes().length != 0) {
proxyMethod.setExceptionTypes(toProxyClasses(method.getExceptionTypes()));
}
StringBuilder methodBuffer = new StringBuilder("{");
methodBuffer.append(StringUtility.format("{} methodId = {}.valueOf({});", Integer.class.getName(), Integer.class.getName(), cacheInformation.getMethodId(method)));
methodBuffer.append(StringUtility.format("{} changeValues = _information.getMethodChanges(methodId);", HashSet.class.getName()));
// TODO 索引变更部分
// if (!indexChanges.isEmpty()) {
// methodBuilder.append(StringUtility.format("{} indexNames = ({})
// (keyValue.getKey());", TreeSet.class.getName(), TreeSet.class.getName()));
// methodBuilder.append(StringUtility.format("{} newIndexValues = new {}();",
// HashMap.class.getName(), HashMap.class.getName()));
// for (Entry<IndexChange, Integer> entry : indexChanges.entrySet()) {
// methodBuilder.append(StringUtility.format("indexNames.add(\"{}\");",
// entry.getKey().value()));
// methodBuilder.append(StringUtility.format("newIndexValues.put(\"{}\",
// {}.primitiveToWrap(${}));", entry.getKey().value(),
// ConversionUtility.class.getName(), entry.getValue()));
// }
// }
if (returnType != void.class) {
String typeName = returnType.isArray() ? toArrayType(returnType) : returnType.getName();
if (returnType.isPrimitive()) {
methodBuffer.append(StringUtility.format("{} value;", typeName));
} else {
methodBuffer.append(StringUtility.format("{} value = null;", typeName));
}
}
methodBuffer.append(StringUtility.format("try {"));
// if (!indexChanges.isEmpty()) {
// methodBuilder.append(StringUtility.format("
// _information.lockIndexWriteLocks(indexNames);"));
// methodBuilder.append(StringUtility.format(" {} checkIterator =
// newIndexValues.entrySet().iterator();", Iterator.class.getName()));
// methodBuilder.append(StringUtility.format(" while(checkIterator.hasNext())
// {"));
// methodBuilder.append(StringUtility.format(" {} entry =
// checkIterator.next();", Entry.class.getName()));
// methodBuilder.append(StringUtility.format(" boolean has =
// _manager.hasIndex((String) entry.getKey(), entry.getValue());"));
// methodBuilder.append(StringUtility.format(" if (has) {"));
// methodBuilder.append(StringUtility.format(" throw new {}();",
// JavassistEntityProxy.TYPE_INDEX_EXCEPTION));
// methodBuilder.append(StringUtility.format(" }"));
// methodBuilder.append(StringUtility.format(" }"));
// methodBuilder.append(StringUtility.format(" {} oldIndexValues =
// _information.getIndexValues(_instance, indexNames);", Map.class.getName()));
// }
if (returnType != void.class) {
methodBuffer.append(StringUtility.format(" value = super.{}($$);", method.getName()));
} else {
methodBuffer.append(StringUtility.format(" super.{}($$);", method.getName()));
}
// TODO 数据变更部分
if (cacheChange != null) {
if (returnType == void.class) {
// if (!indexChanges.isEmpty()) {
// methodBuilder.append(StringUtility.format(" _manager.modifyIndexes(_instance,
// newIndexValues, oldIndexValues);"));
// }
methodBuffer.append(StringUtility.format(" _manager.modifyInstance(this);"));
} else {
if (cacheChange.values().length > 0) {
methodBuffer.append(StringUtility.format(" if (changeValues.contains({}.primitiveToWrap(value))) {", ConversionUtility.class.getName()));
}
// if (!indexChanges.isEmpty()) {
// methodBuilder.append(StringUtility.format(" _manager.modifyIndexes(_instance,
// newIndexValues, oldIndexValues);"));
// }
methodBuffer.append(StringUtility.format(" _manager.modifyInstance(this);"));
if (cacheChange.values().length > 0) {
methodBuffer.append(StringUtility.format(" }"));
}
}
} else {
// if (!indexChanges.isEmpty()) {
// methodBuilder.append(StringUtility.format(" _manager.modifyIndexes(_instance,
// newIndexValues, oldIndexValues);"));
// }
}
methodBuffer.append(StringUtility.format("} finally {"));
// if (!indexChanges.isEmpty()) {
// methodBuilder.append(StringUtility.format("
// _information.unlockIndexWriteLocks(indexNames);"));
// }
methodBuffer.append(StringUtility.format("}"));
// TODO 返回值部分
if (returnType != void.class) {
methodBuffer.append(StringUtility.format("return value;"));
}
methodBuffer.append(StringUtility.format("}"));
proxyMethod.setBody(methodBuffer.toString());
proxyClazz.addMethod(proxyMethod);
}
}
| HongZhaoHua/jstarcraft-core | jstarcraft-core-cache/src/main/java/com/jstarcraft/core/cache/proxy/JavassistEntityProxy.java | 2,391 | // (keyValue.getKey());", TreeSet.class.getName(), TreeSet.class.getName()));
| line_comment | nl | package com.jstarcraft.core.cache.proxy;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import com.jstarcraft.core.cache.CacheInformation;
import com.jstarcraft.core.cache.annotation.CacheChange;
import com.jstarcraft.core.common.conversion.ConversionUtility;
import com.jstarcraft.core.utility.StringUtility;
import javassist.CtClass;
import javassist.CtMethod;
/**
* 实体代理
*
* @author Birdy
*
*/
public class JavassistEntityProxy extends JavassistProxy {
public JavassistEntityProxy(ProxyManager proxyManager, CacheInformation cacheInformation) {
super(proxyManager, cacheInformation);
}
/**
* 代理方法
*
* <pre>
* // TODO 索引变更部分
* CacheInformation cacheInformation = _manager.getCacheInformation();
* String[] values = _indexChange != null ? _indexChange.values() : new String[] {};
* TreeSet<String> indexNames = new TreeSet(Arrays.asList(values));
* LinkedList<Lock> locks = new LinkedList<Lock>();
* for (String name : indexNames) {
* locks.addLast(cacheInformation.getIndexWriteLock(name));
* }
* Object value = null;
* try {
* for (Lock lock : locks) {
* lock.lock();
* }
* Map<String, Object> oldIndexValues = cacheInformation.getIndexValues(_object, indexNames);
* value = method.invoke(_object);
* Map<String, Object> newIndexValues = cacheInformation.getIndexValues(_object, indexNames);
* boolean result = true;
* for (Entry<String, Object> entry : newIndexValues.entrySet()) {
* if (_manager.hasUnique(entry.getKey(), entry.getValue())) {
* result = false;
* break;
* }
* }
* if (result) {
* for (Entry<String, Object> entry : newIndexValues.entrySet()) {
* _manager.modifyUnique(_object.getId(), entry.getKey(), entry.getValue());
* }
* } else {
* cacheInformation.setIndexValues(_object, oldIndexValues);
* }
* } finally {
* for (Lock lock : locks) {
* lock.unlock();
* }
* }
* // TODO 数据变更部分
* if (_dataChange != null) {
* if (returnType == void.class) {
* _manager.modifyDatas(_object.getId(), _object);
* } else {
* TreeSet<String> resultValues = new TreeSet(Arrays.asList(_dataChange.values()));
* if (resultValues.contains(value.toString())) {
* _manager.modifyDatas(_object.getId(), _object);
* }
* }
* }
* // TODO 返回值部分
* if (returnType != void.class) {
* return value;
* }
* </pre>
*/
final void proxyMethod(Class<?> clazz, CtClass proxyClazz, Method method, CacheChange cacheChange) throws Exception {
Class<?> returnType = method.getReturnType();
CtMethod proxyMethod = new CtMethod(classPool.get(returnType.getName()), method.getName(), toProxyClasses(method.getParameterTypes()), proxyClazz);
proxyMethod.setModifiers(Modifier.PUBLIC);
if (method.getExceptionTypes().length != 0) {
proxyMethod.setExceptionTypes(toProxyClasses(method.getExceptionTypes()));
}
StringBuilder methodBuffer = new StringBuilder("{");
methodBuffer.append(StringUtility.format("{} methodId = {}.valueOf({});", Integer.class.getName(), Integer.class.getName(), cacheInformation.getMethodId(method)));
methodBuffer.append(StringUtility.format("{} changeValues = _information.getMethodChanges(methodId);", HashSet.class.getName()));
// TODO 索引变更部分
// if (!indexChanges.isEmpty()) {
// methodBuilder.append(StringUtility.format("{} indexNames = ({})
// (keyValue.getKey());", TreeSet.class.getName(),<SUF>
// methodBuilder.append(StringUtility.format("{} newIndexValues = new {}();",
// HashMap.class.getName(), HashMap.class.getName()));
// for (Entry<IndexChange, Integer> entry : indexChanges.entrySet()) {
// methodBuilder.append(StringUtility.format("indexNames.add(\"{}\");",
// entry.getKey().value()));
// methodBuilder.append(StringUtility.format("newIndexValues.put(\"{}\",
// {}.primitiveToWrap(${}));", entry.getKey().value(),
// ConversionUtility.class.getName(), entry.getValue()));
// }
// }
if (returnType != void.class) {
String typeName = returnType.isArray() ? toArrayType(returnType) : returnType.getName();
if (returnType.isPrimitive()) {
methodBuffer.append(StringUtility.format("{} value;", typeName));
} else {
methodBuffer.append(StringUtility.format("{} value = null;", typeName));
}
}
methodBuffer.append(StringUtility.format("try {"));
// if (!indexChanges.isEmpty()) {
// methodBuilder.append(StringUtility.format("
// _information.lockIndexWriteLocks(indexNames);"));
// methodBuilder.append(StringUtility.format(" {} checkIterator =
// newIndexValues.entrySet().iterator();", Iterator.class.getName()));
// methodBuilder.append(StringUtility.format(" while(checkIterator.hasNext())
// {"));
// methodBuilder.append(StringUtility.format(" {} entry =
// checkIterator.next();", Entry.class.getName()));
// methodBuilder.append(StringUtility.format(" boolean has =
// _manager.hasIndex((String) entry.getKey(), entry.getValue());"));
// methodBuilder.append(StringUtility.format(" if (has) {"));
// methodBuilder.append(StringUtility.format(" throw new {}();",
// JavassistEntityProxy.TYPE_INDEX_EXCEPTION));
// methodBuilder.append(StringUtility.format(" }"));
// methodBuilder.append(StringUtility.format(" }"));
// methodBuilder.append(StringUtility.format(" {} oldIndexValues =
// _information.getIndexValues(_instance, indexNames);", Map.class.getName()));
// }
if (returnType != void.class) {
methodBuffer.append(StringUtility.format(" value = super.{}($$);", method.getName()));
} else {
methodBuffer.append(StringUtility.format(" super.{}($$);", method.getName()));
}
// TODO 数据变更部分
if (cacheChange != null) {
if (returnType == void.class) {
// if (!indexChanges.isEmpty()) {
// methodBuilder.append(StringUtility.format(" _manager.modifyIndexes(_instance,
// newIndexValues, oldIndexValues);"));
// }
methodBuffer.append(StringUtility.format(" _manager.modifyInstance(this);"));
} else {
if (cacheChange.values().length > 0) {
methodBuffer.append(StringUtility.format(" if (changeValues.contains({}.primitiveToWrap(value))) {", ConversionUtility.class.getName()));
}
// if (!indexChanges.isEmpty()) {
// methodBuilder.append(StringUtility.format(" _manager.modifyIndexes(_instance,
// newIndexValues, oldIndexValues);"));
// }
methodBuffer.append(StringUtility.format(" _manager.modifyInstance(this);"));
if (cacheChange.values().length > 0) {
methodBuffer.append(StringUtility.format(" }"));
}
}
} else {
// if (!indexChanges.isEmpty()) {
// methodBuilder.append(StringUtility.format(" _manager.modifyIndexes(_instance,
// newIndexValues, oldIndexValues);"));
// }
}
methodBuffer.append(StringUtility.format("} finally {"));
// if (!indexChanges.isEmpty()) {
// methodBuilder.append(StringUtility.format("
// _information.unlockIndexWriteLocks(indexNames);"));
// }
methodBuffer.append(StringUtility.format("}"));
// TODO 返回值部分
if (returnType != void.class) {
methodBuffer.append(StringUtility.format("return value;"));
}
methodBuffer.append(StringUtility.format("}"));
proxyMethod.setBody(methodBuffer.toString());
proxyClazz.addMethod(proxyMethod);
}
}
|
196616_17 | /*
* L2jFrozen Project - www.l2jfrozen.com
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jfrozen.gameserver.managers;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Future;
import javolution.util.FastList;
import org.apache.log4j.Logger;
import com.l2jfrozen.Config;
import com.l2jfrozen.gameserver.datatables.sql.ItemTable;
import com.l2jfrozen.gameserver.datatables.sql.NpcTable;
import com.l2jfrozen.gameserver.datatables.sql.SpawnTable;
import com.l2jfrozen.gameserver.idfactory.IdFactory;
import com.l2jfrozen.gameserver.model.L2Attackable;
import com.l2jfrozen.gameserver.model.L2Object;
import com.l2jfrozen.gameserver.model.L2World;
import com.l2jfrozen.gameserver.model.actor.instance.L2ItemInstance;
import com.l2jfrozen.gameserver.model.actor.instance.L2NpcInstance;
import com.l2jfrozen.gameserver.model.actor.instance.L2PcInstance;
import com.l2jfrozen.gameserver.model.entity.Announcements;
import com.l2jfrozen.gameserver.model.spawn.L2Spawn;
import com.l2jfrozen.gameserver.network.SystemMessageId;
import com.l2jfrozen.gameserver.network.serverpackets.CreatureSay;
import com.l2jfrozen.gameserver.network.serverpackets.SystemMessage;
import com.l2jfrozen.gameserver.templates.L2NpcTemplate;
import com.l2jfrozen.gameserver.thread.ThreadPoolManager;
/**
* control for sequence of Christmas.
* @version 1.00
* @author Darki699
*/
public class ChristmasManager
{
private static final Logger LOGGER = Logger.getLogger(ChristmasManager.class);
protected List<L2NpcInstance> objectQueue = new FastList<>();
protected Random rand = new Random();
// X-Mas message list
protected String[] message =
{
"Ho Ho Ho... Merry Christmas!",
"God is Love...",
"Christmas is all about love...",
"Christmas is thus about God and Love...",
"Love is the key to peace among all Lineage creature kind..",
"Love is the key to peace and happiness within all creation...",
"Love needs to be practiced - Love needs to flow - Love needs to make happy...",
"Love starts with your partner, children and family and expands to all world.",
"God bless all kind.",
"God bless Lineage.",
"Forgive all.",
"Ask for forgiveness even from all the \"past away\" ones.",
"Give love in many different ways to your family members, relatives, neighbors and \"foreigners\".",
"Enhance the feeling within yourself of being a member of a far larger family than your physical family",
"MOST important - Christmas is a feast of BLISS given to YOU from God and all beloved ones back home in God !!",
"Open yourself for all divine bliss, forgiveness and divine help that is offered TO YOU by many others AND GOD.",
"Take it easy. Relax these coming days.",
"Every day is Christmas day - it is UP TO YOU to create the proper inner attitude and opening for love toward others AND from others within YOUR SELF !",
"Peace and Silence. Reduced activities. More time for your most direct families. If possible NO other dates or travel may help you most to actually RECEIVE all offered bliss.",
"What ever is offered to you from God either enters YOUR heart and soul or is LOST for GOOD !!! or at least until another such day - next year Christmas or so !!",
"Divine bliss and love NEVER can be stored and received later.",
"There is year round a huge quantity of love and bliss available from God and your Guru and other loving souls, but Christmas days are an extended period FOR ALL PLANET",
"Please open your heart and accept all love and bliss - For your benefit as well as for the benefit of all your beloved ones.",
"Beloved children of God",
"Beyond Christmas days and beyond Christmas season - The Christmas love lives on, the Christmas bliss goes on, the Christmas feeling expands.",
"The holy spirit of Christmas is the holy spirit of God and God's love for all days.",
"When the Christmas spirit lives on and on...",
"When the power of love created during the pre-Christmas days is kept alive and growing.",
"Peace among all mankind is growing as well =)",
"The holy gift of love is an eternal gift of love put into your heart like a seed.",
"Dozens of millions of humans worldwide are changing in their hearts during weeks of pre-Christmas time and find their peak power of love on Christmas nights and Christmas days.",
"What is special during these days, to give all of you this very special power of love, the power to forgive, the power to make others happy, power to join the loved one on his or her path of loving life.",
"It only is your now decision that makes the difference !",
"It only is your now focus in life that makes all the changes. It is your shift from purely worldly matters toward the power of love from God that dwells within all of us that gave you the power to change your own behavior from your normal year long behavior.",
"The decision of love, peace and happiness is the right one.",
"Whatever you focus on is filling your mind and subsequently filling your heart.",
"No one else but you have change your focus these past Christmas days and the days of love you may have experienced in earlier Christmas seasons.",
"God's love is always present.",
"God's Love has always been in same power and purity and quantity available to all of you.",
"Expand the spirit of Christmas love and Christmas joy to span all year of your life...",
"Do all year long what is creating this special Christmas feeling of love joy and happiness.",
"Expand the true Christmas feeling, expand the love you have ever given at your maximum power of love days ... ",
"Expand the power of love over more and more days.",
"Re-focus on what has brought your love to its peak power and refocus on those objects and actions in your focus of mind and actions.",
"Remember the people and surrounding you had when feeling most happy, most loved, most magic",
"People of true loving spirit - who all was present, recall their names, recall the one who may have had the greatest impact in love those hours of magic moments of love...",
"The decoration of your surrounding - Decoration may help to focus on love - Or lack of decoration may make you drift away into darkness or business - away from love...",
"Love songs, songs full of living joy - any of the thousands of true touching love songs and happy songs do contribute to the establishment of an inner attitude perceptible of love.",
"Songs can fine tune and open our heart for love from God and our loved ones.",
"Your power of will and focus of mind can keep Christmas Love and Christmas joy alive beyond Christmas season for eternity",
"Enjoy your love for ever!",
"Christmas can be every day - As soon as you truly love every day =)",
"Christmas is when you love all and are loved by all.",
"Christmas is when you are truly happy by creating true happiness in others with love from the bottom of your heart.",
"Secret in God's creation is that no single person can truly love without ignition of his love.",
"You need another person to love and to receive love, a person to truly fall in love to ignite your own divine fire of love. ",
"God created many and all are made of love and all are made to love...",
"The miracle of love only works if you want to become a fully loving member of the family of divine love.",
"Once you have started to fall in love with the one God created for you - your entire eternal life will be a permanent fire of miracles of love ... Eternally !",
"May all have a happy time on Christmas each year. Merry Christmas!",
"Christmas day is a time for love. It is a time for showing our affection to our loved ones. It is all about love.",
"Have a wonderful Christmas. May god bless our family. I love you all.",
"Wish all living creatures a Happy X-mas and a Happy New Year! By the way I would like us to share a warm fellowship in all places.",
"Just as animals need peace of mind, poeple and also trees need peace of mind. This is why I say, all creatures are waiting upon the Lord for their salvation. May God bless you all creatures in the whole world.",
"Merry Xmas!",
"May the grace of Our Mighty Father be with you all during this eve of Christmas. Have a blessed Christmas and a happy New Year.",
"Merry Christmas my children. May this new year give all of the things you rightly deserve. And may peace finally be yours.",
"I wish everybody a Merry Christmas! May the Holy Spirit be with you all the time.",
"May you have the best of Christmas this year and all your dreams come true.",
"May the miracle of Christmas fill your heart with warmth and love. Merry Christmas!"
},
sender =
{
"Santa Claus",
"Papai Noel",
"Shengdan Laoren",
"Santa",
"Viejo Pascuero",
"Sinter Klaas",
"Father Christmas",
"Saint Nicholas",
"Joulupukki",
"Pere Noel",
"Saint Nikolaus",
"Kanakaloka",
"De Kerstman",
"Winter grandfather",
"Babbo Natale",
"Hoteiosho",
"Kaledu Senelis",
"Black Peter",
"Kerstman",
"Julenissen",
"Swiety Mikolaj",
"Ded Moroz",
"Julenisse",
"El Nino Jesus",
"Jultomten",
"Reindeer Dasher",
"Reindeer Dancer",
"Christmas Spirit",
"Reindeer Prancer",
"Reindeer Vixen",
"Reindeer Comet",
"Reindeer Cupid",
"Reindeer Donner",
"Reindeer Donder",
"Reindeer Dunder",
"Reindeer Blitzen",
"Reindeer Bliksem",
"Reindeer Blixem",
"Reindeer Rudolf",
"Christmas Elf"
};
// Presents List:
protected int[] presents =
{
5560,
5560,
5560,
5560,
5560, /* x-mas tree */
5560,
5560,
5560,
5560,
5560,
5561,
5561,
5561,
5561,
5561, /* special x-mas tree */
5562,
5562,
5562,
5562, /* 1st Carol */
5563,
5563,
5563,
5563, /* 2nd Carol */
5564,
5564,
5564,
5564, /* 3rd Carol */
5565,
5565,
5565,
5565, /* 4th Carol */
5566,
5566,
5566,
5566, /* 5th Carol */
5583,
5583, /* 6th Carol */
5584,
5584, /* 7th Carol */
5585,
5585, /* 8th Carol */
5586,
5586, /* 9th Carol */
5587,
5587, /* 10th Carol */
6403,
6403,
6403,
6403, /* Star Shard */
6403,
6403,
6403,
6403,
6406,
6406,
6406,
6406, /* FireWorks */
6407,
6407, /* Large FireWorks */
5555, /* Token of Love */
7836, /* Santa Hat #1 */
9138, /* Santa Hat #2 */
8936, /* Santa's Antlers Hat */
6394, /* Red Party Mask */
5808
/* Black Party Mask */
};
// The message task sent at fixed rate
protected Future<?> _XMasMessageTask = null, _XMasPresentsTask = null;
// Manager should only be Initialized once:
protected int isManagerInit = 0;
// Interval of Christmas actions:
protected long _IntervalOfChristmas = 600000; // 10 minutes
private final int first = 25000, last = 73099;
/************************************** Initial Functions **************************************/
/**
* Empty constructor Does nothing
*/
public ChristmasManager()
{
//
}
/**
* @return an instance of <b>this</b> InstanceManager.
*/
public static ChristmasManager getInstance()
{
return SingletonHolder._instance;
}
/**
* initialize <b>this</b> ChristmasManager
* @param activeChar
*/
public void init(final L2PcInstance activeChar)
{
if (isManagerInit > 0)
{
activeChar.sendMessage("Christmas Manager has already begun or is processing. Please be patient....");
return;
}
activeChar.sendMessage("Started!!!! This will take a 2-3 hours (in order to reduce system lags to a minimum), please be patient... The process is working in the background and will spawn npcs, give presents and messages at a fixed rate.");
// Tasks:
spawnTrees();
startFestiveMessagesAtFixedRate();
isManagerInit++;
givePresentsAtFixedRate();
isManagerInit++;
checkIfOkToAnnounce();
}
/**
* ends <b>this</b> ChristmasManager
* @param activeChar
*/
public void end(final L2PcInstance activeChar)
{
if (isManagerInit < 4)
{
if (activeChar != null)
{
activeChar.sendMessage("Christmas Manager is not activated yet. Already Ended or is now processing....");
}
return;
}
if (activeChar != null)
{
activeChar.sendMessage("Terminating! This may take a while, please be patient...");
}
// Tasks:
ThreadPoolManager.getInstance().executeTask(new DeleteSpawns());
endFestiveMessagesAtFixedRate();
isManagerInit--;
endPresentGivingAtFixedRate();
isManagerInit--;
checkIfOkToAnnounce();
}
/************************************ - Tree management - *************************************/
/**
* Main function - spawns all trees.
*/
public void spawnTrees()
{
GetTreePos gtp = new GetTreePos(first);
ThreadPoolManager.getInstance().executeTask(gtp);
gtp = null;
}
/**
* returns a random X-Mas tree Npc Id.
* @return int tree Npc Id.
*/
protected int getTreeId()
{
final int[] ids =
{
13006,
13007
};
return ids[rand.nextInt(ids.length)];
}
/**
* gets random world positions according to spawned world objects and spawns x-mas trees around them...
*/
public class GetTreePos implements Runnable
{
private int _iterator;
private Future<?> _task;
public GetTreePos(final int iter)
{
_iterator = iter;
}
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
try
{
L2Object obj = null;
while (obj == null)
{
obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn();
_iterator++;
if (obj != null && obj instanceof L2Attackable)
if (rand.nextInt(100) > 10)
{
obj = null;
}
}
if (rand.nextInt(100) > 50)
{
spawnOneTree(getTreeId(), obj.getX() + rand.nextInt(200) - 100, obj.getY() + rand.nextInt(200) - 100, obj.getZ());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
if (_iterator >= last)
{
isManagerInit++;
SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(first);
_task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300);
ssNPCs.setTask(_task);
ssNPCs = null;
return;
}
_iterator++;
GetTreePos gtp = new GetTreePos(_iterator);
_task = ThreadPoolManager.getInstance().scheduleGeneral(gtp, 300);
gtp.setTask(_task);
gtp = null;
}
}
/**
* Delete all x-mas spawned trees from the world. Delete all x-mas trees spawns, and clears the L2NpcInstance tree queue.
*/
public class DeleteSpawns implements Runnable
{
@Override
public void run()
{
if (objectQueue == null || objectQueue.isEmpty())
return;
for (final L2NpcInstance deleted : objectQueue)
{
if (deleted == null)
{
continue;
}
try
{
L2World.getInstance().removeObject(deleted);
deleted.decayMe();
deleted.deleteMe();
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
continue;
}
}
objectQueue.clear();
objectQueue = null;
isManagerInit = isManagerInit - 2;
checkIfOkToAnnounce();
}
}
/**
* Spawns one x-mas tree at a given location x,y,z
* @param id - int tree npc id.
* @param x - int loc x
* @param y - int loc y
* @param z - int loc z
*/
protected void spawnOneTree(final int id, final int x, final int y, final int z)
{
try
{
L2NpcTemplate template1 = NpcTable.getInstance().getTemplate(id);
L2Spawn spawn = new L2Spawn(template1);
template1 = null;
spawn.setId(IdFactory.getInstance().getNextId());
spawn.setLocx(x);
spawn.setLocy(y);
spawn.setLocz(z);
L2NpcInstance tree = spawn.spawnOne();
L2World.getInstance().storeObject(tree);
objectQueue.add(tree);
spawn = null;
tree = null;
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
}
/**************************** - send players festive messages - *****************************/
/**
* Ends X-Mas messages sent to players, and terminates the thread.
*/
private void endFestiveMessagesAtFixedRate()
{
if (_XMasMessageTask != null)
{
_XMasMessageTask.cancel(true);
_XMasMessageTask = null;
}
}
/**
* Starts X-Mas messages sent to all players, and initialize the thread.
*/
private void startFestiveMessagesAtFixedRate()
{
SendXMasMessage XMasMessage = new SendXMasMessage();
_XMasMessageTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasMessage, 60000, _IntervalOfChristmas);
XMasMessage = null;
}
/**
* Sends X-Mas messages to all world players.
* @author Darki699
*/
class SendXMasMessage implements Runnable
{
@Override
public void run()
{
try
{
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers())
{
if (pc == null)
{
continue;
}
else if (pc.isOnline() == 0)
{
continue;
}
pc.sendPacket(getXMasMessage());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
}
}
/**
* Returns a random X-Mas message.
* @return CreatureSay message
*/
protected CreatureSay getXMasMessage()
{
final CreatureSay cs = new CreatureSay(0, 17, getRandomSender(), getRandomXMasMessage());
return cs;
}
/**
* Returns a random name of the X-Mas message sender, sent to players
* @return String of the message sender's name
*/
private String getRandomSender()
{
return sender[rand.nextInt(sender.length)];
}
/**
* Returns a random X-Mas message String
* @return String containing the random message.
*/
private String getRandomXMasMessage()
{
return message[rand.nextInt(message.length)];
}
/******************************* - give special items trees - ********************************/
// Trees , Carols , Tokens of love, Fireworks, Santa Hats.
/**
* Starts X-Mas Santa presents sent to all players, and initialize the thread.
*/
private void givePresentsAtFixedRate()
{
final XMasPresentGivingTask XMasPresents = new XMasPresentGivingTask();
_XMasPresentsTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasPresents, _IntervalOfChristmas, _IntervalOfChristmas * 3);
}
class XMasPresentGivingTask implements Runnable
{
@Override
public void run()
{
try
{
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers())
{
if (pc == null)
{
continue;
}
else if (pc.isOnline() == 0)
{
continue;
}
else if (pc.getInventoryLimit() <= pc.getInventory().getSize())
{
pc.sendMessage("Santa wanted to give you a Present but your inventory was full :(");
continue;
}
else if (rand.nextInt(100) < 50)
{
final int itemId = getSantaRandomPresent();
L2ItemInstance item = ItemTable.getInstance().createItem("Christmas Event", itemId, 1, pc);
pc.getInventory().addItem("Christmas Event", item.getItemId(), 1, pc, pc);
String itemName = ItemTable.getInstance().getTemplate(itemId).getName();
item = null;
SystemMessage sm;
sm = new SystemMessage(SystemMessageId.EARNED_ITEM);
sm.addString(itemName + " from Santa's Present Bag...");
pc.broadcastPacket(sm);
itemName = null;
sm = null;
}
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
}
}
protected int getSantaRandomPresent()
{
return presents[rand.nextInt(presents.length)];
}
/**
* Ends X-Mas present giving to players, and terminates the thread.
*/
private void endPresentGivingAtFixedRate()
{
if (_XMasPresentsTask != null)
{
_XMasPresentsTask.cancel(true);
_XMasPresentsTask = null;
}
}
/************************************ - spawn NPCs in towns - ***************************************/
// NPC Ids: 31863 , 31864
public class SpawnSantaNPCs implements Runnable
{
private int _iterator;
private Future<?> _task;
public SpawnSantaNPCs(final int iter)
{
_iterator = iter;
}
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
try
{
L2Object obj = null;
while (obj == null)
{
obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn();
_iterator++;
if (obj != null && obj instanceof L2Attackable)
{
obj = null;
}
}
if (rand.nextInt(100) < 80 && obj instanceof L2NpcInstance)
{
spawnOneTree(getSantaId(), obj.getX() + rand.nextInt(500) - 250, obj.getY() + rand.nextInt(500) - 250, obj.getZ());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
if (_iterator >= last)
{
isManagerInit++;
checkIfOkToAnnounce();
return;
}
_iterator++;
SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(_iterator);
_task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300);
ssNPCs.setTask(_task);
ssNPCs = null;
}
}
protected int getSantaId()
{
return rand.nextInt(100) < 50 ? 31863 : 31864;
}
protected void checkIfOkToAnnounce()
{
if (isManagerInit == 4)
{
Announcements.getInstance().announceToAll("Christmas Event has begun, have a Merry Christmas and a Happy New Year.");
Announcements.getInstance().announceToAll("Christmas Event will end in 24 hours.");
LOGGER.info("ChristmasManager:Init ChristmasManager was started successfully, have a festive holiday.");
final EndEvent ee = new EndEvent();
Future<?> task = ThreadPoolManager.getInstance().scheduleGeneral(ee, 86400000);
ee.setTask(task);
task = null;
isManagerInit = 5;
}
if (isManagerInit == 0)
{
Announcements.getInstance().announceToAll("Christmas Event has ended... Hope you enjoyed the festivities.");
LOGGER.info("ChristmasManager:Terminated ChristmasManager.");
isManagerInit = -1;
}
}
public class EndEvent implements Runnable
{
private Future<?> _task;
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
end(null);
}
}
private static class SingletonHolder
{
protected static final ChristmasManager _instance = new ChristmasManager();
}
}
| Horckun/L2jHorckun | L2jFrozen_GameServer/head-src/com/l2jfrozen/gameserver/managers/ChristmasManager.java | 7,691 | /************************************ - Tree management - *************************************/ | block_comment | nl | /*
* L2jFrozen Project - www.l2jfrozen.com
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jfrozen.gameserver.managers;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Future;
import javolution.util.FastList;
import org.apache.log4j.Logger;
import com.l2jfrozen.Config;
import com.l2jfrozen.gameserver.datatables.sql.ItemTable;
import com.l2jfrozen.gameserver.datatables.sql.NpcTable;
import com.l2jfrozen.gameserver.datatables.sql.SpawnTable;
import com.l2jfrozen.gameserver.idfactory.IdFactory;
import com.l2jfrozen.gameserver.model.L2Attackable;
import com.l2jfrozen.gameserver.model.L2Object;
import com.l2jfrozen.gameserver.model.L2World;
import com.l2jfrozen.gameserver.model.actor.instance.L2ItemInstance;
import com.l2jfrozen.gameserver.model.actor.instance.L2NpcInstance;
import com.l2jfrozen.gameserver.model.actor.instance.L2PcInstance;
import com.l2jfrozen.gameserver.model.entity.Announcements;
import com.l2jfrozen.gameserver.model.spawn.L2Spawn;
import com.l2jfrozen.gameserver.network.SystemMessageId;
import com.l2jfrozen.gameserver.network.serverpackets.CreatureSay;
import com.l2jfrozen.gameserver.network.serverpackets.SystemMessage;
import com.l2jfrozen.gameserver.templates.L2NpcTemplate;
import com.l2jfrozen.gameserver.thread.ThreadPoolManager;
/**
* control for sequence of Christmas.
* @version 1.00
* @author Darki699
*/
public class ChristmasManager
{
private static final Logger LOGGER = Logger.getLogger(ChristmasManager.class);
protected List<L2NpcInstance> objectQueue = new FastList<>();
protected Random rand = new Random();
// X-Mas message list
protected String[] message =
{
"Ho Ho Ho... Merry Christmas!",
"God is Love...",
"Christmas is all about love...",
"Christmas is thus about God and Love...",
"Love is the key to peace among all Lineage creature kind..",
"Love is the key to peace and happiness within all creation...",
"Love needs to be practiced - Love needs to flow - Love needs to make happy...",
"Love starts with your partner, children and family and expands to all world.",
"God bless all kind.",
"God bless Lineage.",
"Forgive all.",
"Ask for forgiveness even from all the \"past away\" ones.",
"Give love in many different ways to your family members, relatives, neighbors and \"foreigners\".",
"Enhance the feeling within yourself of being a member of a far larger family than your physical family",
"MOST important - Christmas is a feast of BLISS given to YOU from God and all beloved ones back home in God !!",
"Open yourself for all divine bliss, forgiveness and divine help that is offered TO YOU by many others AND GOD.",
"Take it easy. Relax these coming days.",
"Every day is Christmas day - it is UP TO YOU to create the proper inner attitude and opening for love toward others AND from others within YOUR SELF !",
"Peace and Silence. Reduced activities. More time for your most direct families. If possible NO other dates or travel may help you most to actually RECEIVE all offered bliss.",
"What ever is offered to you from God either enters YOUR heart and soul or is LOST for GOOD !!! or at least until another such day - next year Christmas or so !!",
"Divine bliss and love NEVER can be stored and received later.",
"There is year round a huge quantity of love and bliss available from God and your Guru and other loving souls, but Christmas days are an extended period FOR ALL PLANET",
"Please open your heart and accept all love and bliss - For your benefit as well as for the benefit of all your beloved ones.",
"Beloved children of God",
"Beyond Christmas days and beyond Christmas season - The Christmas love lives on, the Christmas bliss goes on, the Christmas feeling expands.",
"The holy spirit of Christmas is the holy spirit of God and God's love for all days.",
"When the Christmas spirit lives on and on...",
"When the power of love created during the pre-Christmas days is kept alive and growing.",
"Peace among all mankind is growing as well =)",
"The holy gift of love is an eternal gift of love put into your heart like a seed.",
"Dozens of millions of humans worldwide are changing in their hearts during weeks of pre-Christmas time and find their peak power of love on Christmas nights and Christmas days.",
"What is special during these days, to give all of you this very special power of love, the power to forgive, the power to make others happy, power to join the loved one on his or her path of loving life.",
"It only is your now decision that makes the difference !",
"It only is your now focus in life that makes all the changes. It is your shift from purely worldly matters toward the power of love from God that dwells within all of us that gave you the power to change your own behavior from your normal year long behavior.",
"The decision of love, peace and happiness is the right one.",
"Whatever you focus on is filling your mind and subsequently filling your heart.",
"No one else but you have change your focus these past Christmas days and the days of love you may have experienced in earlier Christmas seasons.",
"God's love is always present.",
"God's Love has always been in same power and purity and quantity available to all of you.",
"Expand the spirit of Christmas love and Christmas joy to span all year of your life...",
"Do all year long what is creating this special Christmas feeling of love joy and happiness.",
"Expand the true Christmas feeling, expand the love you have ever given at your maximum power of love days ... ",
"Expand the power of love over more and more days.",
"Re-focus on what has brought your love to its peak power and refocus on those objects and actions in your focus of mind and actions.",
"Remember the people and surrounding you had when feeling most happy, most loved, most magic",
"People of true loving spirit - who all was present, recall their names, recall the one who may have had the greatest impact in love those hours of magic moments of love...",
"The decoration of your surrounding - Decoration may help to focus on love - Or lack of decoration may make you drift away into darkness or business - away from love...",
"Love songs, songs full of living joy - any of the thousands of true touching love songs and happy songs do contribute to the establishment of an inner attitude perceptible of love.",
"Songs can fine tune and open our heart for love from God and our loved ones.",
"Your power of will and focus of mind can keep Christmas Love and Christmas joy alive beyond Christmas season for eternity",
"Enjoy your love for ever!",
"Christmas can be every day - As soon as you truly love every day =)",
"Christmas is when you love all and are loved by all.",
"Christmas is when you are truly happy by creating true happiness in others with love from the bottom of your heart.",
"Secret in God's creation is that no single person can truly love without ignition of his love.",
"You need another person to love and to receive love, a person to truly fall in love to ignite your own divine fire of love. ",
"God created many and all are made of love and all are made to love...",
"The miracle of love only works if you want to become a fully loving member of the family of divine love.",
"Once you have started to fall in love with the one God created for you - your entire eternal life will be a permanent fire of miracles of love ... Eternally !",
"May all have a happy time on Christmas each year. Merry Christmas!",
"Christmas day is a time for love. It is a time for showing our affection to our loved ones. It is all about love.",
"Have a wonderful Christmas. May god bless our family. I love you all.",
"Wish all living creatures a Happy X-mas and a Happy New Year! By the way I would like us to share a warm fellowship in all places.",
"Just as animals need peace of mind, poeple and also trees need peace of mind. This is why I say, all creatures are waiting upon the Lord for their salvation. May God bless you all creatures in the whole world.",
"Merry Xmas!",
"May the grace of Our Mighty Father be with you all during this eve of Christmas. Have a blessed Christmas and a happy New Year.",
"Merry Christmas my children. May this new year give all of the things you rightly deserve. And may peace finally be yours.",
"I wish everybody a Merry Christmas! May the Holy Spirit be with you all the time.",
"May you have the best of Christmas this year and all your dreams come true.",
"May the miracle of Christmas fill your heart with warmth and love. Merry Christmas!"
},
sender =
{
"Santa Claus",
"Papai Noel",
"Shengdan Laoren",
"Santa",
"Viejo Pascuero",
"Sinter Klaas",
"Father Christmas",
"Saint Nicholas",
"Joulupukki",
"Pere Noel",
"Saint Nikolaus",
"Kanakaloka",
"De Kerstman",
"Winter grandfather",
"Babbo Natale",
"Hoteiosho",
"Kaledu Senelis",
"Black Peter",
"Kerstman",
"Julenissen",
"Swiety Mikolaj",
"Ded Moroz",
"Julenisse",
"El Nino Jesus",
"Jultomten",
"Reindeer Dasher",
"Reindeer Dancer",
"Christmas Spirit",
"Reindeer Prancer",
"Reindeer Vixen",
"Reindeer Comet",
"Reindeer Cupid",
"Reindeer Donner",
"Reindeer Donder",
"Reindeer Dunder",
"Reindeer Blitzen",
"Reindeer Bliksem",
"Reindeer Blixem",
"Reindeer Rudolf",
"Christmas Elf"
};
// Presents List:
protected int[] presents =
{
5560,
5560,
5560,
5560,
5560, /* x-mas tree */
5560,
5560,
5560,
5560,
5560,
5561,
5561,
5561,
5561,
5561, /* special x-mas tree */
5562,
5562,
5562,
5562, /* 1st Carol */
5563,
5563,
5563,
5563, /* 2nd Carol */
5564,
5564,
5564,
5564, /* 3rd Carol */
5565,
5565,
5565,
5565, /* 4th Carol */
5566,
5566,
5566,
5566, /* 5th Carol */
5583,
5583, /* 6th Carol */
5584,
5584, /* 7th Carol */
5585,
5585, /* 8th Carol */
5586,
5586, /* 9th Carol */
5587,
5587, /* 10th Carol */
6403,
6403,
6403,
6403, /* Star Shard */
6403,
6403,
6403,
6403,
6406,
6406,
6406,
6406, /* FireWorks */
6407,
6407, /* Large FireWorks */
5555, /* Token of Love */
7836, /* Santa Hat #1 */
9138, /* Santa Hat #2 */
8936, /* Santa's Antlers Hat */
6394, /* Red Party Mask */
5808
/* Black Party Mask */
};
// The message task sent at fixed rate
protected Future<?> _XMasMessageTask = null, _XMasPresentsTask = null;
// Manager should only be Initialized once:
protected int isManagerInit = 0;
// Interval of Christmas actions:
protected long _IntervalOfChristmas = 600000; // 10 minutes
private final int first = 25000, last = 73099;
/************************************** Initial Functions **************************************/
/**
* Empty constructor Does nothing
*/
public ChristmasManager()
{
//
}
/**
* @return an instance of <b>this</b> InstanceManager.
*/
public static ChristmasManager getInstance()
{
return SingletonHolder._instance;
}
/**
* initialize <b>this</b> ChristmasManager
* @param activeChar
*/
public void init(final L2PcInstance activeChar)
{
if (isManagerInit > 0)
{
activeChar.sendMessage("Christmas Manager has already begun or is processing. Please be patient....");
return;
}
activeChar.sendMessage("Started!!!! This will take a 2-3 hours (in order to reduce system lags to a minimum), please be patient... The process is working in the background and will spawn npcs, give presents and messages at a fixed rate.");
// Tasks:
spawnTrees();
startFestiveMessagesAtFixedRate();
isManagerInit++;
givePresentsAtFixedRate();
isManagerInit++;
checkIfOkToAnnounce();
}
/**
* ends <b>this</b> ChristmasManager
* @param activeChar
*/
public void end(final L2PcInstance activeChar)
{
if (isManagerInit < 4)
{
if (activeChar != null)
{
activeChar.sendMessage("Christmas Manager is not activated yet. Already Ended or is now processing....");
}
return;
}
if (activeChar != null)
{
activeChar.sendMessage("Terminating! This may take a while, please be patient...");
}
// Tasks:
ThreadPoolManager.getInstance().executeTask(new DeleteSpawns());
endFestiveMessagesAtFixedRate();
isManagerInit--;
endPresentGivingAtFixedRate();
isManagerInit--;
checkIfOkToAnnounce();
}
/************************************ - Tree management<SUF>*/
/**
* Main function - spawns all trees.
*/
public void spawnTrees()
{
GetTreePos gtp = new GetTreePos(first);
ThreadPoolManager.getInstance().executeTask(gtp);
gtp = null;
}
/**
* returns a random X-Mas tree Npc Id.
* @return int tree Npc Id.
*/
protected int getTreeId()
{
final int[] ids =
{
13006,
13007
};
return ids[rand.nextInt(ids.length)];
}
/**
* gets random world positions according to spawned world objects and spawns x-mas trees around them...
*/
public class GetTreePos implements Runnable
{
private int _iterator;
private Future<?> _task;
public GetTreePos(final int iter)
{
_iterator = iter;
}
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
try
{
L2Object obj = null;
while (obj == null)
{
obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn();
_iterator++;
if (obj != null && obj instanceof L2Attackable)
if (rand.nextInt(100) > 10)
{
obj = null;
}
}
if (rand.nextInt(100) > 50)
{
spawnOneTree(getTreeId(), obj.getX() + rand.nextInt(200) - 100, obj.getY() + rand.nextInt(200) - 100, obj.getZ());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
if (_iterator >= last)
{
isManagerInit++;
SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(first);
_task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300);
ssNPCs.setTask(_task);
ssNPCs = null;
return;
}
_iterator++;
GetTreePos gtp = new GetTreePos(_iterator);
_task = ThreadPoolManager.getInstance().scheduleGeneral(gtp, 300);
gtp.setTask(_task);
gtp = null;
}
}
/**
* Delete all x-mas spawned trees from the world. Delete all x-mas trees spawns, and clears the L2NpcInstance tree queue.
*/
public class DeleteSpawns implements Runnable
{
@Override
public void run()
{
if (objectQueue == null || objectQueue.isEmpty())
return;
for (final L2NpcInstance deleted : objectQueue)
{
if (deleted == null)
{
continue;
}
try
{
L2World.getInstance().removeObject(deleted);
deleted.decayMe();
deleted.deleteMe();
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
continue;
}
}
objectQueue.clear();
objectQueue = null;
isManagerInit = isManagerInit - 2;
checkIfOkToAnnounce();
}
}
/**
* Spawns one x-mas tree at a given location x,y,z
* @param id - int tree npc id.
* @param x - int loc x
* @param y - int loc y
* @param z - int loc z
*/
protected void spawnOneTree(final int id, final int x, final int y, final int z)
{
try
{
L2NpcTemplate template1 = NpcTable.getInstance().getTemplate(id);
L2Spawn spawn = new L2Spawn(template1);
template1 = null;
spawn.setId(IdFactory.getInstance().getNextId());
spawn.setLocx(x);
spawn.setLocy(y);
spawn.setLocz(z);
L2NpcInstance tree = spawn.spawnOne();
L2World.getInstance().storeObject(tree);
objectQueue.add(tree);
spawn = null;
tree = null;
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
}
/**************************** - send players festive messages - *****************************/
/**
* Ends X-Mas messages sent to players, and terminates the thread.
*/
private void endFestiveMessagesAtFixedRate()
{
if (_XMasMessageTask != null)
{
_XMasMessageTask.cancel(true);
_XMasMessageTask = null;
}
}
/**
* Starts X-Mas messages sent to all players, and initialize the thread.
*/
private void startFestiveMessagesAtFixedRate()
{
SendXMasMessage XMasMessage = new SendXMasMessage();
_XMasMessageTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasMessage, 60000, _IntervalOfChristmas);
XMasMessage = null;
}
/**
* Sends X-Mas messages to all world players.
* @author Darki699
*/
class SendXMasMessage implements Runnable
{
@Override
public void run()
{
try
{
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers())
{
if (pc == null)
{
continue;
}
else if (pc.isOnline() == 0)
{
continue;
}
pc.sendPacket(getXMasMessage());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
}
}
/**
* Returns a random X-Mas message.
* @return CreatureSay message
*/
protected CreatureSay getXMasMessage()
{
final CreatureSay cs = new CreatureSay(0, 17, getRandomSender(), getRandomXMasMessage());
return cs;
}
/**
* Returns a random name of the X-Mas message sender, sent to players
* @return String of the message sender's name
*/
private String getRandomSender()
{
return sender[rand.nextInt(sender.length)];
}
/**
* Returns a random X-Mas message String
* @return String containing the random message.
*/
private String getRandomXMasMessage()
{
return message[rand.nextInt(message.length)];
}
/******************************* - give special items trees - ********************************/
// Trees , Carols , Tokens of love, Fireworks, Santa Hats.
/**
* Starts X-Mas Santa presents sent to all players, and initialize the thread.
*/
private void givePresentsAtFixedRate()
{
final XMasPresentGivingTask XMasPresents = new XMasPresentGivingTask();
_XMasPresentsTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasPresents, _IntervalOfChristmas, _IntervalOfChristmas * 3);
}
class XMasPresentGivingTask implements Runnable
{
@Override
public void run()
{
try
{
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers())
{
if (pc == null)
{
continue;
}
else if (pc.isOnline() == 0)
{
continue;
}
else if (pc.getInventoryLimit() <= pc.getInventory().getSize())
{
pc.sendMessage("Santa wanted to give you a Present but your inventory was full :(");
continue;
}
else if (rand.nextInt(100) < 50)
{
final int itemId = getSantaRandomPresent();
L2ItemInstance item = ItemTable.getInstance().createItem("Christmas Event", itemId, 1, pc);
pc.getInventory().addItem("Christmas Event", item.getItemId(), 1, pc, pc);
String itemName = ItemTable.getInstance().getTemplate(itemId).getName();
item = null;
SystemMessage sm;
sm = new SystemMessage(SystemMessageId.EARNED_ITEM);
sm.addString(itemName + " from Santa's Present Bag...");
pc.broadcastPacket(sm);
itemName = null;
sm = null;
}
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
}
}
protected int getSantaRandomPresent()
{
return presents[rand.nextInt(presents.length)];
}
/**
* Ends X-Mas present giving to players, and terminates the thread.
*/
private void endPresentGivingAtFixedRate()
{
if (_XMasPresentsTask != null)
{
_XMasPresentsTask.cancel(true);
_XMasPresentsTask = null;
}
}
/************************************ - spawn NPCs in towns - ***************************************/
// NPC Ids: 31863 , 31864
public class SpawnSantaNPCs implements Runnable
{
private int _iterator;
private Future<?> _task;
public SpawnSantaNPCs(final int iter)
{
_iterator = iter;
}
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
try
{
L2Object obj = null;
while (obj == null)
{
obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn();
_iterator++;
if (obj != null && obj instanceof L2Attackable)
{
obj = null;
}
}
if (rand.nextInt(100) < 80 && obj instanceof L2NpcInstance)
{
spawnOneTree(getSantaId(), obj.getX() + rand.nextInt(500) - 250, obj.getY() + rand.nextInt(500) - 250, obj.getZ());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
if (_iterator >= last)
{
isManagerInit++;
checkIfOkToAnnounce();
return;
}
_iterator++;
SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(_iterator);
_task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300);
ssNPCs.setTask(_task);
ssNPCs = null;
}
}
protected int getSantaId()
{
return rand.nextInt(100) < 50 ? 31863 : 31864;
}
protected void checkIfOkToAnnounce()
{
if (isManagerInit == 4)
{
Announcements.getInstance().announceToAll("Christmas Event has begun, have a Merry Christmas and a Happy New Year.");
Announcements.getInstance().announceToAll("Christmas Event will end in 24 hours.");
LOGGER.info("ChristmasManager:Init ChristmasManager was started successfully, have a festive holiday.");
final EndEvent ee = new EndEvent();
Future<?> task = ThreadPoolManager.getInstance().scheduleGeneral(ee, 86400000);
ee.setTask(task);
task = null;
isManagerInit = 5;
}
if (isManagerInit == 0)
{
Announcements.getInstance().announceToAll("Christmas Event has ended... Hope you enjoyed the festivities.");
LOGGER.info("ChristmasManager:Terminated ChristmasManager.");
isManagerInit = -1;
}
}
public class EndEvent implements Runnable
{
private Future<?> _task;
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
end(null);
}
}
private static class SingletonHolder
{
protected static final ChristmasManager _instance = new ChristmasManager();
}
}
|
10414_2 | import lejos.nxt.Motor;
import lejos.nxt.NXTRegulatedMotor;
public class Dispenser extends Thread {
public void geefGeld(int bedrag){
int a10 = 0;
int a20 = 0;
int a50 = 0;
NXTRegulatedMotor m10 = Motor.A;
NXTRegulatedMotor m20 = Motor.B;
NXTRegulatedMotor m50 = Motor.C;
while(bedrag > 0){
if(bedrag >= 50){
a50 += 1;
bedrag -= 50;
}
else if (bedrag >= 20&& bedrag < 50){
a20 += 1;
bedrag -= 20;
}
else{
a10 += 1;
bedrag -= 10;
}
}
dispense(m50,a50);
dispense(m20,a20);
dispense(m10,a10);
}
public static void dispense(NXTRegulatedMotor m, int aantal){
int tijd = 1100;
m.backward(); // geld gaat voor uit
try {
sleep(tijd*aantal);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.stop();
m.forward(); //geld gaat terug in automaat
}
} | Horofic/ATM | client/Dispenser.java | 403 | //geld gaat terug in automaat | line_comment | nl | import lejos.nxt.Motor;
import lejos.nxt.NXTRegulatedMotor;
public class Dispenser extends Thread {
public void geefGeld(int bedrag){
int a10 = 0;
int a20 = 0;
int a50 = 0;
NXTRegulatedMotor m10 = Motor.A;
NXTRegulatedMotor m20 = Motor.B;
NXTRegulatedMotor m50 = Motor.C;
while(bedrag > 0){
if(bedrag >= 50){
a50 += 1;
bedrag -= 50;
}
else if (bedrag >= 20&& bedrag < 50){
a20 += 1;
bedrag -= 20;
}
else{
a10 += 1;
bedrag -= 10;
}
}
dispense(m50,a50);
dispense(m20,a20);
dispense(m10,a10);
}
public static void dispense(NXTRegulatedMotor m, int aantal){
int tijd = 1100;
m.backward(); // geld gaat voor uit
try {
sleep(tijd*aantal);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.stop();
m.forward(); //geld gaat<SUF>
}
} |
78462_3 | package com.zyw.horrarndoo.yizhi.contract.movie;
import android.widget.ImageView;
import com.zyw.horrarndoo.sdk.base.BasePresenter;
import com.zyw.horrarndoo.sdk.base.IBaseFragment;
import com.zyw.horrarndoo.sdk.base.IBaseModel;
import com.zyw.horrarndoo.yizhi.model.bean.douban.movie.HotMovieBean;
import com.zyw.horrarndoo.yizhi.model.bean.douban.movie.child.SubjectsBean;
import java.util.List;
import io.reactivex.Observable;
/**
* Created by Horrarndoo on 2017/10/16.
* <p>
*/
public interface MovieMainContract {
abstract class MovieMainPresenter extends BasePresenter<IMovieMainModel, IMovieMainView> {
/**
* 加载最新的最热电影
*/
public abstract void loadHotMovieList();
/**
* item点击事件
*
* @param position position
* @param item item
* @param imageView imageView
*/
public abstract void onItemClick(int position, SubjectsBean item, ImageView imageView);
/**
* Header被点击
*/
public abstract void onHeaderClick();
}
interface IMovieMainModel extends IBaseModel {
/**
* 获取最热电影
*
* @return 最热电影
*/
Observable<HotMovieBean> getHotMovieList();
}
interface IMovieMainView extends IBaseFragment {
/**
* 更新界面list
*
* @param list list
*/
void updateContentList(List<SubjectsBean> list);
/**
* 显示网络错误
*/
void showNetworkError();
}
}
| Horrarndoo/YiZhi | app/src/main/java/com/zyw/horrarndoo/yizhi/contract/movie/MovieMainContract.java | 494 | /**
* Header被点击
*/ | block_comment | nl | package com.zyw.horrarndoo.yizhi.contract.movie;
import android.widget.ImageView;
import com.zyw.horrarndoo.sdk.base.BasePresenter;
import com.zyw.horrarndoo.sdk.base.IBaseFragment;
import com.zyw.horrarndoo.sdk.base.IBaseModel;
import com.zyw.horrarndoo.yizhi.model.bean.douban.movie.HotMovieBean;
import com.zyw.horrarndoo.yizhi.model.bean.douban.movie.child.SubjectsBean;
import java.util.List;
import io.reactivex.Observable;
/**
* Created by Horrarndoo on 2017/10/16.
* <p>
*/
public interface MovieMainContract {
abstract class MovieMainPresenter extends BasePresenter<IMovieMainModel, IMovieMainView> {
/**
* 加载最新的最热电影
*/
public abstract void loadHotMovieList();
/**
* item点击事件
*
* @param position position
* @param item item
* @param imageView imageView
*/
public abstract void onItemClick(int position, SubjectsBean item, ImageView imageView);
/**
* Header被点击
<SUF>*/
public abstract void onHeaderClick();
}
interface IMovieMainModel extends IBaseModel {
/**
* 获取最热电影
*
* @return 最热电影
*/
Observable<HotMovieBean> getHotMovieList();
}
interface IMovieMainView extends IBaseFragment {
/**
* 更新界面list
*
* @param list list
*/
void updateContentList(List<SubjectsBean> list);
/**
* 显示网络错误
*/
void showNetworkError();
}
}
|
83496_2 | package com.in28minutes.rest.webservices.restfullwebservices.controller;
import com.in28minutes.rest.webservices.restfullwebservices.entities.HelloWordBean;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.Locale;
@RestController
public class HelloWordController {
private MessageSource mesaggeSource;
public HelloWordController(MessageSource mesaggeSource) {
this.mesaggeSource = mesaggeSource;
}
@RequestMapping(method = RequestMethod.GET, path = "/hello-word-2")
public String helloWord2(){
return "Hello Word";
}
@GetMapping(path = "/hello-word")
public String helloWord(){
return "Hello Word";
}
@GetMapping(path = "/hello-word-bean")
public HelloWordBean helloWordBean(){
return new HelloWordBean("Hello word");
}
@GetMapping(path = "/hello-word/path-variable/{name}")
public HelloWordBean helloWordPathVariable(@PathVariable String name){
return new HelloWordBean(String.format("Hello word %s"+name));
}
@GetMapping(path = "/hello-word-Internationalized")
public String helloWordInternationalized(){
Locale locale= LocaleContextHolder.getLocale();
return mesaggeSource.getMessage("good.morning.message",null,"Default Message",locale);
// return "Hello Word v2";
}
//1:
//2:
// -Example: 'en' - English (Good Morning)
// -Example: 'nl' - Dutch (Goedemorgen)
// -Example: 'fr' - French (Bonjour)
// -Example: 'es' - Español (Buenos dias)
}
| HugoSanche/Microservicios | restfull-web-services/src/main/java/com/in28minutes/rest/webservices/restfullwebservices/controller/HelloWordController.java | 505 | // -Example: 'nl' - Dutch (Goedemorgen)
| line_comment | nl | package com.in28minutes.rest.webservices.restfullwebservices.controller;
import com.in28minutes.rest.webservices.restfullwebservices.entities.HelloWordBean;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.Locale;
@RestController
public class HelloWordController {
private MessageSource mesaggeSource;
public HelloWordController(MessageSource mesaggeSource) {
this.mesaggeSource = mesaggeSource;
}
@RequestMapping(method = RequestMethod.GET, path = "/hello-word-2")
public String helloWord2(){
return "Hello Word";
}
@GetMapping(path = "/hello-word")
public String helloWord(){
return "Hello Word";
}
@GetMapping(path = "/hello-word-bean")
public HelloWordBean helloWordBean(){
return new HelloWordBean("Hello word");
}
@GetMapping(path = "/hello-word/path-variable/{name}")
public HelloWordBean helloWordPathVariable(@PathVariable String name){
return new HelloWordBean(String.format("Hello word %s"+name));
}
@GetMapping(path = "/hello-word-Internationalized")
public String helloWordInternationalized(){
Locale locale= LocaleContextHolder.getLocale();
return mesaggeSource.getMessage("good.morning.message",null,"Default Message",locale);
// return "Hello Word v2";
}
//1:
//2:
// -Example: 'en' - English (Good Morning)
// -Example: 'nl'<SUF>
// -Example: 'fr' - French (Bonjour)
// -Example: 'es' - Español (Buenos dias)
}
|
20348_8 | package edu.cnv;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import trans.misc.*;
import edu.utah.seq.parsers.*;
import util.gen.*;
import trans.roc.*;
import trans.anno.*;
import util.bio.annotation.*;
public class CNVScanner {
//fields
private File barDirectory;
//int numberProbes = 2;
//float minimumScore = 0.2630344f; //1.5x
//float maximumScore = -0.2630344f;
private int numberProbes = 3;
private float minimumScore = 2.8f;
private float maximumScore = 1.2f;
private File resultsDirectory;
private ArrayList<CNV> cnvsAL = new ArrayList<CNV>();
private CNV[] cnvs;
private File ucscGeneFile;
private int neighborhood = 10000;
private boolean antiLog2 = false;
public CNVScanner(String[] args){
//parse args
processArgs(args);
//scan chromosomes
scanChromosomes();
//make coordinates
if (cnvs.length == 0) Misc.printExit("No CNVs found!");
System.out.println(cnvs.length+" CNVs found");
Coordinate[] coor = new Coordinate[cnvs.length];
for (int i=0; i< cnvs.length; i++) coor[i] = new Coordinate(cnvs[i].getGrGraph().getChromosome(), cnvs[i].getStart(), cnvs[i].getStop());
//find neighboring genes
FindNeighboringGenes fng = new FindNeighboringGenes(ucscGeneFile, coor, neighborhood, true);
String[] effGenes = fng.fetchGeneNames();
//print
try{
PrintWriter spreadSheet = new PrintWriter (new FileWriter (new File(resultsDirectory,barDirectory.getName()+".xls")));
spreadSheet.println("Chrom\tStart\tStop\tLength\t#Probes\tMedianCN\tProbeBasePositions\tProbeCNs\tIntersectedGenes\tParams: Min#Probes="+numberProbes+" MinCN="+minimumScore+" MaxCN="+maximumScore+" Neighborhood="+neighborhood);
PrintWriter bed = new PrintWriter (new FileWriter (new File(resultsDirectory,barDirectory.getName()+".bed")));
bed.println("#Chrom\tStart\tStop\tParams: Min#Probes="+numberProbes+" MinCN="+minimumScore+" MaxCN="+maximumScore+" Neighborhood="+neighborhood);
for (int i=0; i< cnvs.length; i++) {
spreadSheet.println(cnvs[i]+"\t"+effGenes[i]);
bed.println(cnvs[i].toStringBed(""+(i+1)));
}
spreadSheet.close();
bed.close();
} catch (Exception e){
e.printStackTrace();
}
//save CNVs
File cnvFile = new File(resultsDirectory, barDirectory.getName()+".cnv");
IO.saveObject(cnvFile, cnvs);
}
public void scanChromosomes(){
File[] barFiles = fetchBarFiles(barDirectory);
for (int i=0; i< barFiles.length; i++){
scanChromosome(barFiles[i]);
}
}
public void scanChromosome(File barFile){
BarParser bp = new BarParser();
bp.readBarFile(barFile, true);
int[] positions = bp.getBasePositions();
float[] values = bp.getValues();
if (antiLog2) values = Num.antiLog(values, 2);
String chromosome = bp.getChromosome();
boolean in = false;
CNV currentCNV = null;
//scan for increased
for (int i=0; i< positions.length; i++){
//does value meet threshold?
if (values[i] >= minimumScore){
if (in == false){
//start new
currentCNV = new CNV(chromosome);
in = true;
}
//add value
currentCNV.grs.add(new Gr(positions[i],values[i]));
}
else {
//doesn't make it
in = false;
//add currentCNV?
if (currentCNV !=null && currentCNV.grs.size() >= numberProbes) cnvsAL.add(currentCNV);
//reset current
currentCNV = new CNV(chromosome);
}
}
//close
in = false;
if (currentCNV !=null && currentCNV.grs.size() >= numberProbes) cnvsAL.add(currentCNV);
currentCNV = new CNV(chromosome);
//scan for decreased
for (int i=0; i< positions.length; i++){
//does value meet threshold?
if (values[i] <= maximumScore){
if (in == false){
//start new
currentCNV = new CNV(chromosome);
in = true;
}
//add value
currentCNV.grs.add(new Gr(positions[i],values[i]));
}
else {
//doesn't make it
in = false;
//add currentCNV?
if (currentCNV !=null && currentCNV.grs.size() >= numberProbes) cnvsAL.add(currentCNV);
//reset current
currentCNV = new CNV(chromosome);
}
}
//close
if (currentCNV !=null && currentCNV.grs.size() >= numberProbes) cnvsAL.add(currentCNV);
//convert
cnvs = new CNV[cnvsAL.size()];
cnvsAL.toArray(cnvs);
//load
for (int i=0; i< cnvs.length; i++) cnvs[i].loadGrGraph();
//sort
Arrays.sort(cnvs, new ComparatorCNVScore());
}
public static File[] fetchBarFiles(File barDirectory){
//fetch files
File[] files = IO.extractFiles(barDirectory, ".bar");
if (files == null || files.length == 0) {
files = IO.extractFiles(barDirectory, ".bar.zip");
if (files == null || files.length == 0) {
System.out.println("\t\tError: no xxx.bar or xxx.bar.zip files found in -> "+barDirectory+"\n");
return null;
}
}
return files;
}
public static void main(String[] args) {
if (args.length ==0){
printDocs();
System.exit(0);
}
new CNVScanner(args);
}
/**This method will process each argument and assign new variables*/
public void processArgs(String[] args){
Pattern pat = Pattern.compile("-[a-z]");
System.out.println("\n"+IO.fetchUSeqVersion()+" Arguments: "+Misc.stringArrayToString(args, " ")+"\n");
for (int i = 0; i<args.length; i++){
String lcArg = args[i].toLowerCase();
Matcher mat = pat.matcher(lcArg);
if (mat.matches()){
char test = args[i].charAt(1);
try{
switch (test){
case 'b': barDirectory = new File(args[++i]); break;
case 'r': resultsDirectory = new File(args[++i]); break;
case 'g': ucscGeneFile = new File(args[++i]); break;
case 'n': numberProbes = Integer.parseInt(args[++i]); break;
case 'm': minimumScore = Float.parseFloat(args[++i]); break;
case 'x': maximumScore = Float.parseFloat(args[++i]); break;
case 'h': printDocs(); System.exit(0);
default: Misc.printExit("\nProblem, unknown option! " + mat.group());
}
}
catch (Exception e){
Misc.printExit("\nSorry, something doesn't look right with this parameter: -"+test+"\n");
}
}
}
System.out.println("\tBar Dir:\t"+barDirectory);
System.out.println("\tResults Dir:\t"+resultsDirectory);
System.out.println("\tUCSC Gene Tbl:\t"+ucscGeneFile);
System.out.println("\tMin # probes:\t"+numberProbes);
System.out.println("\tMin Score:\t"+minimumScore);
System.out.println("\tMax Score:\t"+maximumScore);
}
public static void printDocs(){
System.out.println("\n" +
"**************************************************************************************\n" +
"** CNV Scanner: January 2009 **\n" +
"**************************************************************************************\n" +
"Takes a directory containing chromosome specific xxx.bar files and identifies CNV loci\n" +
"that contain the minimum number of adjacent probes that exceed the set scores. These\n" +
"can then be intersected using the IntersectCNVs application.\n\n" +
"Options:\n"+
"-r Results directory\n"+
"-b Bar file directory\n"+
"-n Minimum number of probes, defaults to 3\n"+
"-m Minimum score for enriched CNVs, defaults to 2.8\n"+
"-x Maximum score for reduced CNVs, defaults to 1.2\n"+
"-g UCSC RefFlat gene table file, See http://genome.ucsc.edu/cgi-bin/hgTables\n"+
"\n"+
"Example: java -Xmx1500M -jar pathTo/CNVAn/Apps/CNVScanner -r /Leuk/Results -b\n" +
" /Leuk/MIPBarData -n 4 -m 3 -x 1 -g /Anno/Hg18/refSeq.txt \n\n" +
"**************************************************************************************\n");
}
}
| HuntsmanCancerInstitute/USeq | Source/edu/cnv/CNVScanner.java | 2,783 | //does value meet threshold? | line_comment | nl | package edu.cnv;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import trans.misc.*;
import edu.utah.seq.parsers.*;
import util.gen.*;
import trans.roc.*;
import trans.anno.*;
import util.bio.annotation.*;
public class CNVScanner {
//fields
private File barDirectory;
//int numberProbes = 2;
//float minimumScore = 0.2630344f; //1.5x
//float maximumScore = -0.2630344f;
private int numberProbes = 3;
private float minimumScore = 2.8f;
private float maximumScore = 1.2f;
private File resultsDirectory;
private ArrayList<CNV> cnvsAL = new ArrayList<CNV>();
private CNV[] cnvs;
private File ucscGeneFile;
private int neighborhood = 10000;
private boolean antiLog2 = false;
public CNVScanner(String[] args){
//parse args
processArgs(args);
//scan chromosomes
scanChromosomes();
//make coordinates
if (cnvs.length == 0) Misc.printExit("No CNVs found!");
System.out.println(cnvs.length+" CNVs found");
Coordinate[] coor = new Coordinate[cnvs.length];
for (int i=0; i< cnvs.length; i++) coor[i] = new Coordinate(cnvs[i].getGrGraph().getChromosome(), cnvs[i].getStart(), cnvs[i].getStop());
//find neighboring genes
FindNeighboringGenes fng = new FindNeighboringGenes(ucscGeneFile, coor, neighborhood, true);
String[] effGenes = fng.fetchGeneNames();
//print
try{
PrintWriter spreadSheet = new PrintWriter (new FileWriter (new File(resultsDirectory,barDirectory.getName()+".xls")));
spreadSheet.println("Chrom\tStart\tStop\tLength\t#Probes\tMedianCN\tProbeBasePositions\tProbeCNs\tIntersectedGenes\tParams: Min#Probes="+numberProbes+" MinCN="+minimumScore+" MaxCN="+maximumScore+" Neighborhood="+neighborhood);
PrintWriter bed = new PrintWriter (new FileWriter (new File(resultsDirectory,barDirectory.getName()+".bed")));
bed.println("#Chrom\tStart\tStop\tParams: Min#Probes="+numberProbes+" MinCN="+minimumScore+" MaxCN="+maximumScore+" Neighborhood="+neighborhood);
for (int i=0; i< cnvs.length; i++) {
spreadSheet.println(cnvs[i]+"\t"+effGenes[i]);
bed.println(cnvs[i].toStringBed(""+(i+1)));
}
spreadSheet.close();
bed.close();
} catch (Exception e){
e.printStackTrace();
}
//save CNVs
File cnvFile = new File(resultsDirectory, barDirectory.getName()+".cnv");
IO.saveObject(cnvFile, cnvs);
}
public void scanChromosomes(){
File[] barFiles = fetchBarFiles(barDirectory);
for (int i=0; i< barFiles.length; i++){
scanChromosome(barFiles[i]);
}
}
public void scanChromosome(File barFile){
BarParser bp = new BarParser();
bp.readBarFile(barFile, true);
int[] positions = bp.getBasePositions();
float[] values = bp.getValues();
if (antiLog2) values = Num.antiLog(values, 2);
String chromosome = bp.getChromosome();
boolean in = false;
CNV currentCNV = null;
//scan for increased
for (int i=0; i< positions.length; i++){
//does value meet threshold?
if (values[i] >= minimumScore){
if (in == false){
//start new
currentCNV = new CNV(chromosome);
in = true;
}
//add value
currentCNV.grs.add(new Gr(positions[i],values[i]));
}
else {
//doesn't make it
in = false;
//add currentCNV?
if (currentCNV !=null && currentCNV.grs.size() >= numberProbes) cnvsAL.add(currentCNV);
//reset current
currentCNV = new CNV(chromosome);
}
}
//close
in = false;
if (currentCNV !=null && currentCNV.grs.size() >= numberProbes) cnvsAL.add(currentCNV);
currentCNV = new CNV(chromosome);
//scan for decreased
for (int i=0; i< positions.length; i++){
//does value<SUF>
if (values[i] <= maximumScore){
if (in == false){
//start new
currentCNV = new CNV(chromosome);
in = true;
}
//add value
currentCNV.grs.add(new Gr(positions[i],values[i]));
}
else {
//doesn't make it
in = false;
//add currentCNV?
if (currentCNV !=null && currentCNV.grs.size() >= numberProbes) cnvsAL.add(currentCNV);
//reset current
currentCNV = new CNV(chromosome);
}
}
//close
if (currentCNV !=null && currentCNV.grs.size() >= numberProbes) cnvsAL.add(currentCNV);
//convert
cnvs = new CNV[cnvsAL.size()];
cnvsAL.toArray(cnvs);
//load
for (int i=0; i< cnvs.length; i++) cnvs[i].loadGrGraph();
//sort
Arrays.sort(cnvs, new ComparatorCNVScore());
}
public static File[] fetchBarFiles(File barDirectory){
//fetch files
File[] files = IO.extractFiles(barDirectory, ".bar");
if (files == null || files.length == 0) {
files = IO.extractFiles(barDirectory, ".bar.zip");
if (files == null || files.length == 0) {
System.out.println("\t\tError: no xxx.bar or xxx.bar.zip files found in -> "+barDirectory+"\n");
return null;
}
}
return files;
}
public static void main(String[] args) {
if (args.length ==0){
printDocs();
System.exit(0);
}
new CNVScanner(args);
}
/**This method will process each argument and assign new variables*/
public void processArgs(String[] args){
Pattern pat = Pattern.compile("-[a-z]");
System.out.println("\n"+IO.fetchUSeqVersion()+" Arguments: "+Misc.stringArrayToString(args, " ")+"\n");
for (int i = 0; i<args.length; i++){
String lcArg = args[i].toLowerCase();
Matcher mat = pat.matcher(lcArg);
if (mat.matches()){
char test = args[i].charAt(1);
try{
switch (test){
case 'b': barDirectory = new File(args[++i]); break;
case 'r': resultsDirectory = new File(args[++i]); break;
case 'g': ucscGeneFile = new File(args[++i]); break;
case 'n': numberProbes = Integer.parseInt(args[++i]); break;
case 'm': minimumScore = Float.parseFloat(args[++i]); break;
case 'x': maximumScore = Float.parseFloat(args[++i]); break;
case 'h': printDocs(); System.exit(0);
default: Misc.printExit("\nProblem, unknown option! " + mat.group());
}
}
catch (Exception e){
Misc.printExit("\nSorry, something doesn't look right with this parameter: -"+test+"\n");
}
}
}
System.out.println("\tBar Dir:\t"+barDirectory);
System.out.println("\tResults Dir:\t"+resultsDirectory);
System.out.println("\tUCSC Gene Tbl:\t"+ucscGeneFile);
System.out.println("\tMin # probes:\t"+numberProbes);
System.out.println("\tMin Score:\t"+minimumScore);
System.out.println("\tMax Score:\t"+maximumScore);
}
public static void printDocs(){
System.out.println("\n" +
"**************************************************************************************\n" +
"** CNV Scanner: January 2009 **\n" +
"**************************************************************************************\n" +
"Takes a directory containing chromosome specific xxx.bar files and identifies CNV loci\n" +
"that contain the minimum number of adjacent probes that exceed the set scores. These\n" +
"can then be intersected using the IntersectCNVs application.\n\n" +
"Options:\n"+
"-r Results directory\n"+
"-b Bar file directory\n"+
"-n Minimum number of probes, defaults to 3\n"+
"-m Minimum score for enriched CNVs, defaults to 2.8\n"+
"-x Maximum score for reduced CNVs, defaults to 1.2\n"+
"-g UCSC RefFlat gene table file, See http://genome.ucsc.edu/cgi-bin/hgTables\n"+
"\n"+
"Example: java -Xmx1500M -jar pathTo/CNVAn/Apps/CNVScanner -r /Leuk/Results -b\n" +
" /Leuk/MIPBarData -n 4 -m 3 -x 1 -g /Anno/Hg18/refSeq.txt \n\n" +
"**************************************************************************************\n");
}
}
|
194600_9 | package be.vyncke.service;
import be.vyncke.domain.Ketel;
import org.junit.jupiter.api.*;
import static org.assertj.core.api.Assertions.*;
class KetelServiceImpTest {
static KetelServiceImp ketelServiceImp;
static Ketel ketel;
@BeforeAll
static void setup(){
ketelServiceImp = new KetelServiceImp();
}
@Test
void TC1() {
// no status >> Beschikbaar (S0 - 1)
ketel = ketelServiceImp.ketelKaken();
assertThat(ketel.getStatus().equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
}
@Test
void TC2() {
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Kapot (S3 - 4)
assertThat(ketelServiceImp.ketelOnrepareerbaarVerklaren(ketel).equals("Kapot"));
}
@Test
void TC3() {
ketel = ketelServiceImp.ketelKaken();
ketel.setStatus("Onder reparatie");
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
}
@Test
void TC4() {
// no status >> Beschikbaar (S0 - 1)
ketel = ketelServiceImp.ketelKaken();
assertThat(ketel.getStatus().equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Kapot (S3 - 4)
assertThat(ketelServiceImp.ketelOnrepareerbaarVerklaren(ketel).equals("Kapot"));
}
@Test
void TC5(){
ketel = ketelServiceImp.ketelKaken();
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Kapot (S3 - 4)
assertThat(ketelServiceImp.ketelOnrepareerbaarVerklaren(ketel).equals("Kapot"));
}
@Test
void TC6(){
// no status >> Beschikbaar (S0 - 1)
ketel = ketelServiceImp.ketelKaken();
assertThat(ketel.getStatus().equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Onder reparatie (S2 - 3) IllegalStateException expected
try{
ketelServiceImp.ketelLatenRepareren(ketel);
}catch (Exception e){
assertThat("De ketel is niet beschikbaar en kan niet naar reparatie gestuurd worden"
.equals(e.getMessage()));
}
ketel.setStatus("Kapot");
// Kapot >> Beschikbaar (S4 - 1) IllegalStateException expected
try {
ketelServiceImp.ketelTerughalen(ketel);
}catch (Exception e){
assertThat("De ketel is niet uitgeleed en kan niet teruggehaald worden"
.equals(e.getMessage()));
}
}
} | Husein-Kasem/Vyncke | vyncke_webfront/tests/be/vyncke/service/KetelServiceImpTest.java | 1,706 | // Uitgeleend >> Beschikbaar (S2 - 1) | line_comment | nl | package be.vyncke.service;
import be.vyncke.domain.Ketel;
import org.junit.jupiter.api.*;
import static org.assertj.core.api.Assertions.*;
class KetelServiceImpTest {
static KetelServiceImp ketelServiceImp;
static Ketel ketel;
@BeforeAll
static void setup(){
ketelServiceImp = new KetelServiceImp();
}
@Test
void TC1() {
// no status >> Beschikbaar (S0 - 1)
ketel = ketelServiceImp.ketelKaken();
assertThat(ketel.getStatus().equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
}
@Test
void TC2() {
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Kapot (S3 - 4)
assertThat(ketelServiceImp.ketelOnrepareerbaarVerklaren(ketel).equals("Kapot"));
}
@Test
void TC3() {
ketel = ketelServiceImp.ketelKaken();
ketel.setStatus("Onder reparatie");
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >><SUF>
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
}
@Test
void TC4() {
// no status >> Beschikbaar (S0 - 1)
ketel = ketelServiceImp.ketelKaken();
assertThat(ketel.getStatus().equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Kapot (S3 - 4)
assertThat(ketelServiceImp.ketelOnrepareerbaarVerklaren(ketel).equals("Kapot"));
}
@Test
void TC5(){
ketel = ketelServiceImp.ketelKaken();
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Kapot (S3 - 4)
assertThat(ketelServiceImp.ketelOnrepareerbaarVerklaren(ketel).equals("Kapot"));
}
@Test
void TC6(){
// no status >> Beschikbaar (S0 - 1)
ketel = ketelServiceImp.ketelKaken();
assertThat(ketel.getStatus().equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Onder reparatie (S2 - 3) IllegalStateException expected
try{
ketelServiceImp.ketelLatenRepareren(ketel);
}catch (Exception e){
assertThat("De ketel is niet beschikbaar en kan niet naar reparatie gestuurd worden"
.equals(e.getMessage()));
}
ketel.setStatus("Kapot");
// Kapot >> Beschikbaar (S4 - 1) IllegalStateException expected
try {
ketelServiceImp.ketelTerughalen(ketel);
}catch (Exception e){
assertThat("De ketel is niet uitgeleed en kan niet teruggehaald worden"
.equals(e.getMessage()));
}
}
} |
83518_3 | package com.microservicedoodles.microservicedoodles.helloworld;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
private MessageSource messageSource;
public HelloWorldController(MessageSource messageSource) {
this.messageSource = messageSource;
}
@GetMapping(path = "/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping(path = "/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("Hello World");
}
// Path Parameters
// /users/{id}/todos/{id} => /users/2/todos/200
// /hello-world/path-variable/{name}
// /hello-world/path-variable/Ranga
@GetMapping(path = "/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {
return new HelloWorldBean(String.format("Hello World, %s", name));
}
@GetMapping(path = "/hello-world-internationalized")
public String helloWorldInternationalized() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("good.morning.message", null, "Default Message", locale);
// return "Hello World V2";
// 1:
// 2:
// - Example: `en` - English (Good Morning)
// - Example: `nl` - Dutch (Goedemorgen)
// - Example: `fr` - French (Bonjour)
// - Example: `de` - Deutsch (Guten Morgen)
}
}
| Huseyinyetisir/Spring-microservices | microservice-doodles/src/main/java/com/microservicedoodles/microservicedoodles/helloworld/HelloWorldController.java | 492 | // - Example: `nl` - Dutch (Goedemorgen) | line_comment | nl | package com.microservicedoodles.microservicedoodles.helloworld;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
private MessageSource messageSource;
public HelloWorldController(MessageSource messageSource) {
this.messageSource = messageSource;
}
@GetMapping(path = "/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping(path = "/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("Hello World");
}
// Path Parameters
// /users/{id}/todos/{id} => /users/2/todos/200
// /hello-world/path-variable/{name}
// /hello-world/path-variable/Ranga
@GetMapping(path = "/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {
return new HelloWorldBean(String.format("Hello World, %s", name));
}
@GetMapping(path = "/hello-world-internationalized")
public String helloWorldInternationalized() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("good.morning.message", null, "Default Message", locale);
// return "Hello World V2";
// 1:
// 2:
// - Example: `en` - English (Good Morning)
// - Example:<SUF>
// - Example: `fr` - French (Bonjour)
// - Example: `de` - Deutsch (Guten Morgen)
}
}
|
8497_0 | package Spel;
import Tools.*;
import javax.swing.JFrame;
import java.util.ArrayList;
/**
* Deze klasse zorgt voor de dynamica van het spel.
*
* @author (E.E. Koldenhof)
* @version (V.1.0)
*
* Deze klasse mag je NIET veranderen
*
*/
public class Beweeg{
private ArrayList<KanBewegen> beweegLijst;
/**
* Vult de 4 basis objecten die de controller nodig heeft om de
* dynamica van het spel te kunnen afhandelen
*/
public Beweeg(){
beweegLijst = new ArrayList<KanBewegen>();
}
public void voegObjectToe(KanBewegen o){
beweegLijst.add(o);
}
public void verwijderObject(KanBewegen o){
beweegLijst.remove(o);
}
public void voegLijstToe(ArrayList lijst){
beweegLijst.addAll(lijst);
}
public void verwijderLijst(ArrayList lijst){
beweegLijst.removeAll(lijst);
}
public void beweegAlles(float stapGrootte){
int teller = 0;
while (teller < beweegLijst.size()){
beweegLijst.get(teller).beweeg(stapGrootte);
teller ++;
}
}
}
| Hutsmeister/Spel | Spelluhtjuh/Spel/Beweeg.java | 413 | /**
* Deze klasse zorgt voor de dynamica van het spel.
*
* @author (E.E. Koldenhof)
* @version (V.1.0)
*
* Deze klasse mag je NIET veranderen
*
*/ | block_comment | nl | package Spel;
import Tools.*;
import javax.swing.JFrame;
import java.util.ArrayList;
/**
* Deze klasse zorgt<SUF>*/
public class Beweeg{
private ArrayList<KanBewegen> beweegLijst;
/**
* Vult de 4 basis objecten die de controller nodig heeft om de
* dynamica van het spel te kunnen afhandelen
*/
public Beweeg(){
beweegLijst = new ArrayList<KanBewegen>();
}
public void voegObjectToe(KanBewegen o){
beweegLijst.add(o);
}
public void verwijderObject(KanBewegen o){
beweegLijst.remove(o);
}
public void voegLijstToe(ArrayList lijst){
beweegLijst.addAll(lijst);
}
public void verwijderLijst(ArrayList lijst){
beweegLijst.removeAll(lijst);
}
public void beweegAlles(float stapGrootte){
int teller = 0;
while (teller < beweegLijst.size()){
beweegLijst.get(teller).beweeg(stapGrootte);
teller ++;
}
}
}
|
111275_1 | package nl.knaw.huc.di.tag.model.graph;
/*-
* #%L
* alexandria-markup-core
* =======
* Copyright (C) 2016 - 2021 HuC DI (KNAW)
* =======
* 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.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nl.knaw.huc.di.tag.model.graph.edges.Edge;
// nu zou ik wel topological sort willen hebben
// teveel gedoe, kan ook gewoon een root node maken
public class DirectedAcyclicGraph<N> extends HyperGraph<N, Edge> {
private static final Logger LOG = LoggerFactory.getLogger(DirectedAcyclicGraph.class);
private N root;
protected DirectedAcyclicGraph() {
super(GraphType.ORDERED);
}
@Override
public void addNode(N node, String label) {
super.addNode(node, label);
}
protected void setRootNode(N root) {
this.root = root;
}
// // Question: do we want labels here?
// public void addDirectedEdge(N source, N target) {
// TraditionalEdge edge = new TraditionalEdge(sigils);
// super.addDirectedHyperEdge(edge, "", source, target);
// }
public List<N> traverse() {
Set<N> visitedNodes = new HashSet<>();
Stack<N> nodesToVisit = new Stack<>();
nodesToVisit.add(root);
List<N> result = new ArrayList<>();
while (!nodesToVisit.isEmpty()) {
N pop = nodesToVisit.pop();
if (!visitedNodes.contains(pop)) {
result.add(pop);
Collection<Edge> outgoingEdges = this.getOutgoingEdges(pop);
visitedNodes.add(pop);
for (Edge e : outgoingEdges) {
N target = this.getTarget(e);
if (target == null) {
throw new RuntimeException("edge target is null for edge " + pop + "->");
}
nodesToVisit.add(target);
}
} else {
LOG.debug("revisiting node {}", pop);
}
}
return result;
}
public N getTarget(Edge e) {
Collection<N> nodes = super.getTargets(e);
if (nodes.size() != 1) {
throw new RuntimeException("trouble!");
}
return nodes.iterator().next();
}
}
| HuygensING/alexandria-markup | main/src/main/java/nl/knaw/huc/di/tag/model/graph/DirectedAcyclicGraph.java | 856 | // nu zou ik wel topological sort willen hebben | line_comment | nl | package nl.knaw.huc.di.tag.model.graph;
/*-
* #%L
* alexandria-markup-core
* =======
* Copyright (C) 2016 - 2021 HuC DI (KNAW)
* =======
* 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.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nl.knaw.huc.di.tag.model.graph.edges.Edge;
// nu zou<SUF>
// teveel gedoe, kan ook gewoon een root node maken
public class DirectedAcyclicGraph<N> extends HyperGraph<N, Edge> {
private static final Logger LOG = LoggerFactory.getLogger(DirectedAcyclicGraph.class);
private N root;
protected DirectedAcyclicGraph() {
super(GraphType.ORDERED);
}
@Override
public void addNode(N node, String label) {
super.addNode(node, label);
}
protected void setRootNode(N root) {
this.root = root;
}
// // Question: do we want labels here?
// public void addDirectedEdge(N source, N target) {
// TraditionalEdge edge = new TraditionalEdge(sigils);
// super.addDirectedHyperEdge(edge, "", source, target);
// }
public List<N> traverse() {
Set<N> visitedNodes = new HashSet<>();
Stack<N> nodesToVisit = new Stack<>();
nodesToVisit.add(root);
List<N> result = new ArrayList<>();
while (!nodesToVisit.isEmpty()) {
N pop = nodesToVisit.pop();
if (!visitedNodes.contains(pop)) {
result.add(pop);
Collection<Edge> outgoingEdges = this.getOutgoingEdges(pop);
visitedNodes.add(pop);
for (Edge e : outgoingEdges) {
N target = this.getTarget(e);
if (target == null) {
throw new RuntimeException("edge target is null for edge " + pop + "->");
}
nodesToVisit.add(target);
}
} else {
LOG.debug("revisiting node {}", pop);
}
}
return result;
}
public N getTarget(Edge e) {
Collection<N> nodes = super.getTargets(e);
if (nodes.size() != 1) {
throw new RuntimeException("trouble!");
}
return nodes.iterator().next();
}
}
|
64060_16 | package elaborate.editor.export.mvn;
/*
* #%L
* elab4-backend
* =======
* Copyright (C) 2011 - 2019 Huygens ING
* =======
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import elaborate.editor.export.mvn.MVNConversionData.AnnotationData;
import elaborate.editor.export.mvn.MVNConversionData.EntryData;
import elaborate.editor.export.mvn.MVNValidator.ValidationResult;
import elaborate.editor.model.orm.Project;
import elaborate.editor.model.orm.TranscriptionType;
import elaborate.editor.publish.Publication.Status;
import elaborate.util.HibernateUtil;
import nl.knaw.huygens.Log;
import nl.knaw.huygens.tei.Document;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.File;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static elaborate.util.XmlUtil.extractAnnotationNos;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.text.StringEscapeUtils.escapeHtml4;
import static org.apache.commons.text.StringEscapeUtils.escapeXml11;
public class MVNConverter {
private static final boolean DEBUG = false; // for release
// private static final boolean DEBUG = true; // for testing, don't release with DEBUG=true!!!
private final Project project;
private final MVNConversionData data;
private final Status status;
private final TranscriptionHierarchyFixer transcriptionHiearchyFixer = new TranscriptionHierarchyFixer();
private final String baseURL;
public MVNConverter(final Project project, final MVNConversionData data, Status status, String baseURL) {
this.project = project;
this.data = data;
this.status = status;
this.baseURL = baseURL;
}
// phase 1: collect MVNFolium with raw transcription
// order by 'order' or entryname
// fail when 1, but not all entries have order
// fail when entrynames are not unique
// fail when entrynames contain characters illegal in xml:id
// select id, name from project_entries where project_id=$projectId
// select
@SuppressWarnings("unchecked")
public static MVNConversionData getConversionData(final long project_id, Status status) {
final MVNConversionData conversionData = new MVNConversionData();
final EntityManager entityManager = HibernateUtil.beginTransaction();
final String transcriptionSQL = ("select"//
+ " e.id as id,"//
+ " e.name as name,"//
+ " m.data as entry_order,"//
+ " t.body as transcription,"//
+ " f.filename"//
+ " from project_entries e"//
+ " left outer join project_entry_metadata_items m on (e.id = m.project_entry_id and m.field='order')"//
+ " left outer join transcriptions t on (e.id = t.project_entry_id and t.text_layer='Diplomatic')"//
+ " left outer join facsimiles f on (e.id = f.project_entry_id)"//
+ " where project_id=" + project_id//
+ " order by entry_order, name").replaceAll(" +", " ");
final Query transcriptionQuery = entityManager.createNativeQuery(transcriptionSQL);
status.addLogline("collecting transcription data");
final List<Object[]> transcriptions = transcriptionQuery.getResultList();
if (transcriptions.isEmpty()) {
status.addError("no transcriptions found");
} else {
for (final Object[] transcriptionData : transcriptions) {
final EntryData entryData = new MVNConversionData.EntryData();
final Integer id = (Integer) transcriptionData[0];
entryData.id = String.valueOf(id);
entryData.name = (String) transcriptionData[1];
entryData.order = (String) transcriptionData[2];
entryData.body = (String) transcriptionData[3];
entryData.facs = (String) transcriptionData[4];
conversionData.getEntryDataList().add(entryData);
}
final String annotationSQL = ("select"//
+ " a.annotation_no as annotation_num,"//
+ " at.name as annotation_type,"//
+ " a.body as annotation_body"//
+ " from project_entries e"//
+ " left outer join transcriptions t"//
+ " left outer join annotations a"//
+ " left outer join annotation_types at"//
+ " on (at.id=a.annotation_type_id)"//
+ " on (t.id = a.transcription_id)"//
+ " on (e.id = t.project_entry_id and t.text_layer='Diplomatic')"//
+ " where project_id=" + project_id//
+ " order by annotation_num;").replaceAll(" +", " ");
final Query annotationQuery = entityManager.createNativeQuery(annotationSQL);
status.addLogline("collecting annotation data");
final List<Object[]> annotations = annotationQuery.getResultList();
// Log.info("SQL: {}", annotationSQL);
// Log.info("{} results:", annotations.size());
for (final Object[] annotation : annotations) {
final AnnotationData annotationData = new MVNConversionData.AnnotationData();
final Integer annotationNum = (Integer) annotation[0];
annotationData.type = (String) annotation[1];
annotationData.body = (String) annotation[2];
conversionData.getAnnotationIndex().put(annotationNum, annotationData);
}
}
HibernateUtil.rollbackTransaction(entityManager);
return conversionData;
}
public MVNConversionResult convert() {
final MVNConversionResult result = new MVNConversionResult(project, status, baseURL);
if (!onlyTextLayerIsDiplomatic()) {
result.addError("", "MVN projecten mogen alleen een Diplomatic textlayer hebben. Dit project heeft textlayer(s): " + Joiner.on(", ").join(project.getTextLayers()));
return result;
}
validateEntryOrderAndName(result);
status.addLogline("joining transcriptions");
final String xml = joinTranscriptions(result);
final String repairedXml = xml.replaceAll("<ab id=\"([0-9]+)\"/><ae id=\"\\1\"/>", "");
final String cooked = replaceAnnotationMilestones(repairedXml);
validateTextNums(cooked, result);
if (DEBUG) {
outputFiles(xml, cooked);
}
final String tei = toTei(xml, result);
Log.info("tei={}", tei);
result.setBody(tei);
String fullTEI = result.getTEI();
result.getStatus().setTei(fullTEI);
ValidationResult validateTEI = MVNValidator.validateTEI(fullTEI);
if (!validateTEI.isValid()) {
result.addError("",
"Gegenereerde TEI voldoet niet aan TEI_MVN.rng:\n"//
+ "<blockquote>" + validateTEI.getMessage() + "</blockquote>\n"//
+ " TEI:\n<pre>" + escapeHtml4(fullTEI) + "</pre>"//
+ " DEBUG:\n<pre>" + escapeHtml4(cooked) + "</pre>"//
);
}
return result;
}
static final String VALID_XML_ID_SUBSTRING_REGEXP = "[A-Za-z0-9\\-_:.]*";
private void validateEntryOrderAndName(MVNConversionResult result) {
boolean orderInUse = false;
Map<String, String> entryOrderMap = Maps.newTreeMap();
for (final MVNConversionData.EntryData entryData : data.getEntryDataList()) {
if (!entryData.name.matches(VALID_XML_ID_SUBSTRING_REGEXP)) {
result.addError(entryData.id, "Ongeldige entrynaam: " + entryData.name + ", voldoet niet aan de regexp " + VALID_XML_ID_SUBSTRING_REGEXP);
}
entryOrderMap.put(entryData.id, entryData.order);
if (entryData.order != null) {
orderInUse = true;
}
}
if (orderInUse) {
for (Entry<String, String> entry : entryOrderMap.entrySet()) {
String entryId = entry.getKey();
String order = entry.getValue();
if (StringUtils.isEmpty(order)) {
result.addError(entryId, "Ontbrekend metadataveld 'order'");
} else if (!StringUtils.isNumeric(order)) {
result.addError(entryId, "Ongeldige waarde voor metadataveld 'order': " + order + ", mag alleen cijfers bevatten");
}
}
}
}
boolean onlyTextLayerIsDiplomatic() {
String[] textLayers = project.getTextLayers();
return textLayers.length == 1 && TranscriptionType.DIPLOMATIC.equals(textLayers[0]);
}
private String joinTranscriptions(final MVNConversionResult result) {
final StringBuilder editionTextBuilder = new StringBuilder("<body>");
List<EntryData> entryDataList = data.getEntryDataList();
int total = entryDataList.size();
int i = 1;
for (final MVNConversionData.EntryData entryData : entryDataList) {
final String pageId = result.getSigle() + "-pb-" + entryData.name;
result.getStatus().addLogline("adding entry '" + entryData.name + "' (" + i++ + "/" + total + ")");
String transcriptionBody = transcriptionBody(entryData);
validateTranscriptionContainsNoEmptyLines(transcriptionBody, result, entryData.id);
editionTextBuilder//
.append("<entry n=\"").append(entryData.name).append("\" xml:id=\"").append(pageId).append("\" facs=\"").append(entryData.facs).append("\" _entryId=\"").append(entryData.id).append("\">")//
.append("<lb/>")//
.append(transcriptionBody.replaceAll("\\s*\n", "<le/><lb/>"))//
.append("<le/>")//
.append("</entry>");
}
return editionTextBuilder.append("</body>").toString().replace("<lb/><le/>", "");
}
private String transcriptionBody(final MVNConversionData.EntryData entryData) {
String rawBody = entryData.body//
.replace(" ", " ")//
.trim();
if (rawBody.contains("tali conuiuio")) {
Log.info(rawBody);
}
return transcriptionHiearchyFixer.fix(rawBody)//
.replace("</i><i>", "")//
.replace("<body>", "")//
.replace("<body/>", "")//
.replace("</body>", "");
}
static void validateTranscriptionContainsNoEmptyLines(String transcriptionBody, MVNConversionResult result, String entryId) {
if (Pattern.compile("\n\\s*\n").matcher(transcriptionBody).find()) {
result.addError(entryId, "Lege regels mogen niet voorkomen.");
}
}
private void validateTextNums(final String cooked, final MVNConversionResult result) {
final Deque<String> textNumStack = new ArrayDeque<String>();
final List<String> openTextNums = Lists.newArrayList();
final List<String> closeTextNums = Lists.newArrayList();
final Matcher matcher = Pattern.compile("<mvn:tekst([be][^ >]+) body=\"([^\"]+)\"").matcher(cooked);
boolean lastTagWasBegin = false;
while (matcher.find()) {
final String beginOrEinde = matcher.group(1);
final String textnum = matcher.group(2).trim().replaceFirst(";.*$", "");
Log.info("{}: textNumStack: {}, textNum: {}", beginOrEinde, textNumStack, textnum);
if ("begin".equals(beginOrEinde)) {
lastTagWasBegin = true;
validateTextNum(result, textnum, textNumStack, "");
textNumStack.push(textnum);
openTextNums.add(textnum);
} else if ("einde".equals(beginOrEinde)) {
if (!textNumStack.isEmpty()) {
final String peek = textNumStack.peek();
if (textnum.equals(peek)) {
if (lastTagWasBegin) {
data.getDeepestTextNums().add(textnum);
}
textNumStack.pop();
} else {
result.addError("", "mvn:teksteinde : tekstnummer '" + textnum + "' gevonden waar '" + peek + "' verwacht was.");
}
} else {
result.addError("", "mvn:teksteinde : tekstnummer '" + textnum + "' heeft geen overeenkomstig mvn:tekstbegin");
}
lastTagWasBegin = false;
closeTextNums.add(textnum);
} else {
throw new RuntimeException("unexpected type mvn:tekst" + beginOrEinde);
}
}
List<String> openedButNotClosed = Lists.newArrayList(openTextNums);
openedButNotClosed.removeAll(closeTextNums);
for (String tekstNum : openedButNotClosed) {
result.addError("", "mvn:teksteinde met tekstnummer '" + tekstNum + "' ontbreekt. ");
}
// List<String> closedButNotOpened = Lists.newArrayList(closeTextNums);
// closedButNotOpened.removeAll(openTextNums);
// for (String tekstNum : closedButNotOpened) {
// result.addError("", "mvn:teksbegin met tekstNum '" + tekstNum + "' ontbreekt. ");
// }
}
private void validateTextNum(MVNConversionResult result, final String textNum, Deque<String> textNumStack, String entryId) {
if (!textNum.matches("^[a-zA-Z0-9.]+$")) {
addError(MVNAnnotationType.TEKSTBEGIN, "Ongeldig tekstnummer: '" + textNum + "' mag alleen letters, cijfers en (maximaal 3) punten bevatten.", result, entryId);
} else if (textNum.split("\\.").length > 4) {
addError(MVNAnnotationType.TEKSTBEGIN, "Ongeldig tekstnummer: '" + textNum + "' mag maximaal 3 punten bevatten.", result, entryId);
} else if (!textNumStack.isEmpty() && !textNum.matches(textNumStack.peek() + "\\.[A-Za-z0-9]+$")) {
addError(MVNAnnotationType.TEKSTBEGIN, "tekstnummer: '" + textNum + "' volgt niet op " + textNumStack.peek(), result, entryId);
} else if (textNumStack.isEmpty() && textNum.contains(".")) {
addError(MVNAnnotationType.TEKSTBEGIN, "tekstnummer '" + textNum + "' niet omvat in " + textNum.replaceFirst("\\..+", "") + " (en dieper)", result, entryId);
}
}
private void outputFiles(final String xml, final String cooked) {
try {
String formatted = xml//
.replace("<entry", "\n <entry")//
.replace("</entry>", "\n </entry>\n")//
.replace("<lb/>", "\n <lb/>");
FileUtils.write(new File("out/raw-formatted-body.xml"), formatted, Charsets.UTF_8);
FileUtils.write(new File("out/cooked-body.xml"), cooked, Charsets.UTF_8);
} catch (final IOException e) {
e.printStackTrace();
}
}
private static void addError(MVNAnnotationType type, String error, MVNConversionResult result, String currentEntryId) {
result.addError(currentEntryId, type.getName() + " : " + error);
}
String toTei(final String xml, final MVNConversionResult conversionResult) {
Log.info("xml={}", xml);
ParseResult parseresult = new ParseResult();
final Document document = Document.createFromXml(xml, true);
final AnnotatedTranscriptionVisitor visitor = new AnnotatedTranscriptionVisitor(data.getAnnotationIndex(), parseresult, conversionResult.getSigle());
document.accept(visitor);
parseresult.index();
MVNTeiExporter teiExporter = new MVNTeiExporter(parseresult, conversionResult);
return teiExporter.export();
}
private String replaceAnnotationMilestones(final String xml) {
String cooked = xml;
for (final String annotationNoString : extractAnnotationNos(xml)) {
final Integer annotationNo = Integer.valueOf(annotationNoString);
if (data.getAnnotationIndex().containsKey(annotationNo)) {
final AnnotationData annotationData = data.getAnnotationIndex().get(annotationNo);
final String type = annotationData.type.replaceAll("[ ()]+", "_").replaceFirst("_$", "");
String attributes = "";
if (isNotBlank(annotationData.body) && !"nvt".equals(annotationData.body)) {
attributes = " body=\"" + escapeXml11(annotationData.body) + "\"";
}
cooked = cooked//
.replace(originalAnnotationBegin(annotationNoString), "<" + type + attributes + ">")//
.replace(originalAnnotationEnd(annotationNoString), "</" + type + ">");
}
}
return cooked.replace("<entry", "\n <entry")//
.replace("</entry>", "\n </entry>\n")//
.replace("<lb/>", "\n <lb/>");
}
private static String originalAnnotationBegin(final String annotationNo) {
return "<ab id=\"" + annotationNo + "\"/>";
}
private static String originalAnnotationEnd(final String annotationNo) {
return "<ae id=\"" + annotationNo + "\"/>";
}
String repairAnnotationHierarchy(String xml) {
AnnotationHierarchyRepairingVisitor visitor = new AnnotationHierarchyRepairingVisitor();
final Document document = Document.createFromXml(xml, false);
document.accept(visitor);
return visitor.getRepairedXml();
}
// public MVNConversionResult convert0() {
// final MVNConversionResult result = new MVNConversionResult(project, status);
// if (!onlyTextLayerIsDiplomatic()) {
// result.addError("", "MVN projecten mogen alleen een Diplomatic textlayer hebben. Dit project heeft textlayer(s): " + Joiner.on(", ").join(project.getTextLayers()));
// return result;
// }
// final StringBuilder editionTextBuilder = new StringBuilder();
// status.addLogline("joining transcriptions");
// for (final MVNConversionData.EntryData entryData : data.getEntryDataList()) {
// final String pageId = result.getSigle() + "-pb-" + entryData.name;
// String transcriptionBody = transcriptionBody(entryData);
// validateTranscriptionContainsNoEmptyLines(transcriptionBody, result, entryData.id);
// editionTextBuilder//
// .append("\n<pb n=\"")//
// .append(entryData.name)//
// .append("\" xml:id=\"")//
// .append(pageId)//
// .append("\" facs=\"")//
// .append(entryData.facs)//
// .append("\" _entryId=\"")//
// .append(entryData.id)//
// .append("\"/>\n")//
// .append("<lb/>")//
// .append(transcriptionBody(entryData).replace("\n", "<le/>\n<lb/>"))//
// .append("<le/>");
// }
//
// final String xml = "<body>" + editionTextBuilder.toString().replace("<lb/><le/>", "").replace("\n\n", "\n") + "</body>";
// final String repairedXml = repairAnnotationHierarchy(xml);
// final String cooked = replaceAnnotationMilestones(repairedXml);
// validateTextNums(cooked, result);
// if (DEBUG) {
// outputFiles(xml, cooked);
// }
// final String tei = toTei(repairedXml, result);
// result.setBody(tei);
// Log.info("tei={}", tei);
// String fullTEI = result.getTEI();
// ValidationResult validateTEI = MVNValidator.validateTEI(fullTEI);
// if (!validateTEI.isValid()) {
// result.addError("",
// "Gegenereerde TEI is niet valide:\n"//
// + "<blockquote>" + validateTEI.getMessage() + "</blockquote>\n"//
// + " TEI:\n<pre>" + escapeHtml(fullTEI) + "</pre>"//
// );
// }
// // for (ProjectEntry entry : project.getProjectEntries()) {
// // MVNFolium page = new MVNFolium();
// // String n = entry.getName();
// // page.setN(n);
// // page.setId(result.getSigle() + "-pb-" + n);
// // setFacs(entry, page, result);
// // setOrder(page, entry);
// // setBody(page, entry, result);
// // result.addPages(page);
// // }
// return result;
// }
//
// private void setFacs(final ProjectEntry entry, final MVNFolium page, final MVNConversionResult result) {
// final List<Facsimile> facsimiles = entry.getFacsimiles();
// if (facsimiles.isEmpty()) {
// result.addError("" + entry.getId(), "no facsimile");
// } else {
// if (facsimiles.size() > 1) {
// result.addError("" + entry.getId(), "multiple facsimiles, using first");
// }
// page.setFacs(facsimiles.get(0).getName());
// }
// }
//
// private void setBody(final MVNFolium page, final ProjectEntry entry, final MVNConversionResult result, final Map<Integer, AnnotationData> annotationIndex) {
// String body = null;
// for (final Transcription transcription : entry.getTranscriptions()) {
// if ("Diplomatic".equals(transcription.getTextLayer())) {
// body = transcription.getBody().replace(" ", " ");
// } else {
// result.addError("" + entry.getId(), "incorrect textlayer found: " + transcription.getTextLayer());
// }
// }
// Log.info("body=[\n{}\n]", body);
// if (body == null) {
// result.addError("" + entry.getId(), "no Diplomatic textlayer");
// } else {
// page.setBody(toTei(body, result));
// }
// Log.info("body=[\n{}\n]", page.getBody());
// }
// String toTei0(final String xml, final MVNConversionResult result) {
// final MVNTranscriptionVisitor visitor = new MVNTranscriptionVisitor(result, data.getAnnotationIndex(), data.getDeepestTextNums());
// Log.info("xml={}", xml);
//
// final Document document = Document.createFromXml(xml, false);
// document.accept(visitor);
//
// final XmlContext c = visitor.getContext();
// final String rawResult = c.getResult();
//
// return rawResult//
// .replace("<b>", "")//
// .replace("</b>", "")//
// .replace("<u>", "")//
// .replace("</u>", "")//
// // .replaceAll("<gap>.*?</gap>", "<gap/>")// according to the rng, gaps should be empty
// .replace("<l><head", "<head")//
// // .replace("<l><hi rend=\"rubric\"><head", "<head")//
// .replace("</head></l>", "</head>")//
// // .replace("</head></hi></l>", "</head>")//
// .replace("<l><closer", "<closer")//
// .replace("</closer></l>", "</closer>")//
// .replace("<hi rend=\"rubric\"><hi rend=\"rubric\">¶</hi></hi>", "<hi rend=\"rubric\">¶</hi>");
// }
}
| HuygensING/elaborate4-backend | elab4-backend/src/main/java/elaborate/editor/export/mvn/MVNConverter.java | 7,150 | // result.addError("", "MVN projecten mogen alleen een Diplomatic textlayer hebben. Dit project heeft textlayer(s): " + Joiner.on(", ").join(project.getTextLayers())); | line_comment | nl | package elaborate.editor.export.mvn;
/*
* #%L
* elab4-backend
* =======
* Copyright (C) 2011 - 2019 Huygens ING
* =======
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import elaborate.editor.export.mvn.MVNConversionData.AnnotationData;
import elaborate.editor.export.mvn.MVNConversionData.EntryData;
import elaborate.editor.export.mvn.MVNValidator.ValidationResult;
import elaborate.editor.model.orm.Project;
import elaborate.editor.model.orm.TranscriptionType;
import elaborate.editor.publish.Publication.Status;
import elaborate.util.HibernateUtil;
import nl.knaw.huygens.Log;
import nl.knaw.huygens.tei.Document;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.File;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static elaborate.util.XmlUtil.extractAnnotationNos;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.text.StringEscapeUtils.escapeHtml4;
import static org.apache.commons.text.StringEscapeUtils.escapeXml11;
public class MVNConverter {
private static final boolean DEBUG = false; // for release
// private static final boolean DEBUG = true; // for testing, don't release with DEBUG=true!!!
private final Project project;
private final MVNConversionData data;
private final Status status;
private final TranscriptionHierarchyFixer transcriptionHiearchyFixer = new TranscriptionHierarchyFixer();
private final String baseURL;
public MVNConverter(final Project project, final MVNConversionData data, Status status, String baseURL) {
this.project = project;
this.data = data;
this.status = status;
this.baseURL = baseURL;
}
// phase 1: collect MVNFolium with raw transcription
// order by 'order' or entryname
// fail when 1, but not all entries have order
// fail when entrynames are not unique
// fail when entrynames contain characters illegal in xml:id
// select id, name from project_entries where project_id=$projectId
// select
@SuppressWarnings("unchecked")
public static MVNConversionData getConversionData(final long project_id, Status status) {
final MVNConversionData conversionData = new MVNConversionData();
final EntityManager entityManager = HibernateUtil.beginTransaction();
final String transcriptionSQL = ("select"//
+ " e.id as id,"//
+ " e.name as name,"//
+ " m.data as entry_order,"//
+ " t.body as transcription,"//
+ " f.filename"//
+ " from project_entries e"//
+ " left outer join project_entry_metadata_items m on (e.id = m.project_entry_id and m.field='order')"//
+ " left outer join transcriptions t on (e.id = t.project_entry_id and t.text_layer='Diplomatic')"//
+ " left outer join facsimiles f on (e.id = f.project_entry_id)"//
+ " where project_id=" + project_id//
+ " order by entry_order, name").replaceAll(" +", " ");
final Query transcriptionQuery = entityManager.createNativeQuery(transcriptionSQL);
status.addLogline("collecting transcription data");
final List<Object[]> transcriptions = transcriptionQuery.getResultList();
if (transcriptions.isEmpty()) {
status.addError("no transcriptions found");
} else {
for (final Object[] transcriptionData : transcriptions) {
final EntryData entryData = new MVNConversionData.EntryData();
final Integer id = (Integer) transcriptionData[0];
entryData.id = String.valueOf(id);
entryData.name = (String) transcriptionData[1];
entryData.order = (String) transcriptionData[2];
entryData.body = (String) transcriptionData[3];
entryData.facs = (String) transcriptionData[4];
conversionData.getEntryDataList().add(entryData);
}
final String annotationSQL = ("select"//
+ " a.annotation_no as annotation_num,"//
+ " at.name as annotation_type,"//
+ " a.body as annotation_body"//
+ " from project_entries e"//
+ " left outer join transcriptions t"//
+ " left outer join annotations a"//
+ " left outer join annotation_types at"//
+ " on (at.id=a.annotation_type_id)"//
+ " on (t.id = a.transcription_id)"//
+ " on (e.id = t.project_entry_id and t.text_layer='Diplomatic')"//
+ " where project_id=" + project_id//
+ " order by annotation_num;").replaceAll(" +", " ");
final Query annotationQuery = entityManager.createNativeQuery(annotationSQL);
status.addLogline("collecting annotation data");
final List<Object[]> annotations = annotationQuery.getResultList();
// Log.info("SQL: {}", annotationSQL);
// Log.info("{} results:", annotations.size());
for (final Object[] annotation : annotations) {
final AnnotationData annotationData = new MVNConversionData.AnnotationData();
final Integer annotationNum = (Integer) annotation[0];
annotationData.type = (String) annotation[1];
annotationData.body = (String) annotation[2];
conversionData.getAnnotationIndex().put(annotationNum, annotationData);
}
}
HibernateUtil.rollbackTransaction(entityManager);
return conversionData;
}
public MVNConversionResult convert() {
final MVNConversionResult result = new MVNConversionResult(project, status, baseURL);
if (!onlyTextLayerIsDiplomatic()) {
result.addError("", "MVN projecten mogen alleen een Diplomatic textlayer hebben. Dit project heeft textlayer(s): " + Joiner.on(", ").join(project.getTextLayers()));
return result;
}
validateEntryOrderAndName(result);
status.addLogline("joining transcriptions");
final String xml = joinTranscriptions(result);
final String repairedXml = xml.replaceAll("<ab id=\"([0-9]+)\"/><ae id=\"\\1\"/>", "");
final String cooked = replaceAnnotationMilestones(repairedXml);
validateTextNums(cooked, result);
if (DEBUG) {
outputFiles(xml, cooked);
}
final String tei = toTei(xml, result);
Log.info("tei={}", tei);
result.setBody(tei);
String fullTEI = result.getTEI();
result.getStatus().setTei(fullTEI);
ValidationResult validateTEI = MVNValidator.validateTEI(fullTEI);
if (!validateTEI.isValid()) {
result.addError("",
"Gegenereerde TEI voldoet niet aan TEI_MVN.rng:\n"//
+ "<blockquote>" + validateTEI.getMessage() + "</blockquote>\n"//
+ " TEI:\n<pre>" + escapeHtml4(fullTEI) + "</pre>"//
+ " DEBUG:\n<pre>" + escapeHtml4(cooked) + "</pre>"//
);
}
return result;
}
static final String VALID_XML_ID_SUBSTRING_REGEXP = "[A-Za-z0-9\\-_:.]*";
private void validateEntryOrderAndName(MVNConversionResult result) {
boolean orderInUse = false;
Map<String, String> entryOrderMap = Maps.newTreeMap();
for (final MVNConversionData.EntryData entryData : data.getEntryDataList()) {
if (!entryData.name.matches(VALID_XML_ID_SUBSTRING_REGEXP)) {
result.addError(entryData.id, "Ongeldige entrynaam: " + entryData.name + ", voldoet niet aan de regexp " + VALID_XML_ID_SUBSTRING_REGEXP);
}
entryOrderMap.put(entryData.id, entryData.order);
if (entryData.order != null) {
orderInUse = true;
}
}
if (orderInUse) {
for (Entry<String, String> entry : entryOrderMap.entrySet()) {
String entryId = entry.getKey();
String order = entry.getValue();
if (StringUtils.isEmpty(order)) {
result.addError(entryId, "Ontbrekend metadataveld 'order'");
} else if (!StringUtils.isNumeric(order)) {
result.addError(entryId, "Ongeldige waarde voor metadataveld 'order': " + order + ", mag alleen cijfers bevatten");
}
}
}
}
boolean onlyTextLayerIsDiplomatic() {
String[] textLayers = project.getTextLayers();
return textLayers.length == 1 && TranscriptionType.DIPLOMATIC.equals(textLayers[0]);
}
private String joinTranscriptions(final MVNConversionResult result) {
final StringBuilder editionTextBuilder = new StringBuilder("<body>");
List<EntryData> entryDataList = data.getEntryDataList();
int total = entryDataList.size();
int i = 1;
for (final MVNConversionData.EntryData entryData : entryDataList) {
final String pageId = result.getSigle() + "-pb-" + entryData.name;
result.getStatus().addLogline("adding entry '" + entryData.name + "' (" + i++ + "/" + total + ")");
String transcriptionBody = transcriptionBody(entryData);
validateTranscriptionContainsNoEmptyLines(transcriptionBody, result, entryData.id);
editionTextBuilder//
.append("<entry n=\"").append(entryData.name).append("\" xml:id=\"").append(pageId).append("\" facs=\"").append(entryData.facs).append("\" _entryId=\"").append(entryData.id).append("\">")//
.append("<lb/>")//
.append(transcriptionBody.replaceAll("\\s*\n", "<le/><lb/>"))//
.append("<le/>")//
.append("</entry>");
}
return editionTextBuilder.append("</body>").toString().replace("<lb/><le/>", "");
}
private String transcriptionBody(final MVNConversionData.EntryData entryData) {
String rawBody = entryData.body//
.replace(" ", " ")//
.trim();
if (rawBody.contains("tali conuiuio")) {
Log.info(rawBody);
}
return transcriptionHiearchyFixer.fix(rawBody)//
.replace("</i><i>", "")//
.replace("<body>", "")//
.replace("<body/>", "")//
.replace("</body>", "");
}
static void validateTranscriptionContainsNoEmptyLines(String transcriptionBody, MVNConversionResult result, String entryId) {
if (Pattern.compile("\n\\s*\n").matcher(transcriptionBody).find()) {
result.addError(entryId, "Lege regels mogen niet voorkomen.");
}
}
private void validateTextNums(final String cooked, final MVNConversionResult result) {
final Deque<String> textNumStack = new ArrayDeque<String>();
final List<String> openTextNums = Lists.newArrayList();
final List<String> closeTextNums = Lists.newArrayList();
final Matcher matcher = Pattern.compile("<mvn:tekst([be][^ >]+) body=\"([^\"]+)\"").matcher(cooked);
boolean lastTagWasBegin = false;
while (matcher.find()) {
final String beginOrEinde = matcher.group(1);
final String textnum = matcher.group(2).trim().replaceFirst(";.*$", "");
Log.info("{}: textNumStack: {}, textNum: {}", beginOrEinde, textNumStack, textnum);
if ("begin".equals(beginOrEinde)) {
lastTagWasBegin = true;
validateTextNum(result, textnum, textNumStack, "");
textNumStack.push(textnum);
openTextNums.add(textnum);
} else if ("einde".equals(beginOrEinde)) {
if (!textNumStack.isEmpty()) {
final String peek = textNumStack.peek();
if (textnum.equals(peek)) {
if (lastTagWasBegin) {
data.getDeepestTextNums().add(textnum);
}
textNumStack.pop();
} else {
result.addError("", "mvn:teksteinde : tekstnummer '" + textnum + "' gevonden waar '" + peek + "' verwacht was.");
}
} else {
result.addError("", "mvn:teksteinde : tekstnummer '" + textnum + "' heeft geen overeenkomstig mvn:tekstbegin");
}
lastTagWasBegin = false;
closeTextNums.add(textnum);
} else {
throw new RuntimeException("unexpected type mvn:tekst" + beginOrEinde);
}
}
List<String> openedButNotClosed = Lists.newArrayList(openTextNums);
openedButNotClosed.removeAll(closeTextNums);
for (String tekstNum : openedButNotClosed) {
result.addError("", "mvn:teksteinde met tekstnummer '" + tekstNum + "' ontbreekt. ");
}
// List<String> closedButNotOpened = Lists.newArrayList(closeTextNums);
// closedButNotOpened.removeAll(openTextNums);
// for (String tekstNum : closedButNotOpened) {
// result.addError("", "mvn:teksbegin met tekstNum '" + tekstNum + "' ontbreekt. ");
// }
}
private void validateTextNum(MVNConversionResult result, final String textNum, Deque<String> textNumStack, String entryId) {
if (!textNum.matches("^[a-zA-Z0-9.]+$")) {
addError(MVNAnnotationType.TEKSTBEGIN, "Ongeldig tekstnummer: '" + textNum + "' mag alleen letters, cijfers en (maximaal 3) punten bevatten.", result, entryId);
} else if (textNum.split("\\.").length > 4) {
addError(MVNAnnotationType.TEKSTBEGIN, "Ongeldig tekstnummer: '" + textNum + "' mag maximaal 3 punten bevatten.", result, entryId);
} else if (!textNumStack.isEmpty() && !textNum.matches(textNumStack.peek() + "\\.[A-Za-z0-9]+$")) {
addError(MVNAnnotationType.TEKSTBEGIN, "tekstnummer: '" + textNum + "' volgt niet op " + textNumStack.peek(), result, entryId);
} else if (textNumStack.isEmpty() && textNum.contains(".")) {
addError(MVNAnnotationType.TEKSTBEGIN, "tekstnummer '" + textNum + "' niet omvat in " + textNum.replaceFirst("\\..+", "") + " (en dieper)", result, entryId);
}
}
private void outputFiles(final String xml, final String cooked) {
try {
String formatted = xml//
.replace("<entry", "\n <entry")//
.replace("</entry>", "\n </entry>\n")//
.replace("<lb/>", "\n <lb/>");
FileUtils.write(new File("out/raw-formatted-body.xml"), formatted, Charsets.UTF_8);
FileUtils.write(new File("out/cooked-body.xml"), cooked, Charsets.UTF_8);
} catch (final IOException e) {
e.printStackTrace();
}
}
private static void addError(MVNAnnotationType type, String error, MVNConversionResult result, String currentEntryId) {
result.addError(currentEntryId, type.getName() + " : " + error);
}
String toTei(final String xml, final MVNConversionResult conversionResult) {
Log.info("xml={}", xml);
ParseResult parseresult = new ParseResult();
final Document document = Document.createFromXml(xml, true);
final AnnotatedTranscriptionVisitor visitor = new AnnotatedTranscriptionVisitor(data.getAnnotationIndex(), parseresult, conversionResult.getSigle());
document.accept(visitor);
parseresult.index();
MVNTeiExporter teiExporter = new MVNTeiExporter(parseresult, conversionResult);
return teiExporter.export();
}
private String replaceAnnotationMilestones(final String xml) {
String cooked = xml;
for (final String annotationNoString : extractAnnotationNos(xml)) {
final Integer annotationNo = Integer.valueOf(annotationNoString);
if (data.getAnnotationIndex().containsKey(annotationNo)) {
final AnnotationData annotationData = data.getAnnotationIndex().get(annotationNo);
final String type = annotationData.type.replaceAll("[ ()]+", "_").replaceFirst("_$", "");
String attributes = "";
if (isNotBlank(annotationData.body) && !"nvt".equals(annotationData.body)) {
attributes = " body=\"" + escapeXml11(annotationData.body) + "\"";
}
cooked = cooked//
.replace(originalAnnotationBegin(annotationNoString), "<" + type + attributes + ">")//
.replace(originalAnnotationEnd(annotationNoString), "</" + type + ">");
}
}
return cooked.replace("<entry", "\n <entry")//
.replace("</entry>", "\n </entry>\n")//
.replace("<lb/>", "\n <lb/>");
}
private static String originalAnnotationBegin(final String annotationNo) {
return "<ab id=\"" + annotationNo + "\"/>";
}
private static String originalAnnotationEnd(final String annotationNo) {
return "<ae id=\"" + annotationNo + "\"/>";
}
String repairAnnotationHierarchy(String xml) {
AnnotationHierarchyRepairingVisitor visitor = new AnnotationHierarchyRepairingVisitor();
final Document document = Document.createFromXml(xml, false);
document.accept(visitor);
return visitor.getRepairedXml();
}
// public MVNConversionResult convert0() {
// final MVNConversionResult result = new MVNConversionResult(project, status);
// if (!onlyTextLayerIsDiplomatic()) {
// result.addError("", "MVN<SUF>
// return result;
// }
// final StringBuilder editionTextBuilder = new StringBuilder();
// status.addLogline("joining transcriptions");
// for (final MVNConversionData.EntryData entryData : data.getEntryDataList()) {
// final String pageId = result.getSigle() + "-pb-" + entryData.name;
// String transcriptionBody = transcriptionBody(entryData);
// validateTranscriptionContainsNoEmptyLines(transcriptionBody, result, entryData.id);
// editionTextBuilder//
// .append("\n<pb n=\"")//
// .append(entryData.name)//
// .append("\" xml:id=\"")//
// .append(pageId)//
// .append("\" facs=\"")//
// .append(entryData.facs)//
// .append("\" _entryId=\"")//
// .append(entryData.id)//
// .append("\"/>\n")//
// .append("<lb/>")//
// .append(transcriptionBody(entryData).replace("\n", "<le/>\n<lb/>"))//
// .append("<le/>");
// }
//
// final String xml = "<body>" + editionTextBuilder.toString().replace("<lb/><le/>", "").replace("\n\n", "\n") + "</body>";
// final String repairedXml = repairAnnotationHierarchy(xml);
// final String cooked = replaceAnnotationMilestones(repairedXml);
// validateTextNums(cooked, result);
// if (DEBUG) {
// outputFiles(xml, cooked);
// }
// final String tei = toTei(repairedXml, result);
// result.setBody(tei);
// Log.info("tei={}", tei);
// String fullTEI = result.getTEI();
// ValidationResult validateTEI = MVNValidator.validateTEI(fullTEI);
// if (!validateTEI.isValid()) {
// result.addError("",
// "Gegenereerde TEI is niet valide:\n"//
// + "<blockquote>" + validateTEI.getMessage() + "</blockquote>\n"//
// + " TEI:\n<pre>" + escapeHtml(fullTEI) + "</pre>"//
// );
// }
// // for (ProjectEntry entry : project.getProjectEntries()) {
// // MVNFolium page = new MVNFolium();
// // String n = entry.getName();
// // page.setN(n);
// // page.setId(result.getSigle() + "-pb-" + n);
// // setFacs(entry, page, result);
// // setOrder(page, entry);
// // setBody(page, entry, result);
// // result.addPages(page);
// // }
// return result;
// }
//
// private void setFacs(final ProjectEntry entry, final MVNFolium page, final MVNConversionResult result) {
// final List<Facsimile> facsimiles = entry.getFacsimiles();
// if (facsimiles.isEmpty()) {
// result.addError("" + entry.getId(), "no facsimile");
// } else {
// if (facsimiles.size() > 1) {
// result.addError("" + entry.getId(), "multiple facsimiles, using first");
// }
// page.setFacs(facsimiles.get(0).getName());
// }
// }
//
// private void setBody(final MVNFolium page, final ProjectEntry entry, final MVNConversionResult result, final Map<Integer, AnnotationData> annotationIndex) {
// String body = null;
// for (final Transcription transcription : entry.getTranscriptions()) {
// if ("Diplomatic".equals(transcription.getTextLayer())) {
// body = transcription.getBody().replace(" ", " ");
// } else {
// result.addError("" + entry.getId(), "incorrect textlayer found: " + transcription.getTextLayer());
// }
// }
// Log.info("body=[\n{}\n]", body);
// if (body == null) {
// result.addError("" + entry.getId(), "no Diplomatic textlayer");
// } else {
// page.setBody(toTei(body, result));
// }
// Log.info("body=[\n{}\n]", page.getBody());
// }
// String toTei0(final String xml, final MVNConversionResult result) {
// final MVNTranscriptionVisitor visitor = new MVNTranscriptionVisitor(result, data.getAnnotationIndex(), data.getDeepestTextNums());
// Log.info("xml={}", xml);
//
// final Document document = Document.createFromXml(xml, false);
// document.accept(visitor);
//
// final XmlContext c = visitor.getContext();
// final String rawResult = c.getResult();
//
// return rawResult//
// .replace("<b>", "")//
// .replace("</b>", "")//
// .replace("<u>", "")//
// .replace("</u>", "")//
// // .replaceAll("<gap>.*?</gap>", "<gap/>")// according to the rng, gaps should be empty
// .replace("<l><head", "<head")//
// // .replace("<l><hi rend=\"rubric\"><head", "<head")//
// .replace("</head></l>", "</head>")//
// // .replace("</head></hi></l>", "</head>")//
// .replace("<l><closer", "<closer")//
// .replace("</closer></l>", "</closer>")//
// .replace("<hi rend=\"rubric\"><hi rend=\"rubric\">¶</hi></hi>", "<hi rend=\"rubric\">¶</hi>");
// }
}
|
18985_0 | package nl.knaw.huygens.timbuctoo.lucene.accentanalyzer;
import java.io.IOException;
import java.util.Stack;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.miscellaneous.ASCIIFoldingFilter;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.util.AttributeSource;
public class MyAccentFilter extends TokenFilter {
private CharTermAttribute termAtt;
private Stack<String> synonymStack;
private PositionIncrementAttribute posIncrAtt;
private AttributeSource.State current;
private TypeAttribute typeAtt;
private String TYPE_SYNONYM = "SYNONYM";
public MyAccentFilter(TokenStream input) {
super(input);
synonymStack = new Stack<String>();
this.termAtt = addAttribute(CharTermAttribute.class);
this.posIncrAtt = addAttribute(PositionIncrementAttribute.class);
this.typeAtt = addAttribute(TypeAttribute.class);
this.current = captureState();
}
@Override
public boolean incrementToken() throws IOException {
if (synonymStack.size() > 0) {
String syn = synonymStack.pop();
restoreState(current);
typeAtt.setType(TYPE_SYNONYM);
termAtt.copyBuffer(syn.toCharArray(), 0, syn.length());
posIncrAtt.setPositionIncrement(0);
return true;
}
if (!input.incrementToken()) {
return false;
}
if (addAliasesToStack()) {
current = captureState();
}
return true;
}
private boolean addAliasesToStack() throws IOException {
// toString werkt niet goed voor 'lastige' utf8 of andere codes
// oplossing lijkt te zitten in het verlengen van de result array
String term = termAtt.toString();
String termLc = term.toLowerCase();
if (!termLc.equals(term)) {
synonymStack.push(termLc); // lc met trema
}
char[] result = new char[term.length()*2];
try {
ASCIIFoldingFilter.foldToASCII(termAtt.buffer(), 0, result, 0, term.length());
} catch(Exception aioobe) {
System.err.println("term: |"+term+"|");
System.err.println("length: "+term.length());
System.err.println("termAtt.length: "+termAtt.length());
System.err.println("termAtt: "+termAtt);
int i = 1;
for(char ch : term.toCharArray()) {
System.err.println(i+": "+ch);
i++;
}
throw aioobe;
}
String termNoAc = String.valueOf(result);
if (!termNoAc.equals(term)) {
synonymStack.push(termNoAc);
String termNoAcLc = termNoAc.toLowerCase();
if (!termNoAcLc.equals(termNoAc)) {
synonymStack.push(termNoAcLc);
}
}
if (synonymStack.isEmpty()) {
return false;
}
return true;
}
}
| HuygensING/timbuctooSolrExample | src/nl/knaw/huygens/timbuctoo/lucene/accentanalyzer/MyAccentFilter.java | 934 | // toString werkt niet goed voor 'lastige' utf8 of andere codes
| line_comment | nl | package nl.knaw.huygens.timbuctoo.lucene.accentanalyzer;
import java.io.IOException;
import java.util.Stack;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.miscellaneous.ASCIIFoldingFilter;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.util.AttributeSource;
public class MyAccentFilter extends TokenFilter {
private CharTermAttribute termAtt;
private Stack<String> synonymStack;
private PositionIncrementAttribute posIncrAtt;
private AttributeSource.State current;
private TypeAttribute typeAtt;
private String TYPE_SYNONYM = "SYNONYM";
public MyAccentFilter(TokenStream input) {
super(input);
synonymStack = new Stack<String>();
this.termAtt = addAttribute(CharTermAttribute.class);
this.posIncrAtt = addAttribute(PositionIncrementAttribute.class);
this.typeAtt = addAttribute(TypeAttribute.class);
this.current = captureState();
}
@Override
public boolean incrementToken() throws IOException {
if (synonymStack.size() > 0) {
String syn = synonymStack.pop();
restoreState(current);
typeAtt.setType(TYPE_SYNONYM);
termAtt.copyBuffer(syn.toCharArray(), 0, syn.length());
posIncrAtt.setPositionIncrement(0);
return true;
}
if (!input.incrementToken()) {
return false;
}
if (addAliasesToStack()) {
current = captureState();
}
return true;
}
private boolean addAliasesToStack() throws IOException {
// toString werkt<SUF>
// oplossing lijkt te zitten in het verlengen van de result array
String term = termAtt.toString();
String termLc = term.toLowerCase();
if (!termLc.equals(term)) {
synonymStack.push(termLc); // lc met trema
}
char[] result = new char[term.length()*2];
try {
ASCIIFoldingFilter.foldToASCII(termAtt.buffer(), 0, result, 0, term.length());
} catch(Exception aioobe) {
System.err.println("term: |"+term+"|");
System.err.println("length: "+term.length());
System.err.println("termAtt.length: "+termAtt.length());
System.err.println("termAtt: "+termAtt);
int i = 1;
for(char ch : term.toCharArray()) {
System.err.println(i+": "+ch);
i++;
}
throw aioobe;
}
String termNoAc = String.valueOf(result);
if (!termNoAc.equals(term)) {
synonymStack.push(termNoAc);
String termNoAcLc = termNoAc.toLowerCase();
if (!termNoAcLc.equals(termNoAc)) {
synonymStack.push(termNoAcLc);
}
}
if (synonymStack.isEmpty()) {
return false;
}
return true;
}
}
|
110954_7 | package nl.knaw.huc.di.tag.treegrammar;
import nl.knaw.huc.di.tag.treegrammar.nodes.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.stream.Location;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import static java.text.MessageFormat.format;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
/*
* author: Ronald Haentjens Dekker
* date: 11-09-2018
*
* in een tree automata willen we een tree bijhouden
* In een state machine ga je van state naar state
* Echter in een tree model zijn er meerdere mogelijke non terminals
* die je kunt vervangen.
*/
class StateMachine {
private static final Logger LOG = LoggerFactory.getLogger(StateMachine.class);
private Tree<Node> completeTree; // tree die we aan het opbouwen zijn
private final Map<NonTerminalNode, NodeReplacementInfo> nodeReplacementInfoMap = new HashMap<>();
class NodeReplacementInfo {
final Supplier<Tree<Node>> replacementSupplier;
final Function<Node, Boolean> nodeMatcher;
NodeReplacementInfo(Supplier<Tree<Node>> replacementSupplier, Function<Node, Boolean> nodeMatcher) {
this.replacementSupplier = replacementSupplier;
this.nodeMatcher = nodeMatcher;
}
boolean matches(final Node inputNode) {
return nodeMatcher.apply(inputNode);
}
}
StateMachine() {
StartNode startNode = new StartNode();
this.completeTree = new Tree<>(startNode);
}
public Tree<Node> getTree() {
return completeTree;
}
public void exit() {
// remove choicenodes and groupnodes
// if any nonterminals remain, throw error
LOG.info("\n\n* completeTree (before exit())=\n{}", TreeVisualizer.asText(completeTree));
walkSubTreeWithRoot(completeTree.root);
LOG.info("\n\n* completeTree (after exit())=\n{}", TreeVisualizer.asText(completeTree));
}
private void walkSubTreeWithRoot(final Node root) {
completeTree.children.putIfAbsent(root, emptyList());
List<Node> rootChildren = completeTree.children.get(root);
root.postProcess(completeTree, rootChildren);
List<Node> originalChildNodes = (rootChildren == null)
? emptyList()
: new ArrayList<>(rootChildren);
originalChildNodes.forEach(this::walkSubTreeWithRoot);
}
void addTransitionRule(TransitionRule transitionRule) {
// this.rules.add(transitionRule);
NodeReplacementInfo nri = new NodeReplacementInfo(
transitionRule.getRightHandSideSupplier(),
transitionRule.getNodeMatcher()
);
nodeReplacementInfoMap.put(transitionRule.leftHandSide, nri);
}
void processInput(Node inputNode, final Location location) {
// bij de state machine komen nodes binnen
// In de tree die we aan het bouwen zijn zitten nog NonTerminal nodes, waarvan er 1 aan de beurt is om vervangen te worden.
// We zoeken nu een transition rule die deze NonTerminal aan de linkerkant heeft, en
// matched met de binnenkomende node
// zo niet; dan zitten we in een error.
// We zoeken eerst op naar welke node de huidige pointer verwijst.
// Dan kijken we welke transitierules er zijn voor dat type node.
String position = position(location);
LOG.info("\n\n* completeTree=\n{}", TreeVisualizer.asText(completeTree));
List<NonTerminalNode> nextNonTerminals = nextNonTerminals();
LOG.info("nextNonTerminals={}", nextNonTerminals);
AnyTextNode anyTextNode = new AnyTextNode();
if (nextNonTerminals.contains(anyTextNode) && inputNode instanceof TextNode) {
NodeReplacementInfo nri = new NodeReplacementInfo(
() -> new Tree<>(inputNode),
inputNode::matches
);
nodeReplacementInfoMap.put(anyTextNode, nri);
}
List<NonTerminalNode> replaceableNodes = nextNonTerminals.stream()
.filter(nodeReplacementInfoMap::containsKey)
.collect(toList());
LOG.info("inputNode={}", inputNode);
final List<Supplier<Tree<Node>>> acceptableReplacementSuppliers = replaceableNodes.stream()
.filter(t -> nodeReplacementInfoMap.containsKey(t) && nodeReplacementInfoMap.get(t).matches(inputNode))
.map(nodeReplacementInfoMap::get)
.map(nri -> nri.replacementSupplier)
.collect(toList());
LOG.info("acceptable replacements={}", acceptableReplacementSuppliers);
Node nodeToReplace = null;
Tree<Node> replacementTree = null;
List<Node> rejectedNonTerminalNodes = new ArrayList<>();
for (NonTerminalNode n : nextNonTerminals) {
Supplier<Tree<Node>> treeSupplier = nodeReplacementInfoMap.get(n).replacementSupplier;
if (acceptableReplacementSuppliers.contains(treeSupplier)) {
nodeToReplace = n;
replacementTree = treeSupplier.get();
} else {
rejectedNonTerminalNodes.add(n);
}
}
if (nodeToReplace == null) {
final List<Tree<Node>> possibleReplacements = replaceableNodes.stream()
.map(nodeReplacementInfoMap::get)
.map(nri -> nri.replacementSupplier)
.map(Supplier::get)
.collect(toList());
LOG.info("possible replacements={}", possibleReplacements);
List<Node> acceptableNodes = possibleReplacements.stream()
.map(t -> t.root)
.collect(toList());
LOG.info("acceptable nodes={}", acceptableNodes);
if (acceptableNodes.isEmpty()) {
throw new RuntimeException(format("{0}: Unexpected node: {1}", position, inputNode));
}
String expected = acceptableNodes.stream()
.map(Object::toString)
.collect(joining(" or "));
throw new RuntimeException(format("{0}: No match: expected {1}, but got {2}", position, expected, inputNode));
}
Node parent = completeTree.parents.get(nodeToReplace);
boolean parentIsXOrMoreNode = (parent instanceof ZeroOrMoreNode || parent instanceof OneOrMoreNode);
LOG.info("action: replace node ({}) with tree ({})", nodeToReplace, replacementTree);
replaceNodeWithTree(nodeToReplace, replacementTree);
if (parentIsXOrMoreNode) {
completeTree.connect(parent, nodeToReplace);
}
LOG.info("action: reject nodes {}", rejectedNonTerminalNodes);
rejectedNonTerminalNodes.forEach(n -> {
Node nodeParent = completeTree.parents.get(n);
if (nodeParent instanceof GroupNode) {
completeTree.removeSubTreeWithRootNode(nodeParent);
} else {
completeTree.removeSubTreeWithRootNode(n);
}
});
nodeReplacementInfoMap.remove(anyTextNode);
}
private String position(final Location location) {
return "@" + location.getLineNumber() + "," + (location.getColumnNumber() - 1);
}
private List<NonTerminalNode> nextNonTerminals() {
final List<NonTerminalNode> list = new ArrayList<>();
Node root = completeTree.root;
if (root instanceof NonTerminalNode) {
list.add((NonTerminalNode) root);
} else {
List<NonTerminalNode> firstNonTerminals = completeTree.getRootChildren().stream()
.map(n -> n.firstNonTerminals(completeTree))
.filter(l -> !l.isEmpty())
.findFirst()
.orElse(emptyList());
list.addAll(firstNonTerminals);
}
return list;
}
private void replaceNodeWithTree(final Node nonTerminalNode, final Tree<Node> replacementTree) {
if (nonTerminalNode == completeTree.root) {
completeTree = replacementTree;
} else {
final Tree<Node> newTree = completeTree.replaceNodeWithTree(nonTerminalNode, replacementTree);
// LOG.info("original={}", TreeVisualizer.asSExpression(completeTree, false));
// LOG.info("new ={}", TreeVisualizer.asSExpression(newTree, false));
completeTree = newTree;
}
}
} | HuygensING/treegrammar | src/main/java/nl/knaw/huc/di/tag/treegrammar/StateMachine.java | 2,323 | // matched met de binnenkomende node | line_comment | nl | package nl.knaw.huc.di.tag.treegrammar;
import nl.knaw.huc.di.tag.treegrammar.nodes.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.stream.Location;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import static java.text.MessageFormat.format;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
/*
* author: Ronald Haentjens Dekker
* date: 11-09-2018
*
* in een tree automata willen we een tree bijhouden
* In een state machine ga je van state naar state
* Echter in een tree model zijn er meerdere mogelijke non terminals
* die je kunt vervangen.
*/
class StateMachine {
private static final Logger LOG = LoggerFactory.getLogger(StateMachine.class);
private Tree<Node> completeTree; // tree die we aan het opbouwen zijn
private final Map<NonTerminalNode, NodeReplacementInfo> nodeReplacementInfoMap = new HashMap<>();
class NodeReplacementInfo {
final Supplier<Tree<Node>> replacementSupplier;
final Function<Node, Boolean> nodeMatcher;
NodeReplacementInfo(Supplier<Tree<Node>> replacementSupplier, Function<Node, Boolean> nodeMatcher) {
this.replacementSupplier = replacementSupplier;
this.nodeMatcher = nodeMatcher;
}
boolean matches(final Node inputNode) {
return nodeMatcher.apply(inputNode);
}
}
StateMachine() {
StartNode startNode = new StartNode();
this.completeTree = new Tree<>(startNode);
}
public Tree<Node> getTree() {
return completeTree;
}
public void exit() {
// remove choicenodes and groupnodes
// if any nonterminals remain, throw error
LOG.info("\n\n* completeTree (before exit())=\n{}", TreeVisualizer.asText(completeTree));
walkSubTreeWithRoot(completeTree.root);
LOG.info("\n\n* completeTree (after exit())=\n{}", TreeVisualizer.asText(completeTree));
}
private void walkSubTreeWithRoot(final Node root) {
completeTree.children.putIfAbsent(root, emptyList());
List<Node> rootChildren = completeTree.children.get(root);
root.postProcess(completeTree, rootChildren);
List<Node> originalChildNodes = (rootChildren == null)
? emptyList()
: new ArrayList<>(rootChildren);
originalChildNodes.forEach(this::walkSubTreeWithRoot);
}
void addTransitionRule(TransitionRule transitionRule) {
// this.rules.add(transitionRule);
NodeReplacementInfo nri = new NodeReplacementInfo(
transitionRule.getRightHandSideSupplier(),
transitionRule.getNodeMatcher()
);
nodeReplacementInfoMap.put(transitionRule.leftHandSide, nri);
}
void processInput(Node inputNode, final Location location) {
// bij de state machine komen nodes binnen
// In de tree die we aan het bouwen zijn zitten nog NonTerminal nodes, waarvan er 1 aan de beurt is om vervangen te worden.
// We zoeken nu een transition rule die deze NonTerminal aan de linkerkant heeft, en
// matched met<SUF>
// zo niet; dan zitten we in een error.
// We zoeken eerst op naar welke node de huidige pointer verwijst.
// Dan kijken we welke transitierules er zijn voor dat type node.
String position = position(location);
LOG.info("\n\n* completeTree=\n{}", TreeVisualizer.asText(completeTree));
List<NonTerminalNode> nextNonTerminals = nextNonTerminals();
LOG.info("nextNonTerminals={}", nextNonTerminals);
AnyTextNode anyTextNode = new AnyTextNode();
if (nextNonTerminals.contains(anyTextNode) && inputNode instanceof TextNode) {
NodeReplacementInfo nri = new NodeReplacementInfo(
() -> new Tree<>(inputNode),
inputNode::matches
);
nodeReplacementInfoMap.put(anyTextNode, nri);
}
List<NonTerminalNode> replaceableNodes = nextNonTerminals.stream()
.filter(nodeReplacementInfoMap::containsKey)
.collect(toList());
LOG.info("inputNode={}", inputNode);
final List<Supplier<Tree<Node>>> acceptableReplacementSuppliers = replaceableNodes.stream()
.filter(t -> nodeReplacementInfoMap.containsKey(t) && nodeReplacementInfoMap.get(t).matches(inputNode))
.map(nodeReplacementInfoMap::get)
.map(nri -> nri.replacementSupplier)
.collect(toList());
LOG.info("acceptable replacements={}", acceptableReplacementSuppliers);
Node nodeToReplace = null;
Tree<Node> replacementTree = null;
List<Node> rejectedNonTerminalNodes = new ArrayList<>();
for (NonTerminalNode n : nextNonTerminals) {
Supplier<Tree<Node>> treeSupplier = nodeReplacementInfoMap.get(n).replacementSupplier;
if (acceptableReplacementSuppliers.contains(treeSupplier)) {
nodeToReplace = n;
replacementTree = treeSupplier.get();
} else {
rejectedNonTerminalNodes.add(n);
}
}
if (nodeToReplace == null) {
final List<Tree<Node>> possibleReplacements = replaceableNodes.stream()
.map(nodeReplacementInfoMap::get)
.map(nri -> nri.replacementSupplier)
.map(Supplier::get)
.collect(toList());
LOG.info("possible replacements={}", possibleReplacements);
List<Node> acceptableNodes = possibleReplacements.stream()
.map(t -> t.root)
.collect(toList());
LOG.info("acceptable nodes={}", acceptableNodes);
if (acceptableNodes.isEmpty()) {
throw new RuntimeException(format("{0}: Unexpected node: {1}", position, inputNode));
}
String expected = acceptableNodes.stream()
.map(Object::toString)
.collect(joining(" or "));
throw new RuntimeException(format("{0}: No match: expected {1}, but got {2}", position, expected, inputNode));
}
Node parent = completeTree.parents.get(nodeToReplace);
boolean parentIsXOrMoreNode = (parent instanceof ZeroOrMoreNode || parent instanceof OneOrMoreNode);
LOG.info("action: replace node ({}) with tree ({})", nodeToReplace, replacementTree);
replaceNodeWithTree(nodeToReplace, replacementTree);
if (parentIsXOrMoreNode) {
completeTree.connect(parent, nodeToReplace);
}
LOG.info("action: reject nodes {}", rejectedNonTerminalNodes);
rejectedNonTerminalNodes.forEach(n -> {
Node nodeParent = completeTree.parents.get(n);
if (nodeParent instanceof GroupNode) {
completeTree.removeSubTreeWithRootNode(nodeParent);
} else {
completeTree.removeSubTreeWithRootNode(n);
}
});
nodeReplacementInfoMap.remove(anyTextNode);
}
private String position(final Location location) {
return "@" + location.getLineNumber() + "," + (location.getColumnNumber() - 1);
}
private List<NonTerminalNode> nextNonTerminals() {
final List<NonTerminalNode> list = new ArrayList<>();
Node root = completeTree.root;
if (root instanceof NonTerminalNode) {
list.add((NonTerminalNode) root);
} else {
List<NonTerminalNode> firstNonTerminals = completeTree.getRootChildren().stream()
.map(n -> n.firstNonTerminals(completeTree))
.filter(l -> !l.isEmpty())
.findFirst()
.orElse(emptyList());
list.addAll(firstNonTerminals);
}
return list;
}
private void replaceNodeWithTree(final Node nonTerminalNode, final Tree<Node> replacementTree) {
if (nonTerminalNode == completeTree.root) {
completeTree = replacementTree;
} else {
final Tree<Node> newTree = completeTree.replaceNodeWithTree(nonTerminalNode, replacementTree);
// LOG.info("original={}", TreeVisualizer.asSExpression(completeTree, false));
// LOG.info("new ={}", TreeVisualizer.asSExpression(newTree, false));
completeTree = newTree;
}
}
} |
30152_0 | package com.hyxogen.authenticator;
import org.apache.commons.codec.digest.DigestUtils;
import org.bukkit.entity.Player;
import com.hyxogen.authenticator.challenge.ChallengeHandler;
import com.hyxogen.authenticator.user.User;
import com.hyxogen.authenticator.user.UserHandler;
import com.hyxogen.authenticator.user.UserLogin;
import com.hyxogen.authenticator.util.CryptoUtils;
import com.hyxogen.authenticator.util.Permissions;
public class AuthenticationHandler {
public static final int COOLDOWN = 30 * 60;
public final ChallengeHandler challengeHandler;
public AuthenticationHandler(ChallengeHandler challengeHandler) {
this.challengeHandler = challengeHandler;
}
public boolean needsAuthentication(Player player) {
if(!player.hasPermission(Permissions.PERM_AUTH_REQUIRED) && !player.hasPermission(Permissions.PERM_AUTH_ALLOWED))
return false;
if(!isReady(player))
return true;
long current = System.currentTimeMillis();
User user = UserHandler.getUser(player.getUniqueId());
UserLogin lastLogin = user.lastLogin;
//TODO cache result zodat dit niet iedere movement gechecked moet worden.
//We zouden ook slowness 100000 kunnen geven zodat ze niet kunnen bewegen
//Dit werkt niet voor commands en chat berichten
if(player.getAddress().getAddress().getAddress() != lastLogin.address)
return true;
if(((lastLogin.time - current) / 1000L) > COOLDOWN)
return true;
return false;
}
public boolean handleAuth(Player player, String code) {
// if(!needsAuthentication(player))
// return true;
User user = UserHandler.getUser(player.getUniqueId());
long current = System.currentTimeMillis();
if(CryptoUtils.checkTOTP(user.key, current / 1000L, 1, 6, code)) {
challengeHandler.finishAll(user);
user.lastLogin = new UserLogin(player.getAddress().getAddress().getAddress(), System.currentTimeMillis());
return true;
} else if (CryptoUtils.containsKey(DigestUtils.sha1(code), user.backupCodes)) {
challengeHandler.finishAll(user);
user.lastLogin = new UserLogin(player.getAddress().getAddress().getAddress(), System.currentTimeMillis());
return true;
} else {
return false;
}
}
public boolean isReady(Player player) {
User user = UserHandler.getUser(player.getUniqueId());
if(user.lastLogin == null)
return false;
else
return true;
}
} | Hyxogen/AuthenticatorPlugin | src/com/hyxogen/authenticator/AuthenticationHandler.java | 762 | //TODO cache result zodat dit niet iedere movement gechecked moet worden. | line_comment | nl | package com.hyxogen.authenticator;
import org.apache.commons.codec.digest.DigestUtils;
import org.bukkit.entity.Player;
import com.hyxogen.authenticator.challenge.ChallengeHandler;
import com.hyxogen.authenticator.user.User;
import com.hyxogen.authenticator.user.UserHandler;
import com.hyxogen.authenticator.user.UserLogin;
import com.hyxogen.authenticator.util.CryptoUtils;
import com.hyxogen.authenticator.util.Permissions;
public class AuthenticationHandler {
public static final int COOLDOWN = 30 * 60;
public final ChallengeHandler challengeHandler;
public AuthenticationHandler(ChallengeHandler challengeHandler) {
this.challengeHandler = challengeHandler;
}
public boolean needsAuthentication(Player player) {
if(!player.hasPermission(Permissions.PERM_AUTH_REQUIRED) && !player.hasPermission(Permissions.PERM_AUTH_ALLOWED))
return false;
if(!isReady(player))
return true;
long current = System.currentTimeMillis();
User user = UserHandler.getUser(player.getUniqueId());
UserLogin lastLogin = user.lastLogin;
//TODO cache<SUF>
//We zouden ook slowness 100000 kunnen geven zodat ze niet kunnen bewegen
//Dit werkt niet voor commands en chat berichten
if(player.getAddress().getAddress().getAddress() != lastLogin.address)
return true;
if(((lastLogin.time - current) / 1000L) > COOLDOWN)
return true;
return false;
}
public boolean handleAuth(Player player, String code) {
// if(!needsAuthentication(player))
// return true;
User user = UserHandler.getUser(player.getUniqueId());
long current = System.currentTimeMillis();
if(CryptoUtils.checkTOTP(user.key, current / 1000L, 1, 6, code)) {
challengeHandler.finishAll(user);
user.lastLogin = new UserLogin(player.getAddress().getAddress().getAddress(), System.currentTimeMillis());
return true;
} else if (CryptoUtils.containsKey(DigestUtils.sha1(code), user.backupCodes)) {
challengeHandler.finishAll(user);
user.lastLogin = new UserLogin(player.getAddress().getAddress().getAddress(), System.currentTimeMillis());
return true;
} else {
return false;
}
}
public boolean isReady(Player player) {
User user = UserHandler.getUser(player.getUniqueId());
if(user.lastLogin == null)
return false;
else
return true;
}
} |
96382_0 | package sample;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class Menu_10 extends Scene {
private Image image;
private Button weiter;
private Button zurueck;
private Label label_text;
VBox box;
int width, height;
Master master;
public Menu_10(VBox box, int width, int height){
super(box,width,height);
this.box = box;
this.width = width;
this.height = height;
this.image = new Image("figure_3.png");
ImageView iv1 = new ImageView();
iv1.setImage(image);
iv1.setFitWidth(794);
iv1.setFitHeight(397);
this.label_text = new Label("Downtown liegt 2012 zwar immer noch mit riesigem Abstand vorne, ist aber im Vergleich zu 2010 fast 100 Punkte, von 420 auf 330,\nlosgeworden. Inner Harbor hat jetzt auf Platz 5 liegend ebenfalls an Kriminalitaetsrate verloren. In den Top 10 liegen nun mehr\nBezirke bei einem Wert von unter 100 als vorher.");
this.weiter = new Button("Weiter");
this.zurueck = new Button("Zurueck");
this.master = Master.getInstance();
box.setAlignment(Pos.CENTER);
box.setPadding(new Insets(0, 50, 0, 50)); //Abstand der GUI-Komponenten zum Rand (top/right/bottom/left)
box.setSpacing(15);
box.getChildren().addAll(iv1, label_text, weiter, zurueck);
this.getStylesheets().add(getClass().getResource("/styles.css").toExternalForm()); //Zugriff auf CSS-Datei
//Registrierung von Listenern
this.weiter.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Main.stage.setScene(Master.getInstance().getMenu_11());
}
});
zurueck.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event ) {
Main.stage.setScene(Master.getInstance().getMenu_9());
}
});
}
}
| I4-Projektseminar-HHU-2016/seminar-project-phinowa | baltimore_gui/src/sample/Menu_10.java | 687 | //Abstand der GUI-Komponenten zum Rand (top/right/bottom/left) | line_comment | nl | package sample;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class Menu_10 extends Scene {
private Image image;
private Button weiter;
private Button zurueck;
private Label label_text;
VBox box;
int width, height;
Master master;
public Menu_10(VBox box, int width, int height){
super(box,width,height);
this.box = box;
this.width = width;
this.height = height;
this.image = new Image("figure_3.png");
ImageView iv1 = new ImageView();
iv1.setImage(image);
iv1.setFitWidth(794);
iv1.setFitHeight(397);
this.label_text = new Label("Downtown liegt 2012 zwar immer noch mit riesigem Abstand vorne, ist aber im Vergleich zu 2010 fast 100 Punkte, von 420 auf 330,\nlosgeworden. Inner Harbor hat jetzt auf Platz 5 liegend ebenfalls an Kriminalitaetsrate verloren. In den Top 10 liegen nun mehr\nBezirke bei einem Wert von unter 100 als vorher.");
this.weiter = new Button("Weiter");
this.zurueck = new Button("Zurueck");
this.master = Master.getInstance();
box.setAlignment(Pos.CENTER);
box.setPadding(new Insets(0, 50, 0, 50)); //Abstand der<SUF>
box.setSpacing(15);
box.getChildren().addAll(iv1, label_text, weiter, zurueck);
this.getStylesheets().add(getClass().getResource("/styles.css").toExternalForm()); //Zugriff auf CSS-Datei
//Registrierung von Listenern
this.weiter.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Main.stage.setScene(Master.getInstance().getMenu_11());
}
});
zurueck.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event ) {
Main.stage.setScene(Master.getInstance().getMenu_9());
}
});
}
}
|
11751_1 | package data;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import data.RegionType.ModelType;
import data.RegionType.RegionName;
/**
* This class has the enumerations for the various dimensions in the M-files
* that are encountered. It also has an enumeration with the region names in it.
* Note that correct behaviour depends on the order of regions in the RegionName
* enumeration! This will also not work with the aggegrated regions in files
* with 33 dimensions!
*
* @author Vortech
*
*/
public class RegionControl
{
static Logger logger = Logger.getLogger(RegionControl.class.getName());
/**
* <pre>
* In onze huidige datafiles kan je verschillende configuraties tegenkomen
* 24 24 Image regios
* 25 24 image regios+wereld
* 26 26 TIMER/FAIR regios
* 27 26 TIMER/FAIR regios+wereld
* 28 26 TIMER/FAIR regios+lege regio+wereld
* 33 26 TIMER/FAIR regios+aggregaties+wereld
*
* Dus je kan wel een bestand tegenkomen met 25 + 1 regios.
*
* De beslisboom wordt dan:
*
* IF 24,
* Report [24 regios, 0 for region 25 en 26]
* LOG: missing regions 25 and 26, LOG missing global
* If 25,
* Report [24 regios, 0 for region 25 en 26, Global(dim25 van data)]
* LOG: missing regions 25 and 26
* IF 26,
* report [26 regions]
* LOG: missing global
* IF 27
* report [26 regions, global(dim27 van data)]
* LOG: missing global
* IF 28
* report [26 regions, global(dim28 van data)]
* LOG: missing global
* IF 33
* report [26 regions, global(dim33 van data)]
* LOG: missing global
*
* Voor wereldtotaal geld ook
* IFNOT 24 of 26 THEN laatste van de array altijd het wereldtotaal.
* IF 24 of 25 THEN report N/A, LOG: missing global
* </pre>
*/
protected static void createRegions(int numRegions, HashMap<RegionName, OutputRow> ioRegions, ModelType iModel,
OutputRow iTemplateRow, String iScenario)
{
int i = 0;
for (RegionName r : RegionName.values())
{
OutputRow aRow = OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, r);
ioRegions.put(r, aRow);
i++;
if (i == numRegions)
{
break;
}
}
}
/**
* This function uses a combination of the global/noglobal/regions and
* ModelType to determine how many outputrows need to be created for the
* current mapping.
*
* @param iModel The modeltype determines the amount of regions when worldtype is not 'global'
* @param iTemplateRow The template row is used to copy some relevant information to the output row, like the variable name and unit.
* @param iScenario The scenario is also part of the result row and is already copied into place here.
* @param iType If the WorldType is set to global then only a single output row is created.
* @return A map that maps regions to output rows, it can contain 1, 24, 25, 26 or 27 entries.
* @throws Exception If the ModelType is not recognized and the WorldType is not global.
*
*/
public static Map<RegionName, OutputRow> createOutputList(ModelType iModel, OutputRow iTemplateRow,
String iScenario, WorldType iType) throws Exception
{
HashMap<RegionName, OutputRow> aResult = new HashMap<RegionName, OutputRow>();
if (iType == WorldType.global)
{
OutputRow aRow = OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World);
aResult.put(RegionName.World, aRow);
}
else
{
switch (iModel)
{
case Image:
createRegions(24, aResult, iModel, iTemplateRow, iScenario);
break;
case ImageWorld:
createRegions(24, aResult, iModel, iTemplateRow, iScenario);
aResult.put(RegionName.World,
OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World));
break;
case TimerFair:
createRegions(26, aResult, iModel, iTemplateRow, iScenario);
break;
case TimerFairWorld:
createRegions(26, aResult, iModel, iTemplateRow, iScenario);
aResult.put(RegionName.World,
OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World));
break;
case TimerFairEmptyWorld:
createRegions(26, aResult, iModel, iTemplateRow, iScenario);
aResult.put(RegionName.World,
OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World));
break;
case TimerFairAggWorld:
createRegions(33, aResult, iModel, iTemplateRow, iScenario);
break;
case SingleValue:
aResult.put(RegionName.World,
OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World));
break;
default:
throw new Exception("Model not supported");
}
}
return aResult;
}
}
| IAMconsortium/reporting_workflows | java2iamc/RegionControl.java | 1,569 | /**
* <pre>
* In onze huidige datafiles kan je verschillende configuraties tegenkomen
* 24 24 Image regios
* 25 24 image regios+wereld
* 26 26 TIMER/FAIR regios
* 27 26 TIMER/FAIR regios+wereld
* 28 26 TIMER/FAIR regios+lege regio+wereld
* 33 26 TIMER/FAIR regios+aggregaties+wereld
*
* Dus je kan wel een bestand tegenkomen met 25 + 1 regios.
*
* De beslisboom wordt dan:
*
* IF 24,
* Report [24 regios, 0 for region 25 en 26]
* LOG: missing regions 25 and 26, LOG missing global
* If 25,
* Report [24 regios, 0 for region 25 en 26, Global(dim25 van data)]
* LOG: missing regions 25 and 26
* IF 26,
* report [26 regions]
* LOG: missing global
* IF 27
* report [26 regions, global(dim27 van data)]
* LOG: missing global
* IF 28
* report [26 regions, global(dim28 van data)]
* LOG: missing global
* IF 33
* report [26 regions, global(dim33 van data)]
* LOG: missing global
*
* Voor wereldtotaal geld ook
* IFNOT 24 of 26 THEN laatste van de array altijd het wereldtotaal.
* IF 24 of 25 THEN report N/A, LOG: missing global
* </pre>
*/ | block_comment | nl | package data;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import data.RegionType.ModelType;
import data.RegionType.RegionName;
/**
* This class has the enumerations for the various dimensions in the M-files
* that are encountered. It also has an enumeration with the region names in it.
* Note that correct behaviour depends on the order of regions in the RegionName
* enumeration! This will also not work with the aggegrated regions in files
* with 33 dimensions!
*
* @author Vortech
*
*/
public class RegionControl
{
static Logger logger = Logger.getLogger(RegionControl.class.getName());
/**
* <pre>
<SUF>*/
protected static void createRegions(int numRegions, HashMap<RegionName, OutputRow> ioRegions, ModelType iModel,
OutputRow iTemplateRow, String iScenario)
{
int i = 0;
for (RegionName r : RegionName.values())
{
OutputRow aRow = OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, r);
ioRegions.put(r, aRow);
i++;
if (i == numRegions)
{
break;
}
}
}
/**
* This function uses a combination of the global/noglobal/regions and
* ModelType to determine how many outputrows need to be created for the
* current mapping.
*
* @param iModel The modeltype determines the amount of regions when worldtype is not 'global'
* @param iTemplateRow The template row is used to copy some relevant information to the output row, like the variable name and unit.
* @param iScenario The scenario is also part of the result row and is already copied into place here.
* @param iType If the WorldType is set to global then only a single output row is created.
* @return A map that maps regions to output rows, it can contain 1, 24, 25, 26 or 27 entries.
* @throws Exception If the ModelType is not recognized and the WorldType is not global.
*
*/
public static Map<RegionName, OutputRow> createOutputList(ModelType iModel, OutputRow iTemplateRow,
String iScenario, WorldType iType) throws Exception
{
HashMap<RegionName, OutputRow> aResult = new HashMap<RegionName, OutputRow>();
if (iType == WorldType.global)
{
OutputRow aRow = OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World);
aResult.put(RegionName.World, aRow);
}
else
{
switch (iModel)
{
case Image:
createRegions(24, aResult, iModel, iTemplateRow, iScenario);
break;
case ImageWorld:
createRegions(24, aResult, iModel, iTemplateRow, iScenario);
aResult.put(RegionName.World,
OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World));
break;
case TimerFair:
createRegions(26, aResult, iModel, iTemplateRow, iScenario);
break;
case TimerFairWorld:
createRegions(26, aResult, iModel, iTemplateRow, iScenario);
aResult.put(RegionName.World,
OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World));
break;
case TimerFairEmptyWorld:
createRegions(26, aResult, iModel, iTemplateRow, iScenario);
aResult.put(RegionName.World,
OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World));
break;
case TimerFairAggWorld:
createRegions(33, aResult, iModel, iTemplateRow, iScenario);
break;
case SingleValue:
aResult.put(RegionName.World,
OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World));
break;
default:
throw new Exception("Model not supported");
}
}
return aResult;
}
}
|
97555_68 | package idlab.examples.generators;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
@WebSocket(maxTextMessageSize = 64 * 1024)
public class SimpleEventSocket {
private final CountDownLatch closeLatch;
@SuppressWarnings("unused")
private Session session;
public SimpleEventSocket() {
this.closeLatch = new CountDownLatch(1);
}
public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException {
return this.closeLatch.await(duration, unit);
}
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
}
@OnWebSocketConnect
public void onConnect(Session session) {
try {
System.out.println("trying to send:");
for (int i = 0; i < 10; i++) {
session.getRemote().sendString(EVENT);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@OnWebSocketMessage
public void onMessage(String msg) {
System.out.println("received");
}
@OnWebSocketError
public void onError(Throwable cause) {
System.out.print("WebSocket Error: ");
cause.printStackTrace(System.out);
}
private static String ONT_EVENT = "<?xml version=\"1.0\"?>\n"
+ "<rdf:RDF xmlns=\"http://IBCNServices.github.io/homelabPlus.owl#\"\n"
+ " xml:base=\"http://IBCNServices.github.io/homelabPlus.owl\"\n"
+ " xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n"
+ " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"
+ " xmlns:ssn=\"http://IBCNServices.github.io/Accio-Ontology/ontologies/ssn#\"\n"
+ " xmlns:xml=\"http://www.w3.org/XML/1998/namespace\"\n"
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n"
+ " xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n"
+ " <owl:Ontology rdf:about=\"http://IBCNServices.github.io/homelabPlus2.owl\">\n"
+ " <owl:imports rdf:resource=\"http://IBCNServices.github.io/homelabPlus.owl\"/>\n"
+ " </owl:Ontology>\n" + " \n" + "\n" + "\n" + " <!-- \n"
+ " ///////////////////////////////////////////////////////////////////////////////////////\n"
+ " //\n" + " // Individuals\n" + " //\n"
+ " ///////////////////////////////////////////////////////////////////////////////////////\n"
+ " -->\n" + "\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelab.owl#lightIntensity -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelab.owl#lightIntensity\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/SSNiot#LightIntensity\"/>\n"
+ " </owl:NamedIndividual>\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelab.owl#motionIntensity -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelab.owl#motionIntensity\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/SSNiot#Motion\"/>\n"
+ " </owl:NamedIndividual>\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelab.owl#soundIntensity -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelab.owl#soundIntensity\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/SSNiot#Sound\"/>\n"
+ " </owl:NamedIndividual>\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelabPlus.owl#obs -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelabPlus.owl#obs\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/ontologies/ssn#Observation\"/>\n"
+ " <ssn:observedProperty rdf:resource=\"http://IBCNServices.github.io/homelab.owl#lightIntensity\"/>\n"
+ " </owl:NamedIndividual>\n" + "</rdf:RDF>";
private static String EVENT = "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n"
+ "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n"
+ "@prefix td: <http://purl.org/td/transportdisruption#> .\n"
+ "@prefix dct: <http://purl.org/dc/terms/> .\n" + "@prefix gtfs: <http://vocab.gtfs.org/terms#> .\n"
+ "@prefix ex: <http://example.com/> .\n" + "\n" + "_:b12_0 rdf:type td:PublicTransportDiversion ;\n"
+ " dct:description \"Door wegenwerken rijdt lijn 6, de rit van 10.50 u. uit Oostende Station & de rit van 11.08 uur uit Raversijde Middenlaan niet\"@nl ;\n"
+ " td:factor td:RoadWorks ;\n"
+ " ex:hasHalte <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501331>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501375>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501372>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501348>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501290>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/510003>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501300>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506290>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506286>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501326>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501262>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501307>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506291>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506307>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506262>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506372>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501345>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501286>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506337>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506289>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506330>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506375>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/510004>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506326>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501373>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506300>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501289>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506345>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506374>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506348>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501291>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501337> ;\n"
+ " ex:hasBusLine <https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/HEEN>, <https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/TERUG> .\n"
+ "\n" + "_:b12_1 rdf:type td:PublicTransportDiversion ;\n"
+ " dct:description \"Door weersomstandigheden is de dienstregeling van alle streeklijnen ernstig verstoord * Vermoedelijk hinder 14:00u tot 19.00u\"@nl ;\n"
+ " td:factor td:BadWeather ;\n"
+ " ex:hasHalte <https://api.delijn.be/DLKernOpenData/v1/haltes/5/109744> .\n" + "\n"
+ "_:b12_2 rdf:type td:PublicTransportDiversion ;\n"
+ " dct:description \"Door weersomstandigheden is de dienstregeling van alle stadslijnen ernstig verstoord. vermoedelijke hinder tussen 12 en 20 uur\"@nl ;\n"
+ " td:factor td:BadWeather ;\n"
+ " ex:hasHalte <https://api.delijn.be/DLKernOpenData/v1/haltes/5/109744> .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501331> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501331\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501331\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501375> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501375\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501375\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501372> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501372\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501372\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501348> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501348\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501348\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501290> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501290\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501290\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/510003> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"510003\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/510003\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501300> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501300\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501300\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506290> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506290\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506290\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506286> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506286\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506286\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501326> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501326\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501326\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501262> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501262\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501262\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501307> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501307\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501307\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506291> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506291\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506291\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506307> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506307\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506307\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506262> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506262\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506262\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506372> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506372\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506372\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501345> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501345\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501345\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501286> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501286\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501286\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506337> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506337\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506337\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506289> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506289\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506289\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506330> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506330\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506330\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506375> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506375\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506375\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/510004> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"510004\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/510004\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506326> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506326\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506326\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501373> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501373\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501373\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506300> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506300\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506300\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501289> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501289\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501289\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506345> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506345\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506345\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506374> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506374\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506374\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506348> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506348\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506348\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501291> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501291\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501291\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501337> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501337\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501337\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/109744> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"109744\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/109744\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/HEEN> rdf:type gtfs:Route ;\n"
+ " dct:description \"Oostende Station-Luchthaven Raversijde\"@nl .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/TERUG> rdf:type gtfs:Route ;\n"
+ " dct:description \"Luchthaven via Raversijde-Oostende Station\"@nl .\n" + "\n" + "";
} | IBCNServices/StreamingMASSIF | src/main/java/idlab/examples/generators/SimpleEventSocket.java | 6,580 | //www.delijn.be/nl/haltes/halte/506345\" .\n" + "\n" | line_comment | nl | package idlab.examples.generators;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
@WebSocket(maxTextMessageSize = 64 * 1024)
public class SimpleEventSocket {
private final CountDownLatch closeLatch;
@SuppressWarnings("unused")
private Session session;
public SimpleEventSocket() {
this.closeLatch = new CountDownLatch(1);
}
public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException {
return this.closeLatch.await(duration, unit);
}
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
}
@OnWebSocketConnect
public void onConnect(Session session) {
try {
System.out.println("trying to send:");
for (int i = 0; i < 10; i++) {
session.getRemote().sendString(EVENT);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@OnWebSocketMessage
public void onMessage(String msg) {
System.out.println("received");
}
@OnWebSocketError
public void onError(Throwable cause) {
System.out.print("WebSocket Error: ");
cause.printStackTrace(System.out);
}
private static String ONT_EVENT = "<?xml version=\"1.0\"?>\n"
+ "<rdf:RDF xmlns=\"http://IBCNServices.github.io/homelabPlus.owl#\"\n"
+ " xml:base=\"http://IBCNServices.github.io/homelabPlus.owl\"\n"
+ " xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n"
+ " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"
+ " xmlns:ssn=\"http://IBCNServices.github.io/Accio-Ontology/ontologies/ssn#\"\n"
+ " xmlns:xml=\"http://www.w3.org/XML/1998/namespace\"\n"
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n"
+ " xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n"
+ " <owl:Ontology rdf:about=\"http://IBCNServices.github.io/homelabPlus2.owl\">\n"
+ " <owl:imports rdf:resource=\"http://IBCNServices.github.io/homelabPlus.owl\"/>\n"
+ " </owl:Ontology>\n" + " \n" + "\n" + "\n" + " <!-- \n"
+ " ///////////////////////////////////////////////////////////////////////////////////////\n"
+ " //\n" + " // Individuals\n" + " //\n"
+ " ///////////////////////////////////////////////////////////////////////////////////////\n"
+ " -->\n" + "\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelab.owl#lightIntensity -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelab.owl#lightIntensity\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/SSNiot#LightIntensity\"/>\n"
+ " </owl:NamedIndividual>\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelab.owl#motionIntensity -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelab.owl#motionIntensity\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/SSNiot#Motion\"/>\n"
+ " </owl:NamedIndividual>\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelab.owl#soundIntensity -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelab.owl#soundIntensity\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/SSNiot#Sound\"/>\n"
+ " </owl:NamedIndividual>\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelabPlus.owl#obs -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelabPlus.owl#obs\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/ontologies/ssn#Observation\"/>\n"
+ " <ssn:observedProperty rdf:resource=\"http://IBCNServices.github.io/homelab.owl#lightIntensity\"/>\n"
+ " </owl:NamedIndividual>\n" + "</rdf:RDF>";
private static String EVENT = "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n"
+ "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n"
+ "@prefix td: <http://purl.org/td/transportdisruption#> .\n"
+ "@prefix dct: <http://purl.org/dc/terms/> .\n" + "@prefix gtfs: <http://vocab.gtfs.org/terms#> .\n"
+ "@prefix ex: <http://example.com/> .\n" + "\n" + "_:b12_0 rdf:type td:PublicTransportDiversion ;\n"
+ " dct:description \"Door wegenwerken rijdt lijn 6, de rit van 10.50 u. uit Oostende Station & de rit van 11.08 uur uit Raversijde Middenlaan niet\"@nl ;\n"
+ " td:factor td:RoadWorks ;\n"
+ " ex:hasHalte <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501331>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501375>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501372>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501348>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501290>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/510003>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501300>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506290>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506286>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501326>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501262>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501307>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506291>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506307>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506262>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506372>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501345>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501286>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506337>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506289>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506330>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506375>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/510004>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506326>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501373>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506300>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501289>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506345>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506374>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506348>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501291>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501337> ;\n"
+ " ex:hasBusLine <https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/HEEN>, <https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/TERUG> .\n"
+ "\n" + "_:b12_1 rdf:type td:PublicTransportDiversion ;\n"
+ " dct:description \"Door weersomstandigheden is de dienstregeling van alle streeklijnen ernstig verstoord * Vermoedelijk hinder 14:00u tot 19.00u\"@nl ;\n"
+ " td:factor td:BadWeather ;\n"
+ " ex:hasHalte <https://api.delijn.be/DLKernOpenData/v1/haltes/5/109744> .\n" + "\n"
+ "_:b12_2 rdf:type td:PublicTransportDiversion ;\n"
+ " dct:description \"Door weersomstandigheden is de dienstregeling van alle stadslijnen ernstig verstoord. vermoedelijke hinder tussen 12 en 20 uur\"@nl ;\n"
+ " td:factor td:BadWeather ;\n"
+ " ex:hasHalte <https://api.delijn.be/DLKernOpenData/v1/haltes/5/109744> .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501331> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501331\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501331\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501375> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501375\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501375\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501372> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501372\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501372\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501348> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501348\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501348\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501290> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501290\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501290\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/510003> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"510003\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/510003\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501300> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501300\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501300\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506290> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506290\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506290\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506286> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506286\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506286\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501326> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501326\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501326\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501262> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501262\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501262\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501307> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501307\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501307\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506291> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506291\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506291\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506307> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506307\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506307\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506262> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506262\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506262\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506372> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506372\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506372\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501345> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501345\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501345\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501286> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501286\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501286\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506337> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506337\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506337\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506289> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506289\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506289\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506330> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506330\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506330\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506375> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506375\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506375\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/510004> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"510004\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/510004\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506326> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506326\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506326\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501373> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501373\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501373\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506300> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506300\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506300\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501289> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501289\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501289\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506345> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506345\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506345\" .\n"<SUF>
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506374> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506374\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506374\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506348> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506348\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506348\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501291> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501291\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501291\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501337> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501337\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501337\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/109744> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"109744\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/109744\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/HEEN> rdf:type gtfs:Route ;\n"
+ " dct:description \"Oostende Station-Luchthaven Raversijde\"@nl .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/TERUG> rdf:type gtfs:Route ;\n"
+ " dct:description \"Luchthaven via Raversijde-Oostende Station\"@nl .\n" + "\n" + "";
} |
10059_0 | package org.ibs.application.service;
import lombok.AllArgsConstructor;
import org.ibs.application.ICategoryService;
import org.ibs.application.dto.CategoryDTO;
import org.ibs.data.CategoryRepository;
import org.ibs.domain.Category;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
// tests nog niet gwschreven omdat ik niet zeker weet of we ook zo de try catch
// willen uitvoeren.
@Service
@Transactional
@AllArgsConstructor
public class CategoryService implements ICategoryService {
private final CategoryRepository categoryRepository;
@Override
public Category getById(long id) throws Exception {
try {
return categoryRepository.getById(id);
} catch (Exception e) {
// misschien een LOG library zoals log4j
throw new Exception("Category could not be found due to an error", e);
}
}
@Override
public List<Category> getAll() throws Exception {
try {
return categoryRepository.findAll();
} catch (Exception e) {
throw new Exception("Categories could not be found due to an error", e);
}
}
@Override
public Category persistCategory(CategoryDTO categoryDTO) throws Exception {
try {
// categoryDTO to category by builder
// categoryRepository.save(category)
return null;
} catch (Exception e) {
// misschien een Log library zoals log4j
throw new Exception("Category was not persisted due to an error", e);
}
}
@Override
public boolean deleteCategory(long id) throws Exception {
try {
categoryRepository.delete(categoryRepository.getById(id));
return true;
} catch (Exception e) {
throw new Exception("Category could not be deleted due to an error", e);
}
}
}
| IBSInnovation/IBS-Fysiotherapy | src/main/java/org/ibs/application/service/CategoryService.java | 476 | // tests nog niet gwschreven omdat ik niet zeker weet of we ook zo de try catch | line_comment | nl | package org.ibs.application.service;
import lombok.AllArgsConstructor;
import org.ibs.application.ICategoryService;
import org.ibs.application.dto.CategoryDTO;
import org.ibs.data.CategoryRepository;
import org.ibs.domain.Category;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
// tests nog<SUF>
// willen uitvoeren.
@Service
@Transactional
@AllArgsConstructor
public class CategoryService implements ICategoryService {
private final CategoryRepository categoryRepository;
@Override
public Category getById(long id) throws Exception {
try {
return categoryRepository.getById(id);
} catch (Exception e) {
// misschien een LOG library zoals log4j
throw new Exception("Category could not be found due to an error", e);
}
}
@Override
public List<Category> getAll() throws Exception {
try {
return categoryRepository.findAll();
} catch (Exception e) {
throw new Exception("Categories could not be found due to an error", e);
}
}
@Override
public Category persistCategory(CategoryDTO categoryDTO) throws Exception {
try {
// categoryDTO to category by builder
// categoryRepository.save(category)
return null;
} catch (Exception e) {
// misschien een Log library zoals log4j
throw new Exception("Category was not persisted due to an error", e);
}
}
@Override
public boolean deleteCategory(long id) throws Exception {
try {
categoryRepository.delete(categoryRepository.getById(id));
return true;
} catch (Exception e) {
throw new Exception("Category could not be deleted due to an error", e);
}
}
}
|
7926_2 | /**
* Copyright 2017 Institute of Computing Technology, Chinese Academy of Sciences.
* Licensed under the terms of the Apache 2.0 license.
* Please see LICENSE file in the project root for terms
*/
package eml.studio.client.ui.panel;
import eml.studio.client.util.Constants;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.*;
/**
* Add directory panel
*/
public class CateAddPanel extends PopupPanel {
private String type;
private Label title = new Label("Hint");
private Label close = new Label();
private Label nameLabel = new Label(Constants.adminUIMsg.cateName());
private TextBox nameBox = new TextBox();
private Label nameErrorLabel = new Label("");
private Label fathLabel = new Label(Constants.adminUIMsg.catePath());
private TextBox fathBox = new TextBox();
private Label fathErrorLabel = new Label("");
private Button confirmBtn = new Button(Constants.adminUIMsg.confirm());
private Button cancelBtn = new Button(Constants.adminUIMsg.cancel());
private VerticalPanel vPanel = new VerticalPanel();
private HorizontalPanel mask = new HorizontalPanel();
private VerticalPanel root = new VerticalPanel();
public CateAddPanel() {
bind();
HorizontalPanel alertHeader = new HorizontalPanel();
HorizontalPanel alertButton = new HorizontalPanel();
VerticalPanel alertContent = new VerticalPanel();
title.setStyleName("cateAddBoxTitle");
close.setStyleName("alertClose");
alertHeader.add(title);
alertHeader.add(close);
alertHeader.addStyleName("alertTitleBG");
HorizontalPanel namePanel = new HorizontalPanel();
HorizontalPanel fathPanel = new HorizontalPanel();
nameLabel.getElement().getStyle().setMargin(9, Unit.PX);
nameBox.removeStyleName("gwt-TextBox");
nameBox.addStyleName("admin-cate-add-input");
nameErrorLabel.addStyleName("account-error");
namePanel.add(nameLabel);
namePanel.add(nameBox);
namePanel.add(nameErrorLabel);
fathLabel.getElement().getStyle().setMargin(12, Unit.PX);
fathBox.removeStyleName("gwt-TextBox");
fathBox.addStyleName("admin-cate-add-input");
fathErrorLabel.addStyleName("account-error");
fathPanel.add(fathLabel);
fathPanel.add(fathBox);
fathPanel.add(fathErrorLabel);
namePanel.getElement().getStyle().setMarginTop(20, Unit.PX);
namePanel.getElement().getStyle().setMarginBottom(20, Unit.PX);
fathPanel.getElement().getStyle().setMarginTop(20, Unit.PX);
fathPanel.getElement().getStyle().setMarginBottom(20, Unit.PX);
alertContent.add(namePanel);
alertContent.add(fathPanel);
alertContent.addStyleName("margin_left_17");
confirmBtn.removeStyleName("gwt-Button");
cancelBtn.removeStyleName("gwt-Button");
cancelBtn.getElement().getStyle().setMarginLeft(105, Unit.PX);
alertButton.add(confirmBtn);
alertButton.add(cancelBtn);
alertButton.addStyleName("alertButton2");
vPanel.add(alertHeader);
vPanel.add(alertContent);
vPanel.add(alertButton);
vPanel.addStyleName("alertBox");
mask.addStyleName("alertBack");
root.add(mask);
root.add(vPanel);
this.add(root);
this.removeStyleName("gwt-PopupPanel");
}
/**
* Event binding
*/
public void bind(){
//close
close.addClickHandler(new ClickHandler(){
@Override
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub
CateAddPanel.this.nameBox.setValue("");
CateAddPanel.this.fathBox.setValue("");
CateAddPanel.this.nameErrorLabel.setText("");
CateAddPanel.this.fathErrorLabel.setText("");
CateAddPanel.this.hide();
}
});
//cancel
cancelBtn.addClickHandler(new ClickHandler(){
@Override
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub
CateAddPanel.this.nameBox.setValue("");
CateAddPanel.this.fathBox.setValue("");
CateAddPanel.this.nameErrorLabel.setText("");
CateAddPanel.this.fathErrorLabel.setText("");
CateAddPanel.this.hide();
}
});
}
@Override
public void setTitle(String msg){
title.setText(msg);
}
public String getType(){
return type;
}
public VerticalPanel getPanel(){
return vPanel;
}
public TextBox getNameBox(){
return nameBox;
}
public Label getNameErrorLabel(){
return nameErrorLabel;
}
public TextBox getFatherBox(){
return fathBox;
}
public Label getFathErrorLabel(){
return fathErrorLabel;
}
public Button getCancelBtn(){
return cancelBtn;
}
public Button getConfirmBtn(){
return confirmBtn;
}
public Label getClose(){
return close;
}
}
| ICT-BDA/EasyML | src/main/java/eml/studio/client/ui/panel/CateAddPanel.java | 1,504 | /**
* Event binding
*/ | block_comment | nl | /**
* Copyright 2017 Institute of Computing Technology, Chinese Academy of Sciences.
* Licensed under the terms of the Apache 2.0 license.
* Please see LICENSE file in the project root for terms
*/
package eml.studio.client.ui.panel;
import eml.studio.client.util.Constants;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.*;
/**
* Add directory panel
*/
public class CateAddPanel extends PopupPanel {
private String type;
private Label title = new Label("Hint");
private Label close = new Label();
private Label nameLabel = new Label(Constants.adminUIMsg.cateName());
private TextBox nameBox = new TextBox();
private Label nameErrorLabel = new Label("");
private Label fathLabel = new Label(Constants.adminUIMsg.catePath());
private TextBox fathBox = new TextBox();
private Label fathErrorLabel = new Label("");
private Button confirmBtn = new Button(Constants.adminUIMsg.confirm());
private Button cancelBtn = new Button(Constants.adminUIMsg.cancel());
private VerticalPanel vPanel = new VerticalPanel();
private HorizontalPanel mask = new HorizontalPanel();
private VerticalPanel root = new VerticalPanel();
public CateAddPanel() {
bind();
HorizontalPanel alertHeader = new HorizontalPanel();
HorizontalPanel alertButton = new HorizontalPanel();
VerticalPanel alertContent = new VerticalPanel();
title.setStyleName("cateAddBoxTitle");
close.setStyleName("alertClose");
alertHeader.add(title);
alertHeader.add(close);
alertHeader.addStyleName("alertTitleBG");
HorizontalPanel namePanel = new HorizontalPanel();
HorizontalPanel fathPanel = new HorizontalPanel();
nameLabel.getElement().getStyle().setMargin(9, Unit.PX);
nameBox.removeStyleName("gwt-TextBox");
nameBox.addStyleName("admin-cate-add-input");
nameErrorLabel.addStyleName("account-error");
namePanel.add(nameLabel);
namePanel.add(nameBox);
namePanel.add(nameErrorLabel);
fathLabel.getElement().getStyle().setMargin(12, Unit.PX);
fathBox.removeStyleName("gwt-TextBox");
fathBox.addStyleName("admin-cate-add-input");
fathErrorLabel.addStyleName("account-error");
fathPanel.add(fathLabel);
fathPanel.add(fathBox);
fathPanel.add(fathErrorLabel);
namePanel.getElement().getStyle().setMarginTop(20, Unit.PX);
namePanel.getElement().getStyle().setMarginBottom(20, Unit.PX);
fathPanel.getElement().getStyle().setMarginTop(20, Unit.PX);
fathPanel.getElement().getStyle().setMarginBottom(20, Unit.PX);
alertContent.add(namePanel);
alertContent.add(fathPanel);
alertContent.addStyleName("margin_left_17");
confirmBtn.removeStyleName("gwt-Button");
cancelBtn.removeStyleName("gwt-Button");
cancelBtn.getElement().getStyle().setMarginLeft(105, Unit.PX);
alertButton.add(confirmBtn);
alertButton.add(cancelBtn);
alertButton.addStyleName("alertButton2");
vPanel.add(alertHeader);
vPanel.add(alertContent);
vPanel.add(alertButton);
vPanel.addStyleName("alertBox");
mask.addStyleName("alertBack");
root.add(mask);
root.add(vPanel);
this.add(root);
this.removeStyleName("gwt-PopupPanel");
}
/**
* Event binding
<SUF>*/
public void bind(){
//close
close.addClickHandler(new ClickHandler(){
@Override
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub
CateAddPanel.this.nameBox.setValue("");
CateAddPanel.this.fathBox.setValue("");
CateAddPanel.this.nameErrorLabel.setText("");
CateAddPanel.this.fathErrorLabel.setText("");
CateAddPanel.this.hide();
}
});
//cancel
cancelBtn.addClickHandler(new ClickHandler(){
@Override
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub
CateAddPanel.this.nameBox.setValue("");
CateAddPanel.this.fathBox.setValue("");
CateAddPanel.this.nameErrorLabel.setText("");
CateAddPanel.this.fathErrorLabel.setText("");
CateAddPanel.this.hide();
}
});
}
@Override
public void setTitle(String msg){
title.setText(msg);
}
public String getType(){
return type;
}
public VerticalPanel getPanel(){
return vPanel;
}
public TextBox getNameBox(){
return nameBox;
}
public Label getNameErrorLabel(){
return nameErrorLabel;
}
public TextBox getFatherBox(){
return fathBox;
}
public Label getFathErrorLabel(){
return fathErrorLabel;
}
public Button getCancelBtn(){
return cancelBtn;
}
public Button getConfirmBtn(){
return confirmBtn;
}
public Label getClose(){
return close;
}
}
|
120393_5 | package eidolons.system.text;
import main.content.OBJ_TYPE;
import main.content.enums.entity.HeroEnums;
import main.content.enums.entity.HeroEnums.SUBRACE;
import main.content.enums.entity.HeroEnums.RACE;
import main.content.values.properties.G_PROPS;
import main.data.DataManager;
import main.entity.DataModel;
import main.entity.Entity;
import main.entity.EntityCheckMaster;
import main.entity.type.ObjType;
import main.swing.generic.components.editors.lists.ListChooser;
import main.swing.generic.components.editors.lists.ListChooser.SELECTION_MODE;
import main.system.auxiliary.*;
import main.system.auxiliary.data.FileManager;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class NameMaster {
/*
Feren Dauril
Edrail Neref Raurim
Sileeve
Eerive
Yvrieec
Uelveec
Visphy
Loie'Tar
Tor'Loiel
Ylm'Theron
Lith'Ygol
Orleeve
Enreil Delian
Melin Aduvir
Venroim Tharguin
Gideon Antar
Abaddon Gleth
David Mendel
Genvil Dalion
Ervilon Xolmir
Domil Anoch
Izrin Minchev
// Eledari
// Sel'Mauri
// Ald'Vemdor
// Irf'Aenor
// Erd'Mingul
// Saer'Vaenfel
// Huir'Lagmoth
// Raeph'Haduin
// Thae'Vaol
*/
public static final String NO_NAME = "No name";
public static final String VERSION = " v";
public static final String ravenNames = "Draco Dorian Jack Pike Quentin Rick Dilrin Denrix Melrix Lidvis Emrin Lervin Carpel Malkin Severard Rinfer Garsiv Virxis Fidvin Mirvin Delvar "
+ "Delven Idlem Vuron Pirkust Esvin Kuigin Nirgus Islog Sarnas Genlyn Avaldur Vatiar Ectis Osmer Pealet Lotard Nertum Kesrin";
public static final String ravenNamesFemale = "Jenisse Sheilin Imlia Lilian Mesbeth Viola Biantha Gioress Sabina Enesse Norette Vosane Fiona";
public static final String ravenNamesSecond = "Dilrin Norux Denrix Melrix Girsis Lidvis Emrin Lervin Carpel Malkin Rinfer Garsiv Virxis Fidvin Mirvin Kaurim Delnur Delvar Delnesse"
+ " Kurifar Nirligus Exerion Lethmer Raegsul Erming Loerg Gidlau Volmevin Molfran Korbulo";
public static final String wolfNames = "Dortan Gauren Girmut Azulf Sivlid Vardel Dersen Alvid Galvir Gimnur Thonril Tholmir Lirmog Gleifnir Wedrhod Gwynreth Rhaglef Cestil Genlun Golrar "
+ "Gargi Vartu Valsteg Higstam Conrik "
+ "Fogmed Tilbruk Brukthel Ogsit Huntok Arfost Hadden Utmer Isfior Ginwad Tair Sefiad Skalg";
public static final String wolfNamesFemale = "Irsida Emrida Ithglen Fidra Lagatha Aituli Gelnifer Igrith Gwynedil Imdaleg Storbia Rhagla";
public static final String wolfNamesSecond = "Valherim Dirhelor Sivlid Visrith Pauren Edlen Igles Moltav Delgrav Dersen Gimnur Mirthud Thonril Tholmir Glerson Dimroth Dortan Gauren Girmut Dirhold Therving Kinrikkl Hamhelik Segervid Tilsinod Vilkannet";
public static final String eagleNames = "Erithec Benihath Elmareth Delfenor Martis Augled Raurim Mauglir Ulraim Geldior Imgisar Inrif Farnil Iffdor Imliad Anbinath Irsenon Kolneru Elsier "
+ "Nethlur Orodrim Irddel Celthin Aemris Urfediv Irlath Laruon Kineil Iseard";
public static final String eagleNamesFemale = "Elsira Asmin Ervina Tulani Aruna Eriana Silda Olvira Nithlara Istra Eilida Niumi Elbira Elnifer Ulrina Silvia ";
public static final String eagleNamesSecond = "Erithec Benihath Elmareth Delfenor Raurim Caerphis Chimrefel Mauglir Lefredol Ulraim Geldior Imgisar Anurphis Menloris Medlorim Eraglen Erniath Athrem";
public static final String kingNames = "John Adam Alnoir Erles Gwahir Bendaf Galdion Gorthiod Rolwain Limrod Sidlur Aupheir Nathlim Demeril Genthel Aldain Brestir Irgvil "
+ "Giflas Ester Menres Eumol Rolwim Adelwyn Rimlod Arnelion Lorwim Wolrim"
+ " Cenhed Adeilar Denuid Gwynros ";
public static final String kingNamesFemale = "Menfa Juthira "
+ "Elari Thinea Eonri Blauri Athna Lydia" + " Aithlin Mirona Nimore Seina Feluna Feina "
+ "Ansila Thide Haitha Lia Amaltha Theola";
public static final String kingNamesSecond = "Bendaf Gorthiod Rolwain Limrod Irsilod Kalroin Ultath Kinter Elsen Drolem Galniod Irtheniod Adlarim Ginlung Arthenon Vaktiar Pirstag Aedainur Emrianor Naellid Esteniad Althair Murwaith Giothrim Maelsiur Firdlain Estariath Lundaine Merphim Barthair Aensulat Phermithas Leinleith Mardalu Gidseol Soamdath Diplard Evengil Fobbled Kaergraf Delnian Nelaigo";
public static final String griffNames = "Jowaine Jurgon Severon Rutheos Raomir Raemir Sinarc Jemid Juraine Onsard Godric Theon Crigol Dagros Simdal "
+ "Gaeglin Gedaeth Belved Nevid Gasglid Ibrin Ordeb Baleg Hadrod "
+ "Haddel Kurdeag Deirid Daereir Thainith Thaemil Tilead Aldvan Cearat Daecar Adimach Angfuil "
+ "Sestian Rodviol Feilod Gaerad";
public static final String griffNamesFemale = "Jenfis Remira Sinara Jemira Arfida Sornila Sanura Amrin Olmra Eola";
public static final String griffNamesSecond = "Edexis Bailen Imsidor Galdion Feincer Rebfil Atephari Jowaine Godleon Rutheos Raomir Ramrid Raemird Sinarc Gotua Arverno Nolvio Rhufeon Juraine ";
public static final String ulduinNames = "Limrog Olavus Grinresar Smidlar Burtug Fargrad "
+ "Grildur Ormund Stryvolur Riddrog "
+ "Trondurin Tormethil Scadmur Miseud Otsiom Relgon Uthlediad Algorn "
+ "Strolar Urtfran Adeladur Anselud";
public static final String ulduinNamesFemale = "Misanna Relga Uthlena Selda Somlesta Valdelen ";
public static final String ulduinNamesSecond = "";
public static final String elvenNames = "Avelar Haevril Sethelon Eniloth Goriad Nirolim Valrith Entelion Raelur Egvilas Eithas Anelur Adrathas Ginleth Diular Ulsair Doluith Daenar Faoir Inriuth Sauir Faoim Maedlon Naoin Nilthuin Nimlod Gondulim Deriath Vendradir Belvenon Surmagil "
+ "EithNaglur MaerhValar Quedlin Sianor Delgalad Orthaelion Teregroth "
+ "Dulvin BaelarAnuir Olvah Mithlur Gilthar Maedroth Elidor Galdir Echfaelion Dorlumin "
+ "Daurim LirthDelion Bellah Salfeon Ingean Milvor Enudeg Daenlehir Atelaeth";
public static final String elvenNamesFemale = "Belia Nelia Anfina Insila Mivlia Iola Aylin Siora Quelthia Quesia Lumina Dirna Tairi Luwien Adulai Ilureth ";
public static final String elvenNamesSecond = "Ilarfis Arveliad Haevril Sedvelon Caelnorith Eniloth AtalunRee Tulanir Goriad Nimrovil Valrith Uthuniel BlithSaeg Faoi";
public static final String dwarvenNames = "Drogon Rhughad Ligrod Gefnod Nogvir Naugrith Thodrim Balrim Droln Drofnod Noru Bosnir Dusmar Golgar Uxi Dunbor Mugrol "
+ "Talsen Donkel Ingins Desger Tugindir "
+ "Ustuk Hambrud Sageli Eprug Norkol Ungron Ysgrithur Ynvigr Gachtarg Drolif Tagair "
+ "Skeltar Braeham Mangif Maersenif Kenthad Deilar Lerthaein Ulmith Utvald Ogvart Aproret Jargsil "
+ "Utanar Ulkmar Baglarod Haglir Tilfram Birenor Tharagur";
public static final String dwarvenNamesFemale = "";
public static final String dwarvenNamesSecond = "Tirledag Semerog Rhughad Brifich Faurhir Ligrod Gefnod Nogvir Naugrith Thodrim Gausod Grenchest Bansiad Forgneth Acurag Olpust Lurraldi Baketar Batasur Viragost Vuthlin Trovarin Kogel";
public static final String easterlingNames = "";
public static final String easterlingNamesFemale = "";
public static final String easterlingNamesSecond = "";
public static final String demonNames = "Irxithor ";
public static final String demonNamesFemale = "";
public static final String pirateNames = "Forent Saeros Neilag Harlen ";
public static final String pirateNamesFemale = "";
public static final String knightNames = "Lanvil Uriel Marcus Flavius Anthony Rubius Victor David Davon Marius Mandos";
public static final String knightNamesSecond = "Bold Brave Strong Swift Valiant Galant Pious Righteous Good Stout Feared Dire Red White Blessed Mighty";
/*
Anaig
De'Lorkai
Giellad Mukami Lohkan Malead Ailad Obea'Wee
*/
public static final String NAME_PREFIX_ELVEN = "";
public static final String NAME_PREFIX_NORSE = "";
public static final String NAME_PREFIX_DARK = "";
public static final String NAME_PREFIX_HUMAN = "";
public static final String NAMES_WOLF_MALE = "Vulthren;Horstwynn;";
public static final String SECOND_NAMES_WOLF_MALE = "Vezmorg;Arverus;Horgron;Dergven;Helvindr;Molandir;Dolgmor";
public static final String NAMES_RAVEN_MALE = "Azmar;Dalreth;Argmann;Ordvil;Movander;DOrlain;"
+ "Morkain;Irvynn;Godric;Ismar;Heldmar";
public static final String SECOND_NAMES_RAVEN_MALE = "Coulon;Calvenir;Carthenn;Woodlard;Oltouron;Pfadeau;Harkis;Chermagne;Lerkou;Verdogne;Taulaise";
public static final String NAMES_EAGLE_MALE = "Ixis;Ezuviel;Thydrod;Quorix;Vezmut;Ezdred;Dalvion;Arodris;Xalvir;Astera;Lumina;Kalthed;Vengor;Mavilor;AedAgor;Tarlos;Kerebor;Ponfinor;Tolmaril;Sixis;DorthArex;Zandimar;Ulviden;Aerthoniel;Arcturus;";
public static final String NAMES_DWARF_MALE = "Mugradon;Duvagor;Odrin;Udrim;Padgor;Twergmar;Gramadan;";
public static final String SECOND_NAMES_DWARF_MALE =
"Uffly;Kuelgh;Oldrich;Boulegon;Barmegad;Kilverin;Sigremon;Throrrus";
static String ravenNameGroups = "Raven Pirate Wolf Eagle King Common Easterling";
static String wolfNameGroups = "wolf Ulduin Raven King Common Eagle";
static String eagleNameGroups = "Eagle King Ulduin Raven Wolf Griff Common";
static String griffNameGroups = "griff King Common Eagle Easterling";
static String kingNameGroups = "king Common Eagle Griff Ulduin Wolf Pirate";
private static final String DEFAULT_NAME_GROUP = kingNameGroups;
static String genericNameGroups = "Common Griff Pirate king Eagle Wolf";
private static final List<String> usedNames = new ArrayList<>();
private static String pirateNamesSecond;
private static String demonNamesSecond;
String orcNames = "Ormog;Nuglog;Usbrol;Buvlud;Xlirg;Xlard;Xumn;Yach-Yach;Guchruk;Durbul;Mubruk;Zurdun;Drufsin;";
public static String generateNewHeroName(ObjType type) {
HeroEnums.SUBRACE bg = getBg(type);
return getFullNameForBackground(bg);
}
public static String getFullNameForBackground(HeroEnums.SUBRACE bg) {
return getRandomName(bg) + " " + getRandomSecondName(bg);
}
private static String getRandomSecondName(HeroEnums.SUBRACE bg) {
// TODO Auto-generated method stub
return null;
}
private static String getRandomName(SUBRACE bg) {
switch (bg) {
}
return null;
}
private static String generateName(Entity hero, String backgroundNameGroups) {
return generateName(hero, backgroundNameGroups, true);
}
private static String generateName(Entity hero, String backgroundNameGroups,
boolean secondIncluded) {
boolean female = EntityCheckMaster.getGender(hero) == HeroEnums.GENDER.FEMALE;
String name = null;
for (String nameGroup : ContainerUtils.open(backgroundNameGroups, " ")) {
while (true) {
if (name != null) {
break;
}
name = getRandomHeroName(hero, getNamesForGroup(nameGroup, female));
}
while (true) {
String secondName = getRandomHeroName(hero, getNamesForGroup(nameGroup, null));
if (secondName != null) {
if (!secondName.equals(name)) {
return name + " " + secondName;
}
}
}
}
return "no name";
}
public static String getNamesForGroup(String nameGroup, Boolean female_male_second) {
if (nameGroup.equalsIgnoreCase("Raven")) {
if (female_male_second == null) {
return ravenNamesSecond;
} else {
return !female_male_second ? ravenNames : ravenNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Griff")) {
if (female_male_second == null) {
return griffNamesSecond;
} else {
return !female_male_second ? griffNames : griffNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Eagle")) {
if (female_male_second == null) {
return eagleNamesSecond;
} else {
return !female_male_second ? eagleNames : eagleNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Easterling")) {
if (female_male_second == null) {
return easterlingNamesSecond;
} else {
return !female_male_second ? easterlingNames : easterlingNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("King")) {
if (female_male_second == null) {
return kingNamesSecond;
} else {
return !female_male_second ? kingNames : kingNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Wolf")) {
if (female_male_second == null) {
return wolfNamesSecond;
} else {
return !female_male_second ? wolfNames : wolfNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Dwarven")) {
if (female_male_second == null) {
return dwarvenNamesSecond;
} else {
return !female_male_second ? dwarvenNames : dwarvenNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Elven")) {
if (female_male_second == null) {
return elvenNamesSecond;
} else {
return !female_male_second ? elvenNames : elvenNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Ulduin")) {
if (female_male_second == null) {
return ulduinNamesSecond;
} else {
return !female_male_second ? ulduinNames : ulduinNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Pirate")) {
if (female_male_second == null) {
return pirateNamesSecond;
} else {
return !female_male_second ? pirateNames : pirateNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Knight")) {
if (female_male_second == null) {
return knightNamesSecond;
} else {
return !female_male_second ? knightNames : kingNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Demon")) {
if (female_male_second == null) {
return demonNamesSecond;
} else {
return !female_male_second ? demonNames : demonNamesFemale;
}
}
return nameGroup;
}
public static String getNamesGroups(SUBRACE bg) {
if (bg.toString().contains("Raven")) {
return (ravenNameGroups);
}
if (bg.toString().contains("Griff")) {
return (griffNameGroups);
}
if (bg.toString().contains("Eagle")) {
return (eagleNameGroups);
}
// if (bg.toString().contains("Easterling"))
// return ( easterlingNameGroups);
if (bg.toString().contains("King")) {
return (kingNameGroups);
}
if (bg.toString().contains("Wolf")) {
return (wolfNameGroups);
}
bg.toString();
return (ravenNameGroups);
}
public static String generateName(Entity hero) {
RACE race = EntityCheckMaster.getRace(hero);
SUBRACE bg = EntityCheckMaster.getBackground(hero);
if (bg==null )
return "Nobackground";
return generateName(hero,race, bg);
}
public static String generateName(Entity hero, RACE race, HeroEnums.SUBRACE bg) {
switch (race) {
case HUMAN:
if (bg.toString().contains("Raven")) {
return generateName(hero, ravenNameGroups);
}
if (bg.toString().contains("Griff")) {
return generateName(hero, griffNameGroups);
}
if (bg.toString().contains("Eagle")) {
return generateName(hero, eagleNameGroups);
}
// if (bg.toString().contains("Easterling"))
// return generateName(hero, easterlingNameGroups);
if (bg.toString().contains("King")) {
return generateName(hero, kingNameGroups);
}
if (bg.toString().contains("Wolf")) {
return generateName(hero, wolfNameGroups);
}
if (bg.toString().contains("Ulduin")) {
return generateName(hero, ravenNameGroups);
}
return generateName(hero, DEFAULT_NAME_GROUP);
// TODO
// return generateName(hero, "Demon");
case DWARF:
return generateName(hero, "Dwarven");
case ELF:
return generateName(hero, "Elven");
}
return null;
}
private static String getRandomHeroName(Entity hero, String namePool) {
List<String> pool = ContainerUtils.openContainer(namePool);
if (pool.isEmpty()) {
return NO_NAME;
}
List<String> names = new ArrayList<>();
for (String s : pool) {
for (String newname : ContainerUtils.open(s, " ")) {
if (!newname.isEmpty()) {
if (!usedNames.contains(newname)) {
names.add(newname);
}
}
}
}
if (names.isEmpty()) {
usedNames.clear();
return getRandomHeroName(hero, namePool);
}
String name = names.get(RandomWizard.getRandomIndex(names));
usedNames.add(name);
return name;
}
public static String pickName(Entity hero) {
List<String> nameGroups = ContainerUtils.openContainer(getNamesGroups(getBg(hero)), " ");
List<String> list = new ArrayList<>();
for (String nameGroup : nameGroups) {
list.addAll(ContainerUtils.openContainer(getNamesForGroup(nameGroup, EntityCheckMaster
.getGender(hero) == HeroEnums.GENDER.FEMALE), " "));
}
String name = new ListChooser(SELECTION_MODE.MULTIPLE, list, false).choose();
if (name != null) {
return ContainerUtils.joinStringList(ContainerUtils.openContainer(name), " ", true);
}
return null;
}
public static void clearNames() {
usedNames.clear();
}
private static SUBRACE getBg(Entity hero) {
return new EnumMaster<HeroEnums.SUBRACE>().retrieveEnumConst(HeroEnums.SUBRACE.class, hero
.getProperty(G_PROPS.BACKGROUND));
}
public static String appendVersionToName(String name) {
return appendVersionToName(name, null);
}
public static String appendVersionToName(String name, Integer i) {
if (name.contains(VERSION)) {
if (NumberUtils.isInteger("" + name.charAt(name.length() - 1))) {
name = name.substring(0, name.lastIndexOf(" "));
}
}
Loop.startLoop(1000);
if (i == null) {
i = 2;
while (!Loop.loopEnded()) {
String newName = name + VERSION + i;
if (!DataManager.isTypeName(newName)) {
break;
}
i++;
}
}
return name + VERSION + i;
}
public static String getUniqueVersionedName(String name, OBJ_TYPE T) {
return getUniqueVersionedName(DataManager.getTypes(T)
.stream().map(DataModel::getName).collect(Collectors.toList())
, name);
}
public static String getUniqueVersionedName(List<String> names, String name) {
int i = 0;
String newName=name;
loop:
while (true) {
i++;
for (String t : names) {
if (t.equalsIgnoreCase(newName)) {
newName = name + Strings.VERSION_SEPARATOR + i;
continue loop;
}
}
break;
}
return newName;
}
public static String getUniqueVersionedFileName(String name, String path) {
List<File> files = FileManager.getFilesFromDirectory(path, false, false);
String format = StringMaster.getFormat(name);
return getUniqueVersionedName(files
.stream().map(type -> StringMaster.cropFormat(type.getName()))
.collect(Collectors.toList())
, StringMaster.cropFormat(name))+format;
}
public static String version(String version) {
return "v" + version;
}
public enum HERO_NAME_GROUPS {
ELVEN, NORSE, DARK, HUMAN
}
}
| IDemiurge/Eidolons | Eidolon-Core/src/main/java/eidolons/system/text/NameMaster.java | 6,642 | // return generateName(hero, "Demon"); | line_comment | nl | package eidolons.system.text;
import main.content.OBJ_TYPE;
import main.content.enums.entity.HeroEnums;
import main.content.enums.entity.HeroEnums.SUBRACE;
import main.content.enums.entity.HeroEnums.RACE;
import main.content.values.properties.G_PROPS;
import main.data.DataManager;
import main.entity.DataModel;
import main.entity.Entity;
import main.entity.EntityCheckMaster;
import main.entity.type.ObjType;
import main.swing.generic.components.editors.lists.ListChooser;
import main.swing.generic.components.editors.lists.ListChooser.SELECTION_MODE;
import main.system.auxiliary.*;
import main.system.auxiliary.data.FileManager;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class NameMaster {
/*
Feren Dauril
Edrail Neref Raurim
Sileeve
Eerive
Yvrieec
Uelveec
Visphy
Loie'Tar
Tor'Loiel
Ylm'Theron
Lith'Ygol
Orleeve
Enreil Delian
Melin Aduvir
Venroim Tharguin
Gideon Antar
Abaddon Gleth
David Mendel
Genvil Dalion
Ervilon Xolmir
Domil Anoch
Izrin Minchev
// Eledari
// Sel'Mauri
// Ald'Vemdor
// Irf'Aenor
// Erd'Mingul
// Saer'Vaenfel
// Huir'Lagmoth
// Raeph'Haduin
// Thae'Vaol
*/
public static final String NO_NAME = "No name";
public static final String VERSION = " v";
public static final String ravenNames = "Draco Dorian Jack Pike Quentin Rick Dilrin Denrix Melrix Lidvis Emrin Lervin Carpel Malkin Severard Rinfer Garsiv Virxis Fidvin Mirvin Delvar "
+ "Delven Idlem Vuron Pirkust Esvin Kuigin Nirgus Islog Sarnas Genlyn Avaldur Vatiar Ectis Osmer Pealet Lotard Nertum Kesrin";
public static final String ravenNamesFemale = "Jenisse Sheilin Imlia Lilian Mesbeth Viola Biantha Gioress Sabina Enesse Norette Vosane Fiona";
public static final String ravenNamesSecond = "Dilrin Norux Denrix Melrix Girsis Lidvis Emrin Lervin Carpel Malkin Rinfer Garsiv Virxis Fidvin Mirvin Kaurim Delnur Delvar Delnesse"
+ " Kurifar Nirligus Exerion Lethmer Raegsul Erming Loerg Gidlau Volmevin Molfran Korbulo";
public static final String wolfNames = "Dortan Gauren Girmut Azulf Sivlid Vardel Dersen Alvid Galvir Gimnur Thonril Tholmir Lirmog Gleifnir Wedrhod Gwynreth Rhaglef Cestil Genlun Golrar "
+ "Gargi Vartu Valsteg Higstam Conrik "
+ "Fogmed Tilbruk Brukthel Ogsit Huntok Arfost Hadden Utmer Isfior Ginwad Tair Sefiad Skalg";
public static final String wolfNamesFemale = "Irsida Emrida Ithglen Fidra Lagatha Aituli Gelnifer Igrith Gwynedil Imdaleg Storbia Rhagla";
public static final String wolfNamesSecond = "Valherim Dirhelor Sivlid Visrith Pauren Edlen Igles Moltav Delgrav Dersen Gimnur Mirthud Thonril Tholmir Glerson Dimroth Dortan Gauren Girmut Dirhold Therving Kinrikkl Hamhelik Segervid Tilsinod Vilkannet";
public static final String eagleNames = "Erithec Benihath Elmareth Delfenor Martis Augled Raurim Mauglir Ulraim Geldior Imgisar Inrif Farnil Iffdor Imliad Anbinath Irsenon Kolneru Elsier "
+ "Nethlur Orodrim Irddel Celthin Aemris Urfediv Irlath Laruon Kineil Iseard";
public static final String eagleNamesFemale = "Elsira Asmin Ervina Tulani Aruna Eriana Silda Olvira Nithlara Istra Eilida Niumi Elbira Elnifer Ulrina Silvia ";
public static final String eagleNamesSecond = "Erithec Benihath Elmareth Delfenor Raurim Caerphis Chimrefel Mauglir Lefredol Ulraim Geldior Imgisar Anurphis Menloris Medlorim Eraglen Erniath Athrem";
public static final String kingNames = "John Adam Alnoir Erles Gwahir Bendaf Galdion Gorthiod Rolwain Limrod Sidlur Aupheir Nathlim Demeril Genthel Aldain Brestir Irgvil "
+ "Giflas Ester Menres Eumol Rolwim Adelwyn Rimlod Arnelion Lorwim Wolrim"
+ " Cenhed Adeilar Denuid Gwynros ";
public static final String kingNamesFemale = "Menfa Juthira "
+ "Elari Thinea Eonri Blauri Athna Lydia" + " Aithlin Mirona Nimore Seina Feluna Feina "
+ "Ansila Thide Haitha Lia Amaltha Theola";
public static final String kingNamesSecond = "Bendaf Gorthiod Rolwain Limrod Irsilod Kalroin Ultath Kinter Elsen Drolem Galniod Irtheniod Adlarim Ginlung Arthenon Vaktiar Pirstag Aedainur Emrianor Naellid Esteniad Althair Murwaith Giothrim Maelsiur Firdlain Estariath Lundaine Merphim Barthair Aensulat Phermithas Leinleith Mardalu Gidseol Soamdath Diplard Evengil Fobbled Kaergraf Delnian Nelaigo";
public static final String griffNames = "Jowaine Jurgon Severon Rutheos Raomir Raemir Sinarc Jemid Juraine Onsard Godric Theon Crigol Dagros Simdal "
+ "Gaeglin Gedaeth Belved Nevid Gasglid Ibrin Ordeb Baleg Hadrod "
+ "Haddel Kurdeag Deirid Daereir Thainith Thaemil Tilead Aldvan Cearat Daecar Adimach Angfuil "
+ "Sestian Rodviol Feilod Gaerad";
public static final String griffNamesFemale = "Jenfis Remira Sinara Jemira Arfida Sornila Sanura Amrin Olmra Eola";
public static final String griffNamesSecond = "Edexis Bailen Imsidor Galdion Feincer Rebfil Atephari Jowaine Godleon Rutheos Raomir Ramrid Raemird Sinarc Gotua Arverno Nolvio Rhufeon Juraine ";
public static final String ulduinNames = "Limrog Olavus Grinresar Smidlar Burtug Fargrad "
+ "Grildur Ormund Stryvolur Riddrog "
+ "Trondurin Tormethil Scadmur Miseud Otsiom Relgon Uthlediad Algorn "
+ "Strolar Urtfran Adeladur Anselud";
public static final String ulduinNamesFemale = "Misanna Relga Uthlena Selda Somlesta Valdelen ";
public static final String ulduinNamesSecond = "";
public static final String elvenNames = "Avelar Haevril Sethelon Eniloth Goriad Nirolim Valrith Entelion Raelur Egvilas Eithas Anelur Adrathas Ginleth Diular Ulsair Doluith Daenar Faoir Inriuth Sauir Faoim Maedlon Naoin Nilthuin Nimlod Gondulim Deriath Vendradir Belvenon Surmagil "
+ "EithNaglur MaerhValar Quedlin Sianor Delgalad Orthaelion Teregroth "
+ "Dulvin BaelarAnuir Olvah Mithlur Gilthar Maedroth Elidor Galdir Echfaelion Dorlumin "
+ "Daurim LirthDelion Bellah Salfeon Ingean Milvor Enudeg Daenlehir Atelaeth";
public static final String elvenNamesFemale = "Belia Nelia Anfina Insila Mivlia Iola Aylin Siora Quelthia Quesia Lumina Dirna Tairi Luwien Adulai Ilureth ";
public static final String elvenNamesSecond = "Ilarfis Arveliad Haevril Sedvelon Caelnorith Eniloth AtalunRee Tulanir Goriad Nimrovil Valrith Uthuniel BlithSaeg Faoi";
public static final String dwarvenNames = "Drogon Rhughad Ligrod Gefnod Nogvir Naugrith Thodrim Balrim Droln Drofnod Noru Bosnir Dusmar Golgar Uxi Dunbor Mugrol "
+ "Talsen Donkel Ingins Desger Tugindir "
+ "Ustuk Hambrud Sageli Eprug Norkol Ungron Ysgrithur Ynvigr Gachtarg Drolif Tagair "
+ "Skeltar Braeham Mangif Maersenif Kenthad Deilar Lerthaein Ulmith Utvald Ogvart Aproret Jargsil "
+ "Utanar Ulkmar Baglarod Haglir Tilfram Birenor Tharagur";
public static final String dwarvenNamesFemale = "";
public static final String dwarvenNamesSecond = "Tirledag Semerog Rhughad Brifich Faurhir Ligrod Gefnod Nogvir Naugrith Thodrim Gausod Grenchest Bansiad Forgneth Acurag Olpust Lurraldi Baketar Batasur Viragost Vuthlin Trovarin Kogel";
public static final String easterlingNames = "";
public static final String easterlingNamesFemale = "";
public static final String easterlingNamesSecond = "";
public static final String demonNames = "Irxithor ";
public static final String demonNamesFemale = "";
public static final String pirateNames = "Forent Saeros Neilag Harlen ";
public static final String pirateNamesFemale = "";
public static final String knightNames = "Lanvil Uriel Marcus Flavius Anthony Rubius Victor David Davon Marius Mandos";
public static final String knightNamesSecond = "Bold Brave Strong Swift Valiant Galant Pious Righteous Good Stout Feared Dire Red White Blessed Mighty";
/*
Anaig
De'Lorkai
Giellad Mukami Lohkan Malead Ailad Obea'Wee
*/
public static final String NAME_PREFIX_ELVEN = "";
public static final String NAME_PREFIX_NORSE = "";
public static final String NAME_PREFIX_DARK = "";
public static final String NAME_PREFIX_HUMAN = "";
public static final String NAMES_WOLF_MALE = "Vulthren;Horstwynn;";
public static final String SECOND_NAMES_WOLF_MALE = "Vezmorg;Arverus;Horgron;Dergven;Helvindr;Molandir;Dolgmor";
public static final String NAMES_RAVEN_MALE = "Azmar;Dalreth;Argmann;Ordvil;Movander;DOrlain;"
+ "Morkain;Irvynn;Godric;Ismar;Heldmar";
public static final String SECOND_NAMES_RAVEN_MALE = "Coulon;Calvenir;Carthenn;Woodlard;Oltouron;Pfadeau;Harkis;Chermagne;Lerkou;Verdogne;Taulaise";
public static final String NAMES_EAGLE_MALE = "Ixis;Ezuviel;Thydrod;Quorix;Vezmut;Ezdred;Dalvion;Arodris;Xalvir;Astera;Lumina;Kalthed;Vengor;Mavilor;AedAgor;Tarlos;Kerebor;Ponfinor;Tolmaril;Sixis;DorthArex;Zandimar;Ulviden;Aerthoniel;Arcturus;";
public static final String NAMES_DWARF_MALE = "Mugradon;Duvagor;Odrin;Udrim;Padgor;Twergmar;Gramadan;";
public static final String SECOND_NAMES_DWARF_MALE =
"Uffly;Kuelgh;Oldrich;Boulegon;Barmegad;Kilverin;Sigremon;Throrrus";
static String ravenNameGroups = "Raven Pirate Wolf Eagle King Common Easterling";
static String wolfNameGroups = "wolf Ulduin Raven King Common Eagle";
static String eagleNameGroups = "Eagle King Ulduin Raven Wolf Griff Common";
static String griffNameGroups = "griff King Common Eagle Easterling";
static String kingNameGroups = "king Common Eagle Griff Ulduin Wolf Pirate";
private static final String DEFAULT_NAME_GROUP = kingNameGroups;
static String genericNameGroups = "Common Griff Pirate king Eagle Wolf";
private static final List<String> usedNames = new ArrayList<>();
private static String pirateNamesSecond;
private static String demonNamesSecond;
String orcNames = "Ormog;Nuglog;Usbrol;Buvlud;Xlirg;Xlard;Xumn;Yach-Yach;Guchruk;Durbul;Mubruk;Zurdun;Drufsin;";
public static String generateNewHeroName(ObjType type) {
HeroEnums.SUBRACE bg = getBg(type);
return getFullNameForBackground(bg);
}
public static String getFullNameForBackground(HeroEnums.SUBRACE bg) {
return getRandomName(bg) + " " + getRandomSecondName(bg);
}
private static String getRandomSecondName(HeroEnums.SUBRACE bg) {
// TODO Auto-generated method stub
return null;
}
private static String getRandomName(SUBRACE bg) {
switch (bg) {
}
return null;
}
private static String generateName(Entity hero, String backgroundNameGroups) {
return generateName(hero, backgroundNameGroups, true);
}
private static String generateName(Entity hero, String backgroundNameGroups,
boolean secondIncluded) {
boolean female = EntityCheckMaster.getGender(hero) == HeroEnums.GENDER.FEMALE;
String name = null;
for (String nameGroup : ContainerUtils.open(backgroundNameGroups, " ")) {
while (true) {
if (name != null) {
break;
}
name = getRandomHeroName(hero, getNamesForGroup(nameGroup, female));
}
while (true) {
String secondName = getRandomHeroName(hero, getNamesForGroup(nameGroup, null));
if (secondName != null) {
if (!secondName.equals(name)) {
return name + " " + secondName;
}
}
}
}
return "no name";
}
public static String getNamesForGroup(String nameGroup, Boolean female_male_second) {
if (nameGroup.equalsIgnoreCase("Raven")) {
if (female_male_second == null) {
return ravenNamesSecond;
} else {
return !female_male_second ? ravenNames : ravenNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Griff")) {
if (female_male_second == null) {
return griffNamesSecond;
} else {
return !female_male_second ? griffNames : griffNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Eagle")) {
if (female_male_second == null) {
return eagleNamesSecond;
} else {
return !female_male_second ? eagleNames : eagleNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Easterling")) {
if (female_male_second == null) {
return easterlingNamesSecond;
} else {
return !female_male_second ? easterlingNames : easterlingNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("King")) {
if (female_male_second == null) {
return kingNamesSecond;
} else {
return !female_male_second ? kingNames : kingNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Wolf")) {
if (female_male_second == null) {
return wolfNamesSecond;
} else {
return !female_male_second ? wolfNames : wolfNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Dwarven")) {
if (female_male_second == null) {
return dwarvenNamesSecond;
} else {
return !female_male_second ? dwarvenNames : dwarvenNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Elven")) {
if (female_male_second == null) {
return elvenNamesSecond;
} else {
return !female_male_second ? elvenNames : elvenNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Ulduin")) {
if (female_male_second == null) {
return ulduinNamesSecond;
} else {
return !female_male_second ? ulduinNames : ulduinNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Pirate")) {
if (female_male_second == null) {
return pirateNamesSecond;
} else {
return !female_male_second ? pirateNames : pirateNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Knight")) {
if (female_male_second == null) {
return knightNamesSecond;
} else {
return !female_male_second ? knightNames : kingNamesFemale;
}
}
if (nameGroup.equalsIgnoreCase("Demon")) {
if (female_male_second == null) {
return demonNamesSecond;
} else {
return !female_male_second ? demonNames : demonNamesFemale;
}
}
return nameGroup;
}
public static String getNamesGroups(SUBRACE bg) {
if (bg.toString().contains("Raven")) {
return (ravenNameGroups);
}
if (bg.toString().contains("Griff")) {
return (griffNameGroups);
}
if (bg.toString().contains("Eagle")) {
return (eagleNameGroups);
}
// if (bg.toString().contains("Easterling"))
// return ( easterlingNameGroups);
if (bg.toString().contains("King")) {
return (kingNameGroups);
}
if (bg.toString().contains("Wolf")) {
return (wolfNameGroups);
}
bg.toString();
return (ravenNameGroups);
}
public static String generateName(Entity hero) {
RACE race = EntityCheckMaster.getRace(hero);
SUBRACE bg = EntityCheckMaster.getBackground(hero);
if (bg==null )
return "Nobackground";
return generateName(hero,race, bg);
}
public static String generateName(Entity hero, RACE race, HeroEnums.SUBRACE bg) {
switch (race) {
case HUMAN:
if (bg.toString().contains("Raven")) {
return generateName(hero, ravenNameGroups);
}
if (bg.toString().contains("Griff")) {
return generateName(hero, griffNameGroups);
}
if (bg.toString().contains("Eagle")) {
return generateName(hero, eagleNameGroups);
}
// if (bg.toString().contains("Easterling"))
// return generateName(hero, easterlingNameGroups);
if (bg.toString().contains("King")) {
return generateName(hero, kingNameGroups);
}
if (bg.toString().contains("Wolf")) {
return generateName(hero, wolfNameGroups);
}
if (bg.toString().contains("Ulduin")) {
return generateName(hero, ravenNameGroups);
}
return generateName(hero, DEFAULT_NAME_GROUP);
// TODO
// return generateName(hero,<SUF>
case DWARF:
return generateName(hero, "Dwarven");
case ELF:
return generateName(hero, "Elven");
}
return null;
}
private static String getRandomHeroName(Entity hero, String namePool) {
List<String> pool = ContainerUtils.openContainer(namePool);
if (pool.isEmpty()) {
return NO_NAME;
}
List<String> names = new ArrayList<>();
for (String s : pool) {
for (String newname : ContainerUtils.open(s, " ")) {
if (!newname.isEmpty()) {
if (!usedNames.contains(newname)) {
names.add(newname);
}
}
}
}
if (names.isEmpty()) {
usedNames.clear();
return getRandomHeroName(hero, namePool);
}
String name = names.get(RandomWizard.getRandomIndex(names));
usedNames.add(name);
return name;
}
public static String pickName(Entity hero) {
List<String> nameGroups = ContainerUtils.openContainer(getNamesGroups(getBg(hero)), " ");
List<String> list = new ArrayList<>();
for (String nameGroup : nameGroups) {
list.addAll(ContainerUtils.openContainer(getNamesForGroup(nameGroup, EntityCheckMaster
.getGender(hero) == HeroEnums.GENDER.FEMALE), " "));
}
String name = new ListChooser(SELECTION_MODE.MULTIPLE, list, false).choose();
if (name != null) {
return ContainerUtils.joinStringList(ContainerUtils.openContainer(name), " ", true);
}
return null;
}
public static void clearNames() {
usedNames.clear();
}
private static SUBRACE getBg(Entity hero) {
return new EnumMaster<HeroEnums.SUBRACE>().retrieveEnumConst(HeroEnums.SUBRACE.class, hero
.getProperty(G_PROPS.BACKGROUND));
}
public static String appendVersionToName(String name) {
return appendVersionToName(name, null);
}
public static String appendVersionToName(String name, Integer i) {
if (name.contains(VERSION)) {
if (NumberUtils.isInteger("" + name.charAt(name.length() - 1))) {
name = name.substring(0, name.lastIndexOf(" "));
}
}
Loop.startLoop(1000);
if (i == null) {
i = 2;
while (!Loop.loopEnded()) {
String newName = name + VERSION + i;
if (!DataManager.isTypeName(newName)) {
break;
}
i++;
}
}
return name + VERSION + i;
}
public static String getUniqueVersionedName(String name, OBJ_TYPE T) {
return getUniqueVersionedName(DataManager.getTypes(T)
.stream().map(DataModel::getName).collect(Collectors.toList())
, name);
}
public static String getUniqueVersionedName(List<String> names, String name) {
int i = 0;
String newName=name;
loop:
while (true) {
i++;
for (String t : names) {
if (t.equalsIgnoreCase(newName)) {
newName = name + Strings.VERSION_SEPARATOR + i;
continue loop;
}
}
break;
}
return newName;
}
public static String getUniqueVersionedFileName(String name, String path) {
List<File> files = FileManager.getFilesFromDirectory(path, false, false);
String format = StringMaster.getFormat(name);
return getUniqueVersionedName(files
.stream().map(type -> StringMaster.cropFormat(type.getName()))
.collect(Collectors.toList())
, StringMaster.cropFormat(name))+format;
}
public static String version(String version) {
return "v" + version;
}
public enum HERO_NAME_GROUPS {
ELVEN, NORSE, DARK, HUMAN
}
}
|
177490_1 | package nl.idgis.downloadtool.domain;
import java.io.Serializable;
/**
* Bean containing feedback information on individual download requests.
*
* @author Rob
*
*/
public class Feedback implements Serializable {
private static final long serialVersionUID = -3600596933670573586L;
/**
* requestId is uniek Id van dit download verzoek, wordt gebruikt bij
* terugmeldingen
*/
private String requestId;
/**
* Result code
*/
private String resultCode;
/**
* @param id
* unique identifier of this downloadrequest.<br>
* Equal to DownloadRequest.requestId
*/
public Feedback(String id) {
super();
this.requestId = id;
}
public String getRequestId() {
return requestId;
}
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
@Override
public String toString() {
return "Feedback [requestId=" + requestId + ", resultCode=" + resultCode + "]";
}
}
| IDgis/download-tool | domain/src/main/java/nl/idgis/downloadtool/domain/Feedback.java | 341 | /**
* requestId is uniek Id van dit download verzoek, wordt gebruikt bij
* terugmeldingen
*/ | block_comment | nl | package nl.idgis.downloadtool.domain;
import java.io.Serializable;
/**
* Bean containing feedback information on individual download requests.
*
* @author Rob
*
*/
public class Feedback implements Serializable {
private static final long serialVersionUID = -3600596933670573586L;
/**
* requestId is uniek<SUF>*/
private String requestId;
/**
* Result code
*/
private String resultCode;
/**
* @param id
* unique identifier of this downloadrequest.<br>
* Equal to DownloadRequest.requestId
*/
public Feedback(String id) {
super();
this.requestId = id;
}
public String getRequestId() {
return requestId;
}
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
@Override
public String toString() {
return "Feedback [requestId=" + requestId + ", resultCode=" + resultCode + "]";
}
}
|
33184_0 | package nl.idgis.geoportaal.conversie;
public class Label {
private String value;
private String table;
private String labelTable;
/**
* Puntkomma's in {@code value} worden vervangen door dubbele punten. Dit gebeurt niet bij {@link Label#setValue}. Null-waarden worden vervangen door lege strings.
* @param value
* @param table
*/
public Label(String value, String table) {
this.value = value;
this.table = table;
this.labelTable = table + "_label";
if (this.value != null)
this.value = value.replace(';', ':');
else
this.value = "";
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public String getLabelTable() {
return labelTable;
}
public void setLabelTable(String labelTable) {
this.labelTable = labelTable;
}
@Override
public String toString() {
return "Label [value=" + value + ", table=" + table + ", labelTable=" + labelTable + "]";
}
}
| IDgis/geoportaal | conversion/src/main/java/nl/idgis/geoportaal/conversie/Label.java | 384 | /**
* Puntkomma's in {@code value} worden vervangen door dubbele punten. Dit gebeurt niet bij {@link Label#setValue}. Null-waarden worden vervangen door lege strings.
* @param value
* @param table
*/ | block_comment | nl | package nl.idgis.geoportaal.conversie;
public class Label {
private String value;
private String table;
private String labelTable;
/**
* Puntkomma's in {@code<SUF>*/
public Label(String value, String table) {
this.value = value;
this.table = table;
this.labelTable = table + "_label";
if (this.value != null)
this.value = value.replace(';', ':');
else
this.value = "";
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public String getLabelTable() {
return labelTable;
}
public void setLabelTable(String labelTable) {
this.labelTable = labelTable;
}
@Override
public String toString() {
return "Label [value=" + value + ", table=" + table + ", labelTable=" + labelTable + "]";
}
}
|
45274_0 | package nl.idgis.importer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.*;
@Component
public class GioImporter {
private final JdbcTemplate jdbcTemplate;
private final String inputFile;
private final String gioName;
private final String regelingExpression;
@Autowired
public GioImporter(JdbcTemplate jdbcTemplate, String inputFile, String gioName, String regelingExpression) {
this.jdbcTemplate = jdbcTemplate;
this.inputFile = inputFile;
this.gioName = gioName;
this.regelingExpression = regelingExpression;
}
public void importGio() {
File file = new File(inputFile);
if (!file.exists()) {
throw new IllegalArgumentException("Het GIO bestand op de volgende locatie kan niet gevonden worden: " + file.getAbsolutePath());
}
// Haal regelingId op
int regelingVersieId = getRegelingVersieId(regelingExpression);
int regelingId = getRegelingId(regelingVersieId);
int eindverantwoordelijkeId = getEindverantwoordelijkeId(regelingVersieId);
int makerId = getMakerId(regelingVersieId);
String eindverantwoordelijke = getEindverantwoordelijke(eindverantwoordelijkeId);
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
XPath xPath = new XPathBuilder()
.xmlns("basisgeo", "http://www.geostandaarden.nl/basisgeometrie/1.0")
.xmlns("geo", "https://standaarden.overheid.nl/stop/imop/geo/")
.xmlns("gio", "https://standaarden.overheid.nl/stop/imop/gio/")
.xmlns("gml", "http://www.opengis.net/gml/3.2")
.build();
NodeList locaties = (NodeList) xPath.compile("//geo:Locatie").evaluate(doc, XPathConstants.NODESET);
List<Integer> locatieIds = new ArrayList<>();
for (int i = 0; i < locaties.getLength(); i++) {
Node locatie = locaties.item(i);
Node naam = (Node) xPath.compile("./geo:naam").evaluate(locatie, XPathConstants.NODE);
Node id = (Node) xPath.compile(".//basisgeo:id").evaluate(locatie, XPathConstants.NODE);
Node gmlNode = (Node) xPath.compile(".//*[@gml:id='id-" + id.getTextContent() + "']").evaluate(locatie, XPathConstants.NODE);
// Geometrie + Locatie
System.out.printf("Bezig met verwerken van locatie '%s' (%d/%d)%n", naam.getTextContent(), i + 1, locaties.getLength());
if (!geometryExists(id.getTextContent())) {
int geometrieId = insertGeometry(id.getTextContent(), naam.getTextContent(), getGml(gmlNode));
String geometryType = getGeometryType(geometrieId);
locatieIds.add(insertLocatie(naam.getTextContent(), LocalDate.now(), regelingId, geometryType, geometrieId, eindverantwoordelijke));
} else {
int geometrieId = getGeometrieId(id.getTextContent());
locatieIds.add(getLocatieId(geometrieId));
}
}
// Groep locatie
System.out.println("Bezig met het maken van de groepslocatie");
String geometryType = getLocatieGeometryType(locatieIds.get(0));
int locatieGroepId = insertLocatie(gioName, LocalDate.now(), regelingId, geometryType, eindverantwoordelijke);
locatieIds.forEach(locatieId -> linkLocatieToGroep(locatieId, locatieGroepId));
// Informatieobjectversie
System.out.println("Bezig met het verwerken van de GIO");
Node frbrWork = (Node) xPath.compile("//geo:FRBRWork").evaluate(doc, XPathConstants.NODE);
Node frbrExpression = (Node) xPath.compile("//geo:FRBRExpression").evaluate(doc, XPathConstants.NODE);
Node achtergrondVerwijzingNode = (Node) xPath.compile("//gio:achtergrondVerwijzing").evaluate(doc, XPathConstants.NODE);
Node achtergrondActualiteitNode = (Node) xPath.compile("//gio:achtergrondActualiteit").evaluate(doc, XPathConstants.NODE);
Node nauwkeurigheidNode = (Node) xPath.compile("//gio:nauwkeurigheid").evaluate(doc, XPathConstants.NODE);
String achtergrondVerwijzing = achtergrondVerwijzingNode != null ? achtergrondVerwijzingNode.getTextContent() : null;
String achtergrondActualiteit = achtergrondActualiteitNode != null ? achtergrondActualiteitNode.getTextContent() : null;
String nauwkeurigheid = nauwkeurigheidNode != null ? nauwkeurigheidNode.getTextContent() : null;
insertInformatieObjectVersie(frbrWork.getTextContent(), frbrExpression.getTextContent(), regelingId, eindverantwoordelijkeId, makerId,
gioName, achtergrondVerwijzing, achtergrondActualiteit, nauwkeurigheid, locatieGroepId);
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
e.printStackTrace();
}
}
private String getGml(Node gmlNode) {
try (StringWriter sw = new StringWriter()) {
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(gmlNode), new StreamResult(sw));
return sw.toString();
} catch (IOException | TransformerException e) {
throw new IllegalStateException("GML kon niet geparsed worden", e);
}
}
private int getRegelingVersieId(String expressionId) {
String sql = "SELECT id FROM bzk.regelingversie WHERE frbr_expression = ?";
String errorMessage = "Expression ID niet gevonden in de database: " + expressionId;
Integer regelingVersieId = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setString(1, expressionId),
rs -> {
if (rs.next()) {
return rs.getInt("id");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (regelingVersieId == null) {
throw new IllegalArgumentException(errorMessage);
}
return regelingVersieId;
}
private int getRegelingId(int regelingVersieId) {
String sql =
"SELECT r.id FROM bzk.regeling r " +
"JOIN bzk.regelingversie rv ON rv.regeling_id = r.id " +
"WHERE rv.id = ?";
String errorMessage = "Regeling niet gevonden in de database met regelingversie id: " + regelingVersieId;
Integer regelingId = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, regelingVersieId),
rs -> {
if (rs.next()) {
return rs.getInt("id");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (regelingId == null) {
throw new IllegalArgumentException(errorMessage);
}
return regelingId;
}
private int getEindverantwoordelijkeId(int regelingVersieId) {
String sql = "SELECT eindverantwoordelijke_id FROM bzk.regelingversie WHERE id = ?";
String errorMessage = "Eindverantwoordelijke niet gevonden in de database";
Integer eindverantwoordelijke = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, regelingVersieId),
rs -> {
if (rs.next()) {
return rs.getInt("eindverantwoordelijke_id");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (eindverantwoordelijke == null) {
throw new IllegalArgumentException(errorMessage);
}
return eindverantwoordelijke;
}
private String getEindverantwoordelijke(int id) {
String sql = "SELECT stop_id FROM public.stop_waarde WHERE id = ?";
String errorMessage = "Eindverantwoordelijke niet gevonden in de database";
String eindverantwoordelijke = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, id),
rs -> {
if (rs.next()) {
return rs.getString(1);
}
throw new IllegalArgumentException(errorMessage);
}
);
if (eindverantwoordelijke == null) {
throw new IllegalArgumentException(errorMessage);
}
return eindverantwoordelijke.substring(eindverantwoordelijke.lastIndexOf('/') + 1);
}
private int getMakerId(int regelingVersieId) {
String sql = "SELECT maker_id FROM bzk.regelingversie WHERE id = ?";
String errorMessage = "Maker niet gevonden in de database";
Integer maker = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, regelingVersieId),
rs -> {
if (rs.next()) {
return rs.getInt("maker_id");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (maker == null) {
throw new IllegalArgumentException(errorMessage);
}
return maker;
}
private boolean geometryExists(String gmlId) {
String sql = "SELECT * FROM bzk.geometrie WHERE geometrie_id = ?";
String errorMessage = "Kon niet bepalen of de geometrie met id '" + gmlId + "' al bestaat";
return jdbcTemplate.query(
sql,
ps -> ps.setString(1, gmlId),
(rs, rowNum) -> rs.getInt(1)
).stream().findFirst().isPresent();
}
private int insertGeometry(String gmlId, String naam, String gml) {
String sql =
"INSERT INTO bzk.geometrie (naam, geometrie_id, geometrie) " +
"VALUES (?, ?, ST_GEOMFROMGML(?, 28992)) " +
"RETURNING id";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
conn -> {
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, naam);
ps.setString(2, gmlId);
ps.setString(3, gml);
return ps;
},
keyHolder
);
return Optional.ofNullable(keyHolder.getKey())
.map(Number::intValue)
.orElseThrow(() -> new IllegalStateException("Er ging iets mis bij het inserten van de geometrie " + gmlId));
}
private int getGeometrieId(String gmlId) {
String sql = "SELECT id FROM bzk.geometrie WHERE geometrie_id = ?";
String errorMessage = "Kon de id van de geometrie '" + gmlId + "' niet ophalen";
Integer id = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setString(1, gmlId),
rs -> {
if (rs.next()) {
return rs.getInt("id");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (id == null) {
throw new IllegalArgumentException(errorMessage);
}
return id;
}
private String getGeometryType(int geometrieId) {
String sql = "SELECT ST_GEOMETRYTYPE(geometrie) geom_type FROM bzk.geometrie WHERE id = ?";
String errorMessage = "Kon het type van de geometrie niet bepalen";
String geometryType = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, geometrieId),
rs -> {
if (rs.next()) {
String type = rs.getString("geom_type").toLowerCase();
if (type.contains("polygon")) {
return "vlak";
} else if (type.contains("line")) {
return "lijn";
} else if (type.contains("point")) {
return "punt";
}
}
throw new IllegalArgumentException(errorMessage);
}
);
if (geometryType == null) {
throw new IllegalArgumentException(errorMessage);
}
return geometryType;
}
private String getLocatieGeometryType(int locatieId) {
String sql = "SELECT geometrietype FROM bzk.locatie WHERE id = ?";
String errorMessage = "Kon het geometrietype van de locatie niet bepalen";
String geometryType = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, locatieId),
rs -> {
if (rs.next()) {
return rs.getString("geometrietype");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (geometryType == null) {
throw new IllegalArgumentException(errorMessage);
}
return geometryType;
}
private int getLocatieId(int geometrieId) {
String sql = "SELECT id FROM bzk.locatie WHERE geometrie_id = ?";
String errorMessage = "Kon de id van de locatie niet ophalen";
Integer id = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, geometrieId),
rs -> {
if (rs.next()) {
return rs.getInt("id");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (id == null) {
throw new IllegalArgumentException(errorMessage);
}
return id;
}
private int insertLocatie(String name, LocalDate dateStart, int regelingId, String geometryType, int geometryId, String bgCode) {
String sql =
"INSERT INTO bzk.locatie (naam, datum_begin, ind_groep_jn, regeling_id, geometrietype, geometrie_id, identificatie) " +
"VALUES (?, ?, false, ?, ?, ?, ?) " +
"RETURNING id";
KeyHolder keyHolder = new GeneratedKeyHolder();
String objectType = "vlak".equals(geometryType) ? "gebied" : geometryType;
String identificatie = "nl.imow-" + bgCode + "." + objectType + "." + UUID.randomUUID().toString().replace("-", "").toLowerCase();
jdbcTemplate.update(
conn -> {
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, name);
ps.setDate(2, Date.valueOf(dateStart));
ps.setInt(3, regelingId);
ps.setString(4, geometryType);
ps.setInt(5, geometryId);
ps.setString(6, identificatie);
return ps;
},
keyHolder
);
return Optional.ofNullable(keyHolder.getKey())
.map(Number::intValue)
.orElseThrow(() -> new IllegalStateException("Er ging iets mis bij het inserten van de locatie"));
}
private int insertLocatie(String name, LocalDate dateStart, int regelingId, String geometryType, String bgCode) {
String sql =
"INSERT INTO bzk.locatie (naam, datum_begin, ind_groep_jn, regeling_id, geometrietype, identificatie) " +
"VALUES (?, ?, true, ?, ?, ?) " +
"RETURNING id";
KeyHolder keyHolder = new GeneratedKeyHolder();
String objectType = "vlak".equals(geometryType) ? "gebied" : geometryType;
String identificatie = "nl.imow-" + bgCode + "." + objectType + "engroep." + UUID.randomUUID().toString().replace("-", "").toLowerCase();
jdbcTemplate.update(
conn -> {
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, name);
ps.setDate(2, Date.valueOf(dateStart));
ps.setInt(3, regelingId);
ps.setString(4, geometryType);
ps.setString(5, identificatie);
return ps;
},
keyHolder
);
return Optional.ofNullable(keyHolder.getKey())
.map(Number::intValue)
.orElseThrow(() -> new IllegalStateException("Er ging iets mis bij het inserten van de locatie"));
}
private void linkLocatieToGroep(int locatieId, int locatieGroepId) {
String sql = "INSERT INTO bzk.groep_locatie (locatiegroep_id, locatie_id) VALUES (?, ?)";
jdbcTemplate.update(sql, ps -> {
ps.setInt(1, locatieGroepId);
ps.setInt(2, locatieId);
});
}
private void insertInformatieObjectVersie(String frbrWork, String frbrExpression, int regelingId, int eindverantwoordelijkeId,
int makerId, String gioName, String achtergrondVerwijzing, String achergrondActualiteit, String nauwkeurigheid,
int locatieId) {
String sql =
"INSERT INTO bzk.informatieobjectversie (frbr_work, frbr_expression, soort_work_id, regeling_id, eindverantwoordelijke_id, maker_id, " +
"formaat_informatieobject_id, naam, officiele_titel, publicatie_instructie_id, stop_schema_versie, achtergrond_verwijzing, " +
"achtergrond_actualiteit, nauwkeurigheid, locatie_id) " +
"VALUES (?, ?, 2056, ?, ?, ?, 1410, ?, ?, 3, '1.3.0', ?, ?, ?, ?)";
jdbcTemplate.update(sql, ps -> {
ps.setObject(1, frbrWork);
ps.setObject(2, frbrExpression);
ps.setObject(3, regelingId);
ps.setObject(4, eindverantwoordelijkeId);
ps.setObject(5, makerId);
ps.setObject(6, gioName);
ps.setObject(7, frbrWork);
ps.setObject(8, achtergrondVerwijzing);
ps.setObject(9, achergrondActualiteit != null ? Date.valueOf(achergrondActualiteit) : null);
ps.setObject(10, nauwkeurigheid != null ? Integer.parseInt(nauwkeurigheid) : null);
ps.setObject(11, locatieId);
});
}
private static class XPathBuilder {
private final Map<String, String> namespaces = new HashMap<>();
public XPathBuilder xmlns(String prefix, String namespaceURI) {
namespaces.put(prefix, namespaceURI);
return this;
}
public XPath build() {
XPath xp = XPathFactory.newInstance().newXPath();
xp.setNamespaceContext(new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
return namespaces.get(prefix);
}
@Override
public String getPrefix(String namespaceURI) {
return getPrefixes(namespaceURI).next();
}
@Override
public Iterator<String> getPrefixes(String namespaceURI) {
return namespaces.entrySet().stream()
.filter(entry -> entry.getValue().equals(namespaceURI))
.map(Map.Entry::getKey)
.iterator();
}
});
return xp;
}
}
}
| IDgis/odtekst-gio-importer | src/main/java/nl/idgis/importer/GioImporter.java | 5,980 | // Haal regelingId op | line_comment | nl | package nl.idgis.importer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.*;
@Component
public class GioImporter {
private final JdbcTemplate jdbcTemplate;
private final String inputFile;
private final String gioName;
private final String regelingExpression;
@Autowired
public GioImporter(JdbcTemplate jdbcTemplate, String inputFile, String gioName, String regelingExpression) {
this.jdbcTemplate = jdbcTemplate;
this.inputFile = inputFile;
this.gioName = gioName;
this.regelingExpression = regelingExpression;
}
public void importGio() {
File file = new File(inputFile);
if (!file.exists()) {
throw new IllegalArgumentException("Het GIO bestand op de volgende locatie kan niet gevonden worden: " + file.getAbsolutePath());
}
// Haal regelingId<SUF>
int regelingVersieId = getRegelingVersieId(regelingExpression);
int regelingId = getRegelingId(regelingVersieId);
int eindverantwoordelijkeId = getEindverantwoordelijkeId(regelingVersieId);
int makerId = getMakerId(regelingVersieId);
String eindverantwoordelijke = getEindverantwoordelijke(eindverantwoordelijkeId);
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
XPath xPath = new XPathBuilder()
.xmlns("basisgeo", "http://www.geostandaarden.nl/basisgeometrie/1.0")
.xmlns("geo", "https://standaarden.overheid.nl/stop/imop/geo/")
.xmlns("gio", "https://standaarden.overheid.nl/stop/imop/gio/")
.xmlns("gml", "http://www.opengis.net/gml/3.2")
.build();
NodeList locaties = (NodeList) xPath.compile("//geo:Locatie").evaluate(doc, XPathConstants.NODESET);
List<Integer> locatieIds = new ArrayList<>();
for (int i = 0; i < locaties.getLength(); i++) {
Node locatie = locaties.item(i);
Node naam = (Node) xPath.compile("./geo:naam").evaluate(locatie, XPathConstants.NODE);
Node id = (Node) xPath.compile(".//basisgeo:id").evaluate(locatie, XPathConstants.NODE);
Node gmlNode = (Node) xPath.compile(".//*[@gml:id='id-" + id.getTextContent() + "']").evaluate(locatie, XPathConstants.NODE);
// Geometrie + Locatie
System.out.printf("Bezig met verwerken van locatie '%s' (%d/%d)%n", naam.getTextContent(), i + 1, locaties.getLength());
if (!geometryExists(id.getTextContent())) {
int geometrieId = insertGeometry(id.getTextContent(), naam.getTextContent(), getGml(gmlNode));
String geometryType = getGeometryType(geometrieId);
locatieIds.add(insertLocatie(naam.getTextContent(), LocalDate.now(), regelingId, geometryType, geometrieId, eindverantwoordelijke));
} else {
int geometrieId = getGeometrieId(id.getTextContent());
locatieIds.add(getLocatieId(geometrieId));
}
}
// Groep locatie
System.out.println("Bezig met het maken van de groepslocatie");
String geometryType = getLocatieGeometryType(locatieIds.get(0));
int locatieGroepId = insertLocatie(gioName, LocalDate.now(), regelingId, geometryType, eindverantwoordelijke);
locatieIds.forEach(locatieId -> linkLocatieToGroep(locatieId, locatieGroepId));
// Informatieobjectversie
System.out.println("Bezig met het verwerken van de GIO");
Node frbrWork = (Node) xPath.compile("//geo:FRBRWork").evaluate(doc, XPathConstants.NODE);
Node frbrExpression = (Node) xPath.compile("//geo:FRBRExpression").evaluate(doc, XPathConstants.NODE);
Node achtergrondVerwijzingNode = (Node) xPath.compile("//gio:achtergrondVerwijzing").evaluate(doc, XPathConstants.NODE);
Node achtergrondActualiteitNode = (Node) xPath.compile("//gio:achtergrondActualiteit").evaluate(doc, XPathConstants.NODE);
Node nauwkeurigheidNode = (Node) xPath.compile("//gio:nauwkeurigheid").evaluate(doc, XPathConstants.NODE);
String achtergrondVerwijzing = achtergrondVerwijzingNode != null ? achtergrondVerwijzingNode.getTextContent() : null;
String achtergrondActualiteit = achtergrondActualiteitNode != null ? achtergrondActualiteitNode.getTextContent() : null;
String nauwkeurigheid = nauwkeurigheidNode != null ? nauwkeurigheidNode.getTextContent() : null;
insertInformatieObjectVersie(frbrWork.getTextContent(), frbrExpression.getTextContent(), regelingId, eindverantwoordelijkeId, makerId,
gioName, achtergrondVerwijzing, achtergrondActualiteit, nauwkeurigheid, locatieGroepId);
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
e.printStackTrace();
}
}
private String getGml(Node gmlNode) {
try (StringWriter sw = new StringWriter()) {
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(gmlNode), new StreamResult(sw));
return sw.toString();
} catch (IOException | TransformerException e) {
throw new IllegalStateException("GML kon niet geparsed worden", e);
}
}
private int getRegelingVersieId(String expressionId) {
String sql = "SELECT id FROM bzk.regelingversie WHERE frbr_expression = ?";
String errorMessage = "Expression ID niet gevonden in de database: " + expressionId;
Integer regelingVersieId = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setString(1, expressionId),
rs -> {
if (rs.next()) {
return rs.getInt("id");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (regelingVersieId == null) {
throw new IllegalArgumentException(errorMessage);
}
return regelingVersieId;
}
private int getRegelingId(int regelingVersieId) {
String sql =
"SELECT r.id FROM bzk.regeling r " +
"JOIN bzk.regelingversie rv ON rv.regeling_id = r.id " +
"WHERE rv.id = ?";
String errorMessage = "Regeling niet gevonden in de database met regelingversie id: " + regelingVersieId;
Integer regelingId = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, regelingVersieId),
rs -> {
if (rs.next()) {
return rs.getInt("id");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (regelingId == null) {
throw new IllegalArgumentException(errorMessage);
}
return regelingId;
}
private int getEindverantwoordelijkeId(int regelingVersieId) {
String sql = "SELECT eindverantwoordelijke_id FROM bzk.regelingversie WHERE id = ?";
String errorMessage = "Eindverantwoordelijke niet gevonden in de database";
Integer eindverantwoordelijke = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, regelingVersieId),
rs -> {
if (rs.next()) {
return rs.getInt("eindverantwoordelijke_id");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (eindverantwoordelijke == null) {
throw new IllegalArgumentException(errorMessage);
}
return eindverantwoordelijke;
}
private String getEindverantwoordelijke(int id) {
String sql = "SELECT stop_id FROM public.stop_waarde WHERE id = ?";
String errorMessage = "Eindverantwoordelijke niet gevonden in de database";
String eindverantwoordelijke = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, id),
rs -> {
if (rs.next()) {
return rs.getString(1);
}
throw new IllegalArgumentException(errorMessage);
}
);
if (eindverantwoordelijke == null) {
throw new IllegalArgumentException(errorMessage);
}
return eindverantwoordelijke.substring(eindverantwoordelijke.lastIndexOf('/') + 1);
}
private int getMakerId(int regelingVersieId) {
String sql = "SELECT maker_id FROM bzk.regelingversie WHERE id = ?";
String errorMessage = "Maker niet gevonden in de database";
Integer maker = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, regelingVersieId),
rs -> {
if (rs.next()) {
return rs.getInt("maker_id");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (maker == null) {
throw new IllegalArgumentException(errorMessage);
}
return maker;
}
private boolean geometryExists(String gmlId) {
String sql = "SELECT * FROM bzk.geometrie WHERE geometrie_id = ?";
String errorMessage = "Kon niet bepalen of de geometrie met id '" + gmlId + "' al bestaat";
return jdbcTemplate.query(
sql,
ps -> ps.setString(1, gmlId),
(rs, rowNum) -> rs.getInt(1)
).stream().findFirst().isPresent();
}
private int insertGeometry(String gmlId, String naam, String gml) {
String sql =
"INSERT INTO bzk.geometrie (naam, geometrie_id, geometrie) " +
"VALUES (?, ?, ST_GEOMFROMGML(?, 28992)) " +
"RETURNING id";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
conn -> {
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, naam);
ps.setString(2, gmlId);
ps.setString(3, gml);
return ps;
},
keyHolder
);
return Optional.ofNullable(keyHolder.getKey())
.map(Number::intValue)
.orElseThrow(() -> new IllegalStateException("Er ging iets mis bij het inserten van de geometrie " + gmlId));
}
private int getGeometrieId(String gmlId) {
String sql = "SELECT id FROM bzk.geometrie WHERE geometrie_id = ?";
String errorMessage = "Kon de id van de geometrie '" + gmlId + "' niet ophalen";
Integer id = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setString(1, gmlId),
rs -> {
if (rs.next()) {
return rs.getInt("id");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (id == null) {
throw new IllegalArgumentException(errorMessage);
}
return id;
}
private String getGeometryType(int geometrieId) {
String sql = "SELECT ST_GEOMETRYTYPE(geometrie) geom_type FROM bzk.geometrie WHERE id = ?";
String errorMessage = "Kon het type van de geometrie niet bepalen";
String geometryType = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, geometrieId),
rs -> {
if (rs.next()) {
String type = rs.getString("geom_type").toLowerCase();
if (type.contains("polygon")) {
return "vlak";
} else if (type.contains("line")) {
return "lijn";
} else if (type.contains("point")) {
return "punt";
}
}
throw new IllegalArgumentException(errorMessage);
}
);
if (geometryType == null) {
throw new IllegalArgumentException(errorMessage);
}
return geometryType;
}
private String getLocatieGeometryType(int locatieId) {
String sql = "SELECT geometrietype FROM bzk.locatie WHERE id = ?";
String errorMessage = "Kon het geometrietype van de locatie niet bepalen";
String geometryType = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, locatieId),
rs -> {
if (rs.next()) {
return rs.getString("geometrietype");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (geometryType == null) {
throw new IllegalArgumentException(errorMessage);
}
return geometryType;
}
private int getLocatieId(int geometrieId) {
String sql = "SELECT id FROM bzk.locatie WHERE geometrie_id = ?";
String errorMessage = "Kon de id van de locatie niet ophalen";
Integer id = jdbcTemplate.query(
conn -> conn.prepareStatement(sql),
ps -> ps.setInt(1, geometrieId),
rs -> {
if (rs.next()) {
return rs.getInt("id");
}
throw new IllegalArgumentException(errorMessage);
}
);
if (id == null) {
throw new IllegalArgumentException(errorMessage);
}
return id;
}
private int insertLocatie(String name, LocalDate dateStart, int regelingId, String geometryType, int geometryId, String bgCode) {
String sql =
"INSERT INTO bzk.locatie (naam, datum_begin, ind_groep_jn, regeling_id, geometrietype, geometrie_id, identificatie) " +
"VALUES (?, ?, false, ?, ?, ?, ?) " +
"RETURNING id";
KeyHolder keyHolder = new GeneratedKeyHolder();
String objectType = "vlak".equals(geometryType) ? "gebied" : geometryType;
String identificatie = "nl.imow-" + bgCode + "." + objectType + "." + UUID.randomUUID().toString().replace("-", "").toLowerCase();
jdbcTemplate.update(
conn -> {
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, name);
ps.setDate(2, Date.valueOf(dateStart));
ps.setInt(3, regelingId);
ps.setString(4, geometryType);
ps.setInt(5, geometryId);
ps.setString(6, identificatie);
return ps;
},
keyHolder
);
return Optional.ofNullable(keyHolder.getKey())
.map(Number::intValue)
.orElseThrow(() -> new IllegalStateException("Er ging iets mis bij het inserten van de locatie"));
}
private int insertLocatie(String name, LocalDate dateStart, int regelingId, String geometryType, String bgCode) {
String sql =
"INSERT INTO bzk.locatie (naam, datum_begin, ind_groep_jn, regeling_id, geometrietype, identificatie) " +
"VALUES (?, ?, true, ?, ?, ?) " +
"RETURNING id";
KeyHolder keyHolder = new GeneratedKeyHolder();
String objectType = "vlak".equals(geometryType) ? "gebied" : geometryType;
String identificatie = "nl.imow-" + bgCode + "." + objectType + "engroep." + UUID.randomUUID().toString().replace("-", "").toLowerCase();
jdbcTemplate.update(
conn -> {
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, name);
ps.setDate(2, Date.valueOf(dateStart));
ps.setInt(3, regelingId);
ps.setString(4, geometryType);
ps.setString(5, identificatie);
return ps;
},
keyHolder
);
return Optional.ofNullable(keyHolder.getKey())
.map(Number::intValue)
.orElseThrow(() -> new IllegalStateException("Er ging iets mis bij het inserten van de locatie"));
}
private void linkLocatieToGroep(int locatieId, int locatieGroepId) {
String sql = "INSERT INTO bzk.groep_locatie (locatiegroep_id, locatie_id) VALUES (?, ?)";
jdbcTemplate.update(sql, ps -> {
ps.setInt(1, locatieGroepId);
ps.setInt(2, locatieId);
});
}
private void insertInformatieObjectVersie(String frbrWork, String frbrExpression, int regelingId, int eindverantwoordelijkeId,
int makerId, String gioName, String achtergrondVerwijzing, String achergrondActualiteit, String nauwkeurigheid,
int locatieId) {
String sql =
"INSERT INTO bzk.informatieobjectversie (frbr_work, frbr_expression, soort_work_id, regeling_id, eindverantwoordelijke_id, maker_id, " +
"formaat_informatieobject_id, naam, officiele_titel, publicatie_instructie_id, stop_schema_versie, achtergrond_verwijzing, " +
"achtergrond_actualiteit, nauwkeurigheid, locatie_id) " +
"VALUES (?, ?, 2056, ?, ?, ?, 1410, ?, ?, 3, '1.3.0', ?, ?, ?, ?)";
jdbcTemplate.update(sql, ps -> {
ps.setObject(1, frbrWork);
ps.setObject(2, frbrExpression);
ps.setObject(3, regelingId);
ps.setObject(4, eindverantwoordelijkeId);
ps.setObject(5, makerId);
ps.setObject(6, gioName);
ps.setObject(7, frbrWork);
ps.setObject(8, achtergrondVerwijzing);
ps.setObject(9, achergrondActualiteit != null ? Date.valueOf(achergrondActualiteit) : null);
ps.setObject(10, nauwkeurigheid != null ? Integer.parseInt(nauwkeurigheid) : null);
ps.setObject(11, locatieId);
});
}
private static class XPathBuilder {
private final Map<String, String> namespaces = new HashMap<>();
public XPathBuilder xmlns(String prefix, String namespaceURI) {
namespaces.put(prefix, namespaceURI);
return this;
}
public XPath build() {
XPath xp = XPathFactory.newInstance().newXPath();
xp.setNamespaceContext(new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
return namespaces.get(prefix);
}
@Override
public String getPrefix(String namespaceURI) {
return getPrefixes(namespaceURI).next();
}
@Override
public Iterator<String> getPrefixes(String namespaceURI) {
return namespaces.entrySet().stream()
.filter(entry -> entry.getValue().equals(namespaceURI))
.map(Map.Entry::getKey)
.iterator();
}
});
return xp;
}
}
}
|
75735_0 | package com.github.idragonfire.DragonAntiPvPLeaver.npclib;
import net.minecraft.server.v1_7_R4.EntityPlayer;
import net.minecraft.server.v1_7_R4.EnumGamemode;
import net.minecraft.server.v1_7_R4.PlayerInteractManager;
import net.minecraft.server.v1_7_R4.World;
import net.minecraft.server.v1_7_R4.WorldServer;
import net.minecraft.util.com.mojang.authlib.GameProfile;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftEntity;
/**
* Bukkit:
* "https://github.com/Bukkit/CraftBukkit/blob/master/src/main/java/net/minecraft/server/EntityPlayer.java"
* caliog:
* "https://github.com/caliog/NPCLib/blob/master/com/sharesc/caliog/npclib/NPCEntity.java"
* Citiziens:
* "https://github.com/CitizensDev/Citizens2/blob/master/src/main/java/net/citizensnpcs/npc/entity/EntityHumanNPC.java"
* Combat-Tag:
* "https://github.com/cheddar262/Combat-Tag/blob/master/CombatTag/com/topcat/npclib/nms/NPCEntity.java"
* Top-Cat:
* "https://github.com/Top-Cat/NPCLib/blob/master/src/main/java/com/topcat/npclib/nms/NPCEntity.java"
* lennis0012:
* "https://github.com/lenis0012/NPCFactory/blob/master/src/main/java/com/lenis0012/bukkit/npc/NPCEntity.java"
*/
public class NPCEntity extends EntityPlayer {
public NPCEntity(World world, GameProfile g,
PlayerInteractManager itemInWorldManager) {
super(world.getServer().getServer(), (WorldServer) world, g,
itemInWorldManager);
itemInWorldManager.b(EnumGamemode.SURVIVAL);
this.playerConnection = new NPCNetHandler(
world.getServer().getServer(), this);
}
public void setBukkitEntity(org.bukkit.entity.Entity entity) {
bukkitEntity = (CraftEntity) entity;
}
}
| IDragonfire/DragonAntiPvPLeaver | src/com/github/idragonfire/DragonAntiPvPLeaver/npclib/NPCEntity.java | 649 | /**
* Bukkit:
* "https://github.com/Bukkit/CraftBukkit/blob/master/src/main/java/net/minecraft/server/EntityPlayer.java"
* caliog:
* "https://github.com/caliog/NPCLib/blob/master/com/sharesc/caliog/npclib/NPCEntity.java"
* Citiziens:
* "https://github.com/CitizensDev/Citizens2/blob/master/src/main/java/net/citizensnpcs/npc/entity/EntityHumanNPC.java"
* Combat-Tag:
* "https://github.com/cheddar262/Combat-Tag/blob/master/CombatTag/com/topcat/npclib/nms/NPCEntity.java"
* Top-Cat:
* "https://github.com/Top-Cat/NPCLib/blob/master/src/main/java/com/topcat/npclib/nms/NPCEntity.java"
* lennis0012:
* "https://github.com/lenis0012/NPCFactory/blob/master/src/main/java/com/lenis0012/bukkit/npc/NPCEntity.java"
*/ | block_comment | nl | package com.github.idragonfire.DragonAntiPvPLeaver.npclib;
import net.minecraft.server.v1_7_R4.EntityPlayer;
import net.minecraft.server.v1_7_R4.EnumGamemode;
import net.minecraft.server.v1_7_R4.PlayerInteractManager;
import net.minecraft.server.v1_7_R4.World;
import net.minecraft.server.v1_7_R4.WorldServer;
import net.minecraft.util.com.mojang.authlib.GameProfile;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftEntity;
/**
* Bukkit:
*<SUF>*/
public class NPCEntity extends EntityPlayer {
public NPCEntity(World world, GameProfile g,
PlayerInteractManager itemInWorldManager) {
super(world.getServer().getServer(), (WorldServer) world, g,
itemInWorldManager);
itemInWorldManager.b(EnumGamemode.SURVIVAL);
this.playerConnection = new NPCNetHandler(
world.getServer().getServer(), this);
}
public void setBukkitEntity(org.bukkit.entity.Entity entity) {
bukkitEntity = (CraftEntity) entity;
}
}
|
179566_15 | package fr.ign.cogit.cartagen.agents.gael.deformation;
import java.util.ArrayList;
import java.util.Set;
import fr.ign.cogit.cartagen.agents.gael.deformation.submicro.GAELPointSingleton;
import fr.ign.cogit.cartagen.agents.gael.deformation.submicro.GAELSegment;
import fr.ign.cogit.cartagen.agents.gael.deformation.submicro.ISubMicro;
import fr.ign.cogit.cartagen.agents.gael.field.agent.FieldAgent;
import fr.ign.cogit.cartagen.agents.gael.field.agent.relief.ContourLineAgent;
import fr.ign.cogit.cartagen.graph.triangulation.TriangulationPoint;
import fr.ign.cogit.geoxygene.api.feature.IFeature;
import fr.ign.cogit.geoxygene.api.spatial.coordgeom.IDirectPosition;
import fr.ign.cogit.geoxygene.api.spatial.coordgeom.IDirectPositionList;
import fr.ign.cogit.geoxygene.api.spatial.geomprim.IPoint;
import fr.ign.cogit.geoxygene.contrib.agents.action.ActionProposal;
import fr.ign.cogit.geoxygene.contrib.agents.agent.IAgent;
import fr.ign.cogit.geoxygene.contrib.agents.state.AgentState;
import fr.ign.cogit.geoxygene.contrib.graphe.INode;
/**
* The point fieldAgent class.
* @author julien Gaffuri 26 juil. 2005
*/
public interface IPointAgent extends IAgent, TriangulationPoint, IFeature {
INode getGraphNode();
IDirectPositionList getPositions();
IDirectPosition getPosition();
void updatePosition(IDirectPosition pos);
double getX();
void setX(double x);
double getY();
void setY(double y);
double getZ();
double getZIni();
/**
* @return
*/
@Override
IDirectPosition getPositionIni();
double getXIni();
double getYIni();
@Override
IPoint getGeom();
ArrayList<PointAgentState> getEtats();
void effacerEtats();
boolean isDansListe();
void setDansListe(boolean dansListe);
/**
* @return
*/
ArrayList<ISubMicro> getSubmicros();
/**
* @return
*/
GAELPointSingleton getPointSingleton();
/**
* @param pointSingleton
*/
void setPointSingleton(GAELPointSingleton pointSingleton);
/**
* @return
*/
boolean isFixe();
/**
* @param fixe
*/
void setFixe(boolean fixe);
/**
* @return
*/
boolean isSelectionne();
/**
* @param selectionne
*/
void setSelectionne(boolean selectionne);
/**
* @return
*/
double getSommeImportances();
void incrementerSommeImportances(double dimp);
@Override
int getIndex();
@Override
void setIndex(int posTri);
/**
* @return
*/
ArrayList<IPointAgent> getAgentPointAccointants();
void addAgentPointAccointants(IPointAgent ap);
/**
* @return la courbe de niveau eventuelle a laquelle le point appartient
*/
ContourLineAgent getCourbeDeNiveau();
/**
* @return
*/
GAELLinkableFeature getLinkedFeature();
/**
* @param linkedFeature
*/
void setLinkedFeature(GAELLinkableFeature linkedFeature);
@Override
void clean();
@Override
void goBackToState(AgentState ea);
void goBackToState(PointAgentState eap);
double getDistance(GAELSegment s);
double getDistance(double x_, double y_);
double getDistance(IPointAgent p);
double getDistanceCourante(GAELSegment s);
IDirectPosition getProj(GAELSegment s);
double getDistanceInitiale(double x_, double y_);
double getDistanceCourante(double x_, double y_);
double getDistanceInitiale(IPointAgent p);
double getDistanceCourante(IPointAgent p);
double getDistanceAPositionInitiale();
double getInitialOrientation(IPointAgent p);
/**
* orientation de this a p, en radians entre -PI et PI
* @param p
* @return
*/
double getOrientation(IPointAgent p);
double getOrientationEcart(IPointAgent p);
@Override
boolean isLinkedBySegment(TriangulationPoint point);
@Override
void run();
@Override
void updateActionProposals();
void updateForces();
void computeForces();
Set<ActionProposal> getForces();
double getDistancesFromBalance();
boolean satisfactionParfaite();
@Override
String toString();
/*
* (non-Javadoc)
*
* @see fr.ign.cogit.agentgeoxygene.agent.Agent#getFeature()
*/
/**
* @return
*/
IFeature getFeature();
/*
* (non-Javadoc)
*
* @see
* fr.ign.cogit.agentgeoxygene.agent.Agent#setFeature(fr.ign.cogit.geoxygene
* .api.feature.IFeature)
*/
/**
* @param feature
*/
void setFeature(IFeature feature);
void setFieldAgent(FieldAgent agent);
FieldAgent getFieldAgent();
}
| IGNF/CartAGen | cartagen-core/src/main/java/fr/ign/cogit/cartagen/agents/gael/deformation/IPointAgent.java | 1,740 | /*
* (non-Javadoc)
*
* @see fr.ign.cogit.agentgeoxygene.agent.Agent#getFeature()
*/ | block_comment | nl | package fr.ign.cogit.cartagen.agents.gael.deformation;
import java.util.ArrayList;
import java.util.Set;
import fr.ign.cogit.cartagen.agents.gael.deformation.submicro.GAELPointSingleton;
import fr.ign.cogit.cartagen.agents.gael.deformation.submicro.GAELSegment;
import fr.ign.cogit.cartagen.agents.gael.deformation.submicro.ISubMicro;
import fr.ign.cogit.cartagen.agents.gael.field.agent.FieldAgent;
import fr.ign.cogit.cartagen.agents.gael.field.agent.relief.ContourLineAgent;
import fr.ign.cogit.cartagen.graph.triangulation.TriangulationPoint;
import fr.ign.cogit.geoxygene.api.feature.IFeature;
import fr.ign.cogit.geoxygene.api.spatial.coordgeom.IDirectPosition;
import fr.ign.cogit.geoxygene.api.spatial.coordgeom.IDirectPositionList;
import fr.ign.cogit.geoxygene.api.spatial.geomprim.IPoint;
import fr.ign.cogit.geoxygene.contrib.agents.action.ActionProposal;
import fr.ign.cogit.geoxygene.contrib.agents.agent.IAgent;
import fr.ign.cogit.geoxygene.contrib.agents.state.AgentState;
import fr.ign.cogit.geoxygene.contrib.graphe.INode;
/**
* The point fieldAgent class.
* @author julien Gaffuri 26 juil. 2005
*/
public interface IPointAgent extends IAgent, TriangulationPoint, IFeature {
INode getGraphNode();
IDirectPositionList getPositions();
IDirectPosition getPosition();
void updatePosition(IDirectPosition pos);
double getX();
void setX(double x);
double getY();
void setY(double y);
double getZ();
double getZIni();
/**
* @return
*/
@Override
IDirectPosition getPositionIni();
double getXIni();
double getYIni();
@Override
IPoint getGeom();
ArrayList<PointAgentState> getEtats();
void effacerEtats();
boolean isDansListe();
void setDansListe(boolean dansListe);
/**
* @return
*/
ArrayList<ISubMicro> getSubmicros();
/**
* @return
*/
GAELPointSingleton getPointSingleton();
/**
* @param pointSingleton
*/
void setPointSingleton(GAELPointSingleton pointSingleton);
/**
* @return
*/
boolean isFixe();
/**
* @param fixe
*/
void setFixe(boolean fixe);
/**
* @return
*/
boolean isSelectionne();
/**
* @param selectionne
*/
void setSelectionne(boolean selectionne);
/**
* @return
*/
double getSommeImportances();
void incrementerSommeImportances(double dimp);
@Override
int getIndex();
@Override
void setIndex(int posTri);
/**
* @return
*/
ArrayList<IPointAgent> getAgentPointAccointants();
void addAgentPointAccointants(IPointAgent ap);
/**
* @return la courbe de niveau eventuelle a laquelle le point appartient
*/
ContourLineAgent getCourbeDeNiveau();
/**
* @return
*/
GAELLinkableFeature getLinkedFeature();
/**
* @param linkedFeature
*/
void setLinkedFeature(GAELLinkableFeature linkedFeature);
@Override
void clean();
@Override
void goBackToState(AgentState ea);
void goBackToState(PointAgentState eap);
double getDistance(GAELSegment s);
double getDistance(double x_, double y_);
double getDistance(IPointAgent p);
double getDistanceCourante(GAELSegment s);
IDirectPosition getProj(GAELSegment s);
double getDistanceInitiale(double x_, double y_);
double getDistanceCourante(double x_, double y_);
double getDistanceInitiale(IPointAgent p);
double getDistanceCourante(IPointAgent p);
double getDistanceAPositionInitiale();
double getInitialOrientation(IPointAgent p);
/**
* orientation de this a p, en radians entre -PI et PI
* @param p
* @return
*/
double getOrientation(IPointAgent p);
double getOrientationEcart(IPointAgent p);
@Override
boolean isLinkedBySegment(TriangulationPoint point);
@Override
void run();
@Override
void updateActionProposals();
void updateForces();
void computeForces();
Set<ActionProposal> getForces();
double getDistancesFromBalance();
boolean satisfactionParfaite();
@Override
String toString();
/*
* (non-Javadoc)
<SUF>*/
/**
* @return
*/
IFeature getFeature();
/*
* (non-Javadoc)
*
* @see
* fr.ign.cogit.agentgeoxygene.agent.Agent#setFeature(fr.ign.cogit.geoxygene
* .api.feature.IFeature)
*/
/**
* @param feature
*/
void setFeature(IFeature feature);
void setFieldAgent(FieldAgent agent);
FieldAgent getFieldAgent();
}
|
77092_6 | package org.socialhistory.solr.importer;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.log4j.Logger;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.*;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
/**
* Mass import of files into the index
* <p/>
* args:
* 0=folder containing files with a record; or catalog with records;
* 1=SOLR update url with core, like http://localhost:8080/solr/all/update
* 2=comma separated xslt stylesheets: first must be an identity template
* 3=xslt parameters
*/
public class BatchImport {
private File urlOrigin;
private final String urlResource;
private final List<Transformer> tChain;
private int counter = 0;
final HttpClient httpclient = new HttpClient();
private final boolean debug;
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
public BatchImport(String urlResource, String _xslts, String _parameters) throws TransformerConfigurationException {
this.debug = Boolean.parseBoolean(System.getProperty("debug", "false"));
this.urlResource = urlResource;
final String[] parameters = _parameters.split("[,;]");
final String[] xslts = _xslts.split("[,;]");
tChain = new ArrayList<>(xslts.length + 1);
final TransformerFactory tf = TransformerFactory.newInstance();
tChain.add(tf.newTransformer());
for (String xslt : xslts) {
File file = new File(xslt);
Source source = new StreamSource(file);
final Transformer t = tf.newTransformer(source);
t.setParameter("sheet", file.getName());
for (String parameter : parameters) {
String[] split = parameter.split(":");
t.setParameter(split[0], split[1]);
}
tChain.add(t);
if (debug) log.info("xslt stylesheet: " + file.getAbsolutePath());
}
}
public void process(File f) throws FileNotFoundException, XMLStreamException {
if (f.isFile()) { // everything comes from one catalog file
final XMLInputFactory xif = XMLInputFactory.newInstance();
final FileInputStream inputStream = new FileInputStream(f);
final XMLStreamReader xsr = xif.createXMLStreamReader(inputStream, "utf-8");
while (xsr.hasNext()) {
if (xsr.getEventType() == XMLStreamReader.START_ELEMENT) {
String elementName = xsr.getLocalName();
if ("record".equals(elementName)) {
try {
final byte[] record = process(identity(xsr), null);
sendSolrDocument(record);
} catch (IOException | TransformerException e) {
log.warn(e);
}
} else {
xsr.next();
}
} else {
xsr.next();
}
}
} else { // everything comes from files within a directory
final File[] files = f.listFiles();
if (files == null) throw new FileNotFoundException("Folder has no files: " + f.getAbsolutePath());
for (File file : files) {
try {
byte[] origin = findOrigin(file);
if (urlOrigin != null && origin.length == 0) {
log.warn("Negeer: geen origineel document gevonden bij " + file.getAbsolutePath());
} else {
origin = convertRecord(tChain.get(1), origin); // assumption: the first is normalization of prefix\
final byte[] record = process(Files.readAllBytes(file.toPath()), origin, datestamp(file.lastModified()));
sendSolrDocument(record);
}
} catch (IOException | TransformerException e) {
log.warn(file.getAbsolutePath());
log.warn(e);
}
}
}
}
// Een origin file is simpelweg een file parallel naast de aangeboden file.
// Als we die vinden in een ander pad met dezelfde filenaam, dan gebruiken we die.
//
// Voorbeeld:
// file: /a/b/c/d/e/f/12345.xml
// parent: /a/b/c/d/e/f
// zoek en vind: /a/b/c/d/e/h/12345.xml
private byte[] findOrigin(final File file) throws IOException {
if (urlOrigin == null) { // cache origin root
final File parent = file.getParentFile();// in het voorbeeld is dit /a/b/c/d/e/f
final File root = parent.getParentFile();// in het voorbeeld is dit /a/b/c/d/e
for (File folder : Objects.requireNonNull(root.listFiles(pathname -> {
return pathname.isDirectory()
&& !pathname.getAbsolutePath().equalsIgnoreCase(parent.getAbsolutePath()); // we willen de andere folders vinden
}))) {
final File candidate = new File(folder, file.getName());
if (candidate.exists() && candidate.isFile()) {
urlOrigin = new File(folder.getAbsolutePath());
break;
}
}
if (urlOrigin == null) urlOrigin = new File("dummy");
}
if (urlOrigin.exists()) {
final File candidate = new File(urlOrigin, file.getName());
return (candidate.exists()) ? Files.readAllBytes(candidate.toPath()) : new byte[]{};
}
return new byte[]{};
}
private byte[] process(byte[] record, byte[] origin) throws IOException, TransformerException {
return process(record, origin, datestamp( new Date().getTime()));
}
private byte[] process(byte[] record, byte[] origin, String datestamp) throws IOException, TransformerException {
String resource = null;
for (int i = 1; i < tChain.size(); i++) { // from second sheet. Skip the inbuilt identity template
tChain.get(i).setParameter("datestamp", datestamp);
if (i == tChain.size() - 1) { // last sheet, add resources and original
tChain.get(i).setParameter("resource", resource);
if (origin != null && origin.length != 0) {
final String doc = new String(origin, StandardCharsets.UTF_8);
tChain.get(i).setParameter("original", doc);
}
}
record = convertRecord(tChain.get(i), record);
if (i == tChain.size() - 3) { // before the penultimate sheet
resource = new String(record, StandardCharsets.UTF_8);
}
}
return record;
}
private void sendSolrDocument(byte[] record) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(record.length + 11);
baos.write(record);
if (debug) {
final String doc = new String(baos.toByteArray(), StandardCharsets.UTF_8);
System.out.println(doc);
}
final PostMethod post = new PostMethod(urlResource);
final RequestEntity entity = new ByteArrayRequestEntity(baos.toByteArray(), "text/xml; charset=utf-8");
post.setRequestEntity(entity);
log.info("Sending " + ++counter);
try {
httpclient.executeMethod(post);
} catch (Exception e) {
log.warn(e);
} finally {
post.releaseConnection();
}
}
private byte[] convertRecord(Transformer transformer, byte[] record) throws TransformerException {
final StreamSource source = new StreamSource(new ByteArrayInputStream(record));
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(source, new StreamResult(baos));
transformer.reset();
final byte[] bytes = baos.toByteArray();
if (debug) {
final String s = new String(bytes, StandardCharsets.UTF_8);
log.info("xslt result: " + s);
}
return bytes;
}
private byte[] identity(XMLStreamReader xsr) throws TransformerException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
tChain.get(0).transform(new StAXSource(xsr), new StreamResult(baos));
return baos.toByteArray();
}
private String datestamp(long time) {
final Date date = new Date(time);
return simpleDateFormat.format(date);
}
public static void main(String[] args) throws Exception {
if (args.length != 4) {
System.err.println("Expect: 'file' to resource or folder with resource docuemnts; 'url' to solr; 'xslt' list; 'parameters'");
System.exit(1);
}
File file = new File(args[0]);
if (!file.exists()) {
System.err.println("File or folder not found: " + args[0]);
System.exit(1);
}
final String url = args[1];
final String xslt = args[2]; // het eerste sheet is een identity sheet.
final String parameters = args[3];
final BatchImport importer = new BatchImport(url, xslt, parameters);
importer.process(file);
}
private final Logger log = Logger.getLogger(getClass().getName());
} | IISH/api | import/src/main/java/org/socialhistory/solr/importer/BatchImport.java | 2,680 | // zoek en vind: /a/b/c/d/e/h/12345.xml | line_comment | nl | package org.socialhistory.solr.importer;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.log4j.Logger;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.*;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
/**
* Mass import of files into the index
* <p/>
* args:
* 0=folder containing files with a record; or catalog with records;
* 1=SOLR update url with core, like http://localhost:8080/solr/all/update
* 2=comma separated xslt stylesheets: first must be an identity template
* 3=xslt parameters
*/
public class BatchImport {
private File urlOrigin;
private final String urlResource;
private final List<Transformer> tChain;
private int counter = 0;
final HttpClient httpclient = new HttpClient();
private final boolean debug;
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
public BatchImport(String urlResource, String _xslts, String _parameters) throws TransformerConfigurationException {
this.debug = Boolean.parseBoolean(System.getProperty("debug", "false"));
this.urlResource = urlResource;
final String[] parameters = _parameters.split("[,;]");
final String[] xslts = _xslts.split("[,;]");
tChain = new ArrayList<>(xslts.length + 1);
final TransformerFactory tf = TransformerFactory.newInstance();
tChain.add(tf.newTransformer());
for (String xslt : xslts) {
File file = new File(xslt);
Source source = new StreamSource(file);
final Transformer t = tf.newTransformer(source);
t.setParameter("sheet", file.getName());
for (String parameter : parameters) {
String[] split = parameter.split(":");
t.setParameter(split[0], split[1]);
}
tChain.add(t);
if (debug) log.info("xslt stylesheet: " + file.getAbsolutePath());
}
}
public void process(File f) throws FileNotFoundException, XMLStreamException {
if (f.isFile()) { // everything comes from one catalog file
final XMLInputFactory xif = XMLInputFactory.newInstance();
final FileInputStream inputStream = new FileInputStream(f);
final XMLStreamReader xsr = xif.createXMLStreamReader(inputStream, "utf-8");
while (xsr.hasNext()) {
if (xsr.getEventType() == XMLStreamReader.START_ELEMENT) {
String elementName = xsr.getLocalName();
if ("record".equals(elementName)) {
try {
final byte[] record = process(identity(xsr), null);
sendSolrDocument(record);
} catch (IOException | TransformerException e) {
log.warn(e);
}
} else {
xsr.next();
}
} else {
xsr.next();
}
}
} else { // everything comes from files within a directory
final File[] files = f.listFiles();
if (files == null) throw new FileNotFoundException("Folder has no files: " + f.getAbsolutePath());
for (File file : files) {
try {
byte[] origin = findOrigin(file);
if (urlOrigin != null && origin.length == 0) {
log.warn("Negeer: geen origineel document gevonden bij " + file.getAbsolutePath());
} else {
origin = convertRecord(tChain.get(1), origin); // assumption: the first is normalization of prefix\
final byte[] record = process(Files.readAllBytes(file.toPath()), origin, datestamp(file.lastModified()));
sendSolrDocument(record);
}
} catch (IOException | TransformerException e) {
log.warn(file.getAbsolutePath());
log.warn(e);
}
}
}
}
// Een origin file is simpelweg een file parallel naast de aangeboden file.
// Als we die vinden in een ander pad met dezelfde filenaam, dan gebruiken we die.
//
// Voorbeeld:
// file: /a/b/c/d/e/f/12345.xml
// parent: /a/b/c/d/e/f
// zoek en<SUF>
private byte[] findOrigin(final File file) throws IOException {
if (urlOrigin == null) { // cache origin root
final File parent = file.getParentFile();// in het voorbeeld is dit /a/b/c/d/e/f
final File root = parent.getParentFile();// in het voorbeeld is dit /a/b/c/d/e
for (File folder : Objects.requireNonNull(root.listFiles(pathname -> {
return pathname.isDirectory()
&& !pathname.getAbsolutePath().equalsIgnoreCase(parent.getAbsolutePath()); // we willen de andere folders vinden
}))) {
final File candidate = new File(folder, file.getName());
if (candidate.exists() && candidate.isFile()) {
urlOrigin = new File(folder.getAbsolutePath());
break;
}
}
if (urlOrigin == null) urlOrigin = new File("dummy");
}
if (urlOrigin.exists()) {
final File candidate = new File(urlOrigin, file.getName());
return (candidate.exists()) ? Files.readAllBytes(candidate.toPath()) : new byte[]{};
}
return new byte[]{};
}
private byte[] process(byte[] record, byte[] origin) throws IOException, TransformerException {
return process(record, origin, datestamp( new Date().getTime()));
}
private byte[] process(byte[] record, byte[] origin, String datestamp) throws IOException, TransformerException {
String resource = null;
for (int i = 1; i < tChain.size(); i++) { // from second sheet. Skip the inbuilt identity template
tChain.get(i).setParameter("datestamp", datestamp);
if (i == tChain.size() - 1) { // last sheet, add resources and original
tChain.get(i).setParameter("resource", resource);
if (origin != null && origin.length != 0) {
final String doc = new String(origin, StandardCharsets.UTF_8);
tChain.get(i).setParameter("original", doc);
}
}
record = convertRecord(tChain.get(i), record);
if (i == tChain.size() - 3) { // before the penultimate sheet
resource = new String(record, StandardCharsets.UTF_8);
}
}
return record;
}
private void sendSolrDocument(byte[] record) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(record.length + 11);
baos.write(record);
if (debug) {
final String doc = new String(baos.toByteArray(), StandardCharsets.UTF_8);
System.out.println(doc);
}
final PostMethod post = new PostMethod(urlResource);
final RequestEntity entity = new ByteArrayRequestEntity(baos.toByteArray(), "text/xml; charset=utf-8");
post.setRequestEntity(entity);
log.info("Sending " + ++counter);
try {
httpclient.executeMethod(post);
} catch (Exception e) {
log.warn(e);
} finally {
post.releaseConnection();
}
}
private byte[] convertRecord(Transformer transformer, byte[] record) throws TransformerException {
final StreamSource source = new StreamSource(new ByteArrayInputStream(record));
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(source, new StreamResult(baos));
transformer.reset();
final byte[] bytes = baos.toByteArray();
if (debug) {
final String s = new String(bytes, StandardCharsets.UTF_8);
log.info("xslt result: " + s);
}
return bytes;
}
private byte[] identity(XMLStreamReader xsr) throws TransformerException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
tChain.get(0).transform(new StAXSource(xsr), new StreamResult(baos));
return baos.toByteArray();
}
private String datestamp(long time) {
final Date date = new Date(time);
return simpleDateFormat.format(date);
}
public static void main(String[] args) throws Exception {
if (args.length != 4) {
System.err.println("Expect: 'file' to resource or folder with resource docuemnts; 'url' to solr; 'xslt' list; 'parameters'");
System.exit(1);
}
File file = new File(args[0]);
if (!file.exists()) {
System.err.println("File or folder not found: " + args[0]);
System.exit(1);
}
final String url = args[1];
final String xslt = args[2]; // het eerste sheet is een identity sheet.
final String parameters = args[3];
final BatchImport importer = new BatchImport(url, xslt, parameters);
importer.process(file);
}
private final Logger log = Logger.getLogger(getClass().getName());
} |
178028_33 | package org.socialhistoryservices.delivery.reservation.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.socialhistoryservices.delivery.config.PrinterConfiguration;
import org.socialhistoryservices.delivery.record.entity.ExternalRecordInfo;
import org.socialhistoryservices.delivery.record.entity.Holding;
import org.socialhistoryservices.delivery.record.entity.Record;
import org.socialhistoryservices.delivery.request.entity.HoldingRequest;
import org.socialhistoryservices.delivery.request.entity.Request;
import org.socialhistoryservices.delivery.request.service.*;
import org.socialhistoryservices.delivery.reservation.dao.HoldingReservationDAO;
import org.socialhistoryservices.delivery.reservation.dao.ReservationDAO;
import org.socialhistoryservices.delivery.reservation.entity.HoldingReservation;
import org.socialhistoryservices.delivery.reservation.entity.Reservation;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import javax.persistence.Tuple;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import java.awt.print.PrinterException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Represents the service of the reservation package.
*/
@Service
@Transactional
public class ReservationServiceImpl extends AbstractRequestService implements ReservationService {
private static final Logger LOGGER = LoggerFactory.getLogger(ReservationServiceImpl.class);
@Autowired
private ReservationDAO reservationDAO;
@Autowired
private HoldingReservationDAO holdingReservationDAO;
@Autowired
private ReservationDateExceptionService dateExceptionService;
@Autowired
private BeanFactory bf;
@Autowired
private PrinterConfiguration printerConfiguration;
/**
* Add a Reservation to the database.
*
* @param obj Reservation to add.
*/
public void addReservation(Reservation obj) {
// Make sure the holdings get set to the correct status.
updateStatusAndAssociatedHoldingStatus(obj, obj.getStatus());
// Add to the database
reservationDAO.add(obj);
}
/**
* Remove a Reservation from the database.
*
* @param obj Reservation to remove.
*/
public void removeReservation(Reservation obj) {
// Set all holdings linked to this reservation back to AVAILABLE if
// this is a PENDING/ACTIVE reservation.
// Note that we are in a transaction here, so it does not matter the
// records are still linked to the reservation when setting them to available.
if (obj.getStatus() != Reservation.Status.COMPLETED) {
changeHoldingStatus(obj, Holding.Status.AVAILABLE);
}
reservationDAO.remove(obj);
}
/**
* Change the status of all holdings in a reservation.
*
* @param res Reservation to change status for.
* @param status Status to change holdings to.
*/
public void changeHoldingStatus(Reservation res, Holding.Status status) {
super.changeHoldingStatus(res, status);
updateHoldingStatusForPendingReservations(res);
saveReservation(res);
}
/**
* Save changes to a Reservation in the database.
*
* @param obj Reservation to save.
*/
public Reservation saveReservation(Reservation obj) {
return reservationDAO.save(obj);
}
/**
* Retrieve the Reservation matching the given Id.
*
* @param id Id of the Reservation to retrieve.
* @return The Reservation matching the Id.
*/
public Reservation getReservationById(int id) {
return reservationDAO.getById(id);
}
/**
* Get a criteria builder for querying Reservations.
*
* @return the CriteriaBuilder.
*/
public CriteriaBuilder getReservationCriteriaBuilder() {
return reservationDAO.getCriteriaBuilder();
}
/**
* Get a criteria builder for querying HoldingReservations.
*
* @return the CriteriaBuilder.
*/
public CriteriaBuilder getHoldingReservationCriteriaBuilder() {
return holdingReservationDAO.getCriteriaBuilder();
}
/**
* List all Reservations matching a built query.
*
* @param q The criteria query to execute
* @return A list of matching Reservations.
*/
public List<Reservation> listReservations(CriteriaQuery<Reservation> q) {
return reservationDAO.list(q);
}
/**
* List all Tuples matching a built query.
*
* @param q The criteria query to execute
* @return A list of matching Tuples.
*/
public List<Tuple> listTuples(CriteriaQuery<Tuple> q) {
return reservationDAO.listForTuple(q);
}
/**
* List all HoldingReservations matching a built query.
*
* @param q The criteria query to execute
* @return A list of matching HoldingReservations.
*/
public List<HoldingReservation> listHoldingReservations(CriteriaQuery<HoldingReservation> q) {
return holdingReservationDAO.list(q);
}
/**
* List all HoldingReservations matching a built query.
*
* @param q The criteria query to execute
* @param firstResult The first result to obtain
* @param maxResults The max number of results to obtain
* @return A list of matching HoldingReservations.
*/
public List<HoldingReservation> listHoldingReservations(CriteriaQuery<HoldingReservation> q,
int firstResult, int maxResults) {
return holdingReservationDAO.list(q, firstResult, maxResults);
}
/**
* Count all HoldingReservations matching a built query.
*
* @param q The criteria query to execute
* @return A count of matching HoldingReservations.
*/
public long countHoldingReservations(CriteriaQuery<Long> q) {
return holdingReservationDAO.count(q);
}
/**
* Get a single Reservation matching a built query.
*
* @param query The query to match by.
* @return The matching Reservation.
*/
public Reservation getReservation(CriteriaQuery<Reservation> query) {
return reservationDAO.get(query);
}
/**
* Mark a specific item in a reservation as seen, bumping it to the next status.
*
* @param res Reservation to change status for.
* @param h Holding to bump.
*/
public void markItem(Reservation res, Holding h) {
// Ignore old reservations
if (res == null)
return;
super.markItem(h);
markReservation(res);
updateHoldingStatusForPendingReservations(res);
saveReservation(res);
}
/**
* Mark a reservation, bumping it to the next status.
*
* @param res Reservation to change status for.
*/
private void markReservation(Reservation res) {
boolean complete = true;
boolean reserved = true;
for (HoldingReservation hr : res.getHoldingReservations()) {
if (!hr.isCompleted()) {
Holding holding = hr.getHolding();
if (holding.getStatus() == Holding.Status.AVAILABLE) {
hr.setCompleted(true);
}
else {
complete = false;
}
if (holding.getStatus() != Holding.Status.RESERVED) {
reserved = false;
}
}
}
if (complete) {
res.setStatus(Reservation.Status.COMPLETED);
}
else if (reserved) {
res.setStatus(Reservation.Status.PENDING);
}
else {
res.setStatus(Reservation.Status.ACTIVE);
}
}
/**
* Merge the other reservation's fields into this reservation.
*
* @param reservation The reservation.
* @param other The other reservation to merge with.
*/
public void merge(Reservation reservation, Reservation other) {
reservation.setDate(other.getDate());
reservation.setReturnDate(other.getReturnDate());
reservation.setVisitorName(other.getVisitorName());
reservation.setVisitorEmail(other.getVisitorEmail());
reservation.setComment(other.getComment());
if (other.getHoldingReservations() == null) {
for (HoldingReservation hr : reservation.getHoldingReservations()) {
records.updateHoldingStatus(hr.getHolding(), Holding.Status.AVAILABLE);
}
reservation.setHoldingReservations(new ArrayList<>());
}
else {
// Delete holdings that were not provided.
deleteHoldingsNotInProvidedRequest(reservation, other);
// Add/update provided.
addOrUpdateHoldingsProvidedByRequest(reservation, other);
}
updateStatusAndAssociatedHoldingStatus(reservation, other.getStatus());
}
/**
* Set the reservation status and update the associated holdings status accordingly. Only updates status forward.
*
* @param reservation The reservation.
* @param status The reservation which changed status.
*/
public void updateStatusAndAssociatedHoldingStatus(Reservation reservation, Reservation.Status status) {
if (status.ordinal() < reservation.getStatus().ordinal()) {
return;
}
reservation.setStatus(status);
Holding.Status hStatus;
switch (status) {
case PENDING:
hStatus = Holding.Status.RESERVED;
break;
case ACTIVE:
hStatus = Holding.Status.IN_USE;
break;
default:
hStatus = Holding.Status.AVAILABLE;
break;
}
for (HoldingReservation hr : reservation.getHoldingReservations()) {
if (!hr.isCompleted()) {
if (status == Reservation.Status.COMPLETED)
hr.setCompleted(true);
records.updateHoldingStatus(hr.getHolding(), hStatus);
}
}
updateHoldingStatusForPendingReservations(reservation);
}
/**
* Update the holding status for pending reservations.
*
* @param reservation The reservation to check.
*/
private void updateHoldingStatusForPendingReservations(Reservation reservation) {
if (reservation.getStatus() != Reservation.Status.COMPLETED) {
return;
}
for (HoldingReservation hr : reservation.getHoldingReservations()) {
Holding holding = hr.getHolding();
if (holding.getStatus() == Holding.Status.AVAILABLE) {
Record record = holding.getRecord();
if (record.getParent() != null && record.getExternalInfo().getContainer() != null
&& reservationDAO.hasPendingReservation(record)) {
records.updateHoldingStatus(holding, Holding.Status.RESERVED);
}
}
}
}
/**
* Adds a HoldingRequest to the HoldingRequests assoicated with this request.
*
* @param holdingRequest The HoldingRequests to add.
*/
protected void addToHoldingRequests(Request request, HoldingRequest holdingRequest) {
Reservation reservation = (Reservation) request;
HoldingReservation holdingReservation = (HoldingReservation) holdingRequest;
holdingReservation.setReservation(reservation);
reservation.getHoldingReservations().add(holdingReservation);
}
/**
* Prints holding reservations by using the default printer.
*
* @param hrs The holding reservations to print.
* @param alwaysPrint If set to true, already printed holdings will also be printed.
* @throws PrinterException Thrown when delivering the print job to the
* printer failed. Does not say anything if the printer actually printed
* (or ran out of paper for example).
*/
public void printItems(List<HoldingReservation> hrs, boolean alwaysPrint) throws PrinterException {
try {
Set<Reservation> reservations = new HashSet<>();
List<RequestPrintable> requestPrintables = new ArrayList<>();
List<RequestPrintable> requestPrintablesArchive = new ArrayList<>();
for (HoldingReservation hr : hrs) {
ExternalRecordInfo.MaterialType mt = hr.getHolding().getRecord().getExternalInfo().getMaterialType();
if (mt == ExternalRecordInfo.MaterialType.ARCHIVE) {
requestPrintablesArchive.add(new ArchiveReservationPrintable(
hr, msgSource, (DateFormat) bf.getBean("dateFormat"), deliveryProperties));
}
else {
requestPrintables.add(new ReservationPrintable(
hr, msgSource, (DateFormat) bf.getBean("dateFormat"), deliveryProperties));
}
reservations.add(hr.getReservation());
}
printRequest(requestPrintables, printerConfiguration.getPrinterNameArchive(), alwaysPrint);
printRequest(requestPrintablesArchive, printerConfiguration.getPrinterNameReadingRoom(), alwaysPrint);
for (Reservation r : reservations) {
saveReservation(r);
}
}
catch (PrinterException e) {
LOGGER.warn("Printing reservation failed", e);
throw e;
}
}
/**
* Print a reservation if it was not printed yet.
*
* @param res The reservation to print.
* @throws PrinterException Thrown when delivering the print job to the
* printer failed. Does not say anything if the printer actually printed
* (or ran out of paper for example).
*/
public void printReservation(Reservation res) throws PrinterException {
printItems(res.getHoldingReservations(), false);
}
/**
* Edit reservations.
*
* @param newRes The new reservation to put in the database.
* @param oldRes The old reservation in the database (if present).
* @param result The binding result object to put the validation errors in.
* @throws ClosedException Thrown when a holding is provided which
* references a record which is restrictionType=CLOSED.
* @throws NoHoldingsException Thrown when no holdings are provided.
*/
public void createOrEdit(Reservation newRes, Reservation oldRes, BindingResult result)
throws ClosedException, NoHoldingsException {
// Validate the reservation.
validateRequest(newRes, result);
// Make sure a valid reservation date is provided (Only upon creation
// because time dependent!).
if (oldRes == null) {
Date resDate = newRes.getDate();
if (resDate != null && !resDate.equals(getFirstValidReservationDate(resDate))) {
Calendar resCalendar = Calendar.getInstance();
resCalendar.setTime(resDate);
String msg;
if (dateExceptionService.getExceptionDates().contains(resCalendar)) {
msg = msgSource.getMessage("reservationDateException.dateIsException",
new Object[]{}, LocaleContextHolder.getLocale()) +
dateExceptionService.getReasonForExceptionDate(resCalendar);
}
else {
msg = msgSource.getMessage("validator.reservationDate", null,
"Invalid date", LocaleContextHolder.getLocale());
}
result.addError(new FieldError(result.getObjectName(), "date",
newRes.getDate(), false, null, null, msg));
}
}
// If the return date is provided, it should be >= to the date of visit.
Date d = newRes.getDate();
Date rd = newRes.getReturnDate();
if (d != null && rd != null && rd.before(d)) {
String msg = msgSource.getMessage("validator.reservationReturnDate", null,
"Invalid date", LocaleContextHolder.getLocale());
result.addError(new FieldError(result.getObjectName(), "returnDate",
newRes.getDate(), false, null, null, msg));
}
// Execute this method below the date check, or else the date will
// not be checked if this method throws an exception; not displaying
// the error immediately, but only when the holdings are valid instead.
validateHoldings(newRes, oldRes);
// Add or save the record when no errors are present.
if (!result.hasErrors()) {
if (oldRes == null) {
newRes.setCreationDate(new Date());
addReservation(newRes);
}
else {
merge(oldRes, newRes);
saveReservation(oldRes);
}
}
}
/**
* Get the first valid reservation date after or equal to from.
*
* @param from The date to start from.
* @return The first valid date, or null when maxDaysInAdvance was exceeded.
*/
public Date getFirstValidReservationDate(Date from) {
Calendar fromCal = GregorianCalendar.getInstance();
fromCal.setTime(from);
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
format.setLenient(false);
Calendar t = GregorianCalendar.getInstance();
try {
t.setTime(format.parse(deliveryProperties.getRequestLatestTime()));
}
catch (ParseException e) {
throw new RuntimeException("Invalid reservationLatestTime provided in config. Should be of format HH:mm");
}
Calendar firstPossibleCal = GregorianCalendar.getInstance();
// Cannot reserve after "closing" time.
if (firstPossibleCal.get(Calendar.HOUR_OF_DAY) > t.get(Calendar.HOUR_OF_DAY) ||
(firstPossibleCal.get(Calendar.HOUR_OF_DAY) == t.get(Calendar.HOUR_OF_DAY) &&
firstPossibleCal.get(Calendar.MINUTE) >= t.get(Calendar.MINUTE))) {
firstPossibleCal.add(Calendar.DAY_OF_YEAR, 1);
}
// Cannot reserve in past (or after closing time).
if (fromCal.get(Calendar.YEAR) < firstPossibleCal.get(Calendar.YEAR)
|| (fromCal.get(Calendar.YEAR) == firstPossibleCal.get(Calendar.YEAR)
&& fromCal.get(Calendar.DAY_OF_YEAR) < firstPossibleCal.get(Calendar.DAY_OF_YEAR))) {
fromCal = firstPossibleCal;
}
// Check if date is an exception date
// Vrijdag zaterdag en zondag geen diensten.
List<Calendar> exceptionDates = dateExceptionService.getExceptionDates();
for (Calendar exceptionDate : exceptionDates) {
if (fromCal.equals(exceptionDate)) {
fromCal.add(Calendar.DAY_OF_YEAR, 1);
// Check for weekends
if (fromCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
fromCal.add(Calendar.DAY_OF_YEAR, 3);
}
if (fromCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
fromCal.add(Calendar.DAY_OF_YEAR, 2);
}
if (fromCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
fromCal.add(Calendar.DAY_OF_YEAR, 1);
}
}
}
// Vrijdag zaterdag en zondag geen diensten.
if (fromCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
fromCal.add(Calendar.DAY_OF_YEAR, 3);
}
if (fromCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
fromCal.add(Calendar.DAY_OF_YEAR, 2);
}
if (fromCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
fromCal.add(Calendar.DAY_OF_YEAR, 1);
}
Calendar maxCal = GregorianCalendar.getInstance();
int maxDaysInAdvance = deliveryProperties.getReservationMaxDaysInAdvance();
maxCal.add(Calendar.DAY_OF_YEAR, maxDaysInAdvance);
if (fromCal.get(Calendar.YEAR) > maxCal.get(Calendar.YEAR)
|| (fromCal.get(Calendar.YEAR) == maxCal.get(Calendar.YEAR)
&& fromCal.get(Calendar.DAY_OF_YEAR) > maxCal.get(Calendar.DAY_OF_YEAR))) {
return null;
}
return fromCal.getTime();
}
/**
* Returns the active reservation with which this holding is associated.
*
* @param holding The Holding to get the active reservation of.
* @return The active reservation, or null if no active reservation exists.
*/
public Reservation getActiveFor(Holding holding) {
return reservationDAO.getActiveFor(holding);
}
}
| IISH/delivery | src/main/java/org/socialhistoryservices/delivery/reservation/service/ReservationServiceImpl.java | 5,752 | // because time dependent!). | line_comment | nl | package org.socialhistoryservices.delivery.reservation.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.socialhistoryservices.delivery.config.PrinterConfiguration;
import org.socialhistoryservices.delivery.record.entity.ExternalRecordInfo;
import org.socialhistoryservices.delivery.record.entity.Holding;
import org.socialhistoryservices.delivery.record.entity.Record;
import org.socialhistoryservices.delivery.request.entity.HoldingRequest;
import org.socialhistoryservices.delivery.request.entity.Request;
import org.socialhistoryservices.delivery.request.service.*;
import org.socialhistoryservices.delivery.reservation.dao.HoldingReservationDAO;
import org.socialhistoryservices.delivery.reservation.dao.ReservationDAO;
import org.socialhistoryservices.delivery.reservation.entity.HoldingReservation;
import org.socialhistoryservices.delivery.reservation.entity.Reservation;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import javax.persistence.Tuple;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import java.awt.print.PrinterException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Represents the service of the reservation package.
*/
@Service
@Transactional
public class ReservationServiceImpl extends AbstractRequestService implements ReservationService {
private static final Logger LOGGER = LoggerFactory.getLogger(ReservationServiceImpl.class);
@Autowired
private ReservationDAO reservationDAO;
@Autowired
private HoldingReservationDAO holdingReservationDAO;
@Autowired
private ReservationDateExceptionService dateExceptionService;
@Autowired
private BeanFactory bf;
@Autowired
private PrinterConfiguration printerConfiguration;
/**
* Add a Reservation to the database.
*
* @param obj Reservation to add.
*/
public void addReservation(Reservation obj) {
// Make sure the holdings get set to the correct status.
updateStatusAndAssociatedHoldingStatus(obj, obj.getStatus());
// Add to the database
reservationDAO.add(obj);
}
/**
* Remove a Reservation from the database.
*
* @param obj Reservation to remove.
*/
public void removeReservation(Reservation obj) {
// Set all holdings linked to this reservation back to AVAILABLE if
// this is a PENDING/ACTIVE reservation.
// Note that we are in a transaction here, so it does not matter the
// records are still linked to the reservation when setting them to available.
if (obj.getStatus() != Reservation.Status.COMPLETED) {
changeHoldingStatus(obj, Holding.Status.AVAILABLE);
}
reservationDAO.remove(obj);
}
/**
* Change the status of all holdings in a reservation.
*
* @param res Reservation to change status for.
* @param status Status to change holdings to.
*/
public void changeHoldingStatus(Reservation res, Holding.Status status) {
super.changeHoldingStatus(res, status);
updateHoldingStatusForPendingReservations(res);
saveReservation(res);
}
/**
* Save changes to a Reservation in the database.
*
* @param obj Reservation to save.
*/
public Reservation saveReservation(Reservation obj) {
return reservationDAO.save(obj);
}
/**
* Retrieve the Reservation matching the given Id.
*
* @param id Id of the Reservation to retrieve.
* @return The Reservation matching the Id.
*/
public Reservation getReservationById(int id) {
return reservationDAO.getById(id);
}
/**
* Get a criteria builder for querying Reservations.
*
* @return the CriteriaBuilder.
*/
public CriteriaBuilder getReservationCriteriaBuilder() {
return reservationDAO.getCriteriaBuilder();
}
/**
* Get a criteria builder for querying HoldingReservations.
*
* @return the CriteriaBuilder.
*/
public CriteriaBuilder getHoldingReservationCriteriaBuilder() {
return holdingReservationDAO.getCriteriaBuilder();
}
/**
* List all Reservations matching a built query.
*
* @param q The criteria query to execute
* @return A list of matching Reservations.
*/
public List<Reservation> listReservations(CriteriaQuery<Reservation> q) {
return reservationDAO.list(q);
}
/**
* List all Tuples matching a built query.
*
* @param q The criteria query to execute
* @return A list of matching Tuples.
*/
public List<Tuple> listTuples(CriteriaQuery<Tuple> q) {
return reservationDAO.listForTuple(q);
}
/**
* List all HoldingReservations matching a built query.
*
* @param q The criteria query to execute
* @return A list of matching HoldingReservations.
*/
public List<HoldingReservation> listHoldingReservations(CriteriaQuery<HoldingReservation> q) {
return holdingReservationDAO.list(q);
}
/**
* List all HoldingReservations matching a built query.
*
* @param q The criteria query to execute
* @param firstResult The first result to obtain
* @param maxResults The max number of results to obtain
* @return A list of matching HoldingReservations.
*/
public List<HoldingReservation> listHoldingReservations(CriteriaQuery<HoldingReservation> q,
int firstResult, int maxResults) {
return holdingReservationDAO.list(q, firstResult, maxResults);
}
/**
* Count all HoldingReservations matching a built query.
*
* @param q The criteria query to execute
* @return A count of matching HoldingReservations.
*/
public long countHoldingReservations(CriteriaQuery<Long> q) {
return holdingReservationDAO.count(q);
}
/**
* Get a single Reservation matching a built query.
*
* @param query The query to match by.
* @return The matching Reservation.
*/
public Reservation getReservation(CriteriaQuery<Reservation> query) {
return reservationDAO.get(query);
}
/**
* Mark a specific item in a reservation as seen, bumping it to the next status.
*
* @param res Reservation to change status for.
* @param h Holding to bump.
*/
public void markItem(Reservation res, Holding h) {
// Ignore old reservations
if (res == null)
return;
super.markItem(h);
markReservation(res);
updateHoldingStatusForPendingReservations(res);
saveReservation(res);
}
/**
* Mark a reservation, bumping it to the next status.
*
* @param res Reservation to change status for.
*/
private void markReservation(Reservation res) {
boolean complete = true;
boolean reserved = true;
for (HoldingReservation hr : res.getHoldingReservations()) {
if (!hr.isCompleted()) {
Holding holding = hr.getHolding();
if (holding.getStatus() == Holding.Status.AVAILABLE) {
hr.setCompleted(true);
}
else {
complete = false;
}
if (holding.getStatus() != Holding.Status.RESERVED) {
reserved = false;
}
}
}
if (complete) {
res.setStatus(Reservation.Status.COMPLETED);
}
else if (reserved) {
res.setStatus(Reservation.Status.PENDING);
}
else {
res.setStatus(Reservation.Status.ACTIVE);
}
}
/**
* Merge the other reservation's fields into this reservation.
*
* @param reservation The reservation.
* @param other The other reservation to merge with.
*/
public void merge(Reservation reservation, Reservation other) {
reservation.setDate(other.getDate());
reservation.setReturnDate(other.getReturnDate());
reservation.setVisitorName(other.getVisitorName());
reservation.setVisitorEmail(other.getVisitorEmail());
reservation.setComment(other.getComment());
if (other.getHoldingReservations() == null) {
for (HoldingReservation hr : reservation.getHoldingReservations()) {
records.updateHoldingStatus(hr.getHolding(), Holding.Status.AVAILABLE);
}
reservation.setHoldingReservations(new ArrayList<>());
}
else {
// Delete holdings that were not provided.
deleteHoldingsNotInProvidedRequest(reservation, other);
// Add/update provided.
addOrUpdateHoldingsProvidedByRequest(reservation, other);
}
updateStatusAndAssociatedHoldingStatus(reservation, other.getStatus());
}
/**
* Set the reservation status and update the associated holdings status accordingly. Only updates status forward.
*
* @param reservation The reservation.
* @param status The reservation which changed status.
*/
public void updateStatusAndAssociatedHoldingStatus(Reservation reservation, Reservation.Status status) {
if (status.ordinal() < reservation.getStatus().ordinal()) {
return;
}
reservation.setStatus(status);
Holding.Status hStatus;
switch (status) {
case PENDING:
hStatus = Holding.Status.RESERVED;
break;
case ACTIVE:
hStatus = Holding.Status.IN_USE;
break;
default:
hStatus = Holding.Status.AVAILABLE;
break;
}
for (HoldingReservation hr : reservation.getHoldingReservations()) {
if (!hr.isCompleted()) {
if (status == Reservation.Status.COMPLETED)
hr.setCompleted(true);
records.updateHoldingStatus(hr.getHolding(), hStatus);
}
}
updateHoldingStatusForPendingReservations(reservation);
}
/**
* Update the holding status for pending reservations.
*
* @param reservation The reservation to check.
*/
private void updateHoldingStatusForPendingReservations(Reservation reservation) {
if (reservation.getStatus() != Reservation.Status.COMPLETED) {
return;
}
for (HoldingReservation hr : reservation.getHoldingReservations()) {
Holding holding = hr.getHolding();
if (holding.getStatus() == Holding.Status.AVAILABLE) {
Record record = holding.getRecord();
if (record.getParent() != null && record.getExternalInfo().getContainer() != null
&& reservationDAO.hasPendingReservation(record)) {
records.updateHoldingStatus(holding, Holding.Status.RESERVED);
}
}
}
}
/**
* Adds a HoldingRequest to the HoldingRequests assoicated with this request.
*
* @param holdingRequest The HoldingRequests to add.
*/
protected void addToHoldingRequests(Request request, HoldingRequest holdingRequest) {
Reservation reservation = (Reservation) request;
HoldingReservation holdingReservation = (HoldingReservation) holdingRequest;
holdingReservation.setReservation(reservation);
reservation.getHoldingReservations().add(holdingReservation);
}
/**
* Prints holding reservations by using the default printer.
*
* @param hrs The holding reservations to print.
* @param alwaysPrint If set to true, already printed holdings will also be printed.
* @throws PrinterException Thrown when delivering the print job to the
* printer failed. Does not say anything if the printer actually printed
* (or ran out of paper for example).
*/
public void printItems(List<HoldingReservation> hrs, boolean alwaysPrint) throws PrinterException {
try {
Set<Reservation> reservations = new HashSet<>();
List<RequestPrintable> requestPrintables = new ArrayList<>();
List<RequestPrintable> requestPrintablesArchive = new ArrayList<>();
for (HoldingReservation hr : hrs) {
ExternalRecordInfo.MaterialType mt = hr.getHolding().getRecord().getExternalInfo().getMaterialType();
if (mt == ExternalRecordInfo.MaterialType.ARCHIVE) {
requestPrintablesArchive.add(new ArchiveReservationPrintable(
hr, msgSource, (DateFormat) bf.getBean("dateFormat"), deliveryProperties));
}
else {
requestPrintables.add(new ReservationPrintable(
hr, msgSource, (DateFormat) bf.getBean("dateFormat"), deliveryProperties));
}
reservations.add(hr.getReservation());
}
printRequest(requestPrintables, printerConfiguration.getPrinterNameArchive(), alwaysPrint);
printRequest(requestPrintablesArchive, printerConfiguration.getPrinterNameReadingRoom(), alwaysPrint);
for (Reservation r : reservations) {
saveReservation(r);
}
}
catch (PrinterException e) {
LOGGER.warn("Printing reservation failed", e);
throw e;
}
}
/**
* Print a reservation if it was not printed yet.
*
* @param res The reservation to print.
* @throws PrinterException Thrown when delivering the print job to the
* printer failed. Does not say anything if the printer actually printed
* (or ran out of paper for example).
*/
public void printReservation(Reservation res) throws PrinterException {
printItems(res.getHoldingReservations(), false);
}
/**
* Edit reservations.
*
* @param newRes The new reservation to put in the database.
* @param oldRes The old reservation in the database (if present).
* @param result The binding result object to put the validation errors in.
* @throws ClosedException Thrown when a holding is provided which
* references a record which is restrictionType=CLOSED.
* @throws NoHoldingsException Thrown when no holdings are provided.
*/
public void createOrEdit(Reservation newRes, Reservation oldRes, BindingResult result)
throws ClosedException, NoHoldingsException {
// Validate the reservation.
validateRequest(newRes, result);
// Make sure a valid reservation date is provided (Only upon creation
// because time<SUF>
if (oldRes == null) {
Date resDate = newRes.getDate();
if (resDate != null && !resDate.equals(getFirstValidReservationDate(resDate))) {
Calendar resCalendar = Calendar.getInstance();
resCalendar.setTime(resDate);
String msg;
if (dateExceptionService.getExceptionDates().contains(resCalendar)) {
msg = msgSource.getMessage("reservationDateException.dateIsException",
new Object[]{}, LocaleContextHolder.getLocale()) +
dateExceptionService.getReasonForExceptionDate(resCalendar);
}
else {
msg = msgSource.getMessage("validator.reservationDate", null,
"Invalid date", LocaleContextHolder.getLocale());
}
result.addError(new FieldError(result.getObjectName(), "date",
newRes.getDate(), false, null, null, msg));
}
}
// If the return date is provided, it should be >= to the date of visit.
Date d = newRes.getDate();
Date rd = newRes.getReturnDate();
if (d != null && rd != null && rd.before(d)) {
String msg = msgSource.getMessage("validator.reservationReturnDate", null,
"Invalid date", LocaleContextHolder.getLocale());
result.addError(new FieldError(result.getObjectName(), "returnDate",
newRes.getDate(), false, null, null, msg));
}
// Execute this method below the date check, or else the date will
// not be checked if this method throws an exception; not displaying
// the error immediately, but only when the holdings are valid instead.
validateHoldings(newRes, oldRes);
// Add or save the record when no errors are present.
if (!result.hasErrors()) {
if (oldRes == null) {
newRes.setCreationDate(new Date());
addReservation(newRes);
}
else {
merge(oldRes, newRes);
saveReservation(oldRes);
}
}
}
/**
* Get the first valid reservation date after or equal to from.
*
* @param from The date to start from.
* @return The first valid date, or null when maxDaysInAdvance was exceeded.
*/
public Date getFirstValidReservationDate(Date from) {
Calendar fromCal = GregorianCalendar.getInstance();
fromCal.setTime(from);
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
format.setLenient(false);
Calendar t = GregorianCalendar.getInstance();
try {
t.setTime(format.parse(deliveryProperties.getRequestLatestTime()));
}
catch (ParseException e) {
throw new RuntimeException("Invalid reservationLatestTime provided in config. Should be of format HH:mm");
}
Calendar firstPossibleCal = GregorianCalendar.getInstance();
// Cannot reserve after "closing" time.
if (firstPossibleCal.get(Calendar.HOUR_OF_DAY) > t.get(Calendar.HOUR_OF_DAY) ||
(firstPossibleCal.get(Calendar.HOUR_OF_DAY) == t.get(Calendar.HOUR_OF_DAY) &&
firstPossibleCal.get(Calendar.MINUTE) >= t.get(Calendar.MINUTE))) {
firstPossibleCal.add(Calendar.DAY_OF_YEAR, 1);
}
// Cannot reserve in past (or after closing time).
if (fromCal.get(Calendar.YEAR) < firstPossibleCal.get(Calendar.YEAR)
|| (fromCal.get(Calendar.YEAR) == firstPossibleCal.get(Calendar.YEAR)
&& fromCal.get(Calendar.DAY_OF_YEAR) < firstPossibleCal.get(Calendar.DAY_OF_YEAR))) {
fromCal = firstPossibleCal;
}
// Check if date is an exception date
// Vrijdag zaterdag en zondag geen diensten.
List<Calendar> exceptionDates = dateExceptionService.getExceptionDates();
for (Calendar exceptionDate : exceptionDates) {
if (fromCal.equals(exceptionDate)) {
fromCal.add(Calendar.DAY_OF_YEAR, 1);
// Check for weekends
if (fromCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
fromCal.add(Calendar.DAY_OF_YEAR, 3);
}
if (fromCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
fromCal.add(Calendar.DAY_OF_YEAR, 2);
}
if (fromCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
fromCal.add(Calendar.DAY_OF_YEAR, 1);
}
}
}
// Vrijdag zaterdag en zondag geen diensten.
if (fromCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
fromCal.add(Calendar.DAY_OF_YEAR, 3);
}
if (fromCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
fromCal.add(Calendar.DAY_OF_YEAR, 2);
}
if (fromCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
fromCal.add(Calendar.DAY_OF_YEAR, 1);
}
Calendar maxCal = GregorianCalendar.getInstance();
int maxDaysInAdvance = deliveryProperties.getReservationMaxDaysInAdvance();
maxCal.add(Calendar.DAY_OF_YEAR, maxDaysInAdvance);
if (fromCal.get(Calendar.YEAR) > maxCal.get(Calendar.YEAR)
|| (fromCal.get(Calendar.YEAR) == maxCal.get(Calendar.YEAR)
&& fromCal.get(Calendar.DAY_OF_YEAR) > maxCal.get(Calendar.DAY_OF_YEAR))) {
return null;
}
return fromCal.getTime();
}
/**
* Returns the active reservation with which this holding is associated.
*
* @param holding The Holding to get the active reservation of.
* @return The active reservation, or null if no active reservation exists.
*/
public Reservation getActiveFor(Holding holding) {
return reservationDAO.getActiveFor(holding);
}
}
|
112185_1 | package org;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils {
final private static Pattern pattern = Pattern.compile("^[1-9][0-9]{3}$");
final private static HashMap<String, String> map = new HashMap<>(35);
static {
map.put("affiches", "Posters");
map.put("posters", "Posters");
map.put("ansichtkaarten", "Picture postcards");
map.put("boeken", "Books");
map.put("books", "Books");
map.put("buttons", "Buttons");
map.put("cassetteband", "Audiocassettes");
map.put("cassettebanden", "Audiocassettes");
map.put("cassettebandjes", "Audiocassettes");
map.put("geluidscassettes", "Audiocassettes");
map.put("audiocassettes", "Audiocassettes");
map.put("audio cassettes", "Audiocassettes");
map.put("cd-rom", "Compact discs");
map.put("cds", "Compact discs");
map.put("dias", "Slides");
map.put("dvds", "DVDs");
map.put("files", "Files");
map.put("films", "Films");
map.put("gb", "Gigabytes");
map.put("glasdias", "Lantern slides");
map.put("glasdia", "Lantern slides");
map.put("glasnegatieven", "Glass negatives");
map.put("m", "Meters");
map.put("mb", "Megabytes");
map.put("microfiches", "Microfiches");
map.put("microfilms", "Microfilms");
map.put("microfilm", "Microfilms");
map.put("negatieven", "Negatives (photographs)");
map.put("objecten", "Objects");
map.put("periodicals", "Periodicals");
map.put("periodieken", "Periodicals");
map.put("fotos", "Photographs");
map.put("photos", "Photographs");
map.put("prenten", "Prints");
map.put("tekeningen", "Drawings");
map.put("videocassettes", "Videocassettes");
map.put("videobanden", "Videocassettes");
}
public static String unitdate(org.w3c.dom.NodeList nodelist) {
int van = Integer.MAX_VALUE, tot = Integer.MIN_VALUE;
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < nodelist.getLength(); i++) {
final String text = nodelist.item(i).getNodeValue();
sb.append(text).append(" | ");
final String str = text.replaceAll("[^\\d]", " ")
.trim()
.replaceAll(" +", " ");
final String[] split = str.split(" ");
for (String candidate : split) {
final Matcher matcher = pattern.matcher(candidate);
if (matcher.matches()) {
final int n = Integer.parseInt(candidate);
if (n < van) van = n;
if (n > tot) tot = n;
}
}
}
final String ret;
if (van == Integer.MAX_VALUE && tot == Integer.MIN_VALUE) {
System.out.println("No matches with " + sb);
return null;
} else if (van == Integer.MAX_VALUE) {
ret = String.valueOf(tot);
} else if (tot == Integer.MIN_VALUE) {
ret = String.valueOf(van);
} else {
ret = van + "-" + tot;
}
return ret;
}
public static String normalDate(String text) {
return text.replaceAll("-", "");
}
public static String extent(String text) {
final StringBuilder sb = new StringBuilder();
final String[] keys = text.split(" "); // 98.52 Meters wordt ["98.52", "Meters"]
for (String key : keys) {
final String value = map.get(key.replace("'", "").replace("’", "").replace(".", "").toLowerCase());
if (value == null) {
sb.append(key);
} else {
sb.append(value);
}
sb.append(" ");
}
return sb.toString().trim();
}
// https://jira.socialhistoryservices.org/browse/AR-39
public static boolean isUnitDate(org.w3c.dom.Node node) {
final Node previousSibling = node.getPreviousSibling();
if (previousSibling != null) {
final String text = previousSibling.getTextContent().trim();
if (text.endsWith(".")) {
final Node nextSibling = node.getNextSibling();
if (nextSibling != null) {
for (byte b : nextSibling.getTextContent().trim().getBytes()) { // alleen scheidingstekens, e.a.
if (b > 64) return false;
}
}
return true;
}
}
return false;
}
public static String shortTitle(NodeList list) {
if ( list.getLength() == 0) return null;
return shortTitle(list.item(0));
}
private static String shortTitle(Node node) {
return shortTitle(node.getTextContent());
}
private static String shortTitle(String _text) {
if (_text == null) return null;
final String[] __text = _text.trim().split("[\\\\,?/\\.;:\\]\\[]");
if ( __text.length == 0) return _text.trim();
final StringBuilder sb = new StringBuilder();
for (String text : __text) {
final String t = text.trim();
if ( t.length() != 0) {
sb.append(t);
sb.append(" ");
}
}
return sb.toString().trim();
}
public static String urlDecode(String text) {
return java.net.URLDecoder.decode(text);
}
}
| IISH/ead2as | src/main/java/org/Utils.java | 1,696 | // alleen scheidingstekens, e.a. | line_comment | nl | package org;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils {
final private static Pattern pattern = Pattern.compile("^[1-9][0-9]{3}$");
final private static HashMap<String, String> map = new HashMap<>(35);
static {
map.put("affiches", "Posters");
map.put("posters", "Posters");
map.put("ansichtkaarten", "Picture postcards");
map.put("boeken", "Books");
map.put("books", "Books");
map.put("buttons", "Buttons");
map.put("cassetteband", "Audiocassettes");
map.put("cassettebanden", "Audiocassettes");
map.put("cassettebandjes", "Audiocassettes");
map.put("geluidscassettes", "Audiocassettes");
map.put("audiocassettes", "Audiocassettes");
map.put("audio cassettes", "Audiocassettes");
map.put("cd-rom", "Compact discs");
map.put("cds", "Compact discs");
map.put("dias", "Slides");
map.put("dvds", "DVDs");
map.put("files", "Files");
map.put("films", "Films");
map.put("gb", "Gigabytes");
map.put("glasdias", "Lantern slides");
map.put("glasdia", "Lantern slides");
map.put("glasnegatieven", "Glass negatives");
map.put("m", "Meters");
map.put("mb", "Megabytes");
map.put("microfiches", "Microfiches");
map.put("microfilms", "Microfilms");
map.put("microfilm", "Microfilms");
map.put("negatieven", "Negatives (photographs)");
map.put("objecten", "Objects");
map.put("periodicals", "Periodicals");
map.put("periodieken", "Periodicals");
map.put("fotos", "Photographs");
map.put("photos", "Photographs");
map.put("prenten", "Prints");
map.put("tekeningen", "Drawings");
map.put("videocassettes", "Videocassettes");
map.put("videobanden", "Videocassettes");
}
public static String unitdate(org.w3c.dom.NodeList nodelist) {
int van = Integer.MAX_VALUE, tot = Integer.MIN_VALUE;
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < nodelist.getLength(); i++) {
final String text = nodelist.item(i).getNodeValue();
sb.append(text).append(" | ");
final String str = text.replaceAll("[^\\d]", " ")
.trim()
.replaceAll(" +", " ");
final String[] split = str.split(" ");
for (String candidate : split) {
final Matcher matcher = pattern.matcher(candidate);
if (matcher.matches()) {
final int n = Integer.parseInt(candidate);
if (n < van) van = n;
if (n > tot) tot = n;
}
}
}
final String ret;
if (van == Integer.MAX_VALUE && tot == Integer.MIN_VALUE) {
System.out.println("No matches with " + sb);
return null;
} else if (van == Integer.MAX_VALUE) {
ret = String.valueOf(tot);
} else if (tot == Integer.MIN_VALUE) {
ret = String.valueOf(van);
} else {
ret = van + "-" + tot;
}
return ret;
}
public static String normalDate(String text) {
return text.replaceAll("-", "");
}
public static String extent(String text) {
final StringBuilder sb = new StringBuilder();
final String[] keys = text.split(" "); // 98.52 Meters wordt ["98.52", "Meters"]
for (String key : keys) {
final String value = map.get(key.replace("'", "").replace("’", "").replace(".", "").toLowerCase());
if (value == null) {
sb.append(key);
} else {
sb.append(value);
}
sb.append(" ");
}
return sb.toString().trim();
}
// https://jira.socialhistoryservices.org/browse/AR-39
public static boolean isUnitDate(org.w3c.dom.Node node) {
final Node previousSibling = node.getPreviousSibling();
if (previousSibling != null) {
final String text = previousSibling.getTextContent().trim();
if (text.endsWith(".")) {
final Node nextSibling = node.getNextSibling();
if (nextSibling != null) {
for (byte b : nextSibling.getTextContent().trim().getBytes()) { // alleen scheidingstekens,<SUF>
if (b > 64) return false;
}
}
return true;
}
}
return false;
}
public static String shortTitle(NodeList list) {
if ( list.getLength() == 0) return null;
return shortTitle(list.item(0));
}
private static String shortTitle(Node node) {
return shortTitle(node.getTextContent());
}
private static String shortTitle(String _text) {
if (_text == null) return null;
final String[] __text = _text.trim().split("[\\\\,?/\\.;:\\]\\[]");
if ( __text.length == 0) return _text.trim();
final StringBuilder sb = new StringBuilder();
for (String text : __text) {
final String t = text.trim();
if ( t.length() != 0) {
sb.append(t);
sb.append(" ");
}
}
return sb.toString().trim();
}
public static String urlDecode(String text) {
return java.net.URLDecoder.decode(text);
}
}
|
104753_30 | /*
* Naam: CheckKeys
* Version: 0.1
* Author: Cor Munnik
* Copyright
*/
package nl.iisg.ids03;
/**
*
* This class handles the validation of relations between the Person, PersonDynamic, Registration and RegistrationAddress objects
* It also performs some checks on completeness of administrative fields in the objects
*
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Iterator;
import javax.persistence.Column;
import javax.persistence.Id;
import nl.iisg.ref.*;
/**
*
* This routine performs consistency checks on the B* tables
*
*
*/
public class KeyChecks {
public boolean CheckKeys(List<Person> persons, List<PersonDynamic> personsDynamic, List<Registration> registrations, List<RegistrationAddress> registrationAddresses){
boolean keysOK = true;
boolean found = false;
int count = 0;
int keyToSourceRegister = 0;
int dayEntryHeadOfHousehold = 0;
int monthEntryHeadOfHousehold = 0;
int yearEntryHeadOfHousehold = 0;
int keyToHSNResearchPerson = 0;
// Check that B2 keys are in B4
System.out.println("Checking Keys...");
System.out.println("Check that B2 keys are in B4");
for(Person p: persons){
Registration r = new Registration();
r.setKeyToSourceRegister(p.getKeyToSourceRegister());
r.setDayEntryHead(p.getDayEntryHead());
r.setMonthEntryHead(p.getMonthEntryHead());
r.setYearEntryHead(p.getYearEntryHead());
r.setKeyToRP(p.getKeyToRP());
int i = Collections.binarySearch(registrations, r, new ComparatorRegistration());
if(i < 0){
Message m = new Message("1021"); // '1021', 'FS', 'Sleutel B2 niet in B4'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
}
// Check that B3 keys are in B4
System.out.println("Check that B3 keys are in B4");
for(PersonDynamic pd: personsDynamic){
Registration r = new Registration();
r.setKeyToSourceRegister(pd.getKeyToSourceRegister());
r.setDayEntryHead(pd.getDayEntryHead());
r.setMonthEntryHead(pd.getMonthEntryHead());
r.setYearEntryHead(pd.getYearEntryHead());
r.setKeyToRP(pd.getKeyToRP());
int i = Collections.binarySearch(registrations, r, new ComparatorRegistration());
if(i < 0){
Message m = new Message("1022"); // '1022', 'FS', 'Sleutel B3 niet in B4'
m.setKeyToRP(pd.getKeyToRP());
m.setKeyToSourceRegister(pd.getKeyToSourceRegister());
m.setDayEntryHead(pd.getDayEntryHead());
m.setMonthEntryHead(pd.getMonthEntryHead());
m.setYearEntryHead(pd.getYearEntryHead());
m.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
}
// Check that B6 keys are in B4
System.out.println("Check that B6 keys are in B4");
for(RegistrationAddress ra: registrationAddresses){
Registration r = new Registration();
r.setKeyToSourceRegister(ra.getKeyToSourceRegister());
r.setDayEntryHead(ra.getDayEntryHead());
r.setMonthEntryHead(ra.getMonthEntryHead());
r.setYearEntryHead(ra.getYearEntryHead());
r.setKeyToRP(ra.getKeyToRP());
int i = Collections.binarySearch(registrations, r, new ComparatorRegistration());
if(i < 0){
Message m = new Message("1023"); // '1023', 'FS', 'Sleutel B6 niet in B4'
m.setKeyToRP(ra.getKeyToRP());
m.setKeyToSourceRegister(ra.getKeyToSourceRegister());
m.setDayEntryHead(ra.getDayEntryHead());
m.setMonthEntryHead(ra.getMonthEntryHead());
m.setYearEntryHead(ra.getYearEntryHead());
m.setKeyToRegistrationPersons(ra.getKeyToRegistrationPersons());
m.save();
keysOK = false;
//break;
}
}
// Check that B4 does not have double key
System.out.println("Check that B4 has no double key");
keyToSourceRegister = 0;
dayEntryHeadOfHousehold = 0;
monthEntryHeadOfHousehold = 0;
yearEntryHeadOfHousehold = 0;
keyToHSNResearchPerson = 0;
for(Registration r: registrations){
if(keyToSourceRegister == r.getKeyToSourceRegister() &&
dayEntryHeadOfHousehold == r.getDayEntryHead() &&
monthEntryHeadOfHousehold == r.getMonthEntryHead() &&
yearEntryHeadOfHousehold == r.getYearEntryHead() &&
keyToHSNResearchPerson == r.getKeyToRP()){
Message m = new Message("1028"); // '1028', 'FS', 'Dubbele sleutel in B4'
m.setKeyToRP(keyToHSNResearchPerson);
m.setKeyToSourceRegister(keyToSourceRegister);
m.setDayEntryHead(dayEntryHeadOfHousehold);
m.setMonthEntryHead(monthEntryHeadOfHousehold);
m.setYearEntryHead(yearEntryHeadOfHousehold);
m.save();
keysOK = false;
break;
}
else{
keyToSourceRegister = r.getKeyToSourceRegister();
dayEntryHeadOfHousehold = r.getDayEntryHead();
monthEntryHeadOfHousehold = r.getMonthEntryHead();
yearEntryHeadOfHousehold = r.getYearEntryHead();
keyToHSNResearchPerson = r.getKeyToRP();
}
}
// Check that B4 keys are in B2
System.out.println("Check that B4 keys are in B2");
for(Registration r: registrations){
Person p = new Person();
p.setKeyToSourceRegister(r.getKeyToSourceRegister());
p.setDayEntryHead(r.getDayEntryHead());
p.setMonthEntryHead(r.getMonthEntryHead());
p.setYearEntryHead(r.getYearEntryHead());
p.setKeyToRP(r.getKeyToRP());
p.setKeyToRegistrationPersons(1); // because numbering starts with 1
int i = Collections.binarySearch(persons, p, new ComparatorPerson());
if(i < 0){
Message m = new Message("1020"); // '1020', 'FS', 'Sleutel B4 niet in B2'
m.setKeyToRP(r.getKeyToRP());
m.setKeyToSourceRegister(r.getKeyToSourceRegister());
m.setDayEntryHead(r.getDayEntryHead());
m.setMonthEntryHead(r.getMonthEntryHead());
m.setYearEntryHead(r.getYearEntryHead());
m.save();
keysOK = false;
//break;
}
}
// Check that administrative fields in B2 are filled in
System.out.println("Check that administrative fields in B2 are filled in");
count = 0;
for(Person p: persons){
if(p.getOrderNumberOriginal() == null || p.getOrderNumberOriginal().trim().length() == 0 ||
p.getDateOriginal() == null || p.getDateOriginal().trim().length() == 0 ||
p.getInitialOriginal() == null || p.getInitialOriginal().trim().length() == 0 ||
p.getVersionOriginalDataEntry() == null || p.getVersionOriginalDataEntry().trim().length() == 0 ||
p.getResearchCodeOriginal() == null || p.getResearchCodeOriginal().trim().length() == 0){
if(count++ < 5){
Message m = new Message("1024"); // '1024', 'FS', 'B2 administratieve velden niet volledig ingevuld (alleen 1ste 5 gevallen)'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
}
}
}
// Check that administrative fields in B3 are filled in
System.out.println("Check that administrative fields in B3 are filled in");
count = 0;
for(PersonDynamic pd: personsDynamic){
if(pd.getOrderNumberOriginal() == null || pd.getOrderNumberOriginal().trim().length() == 0 ||
pd.getDateOriginal() == null || pd.getDateOriginal().trim().length() == 0 ||
pd.getInitialOriginal() == null || pd.getInitialOriginal().trim().length() == 0 ||
pd.getVersionOriginalDataEntry() == null || pd.getVersionOriginalDataEntry().trim().length() == 0 ||
pd.getResearchCodeOriginal() == null || pd.getResearchCodeOriginal().trim().length() == 0){
if(count++ < 5){
Message m = new Message("1025"); // '1025', 'FS', 'B3 administratieve velden niet volledig ingevuld (alleen 1ste 5 gevallen)'
m.setKeyToRP(pd.getKeyToRP());
m.setKeyToSourceRegister(pd.getKeyToSourceRegister());
m.setDayEntryHead(pd.getDayEntryHead());
m.setMonthEntryHead(pd.getMonthEntryHead());
m.setYearEntryHead(pd.getYearEntryHead());
m.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
m.save();
}
}
}
// Check that administrative fields in B4 are filled in
System.out.println("Check that administrative fields in B4 are filled in");
count = 0;
for(Registration r: registrations){
if(r.getOrderNumberOriginal() == null || r.getOrderNumberOriginal().trim().length() == 0 ||
r.getDateOriginal() == null || r.getDateOriginal().trim().length() == 0 ||
r.getInitialOriginal() == null || r.getInitialOriginal().trim().length() == 0 ||
r.getVersionOriginalDataEntry() == null || r.getVersionOriginalDataEntry().trim().length() == 0 ||
r.getResearchCodeOriginal() == null || r.getResearchCodeOriginal().trim().length() == 0){
if(count++ < 5){
Message m = new Message("1026"); // '1026', 'FS', 'B4 administratieve velden niet volledig ingevuld (alleen 1ste 5 gevallen)'
m.setKeyToRP(r.getKeyToRP());
m.setKeyToSourceRegister(r.getKeyToSourceRegister());
m.setDayEntryHead(r.getDayEntryHead());
m.setMonthEntryHead(r.getMonthEntryHead());
m.setYearEntryHead(r.getYearEntryHead());
m.save();
}
}
}
// Check that administrative fields in B6 are filled in
System.out.println("Check that administrative fields in B6 are filled in");
count = 0;
for(RegistrationAddress ra: registrationAddresses){
if(ra.getOrderNumberOriginal() == null || ra.getOrderNumberOriginal().trim().length() == 0 ||
ra.getDateOriginal() == null || ra.getDateOriginal().trim().length() == 0 ||
ra.getInitialOriginal() == null || ra.getInitialOriginal().trim().length() == 0 ||
ra.getVersionOriginalDataEntry() == null || ra.getVersionOriginalDataEntry().trim().length() == 0 ||
ra.getResearchCodeOriginal() == null || ra.getResearchCodeOriginal().trim().length() == 0){
if(count++ < 5){
Message m = new Message("1027"); // '1027', 'FS', 'B6 administratieve velden niet volledig ingevuld (alleen 1ste 5 gevallen)'
m.setKeyToRP(ra.getKeyToRP());
m.setKeyToSourceRegister(ra.getKeyToSourceRegister());
m.setDayEntryHead(ra.getDayEntryHead());
m.setMonthEntryHead(ra.getMonthEntryHead());
m.setYearEntryHead(ra.getYearEntryHead());
m.setKeyToRegistrationPersons(ra.getKeyToRegistrationPersons());
m.save();
}
}
}
// Check that B2 - B2RNBG starts with 1b
System.out.println("Check that B2:B2RNBG - keyToRegistrationPersons starts with 1");
for(Registration r: registrations){
for(Person p: r.getPersonsInRegistration()){
if(p.getKeyToRegistrationPersons() != 1){
Message m = new Message("1055"); // '1055', 'FS', HSN-volgnummering is in B2 niet goed (begint niet met volgnummer '1')
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
keysOK = false;
//break;
}
break;
}
}
// Check that B2 - B2RNBG is consecutive
System.out.println("Check that B2:B2RNBG - keyToRegistrationPersons is consecutive");
for(Registration r: registrations){
int sn = 0;
for(Person p: r.getPersonsInRegistration()){
if(p.getKeyToRegistrationPersons() != ++sn){
Message m = new Message("1056"); // '1056', 'FS', HSN-volgnummering is niet goed (geconstateerd in B2)
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
keysOK = false;
break;
}
}
}
// Check that B2 - B1IDBG - keyToSourceRegister is in ainb
System.out.println("Check that B2:B1IDBG - keyToSourceRegister is in ainb");
for(Person p: persons){
Ref_AINB ainb = Ref.getAINB(p.getKeyToSourceRegister());
if(ainb == null){
Message m = new Message("1053"); // '1053', 'RF', 'Identificatienummer van de bron <bronnummer> niet in AINB-bestand aanwezig'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save(new Integer(p.getKeyToSourceRegister()).toString());
keysOK = false;
//break;
}
}
// Check that B2 - IDNR - keyToHSNResearchPerson is in HSNRP (geboorteakten)
System.out.println("Check that B2:IDNR - keyToHSNResearchPerson is in HSNRP (geboorteakten)");
for(Person p: persons){
//Ref_GB gb = Ref.getGB(p.getKeyToRP());
Ref_RP rp = Ref.getRP(p.getKeyToRP());
if(rp == null){
Message m = new Message("1054"); // '1054', 'RF', 'Identificatienummer Onderzoekspersoon NIET in HSNRP bestand aanwezig! <idnr>'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save(new Integer(p.getKeyToRP()).toString());
keysOK = false;
//break;
}
}
// Check that key B2 is in B3 at least 3 times (for b3type = 1,2,3)
System.out.println("Check that key B2 is in B3 at least 3 times (for b3type = 1,2,3)");
int i_pd = 0;
for(Person p: persons){
PersonDynamic pd = new PersonDynamic();
pd.setKeyToSourceRegister(p.getKeyToSourceRegister());
pd.setDayEntryHead(p.getDayEntryHead());
pd.setMonthEntryHead(p.getMonthEntryHead());
pd.setYearEntryHead(p.getYearEntryHead());
pd.setKeyToRP(p.getKeyToRP());
pd.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
pd.setDynamicDataSequenceNumber(1); // because we look at the first dynamic data element for different values of dynamicDataType
pd.setDynamicDataType(1);
int i = Collections.binarySearch(personsDynamic, pd, new ComparatorPersonDynamic());
if(i < 0){
Message m = new Message("1058"); // '1058', 'FS', 'Sleutel van B2 komt niet voor in B3-bestand, (typenummer 1)'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
pd.setDynamicDataType(2);
i = Collections.binarySearch(personsDynamic, pd, new ComparatorPersonDynamic());
if(i < 0){
Message m = new Message("1059"); // '1059', 'FS', 'Sleutel van B2 komt niet voor in B3-bestand, (typenummer 2)'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
pd.setDynamicDataType(3);
i = Collections.binarySearch(personsDynamic, pd, new ComparatorPersonDynamic());
if(i < 0){
Message m = new Message("1060"); // '1060', 'FS', 'Sleutel van B2 komt niet voor in B3-bestand, (typenummer 3)'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
}
// Check that key B3 is in B2
System.out.println("Check that key B3 is in B2 ");
for(PersonDynamic pd: personsDynamic){
Person p = new Person();
p.setKeyToSourceRegister(pd.getKeyToSourceRegister());
p.setDayEntryHead(pd.getDayEntryHead());
p.setMonthEntryHead(pd.getMonthEntryHead());
p.setYearEntryHead(pd.getYearEntryHead());
p.setKeyToRP(pd.getKeyToRP());
p.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
int i = Collections.binarySearch(persons, p, new ComparatorPerson());
if(i < 0){
Message m = new Message("1061"); // '1061', 'FS', 'Sleutel van B3 komt niet voor in B2-bestand'
m.setKeyToRP(pd.getKeyToRP());
m.setKeyToSourceRegister(pd.getKeyToSourceRegister());
m.setDayEntryHead(pd.getDayEntryHead());
m.setMonthEntryHead(pd.getMonthEntryHead());
m.setYearEntryHead(pd.getYearEntryHead());
m.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
}
// Check that key B3 key is ok (per dynamicDataType the dynamicDataSequenceNumber must start with 1 and be contiguous (1, 2, 3, 4......)
System.out.println("Check that key B3 key OK");
int prevType = -1;
int prevSeqNo = -1;
for(PersonDynamic pd: personsDynamic){
if(prevType != pd.getDynamicDataType()){
prevType = pd.getDynamicDataType();
if(pd.getDynamicDataSequenceNumber() != 1){
Message m = new Message("1062"); // '1062', 'FS', 1062, Sleutel van B3 klopt niet (doornummering regels fout bij <typenummer>)
m.setKeyToRP(pd.getKeyToRP());
m.setKeyToSourceRegister(pd.getKeyToSourceRegister());
m.setDayEntryHead(pd.getDayEntryHead());
m.setMonthEntryHead(pd.getMonthEntryHead());
m.setYearEntryHead(pd.getYearEntryHead());
m.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
String [] fills = {"" + pd.getDynamicDataType()};
m.save(fills);
keysOK = false;
continue;
}
else
prevSeqNo = 1;
}
else{
if(pd.getDynamicDataSequenceNumber() != ++prevSeqNo){
Message m = new Message("1062"); // '1062', 'FS', 1062, Sleutel van B3 klopt niet (doornummering regels fout bij <typenummer>)
m.setKeyToRP(pd.getKeyToRP());
m.setKeyToSourceRegister(pd.getKeyToSourceRegister());
m.setDayEntryHead(pd.getDayEntryHead());
m.setMonthEntryHead(pd.getMonthEntryHead());
m.setYearEntryHead(pd.getYearEntryHead());
m.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
String [] fills = {"" + pd.getDynamicDataType()};
m.save(fills);
keysOK = false;
continue;
}
}
}
// Check that partial key B6 is in B2
System.out.println("Check that partial key B6 is in B2 ");
for(RegistrationAddress ra: registrationAddresses){
Person p = new Person();
p.setKeyToSourceRegister(ra.getKeyToSourceRegister());
p.setDayEntryHead(ra.getDayEntryHead());
p.setMonthEntryHead(ra.getMonthEntryHead());
p.setYearEntryHead(ra.getYearEntryHead());
p.setKeyToRP(ra.getKeyToRP());
if(ra.getKeyToRegistrationPersons() == 0)
p.setKeyToRegistrationPersons(1); // household bound address, look for first person
else
p.setKeyToRegistrationPersons(ra.getKeyToRegistrationPersons()); // address for specific person
int i = Collections.binarySearch(persons, p, new ComparatorPerson());
if(i < 0){
//System.out.println("XXXXX " + 3);
Message m = new Message("1063"); // '1063', 'FS', 'Sleutel van B6 komt niet voor in B2-bestand'
m.setKeyToRP(ra.getKeyToRP());
m.setKeyToSourceRegister(ra.getKeyToSourceRegister());
m.setDayEntryHead(ra.getDayEntryHead());
m.setMonthEntryHead(ra.getMonthEntryHead());
m.setYearEntryHead(ra.getYearEntryHead());
m.save();
keysOK = false;
}
}
// Check that B3:B2RNBG != B3:B3RGLN. This means the related person is the person itself. This is always incorrect
System.out.println("Check that B3 valueOfRelatedPerson (B3RGLN) is not equal to B3 keyToRegistrationPersons (B2RNGB) ");
for(PersonDynamic pd: personsDynamic){
if(pd.getValueOfRelatedPerson() == pd.getKeyToRegistrationPersons()){
Message m = new Message("1314"); //1314, FT, Regelnummer verwijst voor regelnummer van de relatie naar de eigen regel.
m.setKeyToRP(pd.getKeyToRP());
m.setKeyToSourceRegister(pd.getKeyToSourceRegister());
m.setDayEntryHead(pd.getDayEntryHead());
m.setMonthEntryHead(pd.getMonthEntryHead());
m.setYearEntryHead(pd.getYearEntryHead());
m.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
}
return(keysOK);
}
}
| IISH/hsn | IDSCheckConvert02/src/main/java/nl/iisg/ids03/KeyChecks.java | 7,614 | // '1054', 'RF', 'Identificatienummer Onderzoekspersoon NIET in HSNRP bestand aanwezig! <idnr>' | line_comment | nl | /*
* Naam: CheckKeys
* Version: 0.1
* Author: Cor Munnik
* Copyright
*/
package nl.iisg.ids03;
/**
*
* This class handles the validation of relations between the Person, PersonDynamic, Registration and RegistrationAddress objects
* It also performs some checks on completeness of administrative fields in the objects
*
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Iterator;
import javax.persistence.Column;
import javax.persistence.Id;
import nl.iisg.ref.*;
/**
*
* This routine performs consistency checks on the B* tables
*
*
*/
public class KeyChecks {
public boolean CheckKeys(List<Person> persons, List<PersonDynamic> personsDynamic, List<Registration> registrations, List<RegistrationAddress> registrationAddresses){
boolean keysOK = true;
boolean found = false;
int count = 0;
int keyToSourceRegister = 0;
int dayEntryHeadOfHousehold = 0;
int monthEntryHeadOfHousehold = 0;
int yearEntryHeadOfHousehold = 0;
int keyToHSNResearchPerson = 0;
// Check that B2 keys are in B4
System.out.println("Checking Keys...");
System.out.println("Check that B2 keys are in B4");
for(Person p: persons){
Registration r = new Registration();
r.setKeyToSourceRegister(p.getKeyToSourceRegister());
r.setDayEntryHead(p.getDayEntryHead());
r.setMonthEntryHead(p.getMonthEntryHead());
r.setYearEntryHead(p.getYearEntryHead());
r.setKeyToRP(p.getKeyToRP());
int i = Collections.binarySearch(registrations, r, new ComparatorRegistration());
if(i < 0){
Message m = new Message("1021"); // '1021', 'FS', 'Sleutel B2 niet in B4'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
}
// Check that B3 keys are in B4
System.out.println("Check that B3 keys are in B4");
for(PersonDynamic pd: personsDynamic){
Registration r = new Registration();
r.setKeyToSourceRegister(pd.getKeyToSourceRegister());
r.setDayEntryHead(pd.getDayEntryHead());
r.setMonthEntryHead(pd.getMonthEntryHead());
r.setYearEntryHead(pd.getYearEntryHead());
r.setKeyToRP(pd.getKeyToRP());
int i = Collections.binarySearch(registrations, r, new ComparatorRegistration());
if(i < 0){
Message m = new Message("1022"); // '1022', 'FS', 'Sleutel B3 niet in B4'
m.setKeyToRP(pd.getKeyToRP());
m.setKeyToSourceRegister(pd.getKeyToSourceRegister());
m.setDayEntryHead(pd.getDayEntryHead());
m.setMonthEntryHead(pd.getMonthEntryHead());
m.setYearEntryHead(pd.getYearEntryHead());
m.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
}
// Check that B6 keys are in B4
System.out.println("Check that B6 keys are in B4");
for(RegistrationAddress ra: registrationAddresses){
Registration r = new Registration();
r.setKeyToSourceRegister(ra.getKeyToSourceRegister());
r.setDayEntryHead(ra.getDayEntryHead());
r.setMonthEntryHead(ra.getMonthEntryHead());
r.setYearEntryHead(ra.getYearEntryHead());
r.setKeyToRP(ra.getKeyToRP());
int i = Collections.binarySearch(registrations, r, new ComparatorRegistration());
if(i < 0){
Message m = new Message("1023"); // '1023', 'FS', 'Sleutel B6 niet in B4'
m.setKeyToRP(ra.getKeyToRP());
m.setKeyToSourceRegister(ra.getKeyToSourceRegister());
m.setDayEntryHead(ra.getDayEntryHead());
m.setMonthEntryHead(ra.getMonthEntryHead());
m.setYearEntryHead(ra.getYearEntryHead());
m.setKeyToRegistrationPersons(ra.getKeyToRegistrationPersons());
m.save();
keysOK = false;
//break;
}
}
// Check that B4 does not have double key
System.out.println("Check that B4 has no double key");
keyToSourceRegister = 0;
dayEntryHeadOfHousehold = 0;
monthEntryHeadOfHousehold = 0;
yearEntryHeadOfHousehold = 0;
keyToHSNResearchPerson = 0;
for(Registration r: registrations){
if(keyToSourceRegister == r.getKeyToSourceRegister() &&
dayEntryHeadOfHousehold == r.getDayEntryHead() &&
monthEntryHeadOfHousehold == r.getMonthEntryHead() &&
yearEntryHeadOfHousehold == r.getYearEntryHead() &&
keyToHSNResearchPerson == r.getKeyToRP()){
Message m = new Message("1028"); // '1028', 'FS', 'Dubbele sleutel in B4'
m.setKeyToRP(keyToHSNResearchPerson);
m.setKeyToSourceRegister(keyToSourceRegister);
m.setDayEntryHead(dayEntryHeadOfHousehold);
m.setMonthEntryHead(monthEntryHeadOfHousehold);
m.setYearEntryHead(yearEntryHeadOfHousehold);
m.save();
keysOK = false;
break;
}
else{
keyToSourceRegister = r.getKeyToSourceRegister();
dayEntryHeadOfHousehold = r.getDayEntryHead();
monthEntryHeadOfHousehold = r.getMonthEntryHead();
yearEntryHeadOfHousehold = r.getYearEntryHead();
keyToHSNResearchPerson = r.getKeyToRP();
}
}
// Check that B4 keys are in B2
System.out.println("Check that B4 keys are in B2");
for(Registration r: registrations){
Person p = new Person();
p.setKeyToSourceRegister(r.getKeyToSourceRegister());
p.setDayEntryHead(r.getDayEntryHead());
p.setMonthEntryHead(r.getMonthEntryHead());
p.setYearEntryHead(r.getYearEntryHead());
p.setKeyToRP(r.getKeyToRP());
p.setKeyToRegistrationPersons(1); // because numbering starts with 1
int i = Collections.binarySearch(persons, p, new ComparatorPerson());
if(i < 0){
Message m = new Message("1020"); // '1020', 'FS', 'Sleutel B4 niet in B2'
m.setKeyToRP(r.getKeyToRP());
m.setKeyToSourceRegister(r.getKeyToSourceRegister());
m.setDayEntryHead(r.getDayEntryHead());
m.setMonthEntryHead(r.getMonthEntryHead());
m.setYearEntryHead(r.getYearEntryHead());
m.save();
keysOK = false;
//break;
}
}
// Check that administrative fields in B2 are filled in
System.out.println("Check that administrative fields in B2 are filled in");
count = 0;
for(Person p: persons){
if(p.getOrderNumberOriginal() == null || p.getOrderNumberOriginal().trim().length() == 0 ||
p.getDateOriginal() == null || p.getDateOriginal().trim().length() == 0 ||
p.getInitialOriginal() == null || p.getInitialOriginal().trim().length() == 0 ||
p.getVersionOriginalDataEntry() == null || p.getVersionOriginalDataEntry().trim().length() == 0 ||
p.getResearchCodeOriginal() == null || p.getResearchCodeOriginal().trim().length() == 0){
if(count++ < 5){
Message m = new Message("1024"); // '1024', 'FS', 'B2 administratieve velden niet volledig ingevuld (alleen 1ste 5 gevallen)'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
}
}
}
// Check that administrative fields in B3 are filled in
System.out.println("Check that administrative fields in B3 are filled in");
count = 0;
for(PersonDynamic pd: personsDynamic){
if(pd.getOrderNumberOriginal() == null || pd.getOrderNumberOriginal().trim().length() == 0 ||
pd.getDateOriginal() == null || pd.getDateOriginal().trim().length() == 0 ||
pd.getInitialOriginal() == null || pd.getInitialOriginal().trim().length() == 0 ||
pd.getVersionOriginalDataEntry() == null || pd.getVersionOriginalDataEntry().trim().length() == 0 ||
pd.getResearchCodeOriginal() == null || pd.getResearchCodeOriginal().trim().length() == 0){
if(count++ < 5){
Message m = new Message("1025"); // '1025', 'FS', 'B3 administratieve velden niet volledig ingevuld (alleen 1ste 5 gevallen)'
m.setKeyToRP(pd.getKeyToRP());
m.setKeyToSourceRegister(pd.getKeyToSourceRegister());
m.setDayEntryHead(pd.getDayEntryHead());
m.setMonthEntryHead(pd.getMonthEntryHead());
m.setYearEntryHead(pd.getYearEntryHead());
m.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
m.save();
}
}
}
// Check that administrative fields in B4 are filled in
System.out.println("Check that administrative fields in B4 are filled in");
count = 0;
for(Registration r: registrations){
if(r.getOrderNumberOriginal() == null || r.getOrderNumberOriginal().trim().length() == 0 ||
r.getDateOriginal() == null || r.getDateOriginal().trim().length() == 0 ||
r.getInitialOriginal() == null || r.getInitialOriginal().trim().length() == 0 ||
r.getVersionOriginalDataEntry() == null || r.getVersionOriginalDataEntry().trim().length() == 0 ||
r.getResearchCodeOriginal() == null || r.getResearchCodeOriginal().trim().length() == 0){
if(count++ < 5){
Message m = new Message("1026"); // '1026', 'FS', 'B4 administratieve velden niet volledig ingevuld (alleen 1ste 5 gevallen)'
m.setKeyToRP(r.getKeyToRP());
m.setKeyToSourceRegister(r.getKeyToSourceRegister());
m.setDayEntryHead(r.getDayEntryHead());
m.setMonthEntryHead(r.getMonthEntryHead());
m.setYearEntryHead(r.getYearEntryHead());
m.save();
}
}
}
// Check that administrative fields in B6 are filled in
System.out.println("Check that administrative fields in B6 are filled in");
count = 0;
for(RegistrationAddress ra: registrationAddresses){
if(ra.getOrderNumberOriginal() == null || ra.getOrderNumberOriginal().trim().length() == 0 ||
ra.getDateOriginal() == null || ra.getDateOriginal().trim().length() == 0 ||
ra.getInitialOriginal() == null || ra.getInitialOriginal().trim().length() == 0 ||
ra.getVersionOriginalDataEntry() == null || ra.getVersionOriginalDataEntry().trim().length() == 0 ||
ra.getResearchCodeOriginal() == null || ra.getResearchCodeOriginal().trim().length() == 0){
if(count++ < 5){
Message m = new Message("1027"); // '1027', 'FS', 'B6 administratieve velden niet volledig ingevuld (alleen 1ste 5 gevallen)'
m.setKeyToRP(ra.getKeyToRP());
m.setKeyToSourceRegister(ra.getKeyToSourceRegister());
m.setDayEntryHead(ra.getDayEntryHead());
m.setMonthEntryHead(ra.getMonthEntryHead());
m.setYearEntryHead(ra.getYearEntryHead());
m.setKeyToRegistrationPersons(ra.getKeyToRegistrationPersons());
m.save();
}
}
}
// Check that B2 - B2RNBG starts with 1b
System.out.println("Check that B2:B2RNBG - keyToRegistrationPersons starts with 1");
for(Registration r: registrations){
for(Person p: r.getPersonsInRegistration()){
if(p.getKeyToRegistrationPersons() != 1){
Message m = new Message("1055"); // '1055', 'FS', HSN-volgnummering is in B2 niet goed (begint niet met volgnummer '1')
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
keysOK = false;
//break;
}
break;
}
}
// Check that B2 - B2RNBG is consecutive
System.out.println("Check that B2:B2RNBG - keyToRegistrationPersons is consecutive");
for(Registration r: registrations){
int sn = 0;
for(Person p: r.getPersonsInRegistration()){
if(p.getKeyToRegistrationPersons() != ++sn){
Message m = new Message("1056"); // '1056', 'FS', HSN-volgnummering is niet goed (geconstateerd in B2)
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
keysOK = false;
break;
}
}
}
// Check that B2 - B1IDBG - keyToSourceRegister is in ainb
System.out.println("Check that B2:B1IDBG - keyToSourceRegister is in ainb");
for(Person p: persons){
Ref_AINB ainb = Ref.getAINB(p.getKeyToSourceRegister());
if(ainb == null){
Message m = new Message("1053"); // '1053', 'RF', 'Identificatienummer van de bron <bronnummer> niet in AINB-bestand aanwezig'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save(new Integer(p.getKeyToSourceRegister()).toString());
keysOK = false;
//break;
}
}
// Check that B2 - IDNR - keyToHSNResearchPerson is in HSNRP (geboorteakten)
System.out.println("Check that B2:IDNR - keyToHSNResearchPerson is in HSNRP (geboorteakten)");
for(Person p: persons){
//Ref_GB gb = Ref.getGB(p.getKeyToRP());
Ref_RP rp = Ref.getRP(p.getKeyToRP());
if(rp == null){
Message m = new Message("1054"); // '1054', 'RF',<SUF>
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save(new Integer(p.getKeyToRP()).toString());
keysOK = false;
//break;
}
}
// Check that key B2 is in B3 at least 3 times (for b3type = 1,2,3)
System.out.println("Check that key B2 is in B3 at least 3 times (for b3type = 1,2,3)");
int i_pd = 0;
for(Person p: persons){
PersonDynamic pd = new PersonDynamic();
pd.setKeyToSourceRegister(p.getKeyToSourceRegister());
pd.setDayEntryHead(p.getDayEntryHead());
pd.setMonthEntryHead(p.getMonthEntryHead());
pd.setYearEntryHead(p.getYearEntryHead());
pd.setKeyToRP(p.getKeyToRP());
pd.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
pd.setDynamicDataSequenceNumber(1); // because we look at the first dynamic data element for different values of dynamicDataType
pd.setDynamicDataType(1);
int i = Collections.binarySearch(personsDynamic, pd, new ComparatorPersonDynamic());
if(i < 0){
Message m = new Message("1058"); // '1058', 'FS', 'Sleutel van B2 komt niet voor in B3-bestand, (typenummer 1)'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
pd.setDynamicDataType(2);
i = Collections.binarySearch(personsDynamic, pd, new ComparatorPersonDynamic());
if(i < 0){
Message m = new Message("1059"); // '1059', 'FS', 'Sleutel van B2 komt niet voor in B3-bestand, (typenummer 2)'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
pd.setDynamicDataType(3);
i = Collections.binarySearch(personsDynamic, pd, new ComparatorPersonDynamic());
if(i < 0){
Message m = new Message("1060"); // '1060', 'FS', 'Sleutel van B2 komt niet voor in B3-bestand, (typenummer 3)'
m.setKeyToRP(p.getKeyToRP());
m.setKeyToSourceRegister(p.getKeyToSourceRegister());
m.setDayEntryHead(p.getDayEntryHead());
m.setMonthEntryHead(p.getMonthEntryHead());
m.setYearEntryHead(p.getYearEntryHead());
m.setKeyToRegistrationPersons(p.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
}
// Check that key B3 is in B2
System.out.println("Check that key B3 is in B2 ");
for(PersonDynamic pd: personsDynamic){
Person p = new Person();
p.setKeyToSourceRegister(pd.getKeyToSourceRegister());
p.setDayEntryHead(pd.getDayEntryHead());
p.setMonthEntryHead(pd.getMonthEntryHead());
p.setYearEntryHead(pd.getYearEntryHead());
p.setKeyToRP(pd.getKeyToRP());
p.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
int i = Collections.binarySearch(persons, p, new ComparatorPerson());
if(i < 0){
Message m = new Message("1061"); // '1061', 'FS', 'Sleutel van B3 komt niet voor in B2-bestand'
m.setKeyToRP(pd.getKeyToRP());
m.setKeyToSourceRegister(pd.getKeyToSourceRegister());
m.setDayEntryHead(pd.getDayEntryHead());
m.setMonthEntryHead(pd.getMonthEntryHead());
m.setYearEntryHead(pd.getYearEntryHead());
m.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
}
// Check that key B3 key is ok (per dynamicDataType the dynamicDataSequenceNumber must start with 1 and be contiguous (1, 2, 3, 4......)
System.out.println("Check that key B3 key OK");
int prevType = -1;
int prevSeqNo = -1;
for(PersonDynamic pd: personsDynamic){
if(prevType != pd.getDynamicDataType()){
prevType = pd.getDynamicDataType();
if(pd.getDynamicDataSequenceNumber() != 1){
Message m = new Message("1062"); // '1062', 'FS', 1062, Sleutel van B3 klopt niet (doornummering regels fout bij <typenummer>)
m.setKeyToRP(pd.getKeyToRP());
m.setKeyToSourceRegister(pd.getKeyToSourceRegister());
m.setDayEntryHead(pd.getDayEntryHead());
m.setMonthEntryHead(pd.getMonthEntryHead());
m.setYearEntryHead(pd.getYearEntryHead());
m.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
String [] fills = {"" + pd.getDynamicDataType()};
m.save(fills);
keysOK = false;
continue;
}
else
prevSeqNo = 1;
}
else{
if(pd.getDynamicDataSequenceNumber() != ++prevSeqNo){
Message m = new Message("1062"); // '1062', 'FS', 1062, Sleutel van B3 klopt niet (doornummering regels fout bij <typenummer>)
m.setKeyToRP(pd.getKeyToRP());
m.setKeyToSourceRegister(pd.getKeyToSourceRegister());
m.setDayEntryHead(pd.getDayEntryHead());
m.setMonthEntryHead(pd.getMonthEntryHead());
m.setYearEntryHead(pd.getYearEntryHead());
m.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
String [] fills = {"" + pd.getDynamicDataType()};
m.save(fills);
keysOK = false;
continue;
}
}
}
// Check that partial key B6 is in B2
System.out.println("Check that partial key B6 is in B2 ");
for(RegistrationAddress ra: registrationAddresses){
Person p = new Person();
p.setKeyToSourceRegister(ra.getKeyToSourceRegister());
p.setDayEntryHead(ra.getDayEntryHead());
p.setMonthEntryHead(ra.getMonthEntryHead());
p.setYearEntryHead(ra.getYearEntryHead());
p.setKeyToRP(ra.getKeyToRP());
if(ra.getKeyToRegistrationPersons() == 0)
p.setKeyToRegistrationPersons(1); // household bound address, look for first person
else
p.setKeyToRegistrationPersons(ra.getKeyToRegistrationPersons()); // address for specific person
int i = Collections.binarySearch(persons, p, new ComparatorPerson());
if(i < 0){
//System.out.println("XXXXX " + 3);
Message m = new Message("1063"); // '1063', 'FS', 'Sleutel van B6 komt niet voor in B2-bestand'
m.setKeyToRP(ra.getKeyToRP());
m.setKeyToSourceRegister(ra.getKeyToSourceRegister());
m.setDayEntryHead(ra.getDayEntryHead());
m.setMonthEntryHead(ra.getMonthEntryHead());
m.setYearEntryHead(ra.getYearEntryHead());
m.save();
keysOK = false;
}
}
// Check that B3:B2RNBG != B3:B3RGLN. This means the related person is the person itself. This is always incorrect
System.out.println("Check that B3 valueOfRelatedPerson (B3RGLN) is not equal to B3 keyToRegistrationPersons (B2RNGB) ");
for(PersonDynamic pd: personsDynamic){
if(pd.getValueOfRelatedPerson() == pd.getKeyToRegistrationPersons()){
Message m = new Message("1314"); //1314, FT, Regelnummer verwijst voor regelnummer van de relatie naar de eigen regel.
m.setKeyToRP(pd.getKeyToRP());
m.setKeyToSourceRegister(pd.getKeyToSourceRegister());
m.setDayEntryHead(pd.getDayEntryHead());
m.setMonthEntryHead(pd.getMonthEntryHead());
m.setYearEntryHead(pd.getYearEntryHead());
m.setKeyToRegistrationPersons(pd.getKeyToRegistrationPersons());
m.save();
keysOK = false;
}
}
return(keysOK);
}
}
|
18033_7 | package org.iish.hsn.invoer.service.akte;
import org.iish.hsn.invoer.domain.invoer.Byz;
import org.iish.hsn.invoer.domain.invoer.geb.*;
import org.iish.hsn.invoer.exception.AkteException;
import org.iish.hsn.invoer.exception.NotFoundException;
import org.iish.hsn.invoer.flow.state.*;
import org.iish.hsn.invoer.flow.helper.GeboorteAkteHelper;
import org.iish.hsn.invoer.repository.invoer.geb.*;
import org.iish.hsn.invoer.service.LookupService;
import org.iish.hsn.invoer.util.Cohort;
import org.iish.hsn.invoer.util.InputMetadata;
import org.iish.hsn.invoer.util.InputMetadataChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Deals with the preparation and storage of various elements of the 'geboorte akte' (birth certificate).
*/
@Service
public class GeboorteAkteService extends AkteService {
@Autowired private InputMetadata inputMetadata;
@Autowired private InputMetadataChecker inputMetadataChecker;
@Autowired private GeboorteStart geboorteStart;
@Autowired private GeboorteAkteHelper geboorteAkteHelper;
@Autowired private LookupService lookupService;
@Autowired private GebakteRepository gebakteRepository;
@Autowired private GebkndRepository gebkndRepository;
@Autowired private GebvdrRepository gebvdrRepository;
@Autowired private GebkantRepository gebkantRepository;
@Autowired private GebgtgRepository gebgtgRepository;
@Autowired private GebbyzRepository gebbyzRepository;
/**
* Creates a new geboorte akte flow state for new input with all required domain objects.
*
* @return A new geboorte akte flow state.
*/
public GeboorteAkteFlowState createNewAkteForNewInput() {
GeboorteAkteFlowState geboorteAkteFlow = createNewAkte();
geboorteAkteFlow.setCorrection(false);
geboorteAkteFlow.setViewStateHistory(new ViewStateHistory("GS0I", "checkGebAkte"));
return geboorteAkteFlow;
}
/**
* Creates a new geboorte akte flow state for correction with all required domain objects.
*
* @return A new geboorte akte flow state.
*/
public GeboorteAkteFlowState createNewAkteForCorrection() {
GeboorteAkteFlowState geboorteAkteFlow = createNewAkte();
geboorteAkteFlow.setCorrection(true);
geboorteAkteFlow.setViewStateHistory(new ViewStateHistory("GS0C", "GCOR"));
return geboorteAkteFlow;
}
/**
* Link the OP (onderzoekspersoon, research person) of whom the user has the birth certificate.
*
* @param geboorteAkteFlow The geboorte akte flow state.
* @throws AkteException Thrown when the OP was not found in the sample.
*/
public void registerOP(GeboorteAkteFlowState geboorteAkteFlow) throws AkteException {
try {
Gebakte newGebakte = geboorteAkteFlow.getGebakte();
Gebakte oldGebakte = lookupService.getGebakte(newGebakte.getIdnr(), false);
Stpb stpb = lookupService.getStpb(newGebakte.getIdnr(), true);
newGebakte.setGemnr(stpb.getGemnr());
newGebakte.setJaar(stpb.getJaar());
newGebakte.setAktenr(stpb.getAktenr());
newGebakte.setOversamp(geboorteStart.getOversamp());
if (oldGebakte != null) {
gebakteRepository.delete(oldGebakte);
}
if (newGebakte.getGebkode() != 1) {
inputMetadataChecker.saveToEntity(newGebakte, inputMetadata);
newGebakte = gebakteRepository.save(newGebakte);
}
if ((oldGebakte != null) && (newGebakte.getGebkode() == 1)) {
List<Gebbyz> gebbyz =
gebbyzRepository.findByIdnrAndWorkOrder(newGebakte.getIdnr(), inputMetadata.getWorkOrder());
gebbyzRepository.deleteAll(gebbyz);
}
geboorteAkteFlow.setStpb(stpb);
geboorteAkteFlow.setGebakte(newGebakte);
}
catch (NotFoundException nfe) {
throw new AkteException(nfe);
}
}
/**
* Link the OP (onderzoekspersoon, research person) of whom the user has to edit the birth certificate.
*
* @param geboorteAkteFlow The geboorte akte flow state.
* @throws AkteException Thrown when the OP was not found in the sample.
*/
public void editOP(GeboorteAkteFlowState geboorteAkteFlow) throws AkteException {
try {
Gebakte gebakte = geboorteAkteFlow.getGebakte();
int idnr = gebakte.getIdnr();
// Before we overwrite gebknd, make sure that changes to the date are preserved
Gebknd gebknd = geboorteAkteFlow.getGebknd();
int dag = gebknd.getAktedag();
int maand = gebknd.getAktemnd();
int uur = gebknd.getAkteuur();
geboorteAkteFlow.setStpb(lookupService.getStpb(idnr, true));
// Now look up the gebknd record and update the changes to the date
gebknd = lookupService.getGebknd(idnr, false);
if (gebknd != null) {
gebknd.setAktedag(dag);
gebknd.setAktemnd(maand);
gebknd.setAkteuur(uur);
inputMetadataChecker.saveToEntity(gebknd, inputMetadata);
gebknd = gebkndRepository.save(gebknd);
geboorteAkteFlow.setGebknd(gebknd);
}
gebakte = lookupService.getGebakte(idnr, false);
if (gebakte != null) {
geboorteAkteFlow.setGebakte(gebakte);
}
Gebvdr gebvdr = gebvdrRepository.findByIdnrAndWorkOrder(idnr, inputMetadata.getWorkOrder());
if (gebvdr != null) {
geboorteAkteFlow.setGebvdr(gebvdr);
}
Gebkant gebkant = gebkantRepository.findByIdnrAndWorkOrder(idnr, inputMetadata.getWorkOrder());
if (gebkant != null) {
geboorteAkteFlow.setGebkant(gebkant);
}
List<Gebgtg> gebgtgList = gebgtgRepository.findByIdnrAndWorkOrder(idnr, inputMetadata.getWorkOrder());
if (gebgtgList != null) {
Gebgtg[] gebgtg = {new Gebgtg(1), new Gebgtg(2)};
for (Gebgtg curGebgtg : gebgtgList) {
gebgtg[curGebgtg.getVlgnrgt() - 1] = curGebgtg;
}
geboorteAkteFlow.setGebgtg(gebgtg);
geboorteAkteFlow.setCurGebgtgIndex(0);
}
List<Gebbyz> gebbyz = gebbyzRepository.findByIdnrAndWorkOrder(idnr, inputMetadata.getWorkOrder());
if (gebbyz != null) {
geboorteAkteFlow.setGebbyz(new HashSet<>(gebbyz));
}
geboorteAkteFlow.setNrOfByzEntered(geboorteAkteFlow.getGebbyz().size());
}
catch (NotFoundException nfe) {
throw new AkteException(nfe);
}
}
/**
* Register the aangever, called after screen GS1.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerAangever(GeboorteAkteFlowState geboorteAkteFlow) {
Stpb stpb = geboorteAkteFlow.getStpb();
Gebknd gebknd = geboorteAkteFlow.getGebknd();
// Copy some fields from the sample
if (!geboorteAkteFlow.isCorrection()) {
Cohort cohort = Cohort.getCohortByYear(gebknd.getJaar());
gebknd.setIdnr(stpb.getIdnr());
gebknd.setGemnr(stpb.getGemnr());
gebknd.setJaar(stpb.getJaar());
gebknd.setAktenr(stpb.getAktenr());
gebknd.setCohortnr(cohort.getCohortNumber());
gebknd.setOversamp(geboorteStart.getOversamp());
gebknd.setInvbeper(geboorteStart.getInvbeper());
// Already print the birth year for the user
gebknd.setGebjr(stpb.getJaar());
}
if (gebknd.getInvbeper().equals("j") && gebknd.getAnmag().equals("Xx")) {
gebknd.setAnmag("Vroedvrouw of verg. persoon");
}
if (gebknd.getLftag() == 0) {
gebknd.setLftag(-1);
}
// The user can still stop the flow, so only save during correction
if (geboorteAkteFlow.isCorrection()) {
inputMetadataChecker.saveToEntity(gebknd, inputMetadata);
gebknd = gebkndRepository.save(gebknd);
geboorteAkteFlow.setGebknd(gebknd);
}
}
/**
* Register the geboorte (birth) and the moeder (mother), called after screen GS2.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerGeboorteAndMoeder(GeboorteAkteFlowState geboorteAkteFlow) {
Gebknd gebknd = geboorteAkteFlow.getGebknd();
if (gebknd.getLftmr() == 0) {
gebknd.setLftmr(-1);
}
saveGebknd(geboorteAkteFlow);
}
/**
* Register the moeder (mother) and the kind (child), called after screen GS3.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerMoederAndKind(GeboorteAkteFlowState geboorteAkteFlow) {
saveGebknd(geboorteAkteFlow);
// Already set the last name of the father for the users convenience.
String anmgeb = geboorteAkteFlow.getGebknd().getAnmgeb();
String anmmr = geboorteAkteFlow.getGebknd().getAnmmr();
if (!geboorteAkteFlow.isCorrection() && (anmgeb != null) && !anmgeb.equals(anmmr)) {
geboorteAkteFlow.getGebvdr().setAnmvr(anmgeb);
}
// Delete the information about the father if during correction the father happens to be the declarant as well
String brgstmr = geboorteAkteFlow.getGebknd().getBrgstmr();
if (geboorteAkteFlow.isCorrection() && Arrays.asList(5, 7, 8).contains(Integer.valueOf(brgstmr))) {
gebvdrRepository.delete(geboorteAkteFlow.getGebvdr());
}
}
/**
* Register the vader (father), called after screen GS4.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerVader(GeboorteAkteFlowState geboorteAkteFlow) {
Gebvdr gebvdr = geboorteAkteFlow.getGebvdr();
if (gebvdr.getLftvr() == 0) {
gebvdr.setLftvr(-1);
}
// Simply delete the previous record if there is no information to make sure we have a clean record again
if (geboorteAkteFlow.isCorrection() && !gebvdr.getGegvr().equals("j")) {
gebvdrRepository.delete(gebvdr);
gebvdr = new Gebvdr();
gebvdr.setGegvr("n");
}
// Make sure certain fields are emptied (difference between a previous husband due to a divorce or due to death)
String brgstmr = geboorteAkteFlow.getGebknd().getBrgstmr();
if (Integer.parseInt(brgstmr) != 2) {
gebvdr.setG5vood(0);
gebvdr.setG5voom(0);
gebvdr.setG5vooj(0);
gebvdr.setG5vogo("");
}
if (Integer.parseInt(brgstmr) != 3) {
gebvdr.setG5oosd(0);
gebvdr.setG5oosm(0);
gebvdr.setG5oosj(0);
gebvdr.setG5oogs("");
}
gebvdr.setIdnr(geboorteAkteFlow.getGebknd().getIdnr());
inputMetadataChecker.saveToEntity(gebvdr, inputMetadata);
gebvdr = gebvdrRepository.save(gebvdr);
geboorteAkteFlow.setGebvdr(gebvdr);
}
/**
* Register the getuige (witness), called after screen GS5.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerGetuige(GeboorteAkteFlowState geboorteAkteFlow) {
Gebgtg gebgtgCur = geboorteAkteFlow.getCurGebgtg();
gebgtgCur.setIdnr(geboorteAkteFlow.getGebknd().getIdnr());
if (gebgtgCur.getLftgt() == 0) {
gebgtgCur.setLftgt(-1);
}
inputMetadataChecker.saveToEntity(gebgtgCur, inputMetadata);
gebgtgCur = gebgtgRepository.save(gebgtgCur);
Gebgtg[] gebgtg = geboorteAkteFlow.getGebgtg();
gebgtg[geboorteAkteFlow.getCurGebgtgIndex()] = gebgtgCur;
geboorteAkteFlow.setGebgtg(gebgtg);
}
/**
* Register the kantmelding (side message) type, called after screen GS6.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerKanttype(GeboorteAkteFlowState geboorteAkteFlow) {
Gebkant gebkant = geboorteAkteFlow.getGebkant();
gebkant.setIdnr(geboorteAkteFlow.getGebknd().getIdnr());
inputMetadataChecker.saveToEntity(gebkant, inputMetadata);
gebkant = gebkantRepository.save(gebkant);
geboorteAkteFlow.setGebkant(gebkant);
}
/**
* Register the kantmeldingen (side messages), called after screens GS7a, GS7b, GS7c and GS7d.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerKantmeldingen(GeboorteAkteFlowState geboorteAkteFlow) {
Gebkant gebkant = geboorteAkteFlow.getGebkant();
// Clean up all differences changes between the four different screens
if (gebkant.getKanttype() == 1) {
gebkant.setKanmgeb(gebkant.getKanmvad());
}
if (Arrays.asList(2, 3, 4).contains(gebkant.getKanttype())) {
if (!geboorteAkteHelper.getKantmeldingDatum(gebkant).equals("j")) {
gebkant.setKantdag(-1);
gebkant.setKantmnd(-1);
gebkant.setKantjr(-1);
}
if (!geboorteAkteHelper.getKantmeldingBesluitDatum(gebkant).equals("j")) {
gebkant.setKwyzdag(-1);
gebkant.setKwyzmnd(-1);
gebkant.setKwyzjr(-1);
gebkant.setKwyzkb(-1);
gebkant.setKwyzstbl(-1);
}
}
// Also clean up after correction
if (geboorteAkteFlow.isCorrection() && Arrays.asList(1, 5).contains(gebkant.getKanttype())) {
gebkant.setKwyzdag(0);
gebkant.setKwyzmnd(0);
gebkant.setKwyzjr(0);
gebkant.setKwyzkb(0);
gebkant.setKwyzstbl(0);
gebkant.setKanmgeb("");
gebkant.setKvrn1geb("");
gebkant.setKvrn2geb("");
gebkant.setKvrn3geb("");
gebkant.setKsexgeb("");
gebkant.setKgmrb("");
gebkant.setKgmerk("");
gebkant.setKwgmmr("");
gebkant.setKbrpmr("");
}
if (geboorteAkteFlow.isCorrection() && Arrays.asList(2, 5).contains(gebkant.getKanttype())) {
gebkant.setKhuwdag(0);
gebkant.setKhuwmnd(0);
gebkant.setKhuwjr(0);
gebkant.setKhuwgem("");
gebkant.setKhuwanr("");
gebkant.setKanmvad("");
gebkant.setKvrn1vad("");
gebkant.setKvrn2vad("");
gebkant.setKvrn3vad("");
gebkant.setKgmrb("");
gebkant.setKgmerk("");
gebkant.setKwgmmr("");
gebkant.setKbrpmr("");
}
if (geboorteAkteFlow.isCorrection() && Arrays.asList(3, 5).contains(gebkant.getKanttype())) {
gebkant.setKhuwdag(0);
gebkant.setKhuwmnd(0);
gebkant.setKhuwjr(0);
gebkant.setKhuwgem("");
gebkant.setKhuwanr("");
gebkant.setKanmvad("");
gebkant.setKvrn1vad("");
gebkant.setKvrn2vad("");
gebkant.setKvrn3vad("");
gebkant.setKwyzkb(0);
gebkant.setKwyzstbl(0);
gebkant.setKgmerk("");
gebkant.setKwgmmr("");
gebkant.setKbrpmr("");
}
if (geboorteAkteFlow.isCorrection() && Arrays.asList(4, 5).contains(gebkant.getKanttype())) {
gebkant.setKhuwdag(0);
gebkant.setKhuwmnd(0);
gebkant.setKhuwjr(0);
gebkant.setKhuwgem("");
gebkant.setKhuwanr("");
gebkant.setKanmvad("");
gebkant.setKvrn1vad("");
gebkant.setKvrn2vad("");
gebkant.setKvrn3vad("");
gebkant.setKwyzkb(0);
gebkant.setKwyzstbl(0);
gebkant.setKanmgeb("");
gebkant.setKvrn1geb("");
gebkant.setKvrn2geb("");
gebkant.setKvrn3geb("");
gebkant.setKsexgeb("");
gebkant.setKgmrb("");
}
if (geboorteAkteFlow.isCorrection() && (gebkant.getKanttype() == 5)) {
gebkant.setKantdag(0);
gebkant.setKantmnd(0);
gebkant.setKantjr(0);
}
inputMetadataChecker.saveToEntity(gebkant, inputMetadata);
gebkant = gebkantRepository.save(gebkant);
geboorteAkteFlow.setGebkant(gebkant);
}
/**
* Register the check whether to add byz, called after screen GS8.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerByzCheck(GeboorteAkteFlowState geboorteAkteFlow) {
saveGebknd(geboorteAkteFlow);
}
/**
* Deletes the current geboorte akte.
*
* @param akteFlow The akte flow state.
*/
@Override
public void deleteAkte(AkteFlowState akteFlow) {
GeboorteAkteFlowState geboorteAkteFlow = (GeboorteAkteFlowState) akteFlow;
gebakteRepository.delete(geboorteAkteFlow.getGebakte());
gebkndRepository.delete(geboorteAkteFlow.getGebknd());
gebvdrRepository.delete(geboorteAkteFlow.getGebvdr());
gebkantRepository.delete(geboorteAkteFlow.getGebkant());
gebgtgRepository.deleteAll(Arrays.asList(geboorteAkteFlow.getGebgtg()));
gebbyzRepository.deleteAll(geboorteAkteFlow.getGebbyz());
}
/**
* Save the given byz field.
*
* @param byzAkteFlowState Akte flow state.
* @param byz The byz.
*/
@Override
protected void saveByz(ByzAkteFlowState byzAkteFlowState, Byz byz) {
GeboorteAkteFlowState geboorteAkteFlowState = (GeboorteAkteFlowState) byzAkteFlowState;
Gebbyz gebbyz = (Gebbyz) byz;
gebbyz.setIdnr(geboorteAkteFlowState.getStpb().getIdnr());
inputMetadataChecker.saveToEntity(gebbyz, inputMetadata);
gebbyz = gebbyzRepository.save(gebbyz);
geboorteAkteFlowState.addToGebbyz(gebbyz);
}
@Override
protected void deleteByz(ByzAkteFlowState byzAkteFlowState, Byz byz) {
GeboorteAkteFlowState geboorteAkteFlowState = (GeboorteAkteFlowState) byzAkteFlowState;
Gebbyz gebbyz = (Gebbyz) byz;
gebbyzRepository.delete(gebbyz);
geboorteAkteFlowState.removeFromGebbyz(gebbyz);
}
/**
* Creates a new geboorte akte flow state with all required domain objects.
*
* @return A new geboorte akte flow state.
*/
private GeboorteAkteFlowState createNewAkte() {
Gebakte gebakte = new Gebakte();
Gebknd gebknd = new Gebknd();
Gebvdr gebvdr = new Gebvdr();
Gebkant gebkant = new Gebkant();
Gebgtg[] gebgtg = {new Gebgtg(1), new Gebgtg(2)}; // Always two witnesses
Set<Gebbyz> gebbyz = new HashSet<>();
return new GeboorteAkteFlowState(gebakte, gebknd, gebvdr, gebkant, gebgtg, gebbyz);
}
/**
* Persists the gebknd record (main birth certificate record) to the database.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
private void saveGebknd(GeboorteAkteFlowState geboorteAkteFlow) {
Gebknd gebknd = geboorteAkteFlow.getGebknd();
inputMetadataChecker.saveToEntity(gebknd, inputMetadata);
gebknd = gebkndRepository.save(gebknd);
geboorteAkteFlow.setGebknd(gebknd);
}
} | IISH/hsn-invoer | src/main/java/org/iish/hsn/invoer/service/akte/GeboorteAkteService.java | 6,649 | /**
* Register the aangever, called after screen GS1.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/ | block_comment | nl | package org.iish.hsn.invoer.service.akte;
import org.iish.hsn.invoer.domain.invoer.Byz;
import org.iish.hsn.invoer.domain.invoer.geb.*;
import org.iish.hsn.invoer.exception.AkteException;
import org.iish.hsn.invoer.exception.NotFoundException;
import org.iish.hsn.invoer.flow.state.*;
import org.iish.hsn.invoer.flow.helper.GeboorteAkteHelper;
import org.iish.hsn.invoer.repository.invoer.geb.*;
import org.iish.hsn.invoer.service.LookupService;
import org.iish.hsn.invoer.util.Cohort;
import org.iish.hsn.invoer.util.InputMetadata;
import org.iish.hsn.invoer.util.InputMetadataChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Deals with the preparation and storage of various elements of the 'geboorte akte' (birth certificate).
*/
@Service
public class GeboorteAkteService extends AkteService {
@Autowired private InputMetadata inputMetadata;
@Autowired private InputMetadataChecker inputMetadataChecker;
@Autowired private GeboorteStart geboorteStart;
@Autowired private GeboorteAkteHelper geboorteAkteHelper;
@Autowired private LookupService lookupService;
@Autowired private GebakteRepository gebakteRepository;
@Autowired private GebkndRepository gebkndRepository;
@Autowired private GebvdrRepository gebvdrRepository;
@Autowired private GebkantRepository gebkantRepository;
@Autowired private GebgtgRepository gebgtgRepository;
@Autowired private GebbyzRepository gebbyzRepository;
/**
* Creates a new geboorte akte flow state for new input with all required domain objects.
*
* @return A new geboorte akte flow state.
*/
public GeboorteAkteFlowState createNewAkteForNewInput() {
GeboorteAkteFlowState geboorteAkteFlow = createNewAkte();
geboorteAkteFlow.setCorrection(false);
geboorteAkteFlow.setViewStateHistory(new ViewStateHistory("GS0I", "checkGebAkte"));
return geboorteAkteFlow;
}
/**
* Creates a new geboorte akte flow state for correction with all required domain objects.
*
* @return A new geboorte akte flow state.
*/
public GeboorteAkteFlowState createNewAkteForCorrection() {
GeboorteAkteFlowState geboorteAkteFlow = createNewAkte();
geboorteAkteFlow.setCorrection(true);
geboorteAkteFlow.setViewStateHistory(new ViewStateHistory("GS0C", "GCOR"));
return geboorteAkteFlow;
}
/**
* Link the OP (onderzoekspersoon, research person) of whom the user has the birth certificate.
*
* @param geboorteAkteFlow The geboorte akte flow state.
* @throws AkteException Thrown when the OP was not found in the sample.
*/
public void registerOP(GeboorteAkteFlowState geboorteAkteFlow) throws AkteException {
try {
Gebakte newGebakte = geboorteAkteFlow.getGebakte();
Gebakte oldGebakte = lookupService.getGebakte(newGebakte.getIdnr(), false);
Stpb stpb = lookupService.getStpb(newGebakte.getIdnr(), true);
newGebakte.setGemnr(stpb.getGemnr());
newGebakte.setJaar(stpb.getJaar());
newGebakte.setAktenr(stpb.getAktenr());
newGebakte.setOversamp(geboorteStart.getOversamp());
if (oldGebakte != null) {
gebakteRepository.delete(oldGebakte);
}
if (newGebakte.getGebkode() != 1) {
inputMetadataChecker.saveToEntity(newGebakte, inputMetadata);
newGebakte = gebakteRepository.save(newGebakte);
}
if ((oldGebakte != null) && (newGebakte.getGebkode() == 1)) {
List<Gebbyz> gebbyz =
gebbyzRepository.findByIdnrAndWorkOrder(newGebakte.getIdnr(), inputMetadata.getWorkOrder());
gebbyzRepository.deleteAll(gebbyz);
}
geboorteAkteFlow.setStpb(stpb);
geboorteAkteFlow.setGebakte(newGebakte);
}
catch (NotFoundException nfe) {
throw new AkteException(nfe);
}
}
/**
* Link the OP (onderzoekspersoon, research person) of whom the user has to edit the birth certificate.
*
* @param geboorteAkteFlow The geboorte akte flow state.
* @throws AkteException Thrown when the OP was not found in the sample.
*/
public void editOP(GeboorteAkteFlowState geboorteAkteFlow) throws AkteException {
try {
Gebakte gebakte = geboorteAkteFlow.getGebakte();
int idnr = gebakte.getIdnr();
// Before we overwrite gebknd, make sure that changes to the date are preserved
Gebknd gebknd = geboorteAkteFlow.getGebknd();
int dag = gebknd.getAktedag();
int maand = gebknd.getAktemnd();
int uur = gebknd.getAkteuur();
geboorteAkteFlow.setStpb(lookupService.getStpb(idnr, true));
// Now look up the gebknd record and update the changes to the date
gebknd = lookupService.getGebknd(idnr, false);
if (gebknd != null) {
gebknd.setAktedag(dag);
gebknd.setAktemnd(maand);
gebknd.setAkteuur(uur);
inputMetadataChecker.saveToEntity(gebknd, inputMetadata);
gebknd = gebkndRepository.save(gebknd);
geboorteAkteFlow.setGebknd(gebknd);
}
gebakte = lookupService.getGebakte(idnr, false);
if (gebakte != null) {
geboorteAkteFlow.setGebakte(gebakte);
}
Gebvdr gebvdr = gebvdrRepository.findByIdnrAndWorkOrder(idnr, inputMetadata.getWorkOrder());
if (gebvdr != null) {
geboorteAkteFlow.setGebvdr(gebvdr);
}
Gebkant gebkant = gebkantRepository.findByIdnrAndWorkOrder(idnr, inputMetadata.getWorkOrder());
if (gebkant != null) {
geboorteAkteFlow.setGebkant(gebkant);
}
List<Gebgtg> gebgtgList = gebgtgRepository.findByIdnrAndWorkOrder(idnr, inputMetadata.getWorkOrder());
if (gebgtgList != null) {
Gebgtg[] gebgtg = {new Gebgtg(1), new Gebgtg(2)};
for (Gebgtg curGebgtg : gebgtgList) {
gebgtg[curGebgtg.getVlgnrgt() - 1] = curGebgtg;
}
geboorteAkteFlow.setGebgtg(gebgtg);
geboorteAkteFlow.setCurGebgtgIndex(0);
}
List<Gebbyz> gebbyz = gebbyzRepository.findByIdnrAndWorkOrder(idnr, inputMetadata.getWorkOrder());
if (gebbyz != null) {
geboorteAkteFlow.setGebbyz(new HashSet<>(gebbyz));
}
geboorteAkteFlow.setNrOfByzEntered(geboorteAkteFlow.getGebbyz().size());
}
catch (NotFoundException nfe) {
throw new AkteException(nfe);
}
}
/**
* Register the aangever,<SUF>*/
public void registerAangever(GeboorteAkteFlowState geboorteAkteFlow) {
Stpb stpb = geboorteAkteFlow.getStpb();
Gebknd gebknd = geboorteAkteFlow.getGebknd();
// Copy some fields from the sample
if (!geboorteAkteFlow.isCorrection()) {
Cohort cohort = Cohort.getCohortByYear(gebknd.getJaar());
gebknd.setIdnr(stpb.getIdnr());
gebknd.setGemnr(stpb.getGemnr());
gebknd.setJaar(stpb.getJaar());
gebknd.setAktenr(stpb.getAktenr());
gebknd.setCohortnr(cohort.getCohortNumber());
gebknd.setOversamp(geboorteStart.getOversamp());
gebknd.setInvbeper(geboorteStart.getInvbeper());
// Already print the birth year for the user
gebknd.setGebjr(stpb.getJaar());
}
if (gebknd.getInvbeper().equals("j") && gebknd.getAnmag().equals("Xx")) {
gebknd.setAnmag("Vroedvrouw of verg. persoon");
}
if (gebknd.getLftag() == 0) {
gebknd.setLftag(-1);
}
// The user can still stop the flow, so only save during correction
if (geboorteAkteFlow.isCorrection()) {
inputMetadataChecker.saveToEntity(gebknd, inputMetadata);
gebknd = gebkndRepository.save(gebknd);
geboorteAkteFlow.setGebknd(gebknd);
}
}
/**
* Register the geboorte (birth) and the moeder (mother), called after screen GS2.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerGeboorteAndMoeder(GeboorteAkteFlowState geboorteAkteFlow) {
Gebknd gebknd = geboorteAkteFlow.getGebknd();
if (gebknd.getLftmr() == 0) {
gebknd.setLftmr(-1);
}
saveGebknd(geboorteAkteFlow);
}
/**
* Register the moeder (mother) and the kind (child), called after screen GS3.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerMoederAndKind(GeboorteAkteFlowState geboorteAkteFlow) {
saveGebknd(geboorteAkteFlow);
// Already set the last name of the father for the users convenience.
String anmgeb = geboorteAkteFlow.getGebknd().getAnmgeb();
String anmmr = geboorteAkteFlow.getGebknd().getAnmmr();
if (!geboorteAkteFlow.isCorrection() && (anmgeb != null) && !anmgeb.equals(anmmr)) {
geboorteAkteFlow.getGebvdr().setAnmvr(anmgeb);
}
// Delete the information about the father if during correction the father happens to be the declarant as well
String brgstmr = geboorteAkteFlow.getGebknd().getBrgstmr();
if (geboorteAkteFlow.isCorrection() && Arrays.asList(5, 7, 8).contains(Integer.valueOf(brgstmr))) {
gebvdrRepository.delete(geboorteAkteFlow.getGebvdr());
}
}
/**
* Register the vader (father), called after screen GS4.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerVader(GeboorteAkteFlowState geboorteAkteFlow) {
Gebvdr gebvdr = geboorteAkteFlow.getGebvdr();
if (gebvdr.getLftvr() == 0) {
gebvdr.setLftvr(-1);
}
// Simply delete the previous record if there is no information to make sure we have a clean record again
if (geboorteAkteFlow.isCorrection() && !gebvdr.getGegvr().equals("j")) {
gebvdrRepository.delete(gebvdr);
gebvdr = new Gebvdr();
gebvdr.setGegvr("n");
}
// Make sure certain fields are emptied (difference between a previous husband due to a divorce or due to death)
String brgstmr = geboorteAkteFlow.getGebknd().getBrgstmr();
if (Integer.parseInt(brgstmr) != 2) {
gebvdr.setG5vood(0);
gebvdr.setG5voom(0);
gebvdr.setG5vooj(0);
gebvdr.setG5vogo("");
}
if (Integer.parseInt(brgstmr) != 3) {
gebvdr.setG5oosd(0);
gebvdr.setG5oosm(0);
gebvdr.setG5oosj(0);
gebvdr.setG5oogs("");
}
gebvdr.setIdnr(geboorteAkteFlow.getGebknd().getIdnr());
inputMetadataChecker.saveToEntity(gebvdr, inputMetadata);
gebvdr = gebvdrRepository.save(gebvdr);
geboorteAkteFlow.setGebvdr(gebvdr);
}
/**
* Register the getuige (witness), called after screen GS5.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerGetuige(GeboorteAkteFlowState geboorteAkteFlow) {
Gebgtg gebgtgCur = geboorteAkteFlow.getCurGebgtg();
gebgtgCur.setIdnr(geboorteAkteFlow.getGebknd().getIdnr());
if (gebgtgCur.getLftgt() == 0) {
gebgtgCur.setLftgt(-1);
}
inputMetadataChecker.saveToEntity(gebgtgCur, inputMetadata);
gebgtgCur = gebgtgRepository.save(gebgtgCur);
Gebgtg[] gebgtg = geboorteAkteFlow.getGebgtg();
gebgtg[geboorteAkteFlow.getCurGebgtgIndex()] = gebgtgCur;
geboorteAkteFlow.setGebgtg(gebgtg);
}
/**
* Register the kantmelding (side message) type, called after screen GS6.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerKanttype(GeboorteAkteFlowState geboorteAkteFlow) {
Gebkant gebkant = geboorteAkteFlow.getGebkant();
gebkant.setIdnr(geboorteAkteFlow.getGebknd().getIdnr());
inputMetadataChecker.saveToEntity(gebkant, inputMetadata);
gebkant = gebkantRepository.save(gebkant);
geboorteAkteFlow.setGebkant(gebkant);
}
/**
* Register the kantmeldingen (side messages), called after screens GS7a, GS7b, GS7c and GS7d.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerKantmeldingen(GeboorteAkteFlowState geboorteAkteFlow) {
Gebkant gebkant = geboorteAkteFlow.getGebkant();
// Clean up all differences changes between the four different screens
if (gebkant.getKanttype() == 1) {
gebkant.setKanmgeb(gebkant.getKanmvad());
}
if (Arrays.asList(2, 3, 4).contains(gebkant.getKanttype())) {
if (!geboorteAkteHelper.getKantmeldingDatum(gebkant).equals("j")) {
gebkant.setKantdag(-1);
gebkant.setKantmnd(-1);
gebkant.setKantjr(-1);
}
if (!geboorteAkteHelper.getKantmeldingBesluitDatum(gebkant).equals("j")) {
gebkant.setKwyzdag(-1);
gebkant.setKwyzmnd(-1);
gebkant.setKwyzjr(-1);
gebkant.setKwyzkb(-1);
gebkant.setKwyzstbl(-1);
}
}
// Also clean up after correction
if (geboorteAkteFlow.isCorrection() && Arrays.asList(1, 5).contains(gebkant.getKanttype())) {
gebkant.setKwyzdag(0);
gebkant.setKwyzmnd(0);
gebkant.setKwyzjr(0);
gebkant.setKwyzkb(0);
gebkant.setKwyzstbl(0);
gebkant.setKanmgeb("");
gebkant.setKvrn1geb("");
gebkant.setKvrn2geb("");
gebkant.setKvrn3geb("");
gebkant.setKsexgeb("");
gebkant.setKgmrb("");
gebkant.setKgmerk("");
gebkant.setKwgmmr("");
gebkant.setKbrpmr("");
}
if (geboorteAkteFlow.isCorrection() && Arrays.asList(2, 5).contains(gebkant.getKanttype())) {
gebkant.setKhuwdag(0);
gebkant.setKhuwmnd(0);
gebkant.setKhuwjr(0);
gebkant.setKhuwgem("");
gebkant.setKhuwanr("");
gebkant.setKanmvad("");
gebkant.setKvrn1vad("");
gebkant.setKvrn2vad("");
gebkant.setKvrn3vad("");
gebkant.setKgmrb("");
gebkant.setKgmerk("");
gebkant.setKwgmmr("");
gebkant.setKbrpmr("");
}
if (geboorteAkteFlow.isCorrection() && Arrays.asList(3, 5).contains(gebkant.getKanttype())) {
gebkant.setKhuwdag(0);
gebkant.setKhuwmnd(0);
gebkant.setKhuwjr(0);
gebkant.setKhuwgem("");
gebkant.setKhuwanr("");
gebkant.setKanmvad("");
gebkant.setKvrn1vad("");
gebkant.setKvrn2vad("");
gebkant.setKvrn3vad("");
gebkant.setKwyzkb(0);
gebkant.setKwyzstbl(0);
gebkant.setKgmerk("");
gebkant.setKwgmmr("");
gebkant.setKbrpmr("");
}
if (geboorteAkteFlow.isCorrection() && Arrays.asList(4, 5).contains(gebkant.getKanttype())) {
gebkant.setKhuwdag(0);
gebkant.setKhuwmnd(0);
gebkant.setKhuwjr(0);
gebkant.setKhuwgem("");
gebkant.setKhuwanr("");
gebkant.setKanmvad("");
gebkant.setKvrn1vad("");
gebkant.setKvrn2vad("");
gebkant.setKvrn3vad("");
gebkant.setKwyzkb(0);
gebkant.setKwyzstbl(0);
gebkant.setKanmgeb("");
gebkant.setKvrn1geb("");
gebkant.setKvrn2geb("");
gebkant.setKvrn3geb("");
gebkant.setKsexgeb("");
gebkant.setKgmrb("");
}
if (geboorteAkteFlow.isCorrection() && (gebkant.getKanttype() == 5)) {
gebkant.setKantdag(0);
gebkant.setKantmnd(0);
gebkant.setKantjr(0);
}
inputMetadataChecker.saveToEntity(gebkant, inputMetadata);
gebkant = gebkantRepository.save(gebkant);
geboorteAkteFlow.setGebkant(gebkant);
}
/**
* Register the check whether to add byz, called after screen GS8.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
public void registerByzCheck(GeboorteAkteFlowState geboorteAkteFlow) {
saveGebknd(geboorteAkteFlow);
}
/**
* Deletes the current geboorte akte.
*
* @param akteFlow The akte flow state.
*/
@Override
public void deleteAkte(AkteFlowState akteFlow) {
GeboorteAkteFlowState geboorteAkteFlow = (GeboorteAkteFlowState) akteFlow;
gebakteRepository.delete(geboorteAkteFlow.getGebakte());
gebkndRepository.delete(geboorteAkteFlow.getGebknd());
gebvdrRepository.delete(geboorteAkteFlow.getGebvdr());
gebkantRepository.delete(geboorteAkteFlow.getGebkant());
gebgtgRepository.deleteAll(Arrays.asList(geboorteAkteFlow.getGebgtg()));
gebbyzRepository.deleteAll(geboorteAkteFlow.getGebbyz());
}
/**
* Save the given byz field.
*
* @param byzAkteFlowState Akte flow state.
* @param byz The byz.
*/
@Override
protected void saveByz(ByzAkteFlowState byzAkteFlowState, Byz byz) {
GeboorteAkteFlowState geboorteAkteFlowState = (GeboorteAkteFlowState) byzAkteFlowState;
Gebbyz gebbyz = (Gebbyz) byz;
gebbyz.setIdnr(geboorteAkteFlowState.getStpb().getIdnr());
inputMetadataChecker.saveToEntity(gebbyz, inputMetadata);
gebbyz = gebbyzRepository.save(gebbyz);
geboorteAkteFlowState.addToGebbyz(gebbyz);
}
@Override
protected void deleteByz(ByzAkteFlowState byzAkteFlowState, Byz byz) {
GeboorteAkteFlowState geboorteAkteFlowState = (GeboorteAkteFlowState) byzAkteFlowState;
Gebbyz gebbyz = (Gebbyz) byz;
gebbyzRepository.delete(gebbyz);
geboorteAkteFlowState.removeFromGebbyz(gebbyz);
}
/**
* Creates a new geboorte akte flow state with all required domain objects.
*
* @return A new geboorte akte flow state.
*/
private GeboorteAkteFlowState createNewAkte() {
Gebakte gebakte = new Gebakte();
Gebknd gebknd = new Gebknd();
Gebvdr gebvdr = new Gebvdr();
Gebkant gebkant = new Gebkant();
Gebgtg[] gebgtg = {new Gebgtg(1), new Gebgtg(2)}; // Always two witnesses
Set<Gebbyz> gebbyz = new HashSet<>();
return new GeboorteAkteFlowState(gebakte, gebknd, gebvdr, gebkant, gebgtg, gebbyz);
}
/**
* Persists the gebknd record (main birth certificate record) to the database.
*
* @param geboorteAkteFlow The geboorte akte flow state.
*/
private void saveGebknd(GeboorteAkteFlowState geboorteAkteFlow) {
Gebknd gebknd = geboorteAkteFlow.getGebknd();
inputMetadataChecker.saveToEntity(gebknd, inputMetadata);
gebknd = gebkndRepository.save(gebknd);
geboorteAkteFlow.setGebknd(gebknd);
}
} |
10258_18 | package general;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFileChooser;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.util.Calendar;
import org.w3c.dom.Document;
import dataset.DateYearMonthDaySet;
import modulemain.LinksSpecific;
/**
* @author Omar Azouguagh
* @author Fons Laan
*
* <p/>
* FL-03-Mar-2015 changed
* FL-17-May-2016 Latest change: ( year > 1500 ) && ( year < 2016 ) )
*
*/
public class Functions
{
/**
*
* @param lineToRepare
* @return
*/
// public final static String funcToDiacritic(String lineToRepare){
// lineToRepare = lineToRepare.
// replaceAll("\\x00", "Ç").
// replaceAll("\\x01", "ü").
// replaceAll("\\x02", "é").
// replaceAll("\\x03", "â").
// replaceAll("\\x04", "ä").
// replaceAll("\\x05", "à").
// replaceAll("\\x06", "å").
// replaceAll("\\x07", "ç").
// replaceAll("\\x08", "ê").
// replaceAll("\\x09", "ë").
// replaceAll("\\x0B", "ï").
// replaceAll("\\x0C", "î").
// replaceAll("\\x0E", "Ä").
// replaceAll("\\x0F", "Å").
// replaceAll("\\x10", "é").
// replaceAll("\\x11", "æ").
// replaceAll("\\x12", "Æ").
// replaceAll("\\x13", "ô").
// replaceAll("\\x14", "ö").
// replaceAll("\\x15", "ò").
// replaceAll("\\x16", "û").
// replaceAll("\\x17", "ù").
// replaceAll("\\x18", "ÿ").
// replaceAll("\\x19", "Ö").
// replaceAll("\\x1A", "Ü").
// replaceAll("\\x1B", "ç");
// return lineToRepare;
// }
/**
*
* @param line
* @return
*/
// public static String funcPrepareForMysql(String line){
// String line1 = line.replaceAll("\\\\", "\\\\\\\\");
// String line2 = line1.replaceAll("'", "\\\\'");
// //String line3 = line2.replaceAll("\"", "\\\\\"");
// return line2;
// }
public static String funcPrepareForMysql(String line){
return line.replaceAll("'", "''");
}
/**
*
* @param line
* @return
*/
public static String funcCleanSides(String line){
while( (line.length() > 0) && (line.substring(0,1).equals("\"") ||
line.substring(0,1).equals(" ") ||
line.substring(line.length()-1,line.length()).equals("\"") ||
line.substring(line.length()-1,line.length()).equals( " " ) ) ){
String begin = line.substring(0,1);
String end = line.substring(line.length()-1,line.length());
if( begin.equals("\"") || begin.equals(" ") ){
line = line.substring( 1 , line.length() );
}
else if( end.equals("\"") ||end.equals(" ") ){
line = line.substring( 0 , ( line.length() -1 ) );
}
}
return line;
}
/**
*
* @return
*/
public static Document createDomDocument() {
try {
return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
}
catch (Exception e) {
// Kan nooit fout gaan
}
return null;
}
/**
*
* @param path
* @return
* @throws Exception
*/
public static Document LoadXmlFromfile(String path) throws Exception{
File file = new File(path);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
return doc;
}
public static String SelectFileWithCheck(String extension){
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter( extension.toUpperCase() + " File (." + extension + ")", extension);
fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showDialog(null, "Select/Create file");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
String extention = "";
if(!(file.getPath().substring((file.getPath().length() -4 ), file.getPath().length())).toLowerCase().equals("" + extension)){
extention = "" + extension;
}
return file.getPath() + extention;
}
return "";
}
/**
* This method writes a DOM document to a file
* @param doc
* @param filename
*/
public static void writeXmlToFile(Document doc, String filename) {
try {
// Prepare the DOM document for writing
Source source = new DOMSource(doc);
// Prepare the output file
File file = new File(filename);
Result result = new StreamResult(file);
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
}
catch (TransformerConfigurationException e) {}
catch (TransformerException e) {}
}
/**
*
* @param extension The extension to filter, leave empty for none-filtering
* @param multiple True if you want to select more than one file.
* @return Path of selected file.
*/
public static String OpenFile(String extension, boolean multiple){
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter( extension.toUpperCase() + " File (." + extension + ")", extension);
fileopen.addChoosableFileFilter(filter);
if(multiple){fileopen.setMultiSelectionEnabled(true);}
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
if(multiple){
File[] file = fileopen.getSelectedFiles();
String fileLocations = "";
for (int i = 0; i < file.length; i++) {
if (i != (file.length-1)) {
fileLocations += file[i].getPath() + ",";
}
else {
fileLocations += file[i].getPath();
}
}
return fileLocations;
}
else {
File file = fileopen.getSelectedFile();
return file.getPath();
}
}
return "";
}
/**
*
* @return true als het om ene Windows OS gaat
*/
public static boolean isWindows(){
String os = System.getProperty("os.name").toLowerCase();
return (os.indexOf( "win") >=0);
}
/**
* Get OS version
* @return true if OS is linux, or unix
*/
private static boolean isUnix() {
String os = System.getProperty("os.name").toLowerCase();
return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0);
}
public static String functieOpmerkingenWaardeNaDubbelePunt(String opmerking) {
return funcCleanSides(opmerking.split(":")[1].replaceAll(";", ""));
}
public static void addLogToGui(String logText, boolean isMinOnly, JTextField tb, JTextArea ta){
tb.setText(logText);
if(!isMinOnly){
ta.append(logText + "\r\n");
}
}
/**
*
* @return
*/
public static String getTimeStamp(){
Calendar cal = Calendar.getInstance();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMddHHmm");
return sdf.format(cal.getTime());
}
/**
*
* @param seconds
* @return
*/
public static String stopWatch(int seconds){
int minutes = seconds / 60;
int restsec = seconds % 60;
int uren = minutes / 60;
int restmin = minutes % 60;
String urenText = "";
String minutenText = "";
String secondenText = "";
if(uren < 10 ) urenText = "0";
if(restmin < 10 ) minutenText = "0";
if(restsec < 10 ) secondenText = "0";
return urenText + uren + ":" + minutenText + restmin + ":" + secondenText + restsec;
}
/**
* Gebruik deze functie om een datum te controleren en te splitsen
* De datum kan splitchars bevatten als -, / \ [] etc.
* Formaat kan zijn: d-M-yyyy or dd-M-yyyy or d-MM-yyyy or dd-MM-yyyy
* @param date to be checked
* @return een DateYearMonthDay object met datum en evt. fouten
*/
public static DateYearMonthDaySet devideCheckDate( String date )
{
dataset.DateYearMonthDaySet dymd = new dataset.DateYearMonthDaySet( date );
if(date == null || date.isEmpty() ){
dymd.setYear( 0 ) ;
dymd.setMonth( 0 ) ;
dymd.setDay( 0 ) ;
dymd.setReportYear( "ERROR" ) ;
dymd.setReportMonth( "ERROR" ) ;
dymd.setReportDay( "ERROR" ) ;
return dymd;
}
// eerst de data er uit met regex
Pattern regex = Pattern.compile("[0-9]+");
Matcher m = regex.matcher(date);
//
int day = 0;
int month = 0;
int year = 0;
// day
if(m.find()){
day = Integer.parseInt(m.group());
}
//month
if(m.find()){
month = Integer.parseInt(m.group());
}
//year
if(m.find()){
year = Integer.parseInt(m.group());
}
// they are devided, now we check the value on errors
if( ( year > 1500 ) && ( year < 2016 ) ) {
dymd.setYear(year);
}
else {
// MELDING
dymd.setReportYear("ERROR");
dymd.setYear(0);
}
// they are devides, now we check the value on errors
if( (month > 0) && ( month < 13 ) ){
dymd.setMonth(month);
}
else {
// MELDING
dymd.setReportMonth("ERROR");
dymd.setMonth(0);
}
// check day number
if( ( day < 1 ) && ( day > 31 ) ){
// MELDING
dymd.setReportDay("ERROR");
dymd.setDay(0);
}
//check if day is 31 in wrong month
else if( ( day == 31 ) && ( ( month == 2 ) || ( month == 4 ) || ( month == 6 ) || ( month == 9 ) || ( month == 11 ) ) ){
// MELDING
dymd.setReportDay("ERROR");
dymd.setDay(0);
}
// Check if februari has 30 days
else if( ( month == 2 ) && ( day == 30 ) ){
// MELDING
dymd.setReportDay("ERROR");
dymd.setDay(0);
}
// leap year calculation
else if ( ( month == 2 ) && ( day == 29 ) ){
if( ( year % 4 == 0 ) && ( year % 100 != 0 ) || ( year % 400 == 0 ) ) { // is leapyear
dymd.setDay(day);
}
else {
// MELDING
dymd.setReportDay("ERROR");
dymd.setDay(0);
}
}
else { //februari with 28 or lesser days
dymd.setDay(day);
}
return dymd;
}
/**
* Decide wich slash to use
* @return slash to use
*/
public static String osSlash() {
if (isUnix()) {
return ("/");
} else {
return ("\\");
}
}
/**
*
* @param file
* @return
* @throws java.io.IOException
*/
public static String getSqlQuery(String file) throws java.io.IOException {
byte[] buffer = new byte[(int) new File("resources/SqlQuery/" + file + ".sql").length()];
BufferedInputStream f = null;
try {
f = new BufferedInputStream(new FileInputStream("resources/SqlQuery/" + file + ".sql"));
f.read(buffer);
} finally {
if (f != null) {
try {
f.close();
} catch (IOException ignored) {
}
}
}
return new String(buffer);
}
/**
*
*
* now("dd MMMMM yyyy");
* now("yyyyMMdd");
* now("dd.MM.yy");
* now("MM/dd/yy");
* now("yyyy.MM.dd G 'at' HH:mm:ss z");
* now("EEE, MMM d, ''yy");
* now("h:mm a");
* now("H:mm:ss:SSS");
* now("K:mm a,z");
* now("yyyy.MMMMM.dd GGG hh:mm aaa");
*
* @param dateFormat
* @return
*/
public static String now(String dateFormat) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
return sdf.format(cal.getTime());
}
public static String millisec2hms( long millisec_start, long millisec_stop ) {
long millisec = millisec_stop - millisec_start;
long sec = millisec / 1000;
long hour = sec / 3600;
long min = sec / 60;
long rmin = min - 60 * hour;
long rsec = sec - ( 60 * ( rmin + 60 * hour ) );
String hms = "";
if( hour == 0 ) {
if( rmin == 0 ) {
double fsec = ((double)millisec) / 1000.0;
//hms = String.format("[%d sec]", rsec );
hms = String.format("[%.1f sec]", fsec );
}
else { hms = String.format( "[%02d:%02d mm:ss]", rmin, rsec ); }
}
else { hms = String.format( "[%02d:%02d:%02d HH:mm:ss]", hour, rmin, rsec ); }
return hms;
}
/**
* Read properties file
* Start the application and specify the property file with a parameter:
* java -Dproperties.path="<path-to-properiesfile>" -jar LinksProject-2.0.jar
* @return Properties
*/
public static Properties getProperties() {
String timestamp = LinksSpecific.getTimeStamp2( "HH:mm:ss" );
System.out.println( timestamp + " readProperties()" );
Properties properties = new Properties();
InputStream input = null;
String propertiesPath = System.getProperty( "properties.path" );
if( propertiesPath == null ) {
System.out.println( "No properties file." );
return properties;
} else {
System.out.println( "properties path: " + propertiesPath );
}
try {
System.out.println( "gettings properties.path" );
input = new FileInputStream(propertiesPath);
if( input == null ) {
System.out.println( "Cannot read: " + propertiesPath + "." );
return properties;
}
System.out.println( "properties file: " + propertiesPath );
properties.load( input );
} catch( IOException ex ) {
ex.printStackTrace();
} finally {
if( input != null ) {
try {
input.close();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
}
return properties;
}
}
| IISH/links | LinksProject/src/main/java/general/Functions.java | 4,806 | /**
*
* @return true als het om ene Windows OS gaat
*/ | block_comment | nl | package general;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFileChooser;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.util.Calendar;
import org.w3c.dom.Document;
import dataset.DateYearMonthDaySet;
import modulemain.LinksSpecific;
/**
* @author Omar Azouguagh
* @author Fons Laan
*
* <p/>
* FL-03-Mar-2015 changed
* FL-17-May-2016 Latest change: ( year > 1500 ) && ( year < 2016 ) )
*
*/
public class Functions
{
/**
*
* @param lineToRepare
* @return
*/
// public final static String funcToDiacritic(String lineToRepare){
// lineToRepare = lineToRepare.
// replaceAll("\\x00", "Ç").
// replaceAll("\\x01", "ü").
// replaceAll("\\x02", "é").
// replaceAll("\\x03", "â").
// replaceAll("\\x04", "ä").
// replaceAll("\\x05", "à").
// replaceAll("\\x06", "å").
// replaceAll("\\x07", "ç").
// replaceAll("\\x08", "ê").
// replaceAll("\\x09", "ë").
// replaceAll("\\x0B", "ï").
// replaceAll("\\x0C", "î").
// replaceAll("\\x0E", "Ä").
// replaceAll("\\x0F", "Å").
// replaceAll("\\x10", "é").
// replaceAll("\\x11", "æ").
// replaceAll("\\x12", "Æ").
// replaceAll("\\x13", "ô").
// replaceAll("\\x14", "ö").
// replaceAll("\\x15", "ò").
// replaceAll("\\x16", "û").
// replaceAll("\\x17", "ù").
// replaceAll("\\x18", "ÿ").
// replaceAll("\\x19", "Ö").
// replaceAll("\\x1A", "Ü").
// replaceAll("\\x1B", "ç");
// return lineToRepare;
// }
/**
*
* @param line
* @return
*/
// public static String funcPrepareForMysql(String line){
// String line1 = line.replaceAll("\\\\", "\\\\\\\\");
// String line2 = line1.replaceAll("'", "\\\\'");
// //String line3 = line2.replaceAll("\"", "\\\\\"");
// return line2;
// }
public static String funcPrepareForMysql(String line){
return line.replaceAll("'", "''");
}
/**
*
* @param line
* @return
*/
public static String funcCleanSides(String line){
while( (line.length() > 0) && (line.substring(0,1).equals("\"") ||
line.substring(0,1).equals(" ") ||
line.substring(line.length()-1,line.length()).equals("\"") ||
line.substring(line.length()-1,line.length()).equals( " " ) ) ){
String begin = line.substring(0,1);
String end = line.substring(line.length()-1,line.length());
if( begin.equals("\"") || begin.equals(" ") ){
line = line.substring( 1 , line.length() );
}
else if( end.equals("\"") ||end.equals(" ") ){
line = line.substring( 0 , ( line.length() -1 ) );
}
}
return line;
}
/**
*
* @return
*/
public static Document createDomDocument() {
try {
return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
}
catch (Exception e) {
// Kan nooit fout gaan
}
return null;
}
/**
*
* @param path
* @return
* @throws Exception
*/
public static Document LoadXmlFromfile(String path) throws Exception{
File file = new File(path);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
return doc;
}
public static String SelectFileWithCheck(String extension){
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter( extension.toUpperCase() + " File (." + extension + ")", extension);
fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showDialog(null, "Select/Create file");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
String extention = "";
if(!(file.getPath().substring((file.getPath().length() -4 ), file.getPath().length())).toLowerCase().equals("" + extension)){
extention = "" + extension;
}
return file.getPath() + extention;
}
return "";
}
/**
* This method writes a DOM document to a file
* @param doc
* @param filename
*/
public static void writeXmlToFile(Document doc, String filename) {
try {
// Prepare the DOM document for writing
Source source = new DOMSource(doc);
// Prepare the output file
File file = new File(filename);
Result result = new StreamResult(file);
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
}
catch (TransformerConfigurationException e) {}
catch (TransformerException e) {}
}
/**
*
* @param extension The extension to filter, leave empty for none-filtering
* @param multiple True if you want to select more than one file.
* @return Path of selected file.
*/
public static String OpenFile(String extension, boolean multiple){
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter( extension.toUpperCase() + " File (." + extension + ")", extension);
fileopen.addChoosableFileFilter(filter);
if(multiple){fileopen.setMultiSelectionEnabled(true);}
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
if(multiple){
File[] file = fileopen.getSelectedFiles();
String fileLocations = "";
for (int i = 0; i < file.length; i++) {
if (i != (file.length-1)) {
fileLocations += file[i].getPath() + ",";
}
else {
fileLocations += file[i].getPath();
}
}
return fileLocations;
}
else {
File file = fileopen.getSelectedFile();
return file.getPath();
}
}
return "";
}
/**
*
* @return true als<SUF>*/
public static boolean isWindows(){
String os = System.getProperty("os.name").toLowerCase();
return (os.indexOf( "win") >=0);
}
/**
* Get OS version
* @return true if OS is linux, or unix
*/
private static boolean isUnix() {
String os = System.getProperty("os.name").toLowerCase();
return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0);
}
public static String functieOpmerkingenWaardeNaDubbelePunt(String opmerking) {
return funcCleanSides(opmerking.split(":")[1].replaceAll(";", ""));
}
public static void addLogToGui(String logText, boolean isMinOnly, JTextField tb, JTextArea ta){
tb.setText(logText);
if(!isMinOnly){
ta.append(logText + "\r\n");
}
}
/**
*
* @return
*/
public static String getTimeStamp(){
Calendar cal = Calendar.getInstance();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMddHHmm");
return sdf.format(cal.getTime());
}
/**
*
* @param seconds
* @return
*/
public static String stopWatch(int seconds){
int minutes = seconds / 60;
int restsec = seconds % 60;
int uren = minutes / 60;
int restmin = minutes % 60;
String urenText = "";
String minutenText = "";
String secondenText = "";
if(uren < 10 ) urenText = "0";
if(restmin < 10 ) minutenText = "0";
if(restsec < 10 ) secondenText = "0";
return urenText + uren + ":" + minutenText + restmin + ":" + secondenText + restsec;
}
/**
* Gebruik deze functie om een datum te controleren en te splitsen
* De datum kan splitchars bevatten als -, / \ [] etc.
* Formaat kan zijn: d-M-yyyy or dd-M-yyyy or d-MM-yyyy or dd-MM-yyyy
* @param date to be checked
* @return een DateYearMonthDay object met datum en evt. fouten
*/
public static DateYearMonthDaySet devideCheckDate( String date )
{
dataset.DateYearMonthDaySet dymd = new dataset.DateYearMonthDaySet( date );
if(date == null || date.isEmpty() ){
dymd.setYear( 0 ) ;
dymd.setMonth( 0 ) ;
dymd.setDay( 0 ) ;
dymd.setReportYear( "ERROR" ) ;
dymd.setReportMonth( "ERROR" ) ;
dymd.setReportDay( "ERROR" ) ;
return dymd;
}
// eerst de data er uit met regex
Pattern regex = Pattern.compile("[0-9]+");
Matcher m = regex.matcher(date);
//
int day = 0;
int month = 0;
int year = 0;
// day
if(m.find()){
day = Integer.parseInt(m.group());
}
//month
if(m.find()){
month = Integer.parseInt(m.group());
}
//year
if(m.find()){
year = Integer.parseInt(m.group());
}
// they are devided, now we check the value on errors
if( ( year > 1500 ) && ( year < 2016 ) ) {
dymd.setYear(year);
}
else {
// MELDING
dymd.setReportYear("ERROR");
dymd.setYear(0);
}
// they are devides, now we check the value on errors
if( (month > 0) && ( month < 13 ) ){
dymd.setMonth(month);
}
else {
// MELDING
dymd.setReportMonth("ERROR");
dymd.setMonth(0);
}
// check day number
if( ( day < 1 ) && ( day > 31 ) ){
// MELDING
dymd.setReportDay("ERROR");
dymd.setDay(0);
}
//check if day is 31 in wrong month
else if( ( day == 31 ) && ( ( month == 2 ) || ( month == 4 ) || ( month == 6 ) || ( month == 9 ) || ( month == 11 ) ) ){
// MELDING
dymd.setReportDay("ERROR");
dymd.setDay(0);
}
// Check if februari has 30 days
else if( ( month == 2 ) && ( day == 30 ) ){
// MELDING
dymd.setReportDay("ERROR");
dymd.setDay(0);
}
// leap year calculation
else if ( ( month == 2 ) && ( day == 29 ) ){
if( ( year % 4 == 0 ) && ( year % 100 != 0 ) || ( year % 400 == 0 ) ) { // is leapyear
dymd.setDay(day);
}
else {
// MELDING
dymd.setReportDay("ERROR");
dymd.setDay(0);
}
}
else { //februari with 28 or lesser days
dymd.setDay(day);
}
return dymd;
}
/**
* Decide wich slash to use
* @return slash to use
*/
public static String osSlash() {
if (isUnix()) {
return ("/");
} else {
return ("\\");
}
}
/**
*
* @param file
* @return
* @throws java.io.IOException
*/
public static String getSqlQuery(String file) throws java.io.IOException {
byte[] buffer = new byte[(int) new File("resources/SqlQuery/" + file + ".sql").length()];
BufferedInputStream f = null;
try {
f = new BufferedInputStream(new FileInputStream("resources/SqlQuery/" + file + ".sql"));
f.read(buffer);
} finally {
if (f != null) {
try {
f.close();
} catch (IOException ignored) {
}
}
}
return new String(buffer);
}
/**
*
*
* now("dd MMMMM yyyy");
* now("yyyyMMdd");
* now("dd.MM.yy");
* now("MM/dd/yy");
* now("yyyy.MM.dd G 'at' HH:mm:ss z");
* now("EEE, MMM d, ''yy");
* now("h:mm a");
* now("H:mm:ss:SSS");
* now("K:mm a,z");
* now("yyyy.MMMMM.dd GGG hh:mm aaa");
*
* @param dateFormat
* @return
*/
public static String now(String dateFormat) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
return sdf.format(cal.getTime());
}
public static String millisec2hms( long millisec_start, long millisec_stop ) {
long millisec = millisec_stop - millisec_start;
long sec = millisec / 1000;
long hour = sec / 3600;
long min = sec / 60;
long rmin = min - 60 * hour;
long rsec = sec - ( 60 * ( rmin + 60 * hour ) );
String hms = "";
if( hour == 0 ) {
if( rmin == 0 ) {
double fsec = ((double)millisec) / 1000.0;
//hms = String.format("[%d sec]", rsec );
hms = String.format("[%.1f sec]", fsec );
}
else { hms = String.format( "[%02d:%02d mm:ss]", rmin, rsec ); }
}
else { hms = String.format( "[%02d:%02d:%02d HH:mm:ss]", hour, rmin, rsec ); }
return hms;
}
/**
* Read properties file
* Start the application and specify the property file with a parameter:
* java -Dproperties.path="<path-to-properiesfile>" -jar LinksProject-2.0.jar
* @return Properties
*/
public static Properties getProperties() {
String timestamp = LinksSpecific.getTimeStamp2( "HH:mm:ss" );
System.out.println( timestamp + " readProperties()" );
Properties properties = new Properties();
InputStream input = null;
String propertiesPath = System.getProperty( "properties.path" );
if( propertiesPath == null ) {
System.out.println( "No properties file." );
return properties;
} else {
System.out.println( "properties path: " + propertiesPath );
}
try {
System.out.println( "gettings properties.path" );
input = new FileInputStream(propertiesPath);
if( input == null ) {
System.out.println( "Cannot read: " + propertiesPath + "." );
return properties;
}
System.out.println( "properties file: " + propertiesPath );
properties.load( input );
} catch( IOException ex ) {
ex.printStackTrace();
} finally {
if( input != null ) {
try {
input.close();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
}
return properties;
}
}
|
148512_23 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Mara Iroaie using IMS Development Environment (version 1.80 build 5308.16958)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
package ims.admin.forms.assignrightsdialog;
import java.util.Arrays;
import java.util.Comparator;
import ims.admin.forms.assignrightsdialog.GenForm.grdRightsRow;
import ims.admin.vo.AppRightVo;
import ims.admin.vo.AppRightVoCollection;
import ims.configuration.AppRight;
import ims.framework.MessageButtons;
import ims.framework.MessageIcon;
import ims.framework.enumerations.DialogResult;
import ims.framework.exceptions.PresentationLogicException;
public class Logic extends BaseLogic
{
private static final long serialVersionUID = 1L;
private static final String PDSSTRING = "PDS_"; //WDEV-20617
@Override
protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
{
if ( args != null && args.length > 0 && args[0] instanceof Boolean )
form.getLocalContext().setIsPdsRight((Boolean)args[0]);
form.getLocalContext().setSelectedRights(null);
}
@Override
protected void onImbClearClick() throws ims.framework.exceptions.PresentationLogicException
{
form.txtName().setValue(null);
form.grdRights().getRows().clear();
}
@Override
protected void onImbSearchClick() throws ims.framework.exceptions.PresentationLogicException
{
populateAppRightsGRid(form.txtName().getValue());
}
private void populateAppRightsGRid(String value)
{
form.grdRights().getRows().clear();
AppRight[] rights = AppRight.getAllRights();
AppRightVo[] voRights = AppRightVo.domArrayToVo(rights);
Arrays.sort(voRights, new AppRightComparator());
String roleRight = "";
if (value != null && value.length() > 0)
roleRight = value.replaceAll("%", "");
for (int i = 0; i < voRights.length; i++)
{
AppRightVo voRight = voRights[i];
if(voRight != null && voRight.getNameIsNotNull() && (voRight.getName().toUpperCase().contains(roleRight.toUpperCase()) || roleRight.length() == 0))
//WDEV-20617
{
boolean bAddRow = form.getLocalContext().getIsPdsRight() && voRight.getName().substring(0,PDSSTRING.length()).toUpperCase().equals(PDSSTRING.toUpperCase())
|| !form.getLocalContext().getIsPdsRight() && !voRight.getName().substring(0,PDSSTRING.length()).toUpperCase().equals(PDSSTRING.toUpperCase());
if (bAddRow)
newRow(voRight);
}
//WDEV-20617 ends here
}
if (form.grdRights().getRows().size() == 0)
engine.showMessage("No records matching your search criteria were found!", "No results",MessageButtons.OK, MessageIcon.INFORMATION);
}
private void newRow(AppRightVo voRight)
{
grdRightsRow row = form.grdRights().getRows().newRow();
row.setAppRight(voRight.getName());
row.setColSelect(isAlreadySelected(voRight) ? true : false);
//WDEV-20577
AppRight right = AppRight.getRight(voRight.getName());
if (right != null)
row.setTooltip(right.getComment()); //WDEV-20577
row.setValue(voRight);
}
private boolean isAlreadySelected(AppRightVo voRight)
{
//WDEV-20617
AppRightVoCollection collSelectedRights;
if (form.getLocalContext().getIsPdsRight())
collSelectedRights = form.getGlobalContext().Admin.getSelectedPdsRoleRights();
else
collSelectedRights = form.getGlobalContext().Admin.getSelectedRoleRigths();
//WDEV-20617 ends here
if (collSelectedRights != null && collSelectedRights.size() > 0)
{
for (int i = 0; i < collSelectedRights.size(); i++)
{
AppRightVo voSelectedRight = collSelectedRights.get(i);
if(voSelectedRight.getName().equals(voRight.getName()))
return true;
}
}
return false;
}
@Override
protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
{
engine.close(DialogResult.CANCEL);
}
@Override
protected void onBtnSelectClick() throws ims.framework.exceptions.PresentationLogicException
{
engine.close(DialogResult.OK);
}
class AppRightComparator implements Comparator<AppRightVo>
{
public int compare(AppRightVo arg0, AppRightVo arg1) {
return getText(arg0).compareToIgnoreCase(getText(arg1));
}
private String getText(AppRightVo vo)
{
if (vo == null || !vo.getNameIsNotNull())
return "";
return vo.getName();
}
}
@Override
protected void onGrdRightsGridCheckBoxClicked(int column, grdRightsRow row, boolean isChecked) throws PresentationLogicException
{
//WDEV-20617
AppRightVoCollection formSelectedRigrts;
if (form.getLocalContext().getIsPdsRight())
formSelectedRigrts = form.getGlobalContext().Admin.getSelectedPdsRoleRights();
else
formSelectedRigrts = form.getGlobalContext().Admin.getSelectedRoleRigths();
//WDEV-20617 ends here
if (formSelectedRigrts == null)
formSelectedRigrts = new AppRightVoCollection();
if (isChecked)
formSelectedRigrts.add(row.getValue());
else
removeRightFromSelection(row.getValue());
//WDEV-20617
if (form.getLocalContext().getIsPdsRight())
form.getGlobalContext().Admin.setSelectedPdsRoleRights(formSelectedRigrts);
else
form.getGlobalContext().Admin.setSelectedRoleRigths(formSelectedRigrts);
//WDEV-20617 ends here
}
private void removeRightFromSelection(AppRightVo value)
{
//WDEV-20617
AppRightVoCollection formSelectedRigrts;
if (form.getLocalContext().getIsPdsRight())
formSelectedRigrts = form.getGlobalContext().Admin.getSelectedPdsRoleRights();
else
formSelectedRigrts = form.getGlobalContext().Admin.getSelectedRoleRigths();
//WDEV-20617 ends here
if (formSelectedRigrts == null || formSelectedRigrts.size() < 1)
return;
for(int i=0; i<formSelectedRigrts.size(); i++)
{
if(formSelectedRigrts.get(i).getName() != null && value.getName() != null && formSelectedRigrts.get(i).getName().toUpperCase().equals(value.getName().toUpperCase()))
formSelectedRigrts.remove(i);
}
}
}
| IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/Admin/src/ims/admin/forms/assignrightsdialog/Logic.java | 2,586 | //WDEV-20617 ends here
| line_comment | nl | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Mara Iroaie using IMS Development Environment (version 1.80 build 5308.16958)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
package ims.admin.forms.assignrightsdialog;
import java.util.Arrays;
import java.util.Comparator;
import ims.admin.forms.assignrightsdialog.GenForm.grdRightsRow;
import ims.admin.vo.AppRightVo;
import ims.admin.vo.AppRightVoCollection;
import ims.configuration.AppRight;
import ims.framework.MessageButtons;
import ims.framework.MessageIcon;
import ims.framework.enumerations.DialogResult;
import ims.framework.exceptions.PresentationLogicException;
public class Logic extends BaseLogic
{
private static final long serialVersionUID = 1L;
private static final String PDSSTRING = "PDS_"; //WDEV-20617
@Override
protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
{
if ( args != null && args.length > 0 && args[0] instanceof Boolean )
form.getLocalContext().setIsPdsRight((Boolean)args[0]);
form.getLocalContext().setSelectedRights(null);
}
@Override
protected void onImbClearClick() throws ims.framework.exceptions.PresentationLogicException
{
form.txtName().setValue(null);
form.grdRights().getRows().clear();
}
@Override
protected void onImbSearchClick() throws ims.framework.exceptions.PresentationLogicException
{
populateAppRightsGRid(form.txtName().getValue());
}
private void populateAppRightsGRid(String value)
{
form.grdRights().getRows().clear();
AppRight[] rights = AppRight.getAllRights();
AppRightVo[] voRights = AppRightVo.domArrayToVo(rights);
Arrays.sort(voRights, new AppRightComparator());
String roleRight = "";
if (value != null && value.length() > 0)
roleRight = value.replaceAll("%", "");
for (int i = 0; i < voRights.length; i++)
{
AppRightVo voRight = voRights[i];
if(voRight != null && voRight.getNameIsNotNull() && (voRight.getName().toUpperCase().contains(roleRight.toUpperCase()) || roleRight.length() == 0))
//WDEV-20617
{
boolean bAddRow = form.getLocalContext().getIsPdsRight() && voRight.getName().substring(0,PDSSTRING.length()).toUpperCase().equals(PDSSTRING.toUpperCase())
|| !form.getLocalContext().getIsPdsRight() && !voRight.getName().substring(0,PDSSTRING.length()).toUpperCase().equals(PDSSTRING.toUpperCase());
if (bAddRow)
newRow(voRight);
}
//WDEV-20617 ends<SUF>
}
if (form.grdRights().getRows().size() == 0)
engine.showMessage("No records matching your search criteria were found!", "No results",MessageButtons.OK, MessageIcon.INFORMATION);
}
private void newRow(AppRightVo voRight)
{
grdRightsRow row = form.grdRights().getRows().newRow();
row.setAppRight(voRight.getName());
row.setColSelect(isAlreadySelected(voRight) ? true : false);
//WDEV-20577
AppRight right = AppRight.getRight(voRight.getName());
if (right != null)
row.setTooltip(right.getComment()); //WDEV-20577
row.setValue(voRight);
}
private boolean isAlreadySelected(AppRightVo voRight)
{
//WDEV-20617
AppRightVoCollection collSelectedRights;
if (form.getLocalContext().getIsPdsRight())
collSelectedRights = form.getGlobalContext().Admin.getSelectedPdsRoleRights();
else
collSelectedRights = form.getGlobalContext().Admin.getSelectedRoleRigths();
//WDEV-20617 ends here
if (collSelectedRights != null && collSelectedRights.size() > 0)
{
for (int i = 0; i < collSelectedRights.size(); i++)
{
AppRightVo voSelectedRight = collSelectedRights.get(i);
if(voSelectedRight.getName().equals(voRight.getName()))
return true;
}
}
return false;
}
@Override
protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
{
engine.close(DialogResult.CANCEL);
}
@Override
protected void onBtnSelectClick() throws ims.framework.exceptions.PresentationLogicException
{
engine.close(DialogResult.OK);
}
class AppRightComparator implements Comparator<AppRightVo>
{
public int compare(AppRightVo arg0, AppRightVo arg1) {
return getText(arg0).compareToIgnoreCase(getText(arg1));
}
private String getText(AppRightVo vo)
{
if (vo == null || !vo.getNameIsNotNull())
return "";
return vo.getName();
}
}
@Override
protected void onGrdRightsGridCheckBoxClicked(int column, grdRightsRow row, boolean isChecked) throws PresentationLogicException
{
//WDEV-20617
AppRightVoCollection formSelectedRigrts;
if (form.getLocalContext().getIsPdsRight())
formSelectedRigrts = form.getGlobalContext().Admin.getSelectedPdsRoleRights();
else
formSelectedRigrts = form.getGlobalContext().Admin.getSelectedRoleRigths();
//WDEV-20617 ends here
if (formSelectedRigrts == null)
formSelectedRigrts = new AppRightVoCollection();
if (isChecked)
formSelectedRigrts.add(row.getValue());
else
removeRightFromSelection(row.getValue());
//WDEV-20617
if (form.getLocalContext().getIsPdsRight())
form.getGlobalContext().Admin.setSelectedPdsRoleRights(formSelectedRigrts);
else
form.getGlobalContext().Admin.setSelectedRoleRigths(formSelectedRigrts);
//WDEV-20617 ends here
}
private void removeRightFromSelection(AppRightVo value)
{
//WDEV-20617
AppRightVoCollection formSelectedRigrts;
if (form.getLocalContext().getIsPdsRight())
formSelectedRigrts = form.getGlobalContext().Admin.getSelectedPdsRoleRights();
else
formSelectedRigrts = form.getGlobalContext().Admin.getSelectedRoleRigths();
//WDEV-20617 ends here
if (formSelectedRigrts == null || formSelectedRigrts.size() < 1)
return;
for(int i=0; i<formSelectedRigrts.size(); i++)
{
if(formSelectedRigrts.get(i).getName() != null && value.getName() != null && formSelectedRigrts.get(i).getName().toUpperCase().equals(value.getName().toUpperCase()))
formSelectedRigrts.remove(i);
}
}
}
|
14665_25 | package nl.inl.blacklab.indexers.config;
import java.io.IOException;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.commons.lang3.StringUtils;
import nl.inl.blacklab.exceptions.BlackLabRuntimeException;
import nl.inl.blacklab.exceptions.InvalidInputFormatConfig;
import nl.inl.blacklab.exceptions.MalformedInputFile;
import nl.inl.blacklab.exceptions.PluginException;
import nl.inl.blacklab.index.annotated.AnnotatedFieldWriter;
import nl.inl.blacklab.index.annotated.AnnotationWriter;
import nl.inl.blacklab.index.annotated.AnnotationWriter.SensitivitySetting;
import nl.inl.blacklab.indexers.preprocess.DocIndexerConvertAndTag;
import nl.inl.blacklab.search.BlackLabIndexImpl;
import nl.inl.blacklab.search.indexmetadata.AnnotatedFieldNameUtil;
import nl.inl.blacklab.search.indexmetadata.IndexMetadataImpl;
/**
* A DocIndexer configured using a ConfigInputFormat structure.
*/
public abstract class DocIndexerConfig extends DocIndexerBase {
protected static String replaceDollarRefs(String pattern, List<String> replacements) {
if (pattern != null) {
int i = 1;
for (String replacement : replacements) {
pattern = pattern.replace("$" + i, replacement);
i++;
}
}
return pattern;
}
public static DocIndexerConfig fromConfig(ConfigInputFormat config) {
DocIndexerConfig docIndexer = null;
switch (config.getFileType()) {
case XML:
for (ConfigInputFormat.FileTypeOption fto: ConfigInputFormat.FileTypeOption.fromConfig(config, ConfigInputFormat.FileType.XML)) {
if (fto == ConfigInputFormat.FileTypeOption.SAXONICA) {
docIndexer = new DocIndexerSaxon();
break;
}
}
if (docIndexer == null) {
docIndexer = new DocIndexerXPath();
}
break;
case TABULAR:
docIndexer = new DocIndexerTabular();
break;
case TEXT:
docIndexer = new DocIndexerPlainText();
break;
case CHAT:
docIndexer = new DocIndexerChat();
break;
default:
throw new InvalidInputFormatConfig(
"Unknown file type: " + config.getFileType() + " (use xml, tabular, text or chat)");
}
docIndexer.setConfigInputFormat(config);
if (config.getConvertPluginId() != null || config.getTagPluginId() != null) {
try {
return new DocIndexerConvertAndTag(docIndexer, config);
} catch (Exception e) {
throw BlackLabRuntimeException.wrap(e);
}
} else {
return docIndexer;
}
}
/** Our input format */
protected ConfigInputFormat config;
boolean inited = false;
protected final Map<String, Collection<String>> sortedMetadataValues = new HashMap<>();
public void setConfigInputFormat(ConfigInputFormat config) {
this.config = config;
}
@SuppressWarnings("deprecation")
protected SensitivitySetting getSensitivitySetting(ConfigAnnotation mainAnnotation) {
SensitivitySetting sensitivity = mainAnnotation.getSensitivity();
if (sensitivity == SensitivitySetting.DEFAULT) {
String name = mainAnnotation.getName();
sensitivity = SensitivitySetting.defaultForAnnotation(name);
if (sensitivity != SensitivitySetting.ONLY_INSENSITIVE) {
// Historic behaviour: if no sensitivity is given, "word" and "lemma" annotations will
// get SensitivitySetting.SENSITIVE_AND_INSENSITIVE; all others get SensitivitySetting.ONLY_INSENSITIVE.
// Warn users about this so they can make their config files explicit before this special case is removed.
logger.warn("Configuration " + config.getName()
+ "relies on special default sensitivity 'sensitive_insensitive' for annotation " + name
+ " (); this behaviour "
+ "is deprecated. Please update your config to explicitly declare the sensitivity setting for this annotation. In a future version, all annotations "
+ "without explicit sensitivity will default to 'insensitive'.");
}
return sensitivity;
}
return sensitivity;
}
@Override
protected String optTranslateFieldName(String from) {
if (config == null) // test
return from;
String to = config.getIndexFieldAs().get(from);
return to == null ? from : to;
}
@SuppressWarnings("deprecation")
protected void init() {
if (inited)
return;
inited = true;
setStoreDocuments(config.shouldStore());
for (ConfigAnnotatedField af : config.getAnnotatedFields().values()) {
// Define the properties that make up our annotated field
if (af.isDummyForStoringLinkedDocuments())
continue;
List<ConfigAnnotation> annotations = new ArrayList<>(af.getAnnotationsFlattened().values());
if (annotations.isEmpty())
throw new InvalidInputFormatConfig("No annotations defined for field " + af.getName());
ConfigAnnotation mainAnnotation = annotations.get(0);
AnnotatedFieldWriter fieldWriter = new AnnotatedFieldWriter(af.getName(), mainAnnotation.getName(),
getSensitivitySetting(mainAnnotation), false);
addAnnotatedField(fieldWriter);
AnnotationWriter annotStartTag = fieldWriter.addAnnotation(null, AnnotatedFieldNameUtil.TAGS_ANNOT_NAME,
SensitivitySetting.ONLY_SENSITIVE, true);
annotStartTag.setHasForwardIndex(false);
// Create properties for the other annotations
for (int i = 1; i < annotations.size(); i++) {
ConfigAnnotation annot = annotations.get(i);
if (!annot.isForEach())
fieldWriter.addAnnotation(annot, annot.getName(), getSensitivitySetting(annot), false);
}
for (ConfigStandoffAnnotations standoff : af.getStandoffAnnotations()) {
for (ConfigAnnotation annot : standoff.getAnnotations().values()) {
fieldWriter.addAnnotation(annot, annot.getName(), getSensitivitySetting(annot), false);
}
}
if (!fieldWriter.hasAnnotation(AnnotatedFieldNameUtil.PUNCTUATION_ANNOT_NAME)) {
// Hasn't been created yet. Create it now.
fieldWriter.addAnnotation(null, AnnotatedFieldNameUtil.PUNCTUATION_ANNOT_NAME,
SensitivitySetting.ONLY_INSENSITIVE, false);
}
if (getDocWriter() != null) {
IndexMetadataImpl indexMetadata = (IndexMetadataImpl)getDocWriter().indexWriter().metadata();
indexMetadata.registerAnnotatedField(fieldWriter);
}
}
}
@Override
public void index() throws IOException, MalformedInputFile, PluginException {
init();
}
@Override
public void indexSpecificDocument(String documentExpr) {
init();
}
protected String processString(String result, List<ConfigProcessStep> process, Map<String, String> mapValues) {
for (ConfigProcessStep step : process) {
String method = step.getMethod();
Map<String, String> param = step.getParam();
switch (method) {
case "replace":
result = opReplace(result, param);
break;
case "default":
result = opDefault(result, param);
break;
case "append":
result = opAppend(result, param);
break;
case "split":
result = opSplit(result, param).get(0);
break;
case "chatFormatAgeToMonths":
result = opChatFormatAgeToMonths(result);
break;
case "strip":
result = opStrip(result, param);
break;
case "concatDate":
result = opConcatDate(param);
break;
case "parsePos":
{
// Get individual feature out of a part of speech string like "NOU(gender=f,number=p)"
String field = param.getOrDefault("field", "_");
result = opParsePartOfSpeech(result, field);
break;
}
default:
// In the future, we'll support user plugins here
throw new UnsupportedOperationException("Unknown processing step method " + method);
}
}
if (mapValues != null && !mapValues.isEmpty()) {
// Finally, apply any value mappings specified.
String mappedResult = mapValues.get(result);
if (mappedResult != null)
result = mappedResult;
}
return result;
}
/**
* process linked documents when configured. An xPath processor can be provided,
* it will retrieve information from the document to construct a path to a linked document.
*/
protected void processLinkedDocument(ConfigLinkedDocument ld, Function<String, String> xpathProcessor) {
// Resolve linkPaths to get the information needed to fetch the document
List<String> results = new ArrayList<>();
for (ConfigLinkValue linkValue : ld.getLinkValues()) {
String valuePath = linkValue.getValuePath();
String valueField = linkValue.getValueField();
if (valuePath != null) {
// Resolve value using XPath
String result = xpathProcessor.apply(valuePath);
if (result == null || result.isEmpty()) {
switch (ld.getIfLinkPathMissing()) {
case IGNORE:
break;
case WARN:
getDocWriter().listener()
.warning("Link path " + valuePath + " not found in document " + documentName);
break;
case FAIL:
throw new BlackLabRuntimeException("Link path " + valuePath + " not found in document " + documentName);
}
}
results.add(result);
} else if (valueField != null) {
// Fetch value from Lucene doc
List<String> metadataField = getMetadataField(valueField);
if (metadataField == null) {
throw new BlackLabRuntimeException("Link value field " + valueField + " has no values (null)!");
}
results.addAll(metadataField);
}
List<String> resultAfterProcessing = new ArrayList<>();
for (String inputValue : results) {
resultAfterProcessing.addAll(processStringMultipleValues(inputValue, linkValue.getProcess(), null));
}
results = resultAfterProcessing;
}
// Substitute link path results in inputFile, pathInsideArchive and documentPath
String inputFile = replaceDollarRefs(ld.getInputFile(), results);
String pathInsideArchive = replaceDollarRefs(ld.getPathInsideArchive(), results);
String documentPath = replaceDollarRefs(ld.getDocumentPath(), results);
try {
// Fetch and index the linked document
indexLinkedDocument(inputFile, pathInsideArchive, documentPath, ld.getInputFormatIdentifier(),
ld.shouldStore() ? ld.getName() : null);
} catch (Exception e) {
String moreInfo = "(inputFile = " + inputFile;
if (pathInsideArchive != null)
moreInfo += ", pathInsideArchive = " + pathInsideArchive;
if (documentPath != null)
moreInfo += ", documentPath = " + documentPath;
moreInfo += ")";
switch (ld.getIfLinkPathMissing()) {
case IGNORE:
case WARN:
getDocWriter().listener().warning("Could not find or parse linked document for " + documentName + moreInfo
+ ": " + e.getMessage());
break;
case FAIL:
throw new BlackLabRuntimeException("Could not find or parse linked document for " + documentName + moreInfo, e);
}
}
}
protected List<String> processStringMultipleValues(String input, List<ConfigProcessStep> process, Map<String, String> mapValues) {
List<String> result = new ArrayList<>();
result.add(input);
for (ConfigProcessStep step : process) {
String method = step.getMethod();
Map<String, String> param = step.getParam();
switch (method) {
case "replace":
for (int i = 0; i < result.size(); ++i) {
result.set(i, opReplace(result.get(i), param));
}
break;
case "default":
for (int i = 0; i < result.size(); ++i) {
result.set(i, opDefault(result.get(i), param));
}
break;
case "append":
for (int i = 0; i < result.size(); ++i) {
result.set(i, opAppend(result.get(i), param));
}
break;
case "split": {
ArrayList<String> r = new ArrayList<>();
for (String s : result) {
r.addAll(opSplit(s, param));
}
result = r;
break;
}
case "chatFormatAgeToMonths":
for (int i = 0; i < result.size(); ++i) {
result.set(i, opChatFormatAgeToMonths(result.get(i)));
}
break;
case "strip":
for (int i = 0; i < result.size(); ++i) {
result.set(i, opStrip(result.get(i), param));
}
break;
case "parsePos":
{
// Get individual feature out of a part of speech string like "NOU(gender=f,number=p)"
String field = param.getOrDefault("field", "_");
for (int i = 0; i < result.size(); ++i) {
result.set(i, opParsePartOfSpeech(result.get(i), field));
}
break;
}
case "concatDate":
String s = opConcatDate(param);
if (!s.isEmpty()) {
result.set(0, s);
}
break;
default:
// In the future, we'll support user plugins here
throw new UnsupportedOperationException("Unknown processing step method " + method);
}
}
if (mapValues != null && !mapValues.isEmpty()) {
// Finally, apply any value mappings specified.
for (int i = 0; i < result.size(); ++i) {
String mappedResult = mapValues.get(result.get(i));
if (mappedResult != null)
result.set(i, mappedResult);
}
}
return result;
}
static final Pattern mainPosPattern = Pattern.compile("^([^(]+)(\\s*\\(.*\\))?$");
static final Pattern featurePattern = Pattern.compile("^[^(]+(\\s*\\((.*)\\))?$");
static String opParsePartOfSpeech(String result, String field) {
// Trim character/string from beginning and end
result = result.trim();
if (field.equals("_")) {
// Get main pos: A(b=c,d=e) -> A
return mainPosPattern.matcher(result).replaceAll("$1");
} else {
// Get feature: A(b=c,d=e) -> e (if field == d)
String featuresString = featurePattern.matcher(result).replaceAll("$2");
return Arrays.stream(featuresString.split(","))
.map(feat -> feat.split("="))
.filter(featParts -> featParts[0].trim().equals(field))
.map(featParts -> featParts[1].trim())
.findFirst()
.orElse("");
}
}
static String opStrip(String result, Map<String, String> param) {
// Trim character/string from beginning and end
String stripChars = param.getOrDefault("chars", " ");
result = StringUtils.strip(result, stripChars);
return result;
}
/**
* Concatenate 3 separate date fields into one.
* E.g.
* Year: 2000
* Month: 10
* Day: 19
*
* Result: "20001019"
*
* @param param operation parameters
* @return resulting value
*/
protected String opConcatDate(Map<String, String> param) {
String yearField = param.get("yearField");
String monthField = param.get("monthField");
String dayField = param.get("dayField");
String mode = param.get("autofill");
if (yearField == null || monthField == null || dayField == null || mode == null || !(mode.equalsIgnoreCase("start")||mode.equalsIgnoreCase("end")))
throw new InvalidInputFormatConfig("concatDate needs parameters yearField, monthField, dayField, and autoFill ('start' or 'end')");
boolean isStart = mode.equalsIgnoreCase("start");
Integer y, m, d;
try { y = Integer.parseInt(getMetadataField(yearField).get(0)); } catch (Exception e) { y = null; }
try { m = Integer.parseInt(getMetadataField(monthField).get(0)); } catch (Exception e) { m = null; }
try { d = Integer.parseInt(getMetadataField(dayField).get(0)); } catch (Exception e) { d = null; }
if (y == null) return "";
if (m == null || m > 12 || m < 1) m = isStart ? 1 : 12;
int maxDay = YearMonth.of(y, m).lengthOfMonth();
if (d == null || d > maxDay || d < 1) d = isStart ? 1 : maxDay;
return StringUtils.leftPad(y.toString(), 4, '0') + StringUtils.leftPad(m.toString(), 2, '0') + StringUtils.leftPad(d.toString(), 2, '0');
}
protected String opChatFormatAgeToMonths(String result) {
// 1;10.30 => 1 jaar, 10 maanden, 30 dagen => afgerond 23 maanden?
String[] parts = result.split("[;.]", 3);
int years = 0;
int months = 0;
int days = 0;
try {
years = Integer.parseInt(parts[0]);
months = parts.length <= 1 ? 0 : Integer.parseInt(parts[1]);
days = parts.length <= 2 ? 0 : Integer.parseInt(parts[2]);
} catch (NumberFormatException e) {
warn("action 'opChatFormatAgeToMonths': illegal value " + result);
}
return Integer.toString(years * 12 + months + (days > 14 ? 1 : 0) );
}
/**
* Split the result string on a separator and return one or all parts.
*
* @param result the string to split
* @param param
* <pre>
* - "separator" for the separator (defaults to ;),
* - "keep" for the keep index, accepts numbers or the special string "all" (defaults to -1)
* if "keep" <= 0 returns the first part.
* if "keep" > number of splits return empty string.
* if "keep" == "all" return all parts
* if "keep" == "both" return both the original (unsplit) string and all parts
* </pre>
*/
private List<String> opSplit(String result, Map<String, String> param) {
// Split on a separator regex and keep one or all parts (first part by default)
String separator = param.getOrDefault("separator", ";");
String keep = param.getOrDefault("keep", "-1").toLowerCase();
String[] parts = result.split(separator, -1);
if (keep.equals("all")) {
return Arrays.asList(parts);
}
if (keep.equals("both")) {
ArrayList<String> r = new ArrayList<>();
r.add(result);
Collections.addAll(r, parts);
return r;
}
int i = -1;
try { i = Integer.parseInt(keep); } catch (NumberFormatException e) { /* handled below */ }
if (i < 0) {
warn("action 'split', parameter 'keep': must be at least 1");
i = 0;
}
return List.of(i < parts.length ? parts[i] : "");
}
/**
* Appends a constant value, or the value of a metadata field to the result string.
*
* @param result the input string
* @param param
* <pre>
* - "separator" for the separator (defaults to " ")
* - "field" for the metadata field whose value will be appended
* - "value" for a constant value ("field" takes precedence if it exists)
* </pre>
*/
private String opAppend(String result, Map<String, String> param) {
String separator = param.getOrDefault("separator", " ");
String field = param.get("field");
String value;
if (field != null)
value = StringUtils.join(getMetadataField(field), separator);
else
value = param.get("value");
if (value != null && value.length() > 0) {
if (result.length() > 0)
result += separator;
result += value;
}
return result;
}
/**
* Optionally replace an empty result with a constant value, or the value of a metadata field.
*
* @param result the input string
* @param param
* <pre>
* - "field" for the metadata field whose value will be used
* - "separator" to join the metadata field if it contains multiple values (defaults to ;)
* - "value" for a constant value ("field" takes precedence if it exists)
* </pre>
*/
private String opDefault(String result, Map<String, String> param) {
if (result.length() == 0) {
String field = param.get("field");
String value;
String sep = param.getOrDefault("separator", ";");
if (field != null)
value = StringUtils.join(getMetadataField(field), sep);
else
value = param.get("value");
if (value != null)
result = value;
}
return result;
}
/**
* Perform a regex replace on result. Allows group references.
*
* @param param
* <pre>
* - "find" for the regex
* - "replace" the replacement string
* </pre>
*/
private static String opReplace(String result, Map<String, String> param) {
String find = param.get("find");
String replace = param.get("replace");
if (find == null || replace == null)
throw new InvalidInputFormatConfig("replace needs parameters find and replace");
try {
result = result.replaceAll(find, replace);
} catch (PatternSyntaxException e) {
throw new InvalidInputFormatConfig("Syntax error in replace regex: " + find);
}
return result;
}
/**
* If any processing steps were defined for this metadata field, apply them now.
*
* This is used for non-XML formats, where we don't actively seek out the
* metadata but encounter it as we go.
*
* @param name metadata field name
* @param value metadata field value
* @return processed value (or original value if not found / no processing steps
* defined)
*/
protected String processMetadataValue(String name, String value) {
ConfigMetadataField f = config.getMetadataField(name);
if (f != null) {
value = processString(value, f.getProcess(), f.getMapValues());
}
return value;
}
/**
* Add metadata field value.
*
* We first collect all metadata values before processing to ensure we have all of them
* in the case of fields with multiple values and to be able to sort them so sorting/grouping
* works correctly on these fields as well.
*
* @param name field name
* @param value value to add
*/
@Override
public void addMetadataField(String name, String value) {
this.sortedMetadataValues.computeIfAbsent(name, __ -> {
ConfigMetadataField conf = this.config.getMetadataField(name);
if (conf != null && conf.getSortValues()) {
return new TreeSet<>(BlackLabIndexImpl.defaultCollator()::compare);
} else {
return new ArrayList<>();
}
}).add(value);
}
private static List<String> collectionToList(Collection<String> c) {
return c == null ? null : c instanceof List ? (List<String>)c : new ArrayList<>(c);
}
/**
* Get a metadata field value.
*
* Overridden because we collect them in sortedMetadataValues while parsing the document,
* and if a value is needed while parsing (such as with linked metadata), we wouldn't
* otherwise be able to return it.
*
* Note that these values aren't processed yet, so that's still an issue.
*
* @param name field name
* @return value(s), or null if not defined
*/
@Override
public List<String> getMetadataField(String name) {
List<String> v = super.getMetadataField(name);
return v == null ? collectionToList(sortedMetadataValues.get(name)) : v;
}
@Override
protected void endDocument() {
for (Map.Entry<String, Collection<String>> metadataValues : sortedMetadataValues.entrySet()) {
String fieldName = metadataValues.getKey();
for (String s : metadataValues.getValue()) {
super.addMetadataField(fieldName, s);
}
}
sortedMetadataValues.clear();
super.endDocument();
}
}
| INL/BlackLab | engine/src/main/java/nl/inl/blacklab/indexers/config/DocIndexerConfig.java | 6,980 | // 1;10.30 => 1 jaar, 10 maanden, 30 dagen => afgerond 23 maanden? | line_comment | nl | package nl.inl.blacklab.indexers.config;
import java.io.IOException;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.commons.lang3.StringUtils;
import nl.inl.blacklab.exceptions.BlackLabRuntimeException;
import nl.inl.blacklab.exceptions.InvalidInputFormatConfig;
import nl.inl.blacklab.exceptions.MalformedInputFile;
import nl.inl.blacklab.exceptions.PluginException;
import nl.inl.blacklab.index.annotated.AnnotatedFieldWriter;
import nl.inl.blacklab.index.annotated.AnnotationWriter;
import nl.inl.blacklab.index.annotated.AnnotationWriter.SensitivitySetting;
import nl.inl.blacklab.indexers.preprocess.DocIndexerConvertAndTag;
import nl.inl.blacklab.search.BlackLabIndexImpl;
import nl.inl.blacklab.search.indexmetadata.AnnotatedFieldNameUtil;
import nl.inl.blacklab.search.indexmetadata.IndexMetadataImpl;
/**
* A DocIndexer configured using a ConfigInputFormat structure.
*/
public abstract class DocIndexerConfig extends DocIndexerBase {
protected static String replaceDollarRefs(String pattern, List<String> replacements) {
if (pattern != null) {
int i = 1;
for (String replacement : replacements) {
pattern = pattern.replace("$" + i, replacement);
i++;
}
}
return pattern;
}
public static DocIndexerConfig fromConfig(ConfigInputFormat config) {
DocIndexerConfig docIndexer = null;
switch (config.getFileType()) {
case XML:
for (ConfigInputFormat.FileTypeOption fto: ConfigInputFormat.FileTypeOption.fromConfig(config, ConfigInputFormat.FileType.XML)) {
if (fto == ConfigInputFormat.FileTypeOption.SAXONICA) {
docIndexer = new DocIndexerSaxon();
break;
}
}
if (docIndexer == null) {
docIndexer = new DocIndexerXPath();
}
break;
case TABULAR:
docIndexer = new DocIndexerTabular();
break;
case TEXT:
docIndexer = new DocIndexerPlainText();
break;
case CHAT:
docIndexer = new DocIndexerChat();
break;
default:
throw new InvalidInputFormatConfig(
"Unknown file type: " + config.getFileType() + " (use xml, tabular, text or chat)");
}
docIndexer.setConfigInputFormat(config);
if (config.getConvertPluginId() != null || config.getTagPluginId() != null) {
try {
return new DocIndexerConvertAndTag(docIndexer, config);
} catch (Exception e) {
throw BlackLabRuntimeException.wrap(e);
}
} else {
return docIndexer;
}
}
/** Our input format */
protected ConfigInputFormat config;
boolean inited = false;
protected final Map<String, Collection<String>> sortedMetadataValues = new HashMap<>();
public void setConfigInputFormat(ConfigInputFormat config) {
this.config = config;
}
@SuppressWarnings("deprecation")
protected SensitivitySetting getSensitivitySetting(ConfigAnnotation mainAnnotation) {
SensitivitySetting sensitivity = mainAnnotation.getSensitivity();
if (sensitivity == SensitivitySetting.DEFAULT) {
String name = mainAnnotation.getName();
sensitivity = SensitivitySetting.defaultForAnnotation(name);
if (sensitivity != SensitivitySetting.ONLY_INSENSITIVE) {
// Historic behaviour: if no sensitivity is given, "word" and "lemma" annotations will
// get SensitivitySetting.SENSITIVE_AND_INSENSITIVE; all others get SensitivitySetting.ONLY_INSENSITIVE.
// Warn users about this so they can make their config files explicit before this special case is removed.
logger.warn("Configuration " + config.getName()
+ "relies on special default sensitivity 'sensitive_insensitive' for annotation " + name
+ " (); this behaviour "
+ "is deprecated. Please update your config to explicitly declare the sensitivity setting for this annotation. In a future version, all annotations "
+ "without explicit sensitivity will default to 'insensitive'.");
}
return sensitivity;
}
return sensitivity;
}
@Override
protected String optTranslateFieldName(String from) {
if (config == null) // test
return from;
String to = config.getIndexFieldAs().get(from);
return to == null ? from : to;
}
@SuppressWarnings("deprecation")
protected void init() {
if (inited)
return;
inited = true;
setStoreDocuments(config.shouldStore());
for (ConfigAnnotatedField af : config.getAnnotatedFields().values()) {
// Define the properties that make up our annotated field
if (af.isDummyForStoringLinkedDocuments())
continue;
List<ConfigAnnotation> annotations = new ArrayList<>(af.getAnnotationsFlattened().values());
if (annotations.isEmpty())
throw new InvalidInputFormatConfig("No annotations defined for field " + af.getName());
ConfigAnnotation mainAnnotation = annotations.get(0);
AnnotatedFieldWriter fieldWriter = new AnnotatedFieldWriter(af.getName(), mainAnnotation.getName(),
getSensitivitySetting(mainAnnotation), false);
addAnnotatedField(fieldWriter);
AnnotationWriter annotStartTag = fieldWriter.addAnnotation(null, AnnotatedFieldNameUtil.TAGS_ANNOT_NAME,
SensitivitySetting.ONLY_SENSITIVE, true);
annotStartTag.setHasForwardIndex(false);
// Create properties for the other annotations
for (int i = 1; i < annotations.size(); i++) {
ConfigAnnotation annot = annotations.get(i);
if (!annot.isForEach())
fieldWriter.addAnnotation(annot, annot.getName(), getSensitivitySetting(annot), false);
}
for (ConfigStandoffAnnotations standoff : af.getStandoffAnnotations()) {
for (ConfigAnnotation annot : standoff.getAnnotations().values()) {
fieldWriter.addAnnotation(annot, annot.getName(), getSensitivitySetting(annot), false);
}
}
if (!fieldWriter.hasAnnotation(AnnotatedFieldNameUtil.PUNCTUATION_ANNOT_NAME)) {
// Hasn't been created yet. Create it now.
fieldWriter.addAnnotation(null, AnnotatedFieldNameUtil.PUNCTUATION_ANNOT_NAME,
SensitivitySetting.ONLY_INSENSITIVE, false);
}
if (getDocWriter() != null) {
IndexMetadataImpl indexMetadata = (IndexMetadataImpl)getDocWriter().indexWriter().metadata();
indexMetadata.registerAnnotatedField(fieldWriter);
}
}
}
@Override
public void index() throws IOException, MalformedInputFile, PluginException {
init();
}
@Override
public void indexSpecificDocument(String documentExpr) {
init();
}
protected String processString(String result, List<ConfigProcessStep> process, Map<String, String> mapValues) {
for (ConfigProcessStep step : process) {
String method = step.getMethod();
Map<String, String> param = step.getParam();
switch (method) {
case "replace":
result = opReplace(result, param);
break;
case "default":
result = opDefault(result, param);
break;
case "append":
result = opAppend(result, param);
break;
case "split":
result = opSplit(result, param).get(0);
break;
case "chatFormatAgeToMonths":
result = opChatFormatAgeToMonths(result);
break;
case "strip":
result = opStrip(result, param);
break;
case "concatDate":
result = opConcatDate(param);
break;
case "parsePos":
{
// Get individual feature out of a part of speech string like "NOU(gender=f,number=p)"
String field = param.getOrDefault("field", "_");
result = opParsePartOfSpeech(result, field);
break;
}
default:
// In the future, we'll support user plugins here
throw new UnsupportedOperationException("Unknown processing step method " + method);
}
}
if (mapValues != null && !mapValues.isEmpty()) {
// Finally, apply any value mappings specified.
String mappedResult = mapValues.get(result);
if (mappedResult != null)
result = mappedResult;
}
return result;
}
/**
* process linked documents when configured. An xPath processor can be provided,
* it will retrieve information from the document to construct a path to a linked document.
*/
protected void processLinkedDocument(ConfigLinkedDocument ld, Function<String, String> xpathProcessor) {
// Resolve linkPaths to get the information needed to fetch the document
List<String> results = new ArrayList<>();
for (ConfigLinkValue linkValue : ld.getLinkValues()) {
String valuePath = linkValue.getValuePath();
String valueField = linkValue.getValueField();
if (valuePath != null) {
// Resolve value using XPath
String result = xpathProcessor.apply(valuePath);
if (result == null || result.isEmpty()) {
switch (ld.getIfLinkPathMissing()) {
case IGNORE:
break;
case WARN:
getDocWriter().listener()
.warning("Link path " + valuePath + " not found in document " + documentName);
break;
case FAIL:
throw new BlackLabRuntimeException("Link path " + valuePath + " not found in document " + documentName);
}
}
results.add(result);
} else if (valueField != null) {
// Fetch value from Lucene doc
List<String> metadataField = getMetadataField(valueField);
if (metadataField == null) {
throw new BlackLabRuntimeException("Link value field " + valueField + " has no values (null)!");
}
results.addAll(metadataField);
}
List<String> resultAfterProcessing = new ArrayList<>();
for (String inputValue : results) {
resultAfterProcessing.addAll(processStringMultipleValues(inputValue, linkValue.getProcess(), null));
}
results = resultAfterProcessing;
}
// Substitute link path results in inputFile, pathInsideArchive and documentPath
String inputFile = replaceDollarRefs(ld.getInputFile(), results);
String pathInsideArchive = replaceDollarRefs(ld.getPathInsideArchive(), results);
String documentPath = replaceDollarRefs(ld.getDocumentPath(), results);
try {
// Fetch and index the linked document
indexLinkedDocument(inputFile, pathInsideArchive, documentPath, ld.getInputFormatIdentifier(),
ld.shouldStore() ? ld.getName() : null);
} catch (Exception e) {
String moreInfo = "(inputFile = " + inputFile;
if (pathInsideArchive != null)
moreInfo += ", pathInsideArchive = " + pathInsideArchive;
if (documentPath != null)
moreInfo += ", documentPath = " + documentPath;
moreInfo += ")";
switch (ld.getIfLinkPathMissing()) {
case IGNORE:
case WARN:
getDocWriter().listener().warning("Could not find or parse linked document for " + documentName + moreInfo
+ ": " + e.getMessage());
break;
case FAIL:
throw new BlackLabRuntimeException("Could not find or parse linked document for " + documentName + moreInfo, e);
}
}
}
protected List<String> processStringMultipleValues(String input, List<ConfigProcessStep> process, Map<String, String> mapValues) {
List<String> result = new ArrayList<>();
result.add(input);
for (ConfigProcessStep step : process) {
String method = step.getMethod();
Map<String, String> param = step.getParam();
switch (method) {
case "replace":
for (int i = 0; i < result.size(); ++i) {
result.set(i, opReplace(result.get(i), param));
}
break;
case "default":
for (int i = 0; i < result.size(); ++i) {
result.set(i, opDefault(result.get(i), param));
}
break;
case "append":
for (int i = 0; i < result.size(); ++i) {
result.set(i, opAppend(result.get(i), param));
}
break;
case "split": {
ArrayList<String> r = new ArrayList<>();
for (String s : result) {
r.addAll(opSplit(s, param));
}
result = r;
break;
}
case "chatFormatAgeToMonths":
for (int i = 0; i < result.size(); ++i) {
result.set(i, opChatFormatAgeToMonths(result.get(i)));
}
break;
case "strip":
for (int i = 0; i < result.size(); ++i) {
result.set(i, opStrip(result.get(i), param));
}
break;
case "parsePos":
{
// Get individual feature out of a part of speech string like "NOU(gender=f,number=p)"
String field = param.getOrDefault("field", "_");
for (int i = 0; i < result.size(); ++i) {
result.set(i, opParsePartOfSpeech(result.get(i), field));
}
break;
}
case "concatDate":
String s = opConcatDate(param);
if (!s.isEmpty()) {
result.set(0, s);
}
break;
default:
// In the future, we'll support user plugins here
throw new UnsupportedOperationException("Unknown processing step method " + method);
}
}
if (mapValues != null && !mapValues.isEmpty()) {
// Finally, apply any value mappings specified.
for (int i = 0; i < result.size(); ++i) {
String mappedResult = mapValues.get(result.get(i));
if (mappedResult != null)
result.set(i, mappedResult);
}
}
return result;
}
static final Pattern mainPosPattern = Pattern.compile("^([^(]+)(\\s*\\(.*\\))?$");
static final Pattern featurePattern = Pattern.compile("^[^(]+(\\s*\\((.*)\\))?$");
static String opParsePartOfSpeech(String result, String field) {
// Trim character/string from beginning and end
result = result.trim();
if (field.equals("_")) {
// Get main pos: A(b=c,d=e) -> A
return mainPosPattern.matcher(result).replaceAll("$1");
} else {
// Get feature: A(b=c,d=e) -> e (if field == d)
String featuresString = featurePattern.matcher(result).replaceAll("$2");
return Arrays.stream(featuresString.split(","))
.map(feat -> feat.split("="))
.filter(featParts -> featParts[0].trim().equals(field))
.map(featParts -> featParts[1].trim())
.findFirst()
.orElse("");
}
}
static String opStrip(String result, Map<String, String> param) {
// Trim character/string from beginning and end
String stripChars = param.getOrDefault("chars", " ");
result = StringUtils.strip(result, stripChars);
return result;
}
/**
* Concatenate 3 separate date fields into one.
* E.g.
* Year: 2000
* Month: 10
* Day: 19
*
* Result: "20001019"
*
* @param param operation parameters
* @return resulting value
*/
protected String opConcatDate(Map<String, String> param) {
String yearField = param.get("yearField");
String monthField = param.get("monthField");
String dayField = param.get("dayField");
String mode = param.get("autofill");
if (yearField == null || monthField == null || dayField == null || mode == null || !(mode.equalsIgnoreCase("start")||mode.equalsIgnoreCase("end")))
throw new InvalidInputFormatConfig("concatDate needs parameters yearField, monthField, dayField, and autoFill ('start' or 'end')");
boolean isStart = mode.equalsIgnoreCase("start");
Integer y, m, d;
try { y = Integer.parseInt(getMetadataField(yearField).get(0)); } catch (Exception e) { y = null; }
try { m = Integer.parseInt(getMetadataField(monthField).get(0)); } catch (Exception e) { m = null; }
try { d = Integer.parseInt(getMetadataField(dayField).get(0)); } catch (Exception e) { d = null; }
if (y == null) return "";
if (m == null || m > 12 || m < 1) m = isStart ? 1 : 12;
int maxDay = YearMonth.of(y, m).lengthOfMonth();
if (d == null || d > maxDay || d < 1) d = isStart ? 1 : maxDay;
return StringUtils.leftPad(y.toString(), 4, '0') + StringUtils.leftPad(m.toString(), 2, '0') + StringUtils.leftPad(d.toString(), 2, '0');
}
protected String opChatFormatAgeToMonths(String result) {
// 1;10.30 =><SUF>
String[] parts = result.split("[;.]", 3);
int years = 0;
int months = 0;
int days = 0;
try {
years = Integer.parseInt(parts[0]);
months = parts.length <= 1 ? 0 : Integer.parseInt(parts[1]);
days = parts.length <= 2 ? 0 : Integer.parseInt(parts[2]);
} catch (NumberFormatException e) {
warn("action 'opChatFormatAgeToMonths': illegal value " + result);
}
return Integer.toString(years * 12 + months + (days > 14 ? 1 : 0) );
}
/**
* Split the result string on a separator and return one or all parts.
*
* @param result the string to split
* @param param
* <pre>
* - "separator" for the separator (defaults to ;),
* - "keep" for the keep index, accepts numbers or the special string "all" (defaults to -1)
* if "keep" <= 0 returns the first part.
* if "keep" > number of splits return empty string.
* if "keep" == "all" return all parts
* if "keep" == "both" return both the original (unsplit) string and all parts
* </pre>
*/
private List<String> opSplit(String result, Map<String, String> param) {
// Split on a separator regex and keep one or all parts (first part by default)
String separator = param.getOrDefault("separator", ";");
String keep = param.getOrDefault("keep", "-1").toLowerCase();
String[] parts = result.split(separator, -1);
if (keep.equals("all")) {
return Arrays.asList(parts);
}
if (keep.equals("both")) {
ArrayList<String> r = new ArrayList<>();
r.add(result);
Collections.addAll(r, parts);
return r;
}
int i = -1;
try { i = Integer.parseInt(keep); } catch (NumberFormatException e) { /* handled below */ }
if (i < 0) {
warn("action 'split', parameter 'keep': must be at least 1");
i = 0;
}
return List.of(i < parts.length ? parts[i] : "");
}
/**
* Appends a constant value, or the value of a metadata field to the result string.
*
* @param result the input string
* @param param
* <pre>
* - "separator" for the separator (defaults to " ")
* - "field" for the metadata field whose value will be appended
* - "value" for a constant value ("field" takes precedence if it exists)
* </pre>
*/
private String opAppend(String result, Map<String, String> param) {
String separator = param.getOrDefault("separator", " ");
String field = param.get("field");
String value;
if (field != null)
value = StringUtils.join(getMetadataField(field), separator);
else
value = param.get("value");
if (value != null && value.length() > 0) {
if (result.length() > 0)
result += separator;
result += value;
}
return result;
}
/**
* Optionally replace an empty result with a constant value, or the value of a metadata field.
*
* @param result the input string
* @param param
* <pre>
* - "field" for the metadata field whose value will be used
* - "separator" to join the metadata field if it contains multiple values (defaults to ;)
* - "value" for a constant value ("field" takes precedence if it exists)
* </pre>
*/
private String opDefault(String result, Map<String, String> param) {
if (result.length() == 0) {
String field = param.get("field");
String value;
String sep = param.getOrDefault("separator", ";");
if (field != null)
value = StringUtils.join(getMetadataField(field), sep);
else
value = param.get("value");
if (value != null)
result = value;
}
return result;
}
/**
* Perform a regex replace on result. Allows group references.
*
* @param param
* <pre>
* - "find" for the regex
* - "replace" the replacement string
* </pre>
*/
private static String opReplace(String result, Map<String, String> param) {
String find = param.get("find");
String replace = param.get("replace");
if (find == null || replace == null)
throw new InvalidInputFormatConfig("replace needs parameters find and replace");
try {
result = result.replaceAll(find, replace);
} catch (PatternSyntaxException e) {
throw new InvalidInputFormatConfig("Syntax error in replace regex: " + find);
}
return result;
}
/**
* If any processing steps were defined for this metadata field, apply them now.
*
* This is used for non-XML formats, where we don't actively seek out the
* metadata but encounter it as we go.
*
* @param name metadata field name
* @param value metadata field value
* @return processed value (or original value if not found / no processing steps
* defined)
*/
protected String processMetadataValue(String name, String value) {
ConfigMetadataField f = config.getMetadataField(name);
if (f != null) {
value = processString(value, f.getProcess(), f.getMapValues());
}
return value;
}
/**
* Add metadata field value.
*
* We first collect all metadata values before processing to ensure we have all of them
* in the case of fields with multiple values and to be able to sort them so sorting/grouping
* works correctly on these fields as well.
*
* @param name field name
* @param value value to add
*/
@Override
public void addMetadataField(String name, String value) {
this.sortedMetadataValues.computeIfAbsent(name, __ -> {
ConfigMetadataField conf = this.config.getMetadataField(name);
if (conf != null && conf.getSortValues()) {
return new TreeSet<>(BlackLabIndexImpl.defaultCollator()::compare);
} else {
return new ArrayList<>();
}
}).add(value);
}
private static List<String> collectionToList(Collection<String> c) {
return c == null ? null : c instanceof List ? (List<String>)c : new ArrayList<>(c);
}
/**
* Get a metadata field value.
*
* Overridden because we collect them in sortedMetadataValues while parsing the document,
* and if a value is needed while parsing (such as with linked metadata), we wouldn't
* otherwise be able to return it.
*
* Note that these values aren't processed yet, so that's still an issue.
*
* @param name field name
* @return value(s), or null if not defined
*/
@Override
public List<String> getMetadataField(String name) {
List<String> v = super.getMetadataField(name);
return v == null ? collectionToList(sortedMetadataValues.get(name)) : v;
}
@Override
protected void endDocument() {
for (Map.Entry<String, Collection<String>> metadataValues : sortedMetadataValues.entrySet()) {
String fieldName = metadataValues.getKey();
for (String s : metadataValues.getValue()) {
super.addMetadataField(fieldName, s);
}
}
sortedMetadataValues.clear();
super.endDocument();
}
}
|
5066_14 | package nl.openconvert.tokenizer;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import nl.openconvert.tei.TEITagClasses;
import nl.openconvert.util.Proxy;
import nl.openconvert.util.Util;
import nl.openconvert.util.XML;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
public class TEITokenizer extends DefaultHandler
{
private Writer out;
private boolean inToken = false;
private boolean insideTokenizedElement = false;
private String pendingToken="";
private boolean deferOpenTags = true;
private boolean deleteIntermediate = true;
private boolean needWhite = false;
private boolean onlyInTextElement = true;
Document currentDocument = null;
private Set<String> inlineTags = new HashSet<String>();
private Set<String> milestoneTags = new HashSet<String>();
Stack<Element> openElementStack = new Stack<Element>();
Stack<Element> pendingElementStack = new Stack<Element>();
SAXParser parser = null;
int wordNumber=0;
public TEITokenizer()
{
addInlineTags(TEITagClasses.inlineTagNames);
addMilestoneTags(TEITagClasses.milestone);
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
currentDocument = docBuilder.newDocument();
} catch (Exception e)
{
e.printStackTrace();
}
}
public void addInlineTags(String [] tagNames)
{
for (String t: tagNames)
inlineTags.add(t);
}
public void addMilestoneTags(String [] tagNames)
{
for (String t: tagNames)
milestoneTags.add(t);
}
private boolean isMilestoneTag(String tagName)
{
return (milestoneTags.contains(tagName));
}
public void characters(char[] ch, int start, int length)
{
StringBuffer b = new StringBuffer("");
for (int p=start; p < start+length; p++)
b.append(ch[p]);
String s = new String(b);
if (!insideTokenizedElement)
{
s = nl.openconvert.util.Util.escapeCharacterData(s);
output(s);
return;
}
s = s.replaceAll("\u00a0", " ");
s = s.replaceAll("\\s+", " ");
// nog niet helemaal goed als ch met whitespace begint of eindigt
boolean leadingWhite = s.startsWith(" ");
boolean trailingWhite = s.endsWith(" ");
s = s.replace("\\s$","");
s = s.replace("^\\s", "");
String[] tokens = new String(s).split("\\s+");
if (leadingWhite)
this.flushCurrentWord();
// whitespace node: echo space
if (tokens.length == 0)
{
if (leadingWhite) output(" ");
return;
}
// het eerste token is ofwel vervolg van een pending token ofwel gewoon een los token...
if (inToken && (tokens.length > 1 || trailingWhite)) // continue previous token
{
outputCharacterData(tokens[0]);
endWTag(); // neen...... niet goed als eerste = laatste.....
inToken = false;
} else if (!inToken && (tokens.length > 1 || trailingWhite))
{
if (tokens[0].length() > 0)
{
startWTag();
outputCharacterData(tokens[0]);
endWTag();
inToken = false;
}
}
// de niet-eerste en niet-laatste kunnen er gewoon uit
// en ook de laatste als je training whitespace hebt
for (int i=1; i < tokens.length-(trailingWhite?0:1); i++)
{
if (tokens[i].length() > 0)
{
startWTag();
outputCharacterData(tokens[i]);
endWTag();
inToken = false;
}
}
if (trailingWhite)
output(" ");
// de laatste wordt even pending...
if (!trailingWhite && tokens.length > 0)
{
String t = tokens[tokens.length -1];
if (t.length() > 0)
{
if (tokens.length > 1 || !inToken)
startWTag();
// why not output the
pendingToken = t;
inToken = true;
outputCharacterData(t);
pendingToken = "";
//System.err.println("\nPending... <" + t + "> in <" + s + ">");
}
}
}
public void startElement(String uri, String localName, String qName, Attributes attributes)
{
Element e = currentDocument.createElement(qName);
//System.err.println(localName);
if (qName.equals("text") || qName.equals("osisText"))
{
//System.err.println("OK....");
insideTokenizedElement=true;
//System.exit(1);
}
for (int i=0; i < attributes.getLength(); i++)
{
if (!attributes.getQName(i).equalsIgnoreCase("teiform"))
e.setAttribute(attributes.getQName(i), attributes.getValue(i));
}
if (!insideTokenizedElement)
{
printStartTag(e);
return;
}
if (isMilestoneTag(qName)) // dit werkt dus niet....
{
printEmptyTag(e);
return;
}
if (TEITagClasses.tagSplitsWords(qName))
{
flushCurrentWord();
needWhite = false;
output("\n");
printStartTag(e);
} else
{
if (inToken)
{
if (pendingToken.length() > 0)
{
startWTag();
outputCharacterData(pendingToken);
pendingToken = "";
}
}
// ofwel zet hem alleen op de pending lijst? en dan moet ie gerealiseerd zodra je karakters ziet
if (deferOpenTags) // && !milestoneTags.contains(qName))
{
pendingElementStack.push(e);
}
else
{
//System.err.println("milestone: " + qName);
printStartTag(e);
openElementStack.push(e);
}
}
}
// het mag niet zo zijn dat hiervoor nog inline tags open staan; die moeten allemaal weer dicht.
public void startWTag()
{
if (needWhite)
{
output(" ");
needWhite = false;
}
flushOpenTags();
output("<w xml:id=\"w." + wordNumber++ + "\">");
realizePendingTags();
}
// het mag niet
public void endWTag()
{
flushOpenTags();
output("</w>");
needWhite = true;
if (!this.deferOpenTags)
realizePendingTags(); // dit hoeft op zich niet?
}
public void output(String s)
{
try
{
out.write(s);
//out.flush();
} catch (Exception e)
{
e.printStackTrace();
}
}
public void outputCharacterData(String s)
{
realizePendingTags();
try
{
s = s.replaceAll("&", "&");
s = s.replaceAll("<", "<");
s = s.replaceAll(">", ">");
out.write(s);
//out.flush();
} catch (Exception e)
{
e.printStackTrace();
}
}
public void flushOpenTags()
{
while(true)
{
try
{
Element e = openElementStack.pop();
if (e != null)
{
printEndTag(e);
pendingElementStack.push(e);
}
} catch (Exception e)
{
break;
// TODO: handle exception
}
}
}
public void flushCurrentWord()
{
if (this.inToken)
{
// flush tag stack
realizePendingTags();
output(this.pendingToken);
flushOpenTags();
endWTag();
this.inToken = false;
this.pendingToken = "";
// flush tag stack in reverse
}
}
public void printStartTag(Element e)
{
try
{
out.write("<" + e.getNodeName());
NamedNodeMap attributes = e.getAttributes();
for (int i=0; i < attributes.getLength(); i++)
{
Node n=attributes.item(i);
out.write(" " + n.getNodeName() + "=\"" + nl.openconvert.util.Util.escapeForAttribute(n.getNodeValue()) + "\"");
}
out.write(">");
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public void printEmptyTag(Element e)
{
try
{
out.write("<" + e.getNodeName());
NamedNodeMap attributes = e.getAttributes();
for (int i=0; i < attributes.getLength(); i++)
{
Node n=attributes.item(i);
out.write(" " + n.getNodeName() + "=\"" + n.getNodeValue() + "\"");
}
out.write("/>");
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public void printEndTag(Element e)
{
try
{
out.write("</" + e.getNodeName() + ">");
} catch (IOException e1)
{
e1.printStackTrace();
}
}
public void printEndTag(String t)
{
try
{
out.write("</" + t + ">");
} catch (IOException e1)
{
e1.printStackTrace();
}
}
public void endElement(String uri, String localName, String qName) // hier moet je nog iets voor de empty elements doen....
{
if (!insideTokenizedElement)
{
printEndTag(qName);
return;
}
if (isMilestoneTag(qName))
return;
if (TEITagClasses.tagSplitsWords(qName)) // hier gaat de volgorde mis..
{
flushCurrentWord();
needWhite = false;
} else
{
// there should not be any pending elements right now..
realizePendingTags();
Element e = openElementStack.pop();
}
printEndTag(qName);
if (TEITagClasses.tagSplitsWords(qName))
output("\n");
}
public void tokenizeFile(String fileName, String outputFilename)
{
try
{
out = new OutputStreamWriter(new FileOutputStream(outputFilename), "UTF8");
if (parser == null)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/validation/schema", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
parser = factory.newSAXParser(); // waarom steeds opnieuw?
}
parser.parse( new File(fileName), this);
out.close();
} catch (Throwable err)
{
err.printStackTrace ();
}
}
public String preTokenizeString(String inputString)
{
try
{
out = new StringWriter();
byte[] bytes = inputString.getBytes("UTF-8");
InputStream input = new ByteArrayInputStream(bytes);
if (parser == null)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/validation/schema", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
parser = factory.newSAXParser(); // waarom steeds opnieuw?
}
this.insideTokenizedElement = true;
parser.parse(input, this);
out.close();
return out.toString();
} catch (Throwable err)
{
err.printStackTrace ();
}
return null;
}
public Document tokenizeString(String inputString)
{
String pretokenized = preTokenizeString(inputString);
Document d = XML.parseString(pretokenized);
new PunctuationTagger().tagPunctuation(d);
return d;
}
public String getTempDir()
{
String property = "java.io.tmpdir";
// Get the temporary directory and print it.
String tempDir = System.getProperty(property);
System.err.println("OS current temporary directory is " + tempDir);
return tempDir;
}
public Document getTokenizedDocument(String fileName, boolean splitPunctuation)
{
File pretokenizedFile = null;
try
{
long startTok = System.currentTimeMillis();
pretokenizedFile = File.createTempFile("tokenized", ".xml");
try
{
if (deleteIntermediate) pretokenizedFile.deleteOnExit();
} catch (Exception e)
{
e.printStackTrace();
}
tokenizeFile(fileName, pretokenizedFile.getCanonicalPath());
double step1Time = (System.currentTimeMillis() - startTok) / 1000.0;
System.err.println("pretokenization time: " + step1Time);
Document d = null;
try
{
d = XML.parse(pretokenizedFile.getCanonicalPath(),true);
} catch (Exception e)
{
System.err.println("error in pretokenized file " + pretokenizedFile.getCanonicalPath() );
e.printStackTrace();
//System.exit(1);
//java.nio.file.Files.copy("aap", "noot");
}
if (deleteIntermediate) pretokenizedFile.delete();
if (splitPunctuation)
new PunctuationTagger().tagPunctuation(d);
//System.out.println(ParseUtils.documentToString(d));
long endTok = System.currentTimeMillis();
double elapsed = (endTok - startTok) / 1000.0;
System.err.println("tokenization time: " + elapsed);
return d;
} catch (Exception e)
{
e.printStackTrace();
if (deleteIntermediate && pretokenizedFile != null) pretokenizedFile.delete();
return null;
}
}
public void preTokenizeFile(String fileName)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
try
{
out = new OutputStreamWriter(System.out, "UTF8");
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( new File(fileName), this);
out.flush();
} catch (Throwable err)
{
err.printStackTrace ();
}
}
/**
* This is silly! should output "deepest" tag first....
*/
public void realizePendingTags()
{
Stack<Element> viceVersa = new Stack<Element>();
while(true)
{
try
{
Element e = pendingElementStack.pop();
if (e != null)
viceVersa.push(e);
} catch (Exception e)
{
break;
}
}
while(true)
{
try
{
Element e = viceVersa.pop();
if (e != null)
{
printStartTag(e);
openElementStack.push(e); // this IS ok? No?
}
} catch (Exception e)
{
break;
}
}
}
public static void main(String[] args)
{
Proxy.setProxy();
Document d = new TEITokenizer().getTokenizedDocument(args[0], true);
System.out.println(XML.documentToString(d));
//new TEITokenizer().preTokenizeFile(args[0]); // getTokenizedDocument(args[0],true);
}
}
| INL/OpenConvert | src/nl/openconvert/tokenizer/TEITokenizer.java | 4,705 | // het mag niet zo zijn dat hiervoor nog inline tags open staan; die moeten allemaal weer dicht. | line_comment | nl | package nl.openconvert.tokenizer;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import nl.openconvert.tei.TEITagClasses;
import nl.openconvert.util.Proxy;
import nl.openconvert.util.Util;
import nl.openconvert.util.XML;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
public class TEITokenizer extends DefaultHandler
{
private Writer out;
private boolean inToken = false;
private boolean insideTokenizedElement = false;
private String pendingToken="";
private boolean deferOpenTags = true;
private boolean deleteIntermediate = true;
private boolean needWhite = false;
private boolean onlyInTextElement = true;
Document currentDocument = null;
private Set<String> inlineTags = new HashSet<String>();
private Set<String> milestoneTags = new HashSet<String>();
Stack<Element> openElementStack = new Stack<Element>();
Stack<Element> pendingElementStack = new Stack<Element>();
SAXParser parser = null;
int wordNumber=0;
public TEITokenizer()
{
addInlineTags(TEITagClasses.inlineTagNames);
addMilestoneTags(TEITagClasses.milestone);
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
currentDocument = docBuilder.newDocument();
} catch (Exception e)
{
e.printStackTrace();
}
}
public void addInlineTags(String [] tagNames)
{
for (String t: tagNames)
inlineTags.add(t);
}
public void addMilestoneTags(String [] tagNames)
{
for (String t: tagNames)
milestoneTags.add(t);
}
private boolean isMilestoneTag(String tagName)
{
return (milestoneTags.contains(tagName));
}
public void characters(char[] ch, int start, int length)
{
StringBuffer b = new StringBuffer("");
for (int p=start; p < start+length; p++)
b.append(ch[p]);
String s = new String(b);
if (!insideTokenizedElement)
{
s = nl.openconvert.util.Util.escapeCharacterData(s);
output(s);
return;
}
s = s.replaceAll("\u00a0", " ");
s = s.replaceAll("\\s+", " ");
// nog niet helemaal goed als ch met whitespace begint of eindigt
boolean leadingWhite = s.startsWith(" ");
boolean trailingWhite = s.endsWith(" ");
s = s.replace("\\s$","");
s = s.replace("^\\s", "");
String[] tokens = new String(s).split("\\s+");
if (leadingWhite)
this.flushCurrentWord();
// whitespace node: echo space
if (tokens.length == 0)
{
if (leadingWhite) output(" ");
return;
}
// het eerste token is ofwel vervolg van een pending token ofwel gewoon een los token...
if (inToken && (tokens.length > 1 || trailingWhite)) // continue previous token
{
outputCharacterData(tokens[0]);
endWTag(); // neen...... niet goed als eerste = laatste.....
inToken = false;
} else if (!inToken && (tokens.length > 1 || trailingWhite))
{
if (tokens[0].length() > 0)
{
startWTag();
outputCharacterData(tokens[0]);
endWTag();
inToken = false;
}
}
// de niet-eerste en niet-laatste kunnen er gewoon uit
// en ook de laatste als je training whitespace hebt
for (int i=1; i < tokens.length-(trailingWhite?0:1); i++)
{
if (tokens[i].length() > 0)
{
startWTag();
outputCharacterData(tokens[i]);
endWTag();
inToken = false;
}
}
if (trailingWhite)
output(" ");
// de laatste wordt even pending...
if (!trailingWhite && tokens.length > 0)
{
String t = tokens[tokens.length -1];
if (t.length() > 0)
{
if (tokens.length > 1 || !inToken)
startWTag();
// why not output the
pendingToken = t;
inToken = true;
outputCharacterData(t);
pendingToken = "";
//System.err.println("\nPending... <" + t + "> in <" + s + ">");
}
}
}
public void startElement(String uri, String localName, String qName, Attributes attributes)
{
Element e = currentDocument.createElement(qName);
//System.err.println(localName);
if (qName.equals("text") || qName.equals("osisText"))
{
//System.err.println("OK....");
insideTokenizedElement=true;
//System.exit(1);
}
for (int i=0; i < attributes.getLength(); i++)
{
if (!attributes.getQName(i).equalsIgnoreCase("teiform"))
e.setAttribute(attributes.getQName(i), attributes.getValue(i));
}
if (!insideTokenizedElement)
{
printStartTag(e);
return;
}
if (isMilestoneTag(qName)) // dit werkt dus niet....
{
printEmptyTag(e);
return;
}
if (TEITagClasses.tagSplitsWords(qName))
{
flushCurrentWord();
needWhite = false;
output("\n");
printStartTag(e);
} else
{
if (inToken)
{
if (pendingToken.length() > 0)
{
startWTag();
outputCharacterData(pendingToken);
pendingToken = "";
}
}
// ofwel zet hem alleen op de pending lijst? en dan moet ie gerealiseerd zodra je karakters ziet
if (deferOpenTags) // && !milestoneTags.contains(qName))
{
pendingElementStack.push(e);
}
else
{
//System.err.println("milestone: " + qName);
printStartTag(e);
openElementStack.push(e);
}
}
}
// het mag<SUF>
public void startWTag()
{
if (needWhite)
{
output(" ");
needWhite = false;
}
flushOpenTags();
output("<w xml:id=\"w." + wordNumber++ + "\">");
realizePendingTags();
}
// het mag niet
public void endWTag()
{
flushOpenTags();
output("</w>");
needWhite = true;
if (!this.deferOpenTags)
realizePendingTags(); // dit hoeft op zich niet?
}
public void output(String s)
{
try
{
out.write(s);
//out.flush();
} catch (Exception e)
{
e.printStackTrace();
}
}
public void outputCharacterData(String s)
{
realizePendingTags();
try
{
s = s.replaceAll("&", "&");
s = s.replaceAll("<", "<");
s = s.replaceAll(">", ">");
out.write(s);
//out.flush();
} catch (Exception e)
{
e.printStackTrace();
}
}
public void flushOpenTags()
{
while(true)
{
try
{
Element e = openElementStack.pop();
if (e != null)
{
printEndTag(e);
pendingElementStack.push(e);
}
} catch (Exception e)
{
break;
// TODO: handle exception
}
}
}
public void flushCurrentWord()
{
if (this.inToken)
{
// flush tag stack
realizePendingTags();
output(this.pendingToken);
flushOpenTags();
endWTag();
this.inToken = false;
this.pendingToken = "";
// flush tag stack in reverse
}
}
public void printStartTag(Element e)
{
try
{
out.write("<" + e.getNodeName());
NamedNodeMap attributes = e.getAttributes();
for (int i=0; i < attributes.getLength(); i++)
{
Node n=attributes.item(i);
out.write(" " + n.getNodeName() + "=\"" + nl.openconvert.util.Util.escapeForAttribute(n.getNodeValue()) + "\"");
}
out.write(">");
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public void printEmptyTag(Element e)
{
try
{
out.write("<" + e.getNodeName());
NamedNodeMap attributes = e.getAttributes();
for (int i=0; i < attributes.getLength(); i++)
{
Node n=attributes.item(i);
out.write(" " + n.getNodeName() + "=\"" + n.getNodeValue() + "\"");
}
out.write("/>");
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public void printEndTag(Element e)
{
try
{
out.write("</" + e.getNodeName() + ">");
} catch (IOException e1)
{
e1.printStackTrace();
}
}
public void printEndTag(String t)
{
try
{
out.write("</" + t + ">");
} catch (IOException e1)
{
e1.printStackTrace();
}
}
public void endElement(String uri, String localName, String qName) // hier moet je nog iets voor de empty elements doen....
{
if (!insideTokenizedElement)
{
printEndTag(qName);
return;
}
if (isMilestoneTag(qName))
return;
if (TEITagClasses.tagSplitsWords(qName)) // hier gaat de volgorde mis..
{
flushCurrentWord();
needWhite = false;
} else
{
// there should not be any pending elements right now..
realizePendingTags();
Element e = openElementStack.pop();
}
printEndTag(qName);
if (TEITagClasses.tagSplitsWords(qName))
output("\n");
}
public void tokenizeFile(String fileName, String outputFilename)
{
try
{
out = new OutputStreamWriter(new FileOutputStream(outputFilename), "UTF8");
if (parser == null)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/validation/schema", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
parser = factory.newSAXParser(); // waarom steeds opnieuw?
}
parser.parse( new File(fileName), this);
out.close();
} catch (Throwable err)
{
err.printStackTrace ();
}
}
public String preTokenizeString(String inputString)
{
try
{
out = new StringWriter();
byte[] bytes = inputString.getBytes("UTF-8");
InputStream input = new ByteArrayInputStream(bytes);
if (parser == null)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/validation/schema", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
parser = factory.newSAXParser(); // waarom steeds opnieuw?
}
this.insideTokenizedElement = true;
parser.parse(input, this);
out.close();
return out.toString();
} catch (Throwable err)
{
err.printStackTrace ();
}
return null;
}
public Document tokenizeString(String inputString)
{
String pretokenized = preTokenizeString(inputString);
Document d = XML.parseString(pretokenized);
new PunctuationTagger().tagPunctuation(d);
return d;
}
public String getTempDir()
{
String property = "java.io.tmpdir";
// Get the temporary directory and print it.
String tempDir = System.getProperty(property);
System.err.println("OS current temporary directory is " + tempDir);
return tempDir;
}
public Document getTokenizedDocument(String fileName, boolean splitPunctuation)
{
File pretokenizedFile = null;
try
{
long startTok = System.currentTimeMillis();
pretokenizedFile = File.createTempFile("tokenized", ".xml");
try
{
if (deleteIntermediate) pretokenizedFile.deleteOnExit();
} catch (Exception e)
{
e.printStackTrace();
}
tokenizeFile(fileName, pretokenizedFile.getCanonicalPath());
double step1Time = (System.currentTimeMillis() - startTok) / 1000.0;
System.err.println("pretokenization time: " + step1Time);
Document d = null;
try
{
d = XML.parse(pretokenizedFile.getCanonicalPath(),true);
} catch (Exception e)
{
System.err.println("error in pretokenized file " + pretokenizedFile.getCanonicalPath() );
e.printStackTrace();
//System.exit(1);
//java.nio.file.Files.copy("aap", "noot");
}
if (deleteIntermediate) pretokenizedFile.delete();
if (splitPunctuation)
new PunctuationTagger().tagPunctuation(d);
//System.out.println(ParseUtils.documentToString(d));
long endTok = System.currentTimeMillis();
double elapsed = (endTok - startTok) / 1000.0;
System.err.println("tokenization time: " + elapsed);
return d;
} catch (Exception e)
{
e.printStackTrace();
if (deleteIntermediate && pretokenizedFile != null) pretokenizedFile.delete();
return null;
}
}
public void preTokenizeFile(String fileName)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
try
{
out = new OutputStreamWriter(System.out, "UTF8");
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( new File(fileName), this);
out.flush();
} catch (Throwable err)
{
err.printStackTrace ();
}
}
/**
* This is silly! should output "deepest" tag first....
*/
public void realizePendingTags()
{
Stack<Element> viceVersa = new Stack<Element>();
while(true)
{
try
{
Element e = pendingElementStack.pop();
if (e != null)
viceVersa.push(e);
} catch (Exception e)
{
break;
}
}
while(true)
{
try
{
Element e = viceVersa.pop();
if (e != null)
{
printStartTag(e);
openElementStack.push(e); // this IS ok? No?
}
} catch (Exception e)
{
break;
}
}
}
public static void main(String[] args)
{
Proxy.setProxy();
Document d = new TEITokenizer().getTokenizedDocument(args[0], true);
System.out.println(XML.documentToString(d));
//new TEITokenizer().preTokenizeFile(args[0]); // getTokenizedDocument(args[0],true);
}
}
|
36192_2 | package org.ivdnt.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/*
* ParseUtils.java
*
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.input.BOMInputStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XML
{
private XML() {}
public abstract static class NodeAction
{
public abstract boolean action(Node n); // true: klaar, geen recursie
}
public static void preorder(Document d, NodeAction action)
{
Element r = d.getDocumentElement();
preorder(r,action);
}
public static void preorder(Node n, NodeAction action)
{
if (!action.action(n))
{
NodeList children = n.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
preorder(children.item(k), action);
}
}
}
public static void findElementsByNameAndAttribute(List<Element> list, Element e, String elementName, String attName, String attValue, boolean recursive) // nonrecursive
{
NodeList children = e.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.ELEMENT_NODE)
{
Element child = (Element) c;
String a;
if (child.getNodeName().equalsIgnoreCase(elementName) && (a = child.getAttribute(attName)) != null && a.equals(attValue))
{
list.add(child);
if (recursive) findElementsByNameAndAttribute(list, child, elementName, attName, attValue, true);
}
else
{
findElementsByNameAndAttribute(list, child, elementName, attName, attValue, recursive);
}
}
}
}
public static void findElementsByName(List<Element> list, Element e, String elementName, boolean recursive) // nonrecursive
{
NodeList children = e.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.ELEMENT_NODE)
{
Element child = (Element) c;
if (child.getNodeName().equalsIgnoreCase(elementName))
{
list.add(child);
if (recursive)
findElementsByName(list, child, elementName, true);
}
else
{
findElementsByName(list, child, elementName, recursive);
}
}
}
}
public static void findElementsByName(List<Element> list, Element e, Set<String> elementNames, boolean recursive) // nonrecursive
{
NodeList children = e.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.ELEMENT_NODE)
{
Element child = (Element) c;
if (elementNames.contains(child.getNodeName()) || elementNames.contains(child.getLocalName()))
{
list.add(child);
if (recursive)
findElementsByName(list, child, elementNames, true);
}
else
{
findElementsByName(list, child, elementNames, recursive);
}
}
}
}
public static void getAllSubelements(List<Element> list, Element e, boolean recursive) // nonrecursive
{
NodeList children = e.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.ELEMENT_NODE)
{
Element child = (Element) c;
list.add(child);
if (recursive)
getAllSubelements(list, child, true);
}
}
}
// vindt wel <x> binnen <x>
public static void findAllElementsByName(List<Element> list, Element e, String elementName) // recursive
{
if (e.getNodeName().equalsIgnoreCase(elementName))
{
list.add(e);
}
NodeList children = e.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.ELEMENT_NODE)
{
Element child = (Element) c;
findAllElementsByName(list, child, elementName);
}
}
}
public static List<Element> getElementsByTagname(Element e, String elementName, boolean recursive)
{
List<Element> list = new ArrayList<>();
if (e != null)
findElementsByName(list, e, elementName, recursive);
return list;
}
public static List<Element> getElementsByTagname(Element e, Set<String> elementNames, boolean recursive)
{
List<Element> list = new ArrayList<>();
if (e != null)
findElementsByName(list, e, elementNames, recursive);
return list;
}
public static List<Element> getElementsByTagname(Element e, String[] elementNames, boolean recursive)
{
Set<String> s = new HashSet<>();
for (String x: elementNames) s.add(x);
List<Element> list = new ArrayList<>();
if (e != null)
findElementsByName(list, e, s, recursive);
return list;
}
public static List<Element> getAllSubelements(Element e, boolean recursive)
{
List<Element> list = new ArrayList<>();
if (e != null)
getAllSubelements(list, e, recursive);
return list;
}
public static List<Element> getElementsByTagnameAndAttribute(Element e, String elementName, String attName, String attValue, boolean recursive)
{
List<Element> list = new ArrayList<>();
findElementsByNameAndAttribute(list, e, elementName, attName, attValue, recursive);
return list;
}
public static Element getElementByTagname(Element e, String elementName)
{
List<Element> list = getElementsByTagname(e, elementName, false);
return !list.isEmpty() ? list.get(0) : null;
}
public static String getElementContent(Element e, String tagname)
{
Element x = getElementByTagname(e,tagname);
return x != null ? x.getTextContent() : null;
}
public static Element findFirstChild(Element e, String tagName)
{
NodeList l = e.getChildNodes();
for (int i=0; i < l.getLength(); i++)
{
try
{
Element c = (Element) l.item(i);
if (c.getNodeName().equals(tagName)) return c;
} catch (Exception ex)
{
ex.printStackTrace();
}
}
return null;
}
public static Element findFirstChild(Element e, String[] tagNames)
{
NodeList l = e.getChildNodes();
for (int i=0; i < l.getLength(); i++)
{
try
{
Element c = (Element) l.item(i);
for (String tagName: tagNames)
if (c.getNodeName().equals(tagName)) return c;
} catch (Exception ex)
{
ex.printStackTrace();
}
}
return null;
}
public static List<Element> findChildren(Element e, String[] tagNames)
{
NodeList l = e.getChildNodes();
ArrayList<Element> r = new ArrayList<>();
for (int i=0; i < l.getLength(); i++)
{
try
{
Element c = (Element) l.item(i);
for (String tagName: tagNames)
if (c.getNodeName().equals(tagName)) r.add(c);
} catch (Exception ex)
{
ex.printStackTrace();
}
}
return r;
}
public static void insertChildAfter(Node n, Node after, Node newChild)
{
Node afterAfter = null;
if ((afterAfter = after.getNextSibling()) == null)
{
n.appendChild(newChild);
} else
{
try
{
if (afterAfter.getParentNode() != n)
{
System.err.println("neee - dat MEEEN je niet");
}
n.insertBefore(newChild, afterAfter);
} catch (Exception e)
{
System.err.println(n + "" +
afterAfter + "" +
afterAfter.getParentNode() + "" + newChild);
e.printStackTrace();
System.exit(1);
}
}
}
public static boolean isWhiteSpaceNode(Node n)
{
String v = n.getNodeValue();
return v.matches("^\\s*$");
}
public static boolean isWhiteSpaceOrPunctuationNode(Node n)
{
String v = n.getNodeValue();
return v.matches("^(\\s|;|\\.)*$");
}
public static void collectNodesBetween(List<Node> nodes, Node currentNode, Node after, Node before)
{
boolean b1 = after.compareDocumentPosition(currentNode) == Node.DOCUMENT_POSITION_FOLLOWING;
boolean b2 = before.compareDocumentPosition(currentNode) == Node.DOCUMENT_POSITION_PRECEDING;
if (b1 && b2)
nodes.add(currentNode);
NodeList children = currentNode.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
Node next = c.getNextSibling();
Node previous = c.getPreviousSibling();
boolean x1 =
next != null &&
after.compareDocumentPosition(next) == Node.DOCUMENT_POSITION_PRECEDING;
boolean x2 = previous != null &&
before.compareDocumentPosition(previous) == Node.DOCUMENT_POSITION_FOLLOWING;
if (!x1 && !x2)
collectNodesBetween(nodes,c,after,before);
}
// klaus 4 oct .... 3 wednesday // 5 mother birthday
}
public static List<Node> collectNodesBetween(Node after, Node before)
{
List<Node> list = new ArrayList<>();
Node p = findCommonAncestor(after,before);
collectNodesBetween(list,p,after,before);
return list;
}
public static List<Element> collectNodesBetween(Set<String> elementNames, Node after, Node before)
{
List<Node> list = collectNodesBetween(after,before);
List<Element> trimmed = new ArrayList<>();
for (Node n: list)
{
if (n.getNodeType() == Node.ELEMENT_NODE)
{
if (elementNames.contains(n.getNodeName()) ||
elementNames.contains(n.getLocalName()))
{
trimmed.add((Element) n);
}
}
}
return trimmed;
}
public static Document parse(String aFilename, boolean namespaceAware) throws
ParserConfigurationException, SAXException, IOException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion", false );
DocumentBuilder builder = factory.newDocumentBuilder();
//There is a bug related to 4 byte UTF8 ... which has to be worked around
// https://issues.apache.org/jira/browse/XERCESJ-1257
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(new File(aFilename)));
InputStreamReader isr = new java.io.InputStreamReader(fis, "UTF-8");
InputSource is = new InputSource(isr);
return builder.parse(is);
}
public static Document parse(String aFilename) throws ParserConfigurationException, SAXException, IOException
{
return parse(aFilename,true);
}
public static Document parseString(String inputString, boolean namespaceAware)
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
try
{
factory.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion", false );
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(new StringReader(inputString)));
} catch (Exception e)
{
e.printStackTrace();
return null;
}
}
/**
*
* @param is
* @param cs (optional) encoding of the stream, attempts to autodetect if missing.
* @param namespaceAware
* @return
*/
public static Document parseStream(InputStream is, Charset cs, boolean namespaceAware)
{
if (cs == null) {
BOMInputStream bis = (is instanceof BOMInputStream) ? ((BOMInputStream)is) : new BOMInputStream(is);
is = bis;
String csName;
try {csName = bis.getBOMCharsetName();} catch (IOException e) {throw new RuntimeException(e);}
cs = csName != null ? Charset.forName(csName) : StandardCharsets.UTF_8;
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
try
{
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion", false );
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(new InputStreamReader(is, cs)));
} catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public static Document parseString(String inputString)
{
return parseString(inputString, true);
}
public static Document createDocument(String rootElementName)
{
try
{
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement(rootElementName);
doc.appendChild(root);
return doc;
} catch (Exception e)
{
return null;
}
}
public static String documentToString(Document d)
{
try
{
// Set up the output transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "no");
// Print the DOM node
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(d.getDocumentElement());
trans.transform(source, result);
String xmlString = sw.toString();
xmlString = xmlString.replaceAll(" xmlns=\"\"", ""); // ugly hack, should be avoidable...
return xmlString;
}
catch (TransformerException e)
{
e.printStackTrace();
}
return null;
}
public void printNode(Node node, Writer writer)
{
try
{
// Set up the output transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.METHOD, "xml");
// Print the DOM node
trans.transform(new DOMSource(node), new StreamResult(writer));
}
catch (TransformerException e)
{
e.printStackTrace();
}
}
public static String nodeToString(Node node)
{
try
{
// Set up the output transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.METHOD, "xml");
// Print the DOM node
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(node);
trans.transform(source, result);
String xmlString = sw.toString();
return xmlString;
}
catch (TransformerException e)
{
e.printStackTrace();
return null;
}
}
public static Document cloneDocument(Document d)
{
try
{
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer tx = tfactory.newTransformer();
DOMSource source = new DOMSource(d);
DOMResult result = new DOMResult();
tx.transform(source,result);
return (Document) result.getNode();
} catch (Exception e)
{
e.printStackTrace();
return null;
}
}
private static void getTextNodesBelow(List<Node> nodes, Node n)
{
NodeList children = n.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.TEXT_NODE)
{
nodes.add(c);
} else if (c.getNodeType() == Node.ELEMENT_NODE)
{
getTextNodesBelow(nodes,c);
}
}
}
public static List<Node> getTextNodesBelow(Node n)
{
List<Node> l = new ArrayList<>();
getTextNodesBelow(l,n);
return l;
}
public static Element findAncestor(Node t, String string)
{
Node p;
for (p=t; p != null; p =p.getParentNode())
{
if (p.getNodeType() ==Node.ELEMENT_NODE && p.getNodeName().equals(string))
return (Element) p;
}
return null;
}
public static Set<Node> getAncestors(Node n)
{
Node p = n.getParentNode();
Set<Node> ancestors = new HashSet<>();
while (p != null)
{
ancestors.add(p );
p = p.getParentNode();
}
return ancestors;
}
public static Node findCommonAncestor(Node n1, Node n2)
{
Set<Node> a1 = getAncestors(n1);
Node p = n2.getParentNode();
while (p!= null)
{
if (a1.contains(p)) return p;
p = p.getParentNode();
}
return null;
}
/**
* Replace the subtree under e with a single text node
* @param e
*/
public static void flattenElementContents(Element e)
{
Document d = e.getOwnerDocument();
Text t = d.createTextNode(e.getTextContent());
NodeList ch = e.getChildNodes();
for (int i=0; i < ch.getLength(); i++)
{
e.removeChild(ch.item(i));
}
e.appendChild(t);
}
public static void removeInterveningNode(Element e)
{
Node p = e.getParentNode();
NodeList n = e.getChildNodes();
List<Node> children = new ArrayList<>();
Node next = e.getNextSibling();
for (int i=0; i < n.getLength(); i++)
{
children.add(n.item(i));
}
for (Node c: children) e.removeChild(c);
p.removeChild(e);
for (Node c: children)
{
if (next != null)
p.insertBefore(c, next);
else
p.appendChild(c);
}
}
public static void findTextNodesBelow(List<Node> list, Element e) // nonrecursive
{
NodeList children = e.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.ELEMENT_NODE)
{
Element child = (Element) c;
{
findTextNodesBelow(list, child);
}
} else if (c.getNodeType() == Node.TEXT_NODE)
{
list.add(c);
}
}
}
public static String escapeForAttribute(String v)
{
v = v.replaceAll("&", "&");
v = v.replaceAll("<", "<");
v = v.replaceAll(">", ">");
v = v.replaceAll("'", "'");
v = v.replaceAll("\"", """);
return v;
}
public static String escapeCharacterData(String v)
{
v = v.replaceAll("&", "&");
v = v.replaceAll("<", "<");
v = v.replaceAll(">", ">");
return v;
}
public static String xmlSingleQuotedEscape(String s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
switch (c)
{
case '\'': sb.append("""); break;
case '&': sb.append("&"); break;
case '<': sb.append("<"); break;
case '\n': sb.append("
"); break;
case '\000': case '\001': case '\002': case '\003': case '\004':
case '\005': case '\006': case '\007': case '\010': case '\013':
case '\014': case '\016': case '\017': case '\020': case '\021':
case '\022': case '\023': case '\024': case '\025': case '\026':
case '\027': case '\030': case '\031': case '\032': case '\033':
case '\034': case '\035': case '\036': case '\037':
// do nothing, these are disallowed characters
break;
default: sb.append(c);
}
}
return sb.toString();
}
}
| INL/UtilitiesForTaggerEtc | src/main/java/org/ivdnt/util/XML.java | 6,522 | // vindt wel <x> binnen <x> | line_comment | nl | package org.ivdnt.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/*
* ParseUtils.java
*
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.input.BOMInputStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XML
{
private XML() {}
public abstract static class NodeAction
{
public abstract boolean action(Node n); // true: klaar, geen recursie
}
public static void preorder(Document d, NodeAction action)
{
Element r = d.getDocumentElement();
preorder(r,action);
}
public static void preorder(Node n, NodeAction action)
{
if (!action.action(n))
{
NodeList children = n.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
preorder(children.item(k), action);
}
}
}
public static void findElementsByNameAndAttribute(List<Element> list, Element e, String elementName, String attName, String attValue, boolean recursive) // nonrecursive
{
NodeList children = e.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.ELEMENT_NODE)
{
Element child = (Element) c;
String a;
if (child.getNodeName().equalsIgnoreCase(elementName) && (a = child.getAttribute(attName)) != null && a.equals(attValue))
{
list.add(child);
if (recursive) findElementsByNameAndAttribute(list, child, elementName, attName, attValue, true);
}
else
{
findElementsByNameAndAttribute(list, child, elementName, attName, attValue, recursive);
}
}
}
}
public static void findElementsByName(List<Element> list, Element e, String elementName, boolean recursive) // nonrecursive
{
NodeList children = e.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.ELEMENT_NODE)
{
Element child = (Element) c;
if (child.getNodeName().equalsIgnoreCase(elementName))
{
list.add(child);
if (recursive)
findElementsByName(list, child, elementName, true);
}
else
{
findElementsByName(list, child, elementName, recursive);
}
}
}
}
public static void findElementsByName(List<Element> list, Element e, Set<String> elementNames, boolean recursive) // nonrecursive
{
NodeList children = e.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.ELEMENT_NODE)
{
Element child = (Element) c;
if (elementNames.contains(child.getNodeName()) || elementNames.contains(child.getLocalName()))
{
list.add(child);
if (recursive)
findElementsByName(list, child, elementNames, true);
}
else
{
findElementsByName(list, child, elementNames, recursive);
}
}
}
}
public static void getAllSubelements(List<Element> list, Element e, boolean recursive) // nonrecursive
{
NodeList children = e.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.ELEMENT_NODE)
{
Element child = (Element) c;
list.add(child);
if (recursive)
getAllSubelements(list, child, true);
}
}
}
// vindt wel<SUF>
public static void findAllElementsByName(List<Element> list, Element e, String elementName) // recursive
{
if (e.getNodeName().equalsIgnoreCase(elementName))
{
list.add(e);
}
NodeList children = e.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.ELEMENT_NODE)
{
Element child = (Element) c;
findAllElementsByName(list, child, elementName);
}
}
}
public static List<Element> getElementsByTagname(Element e, String elementName, boolean recursive)
{
List<Element> list = new ArrayList<>();
if (e != null)
findElementsByName(list, e, elementName, recursive);
return list;
}
public static List<Element> getElementsByTagname(Element e, Set<String> elementNames, boolean recursive)
{
List<Element> list = new ArrayList<>();
if (e != null)
findElementsByName(list, e, elementNames, recursive);
return list;
}
public static List<Element> getElementsByTagname(Element e, String[] elementNames, boolean recursive)
{
Set<String> s = new HashSet<>();
for (String x: elementNames) s.add(x);
List<Element> list = new ArrayList<>();
if (e != null)
findElementsByName(list, e, s, recursive);
return list;
}
public static List<Element> getAllSubelements(Element e, boolean recursive)
{
List<Element> list = new ArrayList<>();
if (e != null)
getAllSubelements(list, e, recursive);
return list;
}
public static List<Element> getElementsByTagnameAndAttribute(Element e, String elementName, String attName, String attValue, boolean recursive)
{
List<Element> list = new ArrayList<>();
findElementsByNameAndAttribute(list, e, elementName, attName, attValue, recursive);
return list;
}
public static Element getElementByTagname(Element e, String elementName)
{
List<Element> list = getElementsByTagname(e, elementName, false);
return !list.isEmpty() ? list.get(0) : null;
}
public static String getElementContent(Element e, String tagname)
{
Element x = getElementByTagname(e,tagname);
return x != null ? x.getTextContent() : null;
}
public static Element findFirstChild(Element e, String tagName)
{
NodeList l = e.getChildNodes();
for (int i=0; i < l.getLength(); i++)
{
try
{
Element c = (Element) l.item(i);
if (c.getNodeName().equals(tagName)) return c;
} catch (Exception ex)
{
ex.printStackTrace();
}
}
return null;
}
public static Element findFirstChild(Element e, String[] tagNames)
{
NodeList l = e.getChildNodes();
for (int i=0; i < l.getLength(); i++)
{
try
{
Element c = (Element) l.item(i);
for (String tagName: tagNames)
if (c.getNodeName().equals(tagName)) return c;
} catch (Exception ex)
{
ex.printStackTrace();
}
}
return null;
}
public static List<Element> findChildren(Element e, String[] tagNames)
{
NodeList l = e.getChildNodes();
ArrayList<Element> r = new ArrayList<>();
for (int i=0; i < l.getLength(); i++)
{
try
{
Element c = (Element) l.item(i);
for (String tagName: tagNames)
if (c.getNodeName().equals(tagName)) r.add(c);
} catch (Exception ex)
{
ex.printStackTrace();
}
}
return r;
}
public static void insertChildAfter(Node n, Node after, Node newChild)
{
Node afterAfter = null;
if ((afterAfter = after.getNextSibling()) == null)
{
n.appendChild(newChild);
} else
{
try
{
if (afterAfter.getParentNode() != n)
{
System.err.println("neee - dat MEEEN je niet");
}
n.insertBefore(newChild, afterAfter);
} catch (Exception e)
{
System.err.println(n + "" +
afterAfter + "" +
afterAfter.getParentNode() + "" + newChild);
e.printStackTrace();
System.exit(1);
}
}
}
public static boolean isWhiteSpaceNode(Node n)
{
String v = n.getNodeValue();
return v.matches("^\\s*$");
}
public static boolean isWhiteSpaceOrPunctuationNode(Node n)
{
String v = n.getNodeValue();
return v.matches("^(\\s|;|\\.)*$");
}
public static void collectNodesBetween(List<Node> nodes, Node currentNode, Node after, Node before)
{
boolean b1 = after.compareDocumentPosition(currentNode) == Node.DOCUMENT_POSITION_FOLLOWING;
boolean b2 = before.compareDocumentPosition(currentNode) == Node.DOCUMENT_POSITION_PRECEDING;
if (b1 && b2)
nodes.add(currentNode);
NodeList children = currentNode.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
Node next = c.getNextSibling();
Node previous = c.getPreviousSibling();
boolean x1 =
next != null &&
after.compareDocumentPosition(next) == Node.DOCUMENT_POSITION_PRECEDING;
boolean x2 = previous != null &&
before.compareDocumentPosition(previous) == Node.DOCUMENT_POSITION_FOLLOWING;
if (!x1 && !x2)
collectNodesBetween(nodes,c,after,before);
}
// klaus 4 oct .... 3 wednesday // 5 mother birthday
}
public static List<Node> collectNodesBetween(Node after, Node before)
{
List<Node> list = new ArrayList<>();
Node p = findCommonAncestor(after,before);
collectNodesBetween(list,p,after,before);
return list;
}
public static List<Element> collectNodesBetween(Set<String> elementNames, Node after, Node before)
{
List<Node> list = collectNodesBetween(after,before);
List<Element> trimmed = new ArrayList<>();
for (Node n: list)
{
if (n.getNodeType() == Node.ELEMENT_NODE)
{
if (elementNames.contains(n.getNodeName()) ||
elementNames.contains(n.getLocalName()))
{
trimmed.add((Element) n);
}
}
}
return trimmed;
}
public static Document parse(String aFilename, boolean namespaceAware) throws
ParserConfigurationException, SAXException, IOException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion", false );
DocumentBuilder builder = factory.newDocumentBuilder();
//There is a bug related to 4 byte UTF8 ... which has to be worked around
// https://issues.apache.org/jira/browse/XERCESJ-1257
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(new File(aFilename)));
InputStreamReader isr = new java.io.InputStreamReader(fis, "UTF-8");
InputSource is = new InputSource(isr);
return builder.parse(is);
}
public static Document parse(String aFilename) throws ParserConfigurationException, SAXException, IOException
{
return parse(aFilename,true);
}
public static Document parseString(String inputString, boolean namespaceAware)
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
try
{
factory.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion", false );
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(new StringReader(inputString)));
} catch (Exception e)
{
e.printStackTrace();
return null;
}
}
/**
*
* @param is
* @param cs (optional) encoding of the stream, attempts to autodetect if missing.
* @param namespaceAware
* @return
*/
public static Document parseStream(InputStream is, Charset cs, boolean namespaceAware)
{
if (cs == null) {
BOMInputStream bis = (is instanceof BOMInputStream) ? ((BOMInputStream)is) : new BOMInputStream(is);
is = bis;
String csName;
try {csName = bis.getBOMCharsetName();} catch (IOException e) {throw new RuntimeException(e);}
cs = csName != null ? Charset.forName(csName) : StandardCharsets.UTF_8;
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
try
{
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion", false );
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(new InputStreamReader(is, cs)));
} catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public static Document parseString(String inputString)
{
return parseString(inputString, true);
}
public static Document createDocument(String rootElementName)
{
try
{
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement(rootElementName);
doc.appendChild(root);
return doc;
} catch (Exception e)
{
return null;
}
}
public static String documentToString(Document d)
{
try
{
// Set up the output transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "no");
// Print the DOM node
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(d.getDocumentElement());
trans.transform(source, result);
String xmlString = sw.toString();
xmlString = xmlString.replaceAll(" xmlns=\"\"", ""); // ugly hack, should be avoidable...
return xmlString;
}
catch (TransformerException e)
{
e.printStackTrace();
}
return null;
}
public void printNode(Node node, Writer writer)
{
try
{
// Set up the output transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.METHOD, "xml");
// Print the DOM node
trans.transform(new DOMSource(node), new StreamResult(writer));
}
catch (TransformerException e)
{
e.printStackTrace();
}
}
public static String nodeToString(Node node)
{
try
{
// Set up the output transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.METHOD, "xml");
// Print the DOM node
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(node);
trans.transform(source, result);
String xmlString = sw.toString();
return xmlString;
}
catch (TransformerException e)
{
e.printStackTrace();
return null;
}
}
public static Document cloneDocument(Document d)
{
try
{
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer tx = tfactory.newTransformer();
DOMSource source = new DOMSource(d);
DOMResult result = new DOMResult();
tx.transform(source,result);
return (Document) result.getNode();
} catch (Exception e)
{
e.printStackTrace();
return null;
}
}
private static void getTextNodesBelow(List<Node> nodes, Node n)
{
NodeList children = n.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.TEXT_NODE)
{
nodes.add(c);
} else if (c.getNodeType() == Node.ELEMENT_NODE)
{
getTextNodesBelow(nodes,c);
}
}
}
public static List<Node> getTextNodesBelow(Node n)
{
List<Node> l = new ArrayList<>();
getTextNodesBelow(l,n);
return l;
}
public static Element findAncestor(Node t, String string)
{
Node p;
for (p=t; p != null; p =p.getParentNode())
{
if (p.getNodeType() ==Node.ELEMENT_NODE && p.getNodeName().equals(string))
return (Element) p;
}
return null;
}
public static Set<Node> getAncestors(Node n)
{
Node p = n.getParentNode();
Set<Node> ancestors = new HashSet<>();
while (p != null)
{
ancestors.add(p );
p = p.getParentNode();
}
return ancestors;
}
public static Node findCommonAncestor(Node n1, Node n2)
{
Set<Node> a1 = getAncestors(n1);
Node p = n2.getParentNode();
while (p!= null)
{
if (a1.contains(p)) return p;
p = p.getParentNode();
}
return null;
}
/**
* Replace the subtree under e with a single text node
* @param e
*/
public static void flattenElementContents(Element e)
{
Document d = e.getOwnerDocument();
Text t = d.createTextNode(e.getTextContent());
NodeList ch = e.getChildNodes();
for (int i=0; i < ch.getLength(); i++)
{
e.removeChild(ch.item(i));
}
e.appendChild(t);
}
public static void removeInterveningNode(Element e)
{
Node p = e.getParentNode();
NodeList n = e.getChildNodes();
List<Node> children = new ArrayList<>();
Node next = e.getNextSibling();
for (int i=0; i < n.getLength(); i++)
{
children.add(n.item(i));
}
for (Node c: children) e.removeChild(c);
p.removeChild(e);
for (Node c: children)
{
if (next != null)
p.insertBefore(c, next);
else
p.appendChild(c);
}
}
public static void findTextNodesBelow(List<Node> list, Element e) // nonrecursive
{
NodeList children = e.getChildNodes();
for (int k = 0; k < children.getLength(); k++)
{
Node c = children.item(k);
if (c.getNodeType() == Node.ELEMENT_NODE)
{
Element child = (Element) c;
{
findTextNodesBelow(list, child);
}
} else if (c.getNodeType() == Node.TEXT_NODE)
{
list.add(c);
}
}
}
public static String escapeForAttribute(String v)
{
v = v.replaceAll("&", "&");
v = v.replaceAll("<", "<");
v = v.replaceAll(">", ">");
v = v.replaceAll("'", "'");
v = v.replaceAll("\"", """);
return v;
}
public static String escapeCharacterData(String v)
{
v = v.replaceAll("&", "&");
v = v.replaceAll("<", "<");
v = v.replaceAll(">", ">");
return v;
}
public static String xmlSingleQuotedEscape(String s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
switch (c)
{
case '\'': sb.append("""); break;
case '&': sb.append("&"); break;
case '<': sb.append("<"); break;
case '\n': sb.append("
"); break;
case '\000': case '\001': case '\002': case '\003': case '\004':
case '\005': case '\006': case '\007': case '\010': case '\013':
case '\014': case '\016': case '\017': case '\020': case '\021':
case '\022': case '\023': case '\024': case '\025': case '\026':
case '\027': case '\030': case '\031': case '\032': case '\033':
case '\034': case '\035': case '\036': case '\037':
// do nothing, these are disallowed characters
break;
default: sb.append(c);
}
}
return sb.toString();
}
}
|
57467_3 | package word2vec.relations;
import java.util.ArrayList;
import java.util.List;
import la.decomposition.QRDecomposition;
import la.decomposition.SingularValueDecomposition;
import la.matrix.DenseMatrix;
import la.matrix.Matrix;
import la.vector.DenseVector;
import ml.options.Options;
import ml.regression.LASSO;
import ml.regression.Regression;
import ml.utils.Printer;
import word2vec.Distance;
import word2vec.Distance.ScoredTerm;
import word2vec.Util;
import word2vec.Vectors;
/**
*
* Test of met lineare relatie tussen twee ruimtes goede woordparen kunnen vinden.
* Wellicht beter te maken door per woord / groepje woorden
* andere lineaire afbeelding te kiezen, meer bepaald door de woorden waarmee het te mappen woord een relatie heeft
*
* <pre>
*
* LASSO is a Java implementation of LASSO, which solves the following convex optimization problem:
min_W 2\1 || Y - X * W ||_F^2 + lambda * || W ||_1
where X is an n-by-p data matrix with each row bing a p dimensional data vector and Y is an n-by-ny dependent variable matrix.
</pre>
* @author does
*
*/
public class VectorRegression
{
double p = 0.01; // is dit slim?
int max = 8000;
boolean useP = false;
boolean useMax = true;
int N_TERMS=10;
private static Regression getLasso()
{
Options options = new Options();
options.maxIter = 30;
options.lambda = 0.01; // regularization
options.verbose = !true;
options.epsilon = 1e-5;
Regression lasso = new LASSO(options);
return lasso;
}
@SuppressWarnings("unused")
private static void test()
{
double[][] data =
{
{1, 2, 3, 2},
{4, 2, 3, 6},
{5, 1, 2, 1}
};
double[][] depVars = {{3, 2}, {2, 3}, {1, 4}};
Options options = new Options();
options.maxIter = 600;
options.lambda = 0.05;
options.verbose = !true;
options.epsilon = 1e-5;
Regression LASSO = new LASSO(options);
LASSO.feedData(data);
LASSO.feedDependentVariables(depVars);
LASSO.train();
System.out.printf("Projection matrix:\n");
Printer.display(LASSO.W);
Matrix Yt =
LASSO.predict(data);
//
System.out.printf("Predicted dependent variables:\n");
Printer.display(Yt);
}
public static float[] doubleToFloat(double[] x)
{
float[] f = new float[x.length];
for (int i=0; i < x.length; i++)
f[i] = (float) x[i];
return f;
}
public static double[] floatToDouble(float[] x)
{
double[] f = new double[x.length];
for (int i=0; i < x.length; i++)
f[i] = x[i];
return f;
}
public static double[][] floatToDouble(float[][] x)
{
double[][] f = new double[x.length][];
for (int i=0; i < x.length; i++)
f[i] = floatToDouble(x[i]);
return f;
}
public static double[][] floatToDouble(List<float[]> x)
{
int d = x.get(0).length;
double[][] f = new double[d][];
for (int i=0; i < d; i++)
{
f[i] = new double[x.size()];
for (int j=0; j < x.size(); j++)
{
f[i][j] = x.get(j)[i];
}
}
return f;
}
public static String[] getCommonVocabulary(Vectors v1, Vectors v2)
{
List<String> common = new ArrayList<>();
for (int i=0; i < v1.wordCount(); i++)
{
String w = v1.getTerm(i);
if (v2.hasTerm(w))
{
common.add(w);
}
}
String[] x = (String[]) common.toArray();
return x;
}
public void testMapping(Vectors v1, Vectors v2)
{
Matrix W = getLinearMappingBetweenSpaces(v1,v2);
//String[] common = getCommonVocabulary(v1,v2);
Matrix Wt = W.transpose();
for (int i=0; i < v1.wordCount(); i++)
{
String w = v1.getTerm(i);
if (v2.hasTerm(w))
{
try
{
float[] vec1 = v1.getVector(i);
float[] vec2 = v2.getVector(w);
double[][] d1 = new double[1][];
d1[0] = floatToDouble(vec1);
DenseVector v = new DenseVector( floatToDouble(vec1));
DenseVector img = (DenseVector) Wt.operate(v);
float[] y1 = doubleToFloat(img.getPr());
Util.normalize(y1);
// now measure distance between y1 and vec2. waarom zit dat verdarrie niet in de interface??
double d = Distance.cosineSimilarity(y1,vec2);
System.out.print(w + " selfdist:" + d + " ");
List<ScoredTerm> close = Distance.getClosestTerms(v2, N_TERMS, y1);
int k=0;
int matchAt = -1;
//boolean selfMatch = false;
String neighbours = "";
for (ScoredTerm st: close)
{
if (st.getTerm().equals(w))
{
matchAt = k;
}
neighbours += st.getTerm() + "/" + st.getScore() + " ";
k++;
}
System.out.println( " selfMatch: " + matchAt + " " + neighbours);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
}
public Matrix getLinearMappingBetweenSpaces(Vectors v1, Vectors v2)
{
//long s = System.currentTimeMillis();
List<String> words = new ArrayList<>();
List<float[]> vectors1 = new ArrayList<>();
List<float[]> vectors2 = new ArrayList<>();
int k=0;
for (int i=0 ; i < v1.wordCount(); i++)
{
if ((!useP || Math.random() < p) && (!useMax || k < max))
{
String w = v1.getTerm(i);
float[] vec1 = v1.getVector(i);
if (v2.hasTerm(w)) try
{
// nl.openconvert.log.ConverterLog.defaultLog.println("selected " + w);
float[] vec2 = v2.getVector(w);
if (vec2 != null)
{
words.add(v1.getTerm(i));
vectors1.add(vec1);
vectors2.add(vec2);
k++;
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
Matrix r = fitLinearMapping(vectors1, vectors2);
// long f = System.currentTimeMillis();
// nl.openconvert.log.ConverterLog.defaultLog.println("Computed linear mapping in " +(f-s) + " milliseconds ");
return r;
}
public static float[] apply(Matrix mT, float[] x)
{
double[] V1 = VectorRegression.floatToDouble(x);
DenseVector img = (DenseVector) mT.operate(new DenseVector(V1));
float[] y1 = VectorRegression.doubleToFloat(img.getPr());
word2vec.Util.normalize(y1);
return y1;
}
public static Matrix Identity(int dim)
{
double[][] x = new double[dim][dim];
for (int i=0; i < dim; i++)
for (int j=0; j < dim; j++)
x[i][j] = (i==j)?1:0;
return new DenseMatrix(x);
}
/**
* ? arg min<sub>R</sub> || RA - B || <br>
* Oplossing: <br>
* X = A * B<sup>T</sup> <br>
* X = UΣV <br>
* R = U * V<sup>T</sup>
* <br>
* https://en.wikipedia.org/wiki/Orthogonal_Procrustes_problem
*/
public static Matrix Procrustes(Matrix A, Matrix B)
{
Matrix X = B.mtimes(A.transpose());
Matrix[] USV = SingularValueDecomposition.decompose(X);
Matrix U = USV[0];
//Matrix S = USV[1];
Matrix V = USV[2];
return U.mtimes(V.transpose());
}
public static Matrix Procrustes(List<float[]> x, List<float[]> y)
{
Matrix A = new DenseMatrix(floatToDouble(x));
Matrix B = new DenseMatrix(floatToDouble(y));
return Procrustes(A,B);
}
public static Matrix fitLinearMapping(List<float[]> x, List<float[]> y, int reduceTo)
{
int dim = x.get(0).length;
Matrix m = fitLinearMapping(x,y);
Matrix A = new DenseMatrix(floatToDouble(x));
Matrix[] QR = QRDecomposition.decompose(A);
Matrix Q = QR[0];
// System.err.println(Q.getColumnDimension() + " x " + Q.getRowDimension());
Matrix P = Q.mtimes(Q.transpose());
Matrix Q2 = Identity(dim).minus(P); // waarom werkte de oude foute keuze beter???
//Matrix Q1 = Q.getColumns(0,x.size()-1);
Matrix I_A = Identity(dim).getColumns(0, x.size()-1);
//Matrix Q1T = Q1.transpose();
Matrix MP = m.mtimes(P);
boolean reduce = false;
if (reduce)
{
Matrix[] USV = SingularValueDecomposition.decompose(MP.minus(I_A), true);
@SuppressWarnings("unused")
Matrix U = USV[0];
Matrix S = USV[1];
@SuppressWarnings("unused")
Matrix V = USV[2];
//Printer.print(V);
//Printer.printMatrix(SVU[1]);
for (int i = reduceTo; i < S.getColumnDimension(); i++)
{
S.setEntry(i, i, 0);
}
// Matrix r1 = U.mtimes(S.mtimes(V.transpose())).plus(I_A);
// // Matrix r = r1.mtimes(Q1T);
}
return MP.plus(Q2); // waarom maakt dit niks uit
//return m;
}
/**
* !Use Procrustes instead of this.... (cf. Hamilton Leskovec Jurafsky 2016)
* Probably better results ....
* @param x
* @param y
* @return
*/
public static Matrix fitLinearMapping(List<float[]> x, List<float[]> y)
{
double[][] X = new double[x.size()][];
double[][] Y = new double[x.size()][];
//nl.openconvert.log.ConverterLog.defaultLog.println("Selected + " + x.size());
for (int i=0; i < x.size(); i++)
{
float[] vec1 = x.get(i);
float[] vec2 = y.get(i);
int nx = vec1.length;
int ny = vec2.length;
X[i] = new double[nx];
Y[i] = new double[ny];
for (int j=0; j < nx; j++)
{
X[i][j]= vec1[j];
}
for (int j=0; j < ny; j++)
{
Y[i][j]= vec2[j];
}
}
Regression lasso = getLasso();
lasso.feedData(X);
lasso.feedDependentVariables(Y);
lasso.train();
//Printer.display(lasso.W);a
Matrix r = lasso.W;
return r;
}
public static void main(String[] args)
{
//test();
VectorRegression l = new VectorRegression();
Vectors v1 = Vectors.readFromFile(args[0]);
Vectors v2 = Vectors.readFromFile(args[1]);
l.testMapping(v1, v2);
}
}
| INL/WordVectors | src/main/java/word2vec/relations/VectorRegression.java | 3,610 | // now measure distance between y1 and vec2. waarom zit dat verdarrie niet in de interface?? | line_comment | nl | package word2vec.relations;
import java.util.ArrayList;
import java.util.List;
import la.decomposition.QRDecomposition;
import la.decomposition.SingularValueDecomposition;
import la.matrix.DenseMatrix;
import la.matrix.Matrix;
import la.vector.DenseVector;
import ml.options.Options;
import ml.regression.LASSO;
import ml.regression.Regression;
import ml.utils.Printer;
import word2vec.Distance;
import word2vec.Distance.ScoredTerm;
import word2vec.Util;
import word2vec.Vectors;
/**
*
* Test of met lineare relatie tussen twee ruimtes goede woordparen kunnen vinden.
* Wellicht beter te maken door per woord / groepje woorden
* andere lineaire afbeelding te kiezen, meer bepaald door de woorden waarmee het te mappen woord een relatie heeft
*
* <pre>
*
* LASSO is a Java implementation of LASSO, which solves the following convex optimization problem:
min_W 2\1 || Y - X * W ||_F^2 + lambda * || W ||_1
where X is an n-by-p data matrix with each row bing a p dimensional data vector and Y is an n-by-ny dependent variable matrix.
</pre>
* @author does
*
*/
public class VectorRegression
{
double p = 0.01; // is dit slim?
int max = 8000;
boolean useP = false;
boolean useMax = true;
int N_TERMS=10;
private static Regression getLasso()
{
Options options = new Options();
options.maxIter = 30;
options.lambda = 0.01; // regularization
options.verbose = !true;
options.epsilon = 1e-5;
Regression lasso = new LASSO(options);
return lasso;
}
@SuppressWarnings("unused")
private static void test()
{
double[][] data =
{
{1, 2, 3, 2},
{4, 2, 3, 6},
{5, 1, 2, 1}
};
double[][] depVars = {{3, 2}, {2, 3}, {1, 4}};
Options options = new Options();
options.maxIter = 600;
options.lambda = 0.05;
options.verbose = !true;
options.epsilon = 1e-5;
Regression LASSO = new LASSO(options);
LASSO.feedData(data);
LASSO.feedDependentVariables(depVars);
LASSO.train();
System.out.printf("Projection matrix:\n");
Printer.display(LASSO.W);
Matrix Yt =
LASSO.predict(data);
//
System.out.printf("Predicted dependent variables:\n");
Printer.display(Yt);
}
public static float[] doubleToFloat(double[] x)
{
float[] f = new float[x.length];
for (int i=0; i < x.length; i++)
f[i] = (float) x[i];
return f;
}
public static double[] floatToDouble(float[] x)
{
double[] f = new double[x.length];
for (int i=0; i < x.length; i++)
f[i] = x[i];
return f;
}
public static double[][] floatToDouble(float[][] x)
{
double[][] f = new double[x.length][];
for (int i=0; i < x.length; i++)
f[i] = floatToDouble(x[i]);
return f;
}
public static double[][] floatToDouble(List<float[]> x)
{
int d = x.get(0).length;
double[][] f = new double[d][];
for (int i=0; i < d; i++)
{
f[i] = new double[x.size()];
for (int j=0; j < x.size(); j++)
{
f[i][j] = x.get(j)[i];
}
}
return f;
}
public static String[] getCommonVocabulary(Vectors v1, Vectors v2)
{
List<String> common = new ArrayList<>();
for (int i=0; i < v1.wordCount(); i++)
{
String w = v1.getTerm(i);
if (v2.hasTerm(w))
{
common.add(w);
}
}
String[] x = (String[]) common.toArray();
return x;
}
public void testMapping(Vectors v1, Vectors v2)
{
Matrix W = getLinearMappingBetweenSpaces(v1,v2);
//String[] common = getCommonVocabulary(v1,v2);
Matrix Wt = W.transpose();
for (int i=0; i < v1.wordCount(); i++)
{
String w = v1.getTerm(i);
if (v2.hasTerm(w))
{
try
{
float[] vec1 = v1.getVector(i);
float[] vec2 = v2.getVector(w);
double[][] d1 = new double[1][];
d1[0] = floatToDouble(vec1);
DenseVector v = new DenseVector( floatToDouble(vec1));
DenseVector img = (DenseVector) Wt.operate(v);
float[] y1 = doubleToFloat(img.getPr());
Util.normalize(y1);
// now measure<SUF>
double d = Distance.cosineSimilarity(y1,vec2);
System.out.print(w + " selfdist:" + d + " ");
List<ScoredTerm> close = Distance.getClosestTerms(v2, N_TERMS, y1);
int k=0;
int matchAt = -1;
//boolean selfMatch = false;
String neighbours = "";
for (ScoredTerm st: close)
{
if (st.getTerm().equals(w))
{
matchAt = k;
}
neighbours += st.getTerm() + "/" + st.getScore() + " ";
k++;
}
System.out.println( " selfMatch: " + matchAt + " " + neighbours);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
}
public Matrix getLinearMappingBetweenSpaces(Vectors v1, Vectors v2)
{
//long s = System.currentTimeMillis();
List<String> words = new ArrayList<>();
List<float[]> vectors1 = new ArrayList<>();
List<float[]> vectors2 = new ArrayList<>();
int k=0;
for (int i=0 ; i < v1.wordCount(); i++)
{
if ((!useP || Math.random() < p) && (!useMax || k < max))
{
String w = v1.getTerm(i);
float[] vec1 = v1.getVector(i);
if (v2.hasTerm(w)) try
{
// nl.openconvert.log.ConverterLog.defaultLog.println("selected " + w);
float[] vec2 = v2.getVector(w);
if (vec2 != null)
{
words.add(v1.getTerm(i));
vectors1.add(vec1);
vectors2.add(vec2);
k++;
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
Matrix r = fitLinearMapping(vectors1, vectors2);
// long f = System.currentTimeMillis();
// nl.openconvert.log.ConverterLog.defaultLog.println("Computed linear mapping in " +(f-s) + " milliseconds ");
return r;
}
public static float[] apply(Matrix mT, float[] x)
{
double[] V1 = VectorRegression.floatToDouble(x);
DenseVector img = (DenseVector) mT.operate(new DenseVector(V1));
float[] y1 = VectorRegression.doubleToFloat(img.getPr());
word2vec.Util.normalize(y1);
return y1;
}
public static Matrix Identity(int dim)
{
double[][] x = new double[dim][dim];
for (int i=0; i < dim; i++)
for (int j=0; j < dim; j++)
x[i][j] = (i==j)?1:0;
return new DenseMatrix(x);
}
/**
* ? arg min<sub>R</sub> || RA - B || <br>
* Oplossing: <br>
* X = A * B<sup>T</sup> <br>
* X = UΣV <br>
* R = U * V<sup>T</sup>
* <br>
* https://en.wikipedia.org/wiki/Orthogonal_Procrustes_problem
*/
public static Matrix Procrustes(Matrix A, Matrix B)
{
Matrix X = B.mtimes(A.transpose());
Matrix[] USV = SingularValueDecomposition.decompose(X);
Matrix U = USV[0];
//Matrix S = USV[1];
Matrix V = USV[2];
return U.mtimes(V.transpose());
}
public static Matrix Procrustes(List<float[]> x, List<float[]> y)
{
Matrix A = new DenseMatrix(floatToDouble(x));
Matrix B = new DenseMatrix(floatToDouble(y));
return Procrustes(A,B);
}
public static Matrix fitLinearMapping(List<float[]> x, List<float[]> y, int reduceTo)
{
int dim = x.get(0).length;
Matrix m = fitLinearMapping(x,y);
Matrix A = new DenseMatrix(floatToDouble(x));
Matrix[] QR = QRDecomposition.decompose(A);
Matrix Q = QR[0];
// System.err.println(Q.getColumnDimension() + " x " + Q.getRowDimension());
Matrix P = Q.mtimes(Q.transpose());
Matrix Q2 = Identity(dim).minus(P); // waarom werkte de oude foute keuze beter???
//Matrix Q1 = Q.getColumns(0,x.size()-1);
Matrix I_A = Identity(dim).getColumns(0, x.size()-1);
//Matrix Q1T = Q1.transpose();
Matrix MP = m.mtimes(P);
boolean reduce = false;
if (reduce)
{
Matrix[] USV = SingularValueDecomposition.decompose(MP.minus(I_A), true);
@SuppressWarnings("unused")
Matrix U = USV[0];
Matrix S = USV[1];
@SuppressWarnings("unused")
Matrix V = USV[2];
//Printer.print(V);
//Printer.printMatrix(SVU[1]);
for (int i = reduceTo; i < S.getColumnDimension(); i++)
{
S.setEntry(i, i, 0);
}
// Matrix r1 = U.mtimes(S.mtimes(V.transpose())).plus(I_A);
// // Matrix r = r1.mtimes(Q1T);
}
return MP.plus(Q2); // waarom maakt dit niks uit
//return m;
}
/**
* !Use Procrustes instead of this.... (cf. Hamilton Leskovec Jurafsky 2016)
* Probably better results ....
* @param x
* @param y
* @return
*/
public static Matrix fitLinearMapping(List<float[]> x, List<float[]> y)
{
double[][] X = new double[x.size()][];
double[][] Y = new double[x.size()][];
//nl.openconvert.log.ConverterLog.defaultLog.println("Selected + " + x.size());
for (int i=0; i < x.size(); i++)
{
float[] vec1 = x.get(i);
float[] vec2 = y.get(i);
int nx = vec1.length;
int ny = vec2.length;
X[i] = new double[nx];
Y[i] = new double[ny];
for (int j=0; j < nx; j++)
{
X[i][j]= vec1[j];
}
for (int j=0; j < ny; j++)
{
Y[i][j]= vec2[j];
}
}
Regression lasso = getLasso();
lasso.feedData(X);
lasso.feedDependentVariables(Y);
lasso.train();
//Printer.display(lasso.W);a
Matrix r = lasso.W;
return r;
}
public static void main(String[] args)
{
//test();
VectorRegression l = new VectorRegression();
Vectors v1 = Vectors.readFromFile(args[0]);
Vectors v2 = Vectors.readFromFile(args[1]);
l.testMapping(v1, v2);
}
}
|
6351_25 | package org.ivdnt.fcs.results;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* This class is used to store FCS keywords in context (kwic) as part of the
* ResultSet (which is part of a FcsSearchResultSet = main result object)
*
* @author jesse
*
*/
public class Kwic {
// A Kwic (keyword in context) is a list of words in which a match was found
// so it consists of [a left context], [a match], and [a right context]
//
// The tokens of those 3 parts are stored together in lists, each of which
// represents one property.
// So, for a given token at position X, we can retrieve the value of a given
// property
// by accessing the corresponding list at the same position X
//
// (t.i. we have one sorted list for each single property, so there are as many
// lists
// as properties)
//
// To be able to recognize each part, the Kwic object has
// hitStart and hitEnd, which indicate the borders of the [match part]
// = start and end position of a keyword, within its context
private int hitStart;
private int hitEnd;
// default property
private String defaultProperty = "word";
// the list contains the names of all the properties contained in our Kwic
// object
private List<String> tokenPropertyNames = new ArrayList<>();
// this maps a property name to a sorted list of token properties
// (sorted, as the list represents the tokens on the result string)
private Map<String, List<String>> tokenProperties = new ConcurrentHashMap<>();
// metadata
private Map<String, String> metadata = new ConcurrentHashMap<>(); // considering the size of opensonar metadata,
// probably better to introduce separate
// document objects
// private Document document = null;
// -----------------------------------------------------------------------------------
// add a new property name to all tokens
public void addTokenProperty(String propertyName) {
// register the property name
// and
// add the property to all tokens
if (!this.tokenPropertyNames.contains(propertyName)) {
this.addTokenPropertyName(propertyName);
List<String> propertyValues = new ArrayList<>(this.size());
for (int i = 0; i < this.size(); i++) {
propertyValues.add(null);
}
this.setTokenProperties(propertyName, propertyValues);
}
}
// -----------------------------------------------------------------------------------
// getters
public void addTokenPropertyName(String pname) {
this.tokenPropertyNames.add(pname);
}
public void addTokenPropertyNames(Set<String> pnames) {
this.tokenPropertyNames.addAll(pnames);
}
public String get(String pname, int i) {
return getLayer(pname).get(i);
}
public String getDefaultProperty() {
return this.defaultProperty;
}
public int getHitEnd() {
return this.hitEnd;
}
public int getHitStart() {
return this.hitStart;
}
public List<String> getLayer(String propertyName) {
return this.tokenProperties.get(propertyName);
}
public URI getLayerURL(String pname) {
try {
return new URI("http://www.ivdnt.org/annotation-layers/" + pname);
} catch (Exception e) {
throw new NullPointerException("Unable to get layer URL for " + pname + ". " + e);
}
}
public Map<String, String> getMetadata() {
return this.metadata;
}
// synonym of getLayer
public List<String> getPropertyValues(String propertyName) {
return getLayer(propertyName);
}
public List<String> getTokenPropertyNames() {
return this.tokenPropertyNames;
}
public String getWord(int i) {
return this.tokenProperties.get(defaultProperty).get(i);
}
// -----------------------------------------------------------------------------------
// setters
public void setHitEnd(int hitEnd) {
this.hitEnd = hitEnd;
}
public void setHitStart(int hitStart) {
this.hitStart = hitStart;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
// set one property for all tokens at once
// eg. the pos-tag of all tokens of a sentence
public void setTokenProperties(String pname, List<String> properties) {
this.tokenProperties.put(pname, properties);
}
// modify the value of a property for token at position X
public void setTokenPropertyAt(String propertyName, String property, int index) {
List<String> propertyValues = this.getLayer(propertyName);
if (propertyValues.size() == 0)
propertyValues = new ArrayList<>(this.getTokenPropertyNames().size());
propertyValues.set(index, property);
this.setTokenProperties(propertyName, propertyValues);
}
public int size() {
return words().size();
}
public String toString() {
List<String> tokens = new ArrayList<String>();
List<String> words = words();
for (int i = 0; i < words.size(); i++) {
String p = (this.hitStart <= i && i <= this.hitEnd) ? ">>" : "";
tokens.add(p + words.get(i));
}
String s = String.format("Kwic(%d,%d):", this.hitStart, this.hitEnd);
return s + tokens.toString();
}
public Kwic translatePrefixes(Map<String, String> map) {
map.forEach((k, v) -> {
this.tokenProperties.put(v, this.tokenProperties.get(k));
this.tokenProperties.remove(k);
});
this.tokenPropertyNames = this.tokenPropertyNames.stream().map(p -> map.containsKey(p) ? map.get(p) : p)
.collect(Collectors.toList());
return this;
}
// -----------------------------------------------------------------------------------
public List<String> words() {
return this.tokenProperties.get(defaultProperty);
}
// -----------------------------------------------------------------------------------
}
/**
* Wat gaan we met metadata doen? In een CMDI profiel stoppen? Hoe halen we dat
* op bij nederlab? Voor blacklab server zelf maken uit de aanwezige metadata.
* https://www.clarin.eu/sites/default/files/CE-2014-0317-CLARIN_FCS_Specification_DataViews_1_0.pdf:
*
* <!-- potential @pid and @ref attributes omitted -->
* <fcs:DataView type="application/x-cmdi+xml">
* <cmdi:CMD xmlns:cmdi="http://www.clarin.eu/cmd/" CMDVersion="1.1"> <!--
* content omitted --> </cmdi:CMD> </fcs:DataView> <!-- potential @pid attribute
* omitted --> <fcs:DataView type="application/x-cmdi+xml" ref=
* "http://repos.example.org/resources/4711/0815.cmdi" />
*/
| INL/clariah-fcs-endpoints | src/main/java/org/ivdnt/fcs/results/Kwic.java | 1,899 | /**
* Wat gaan we met metadata doen? In een CMDI profiel stoppen? Hoe halen we dat
* op bij nederlab? Voor blacklab server zelf maken uit de aanwezige metadata.
* https://www.clarin.eu/sites/default/files/CE-2014-0317-CLARIN_FCS_Specification_DataViews_1_0.pdf:
*
* <!-- potential @pid and @ref attributes omitted -->
* <fcs:DataView type="application/x-cmdi+xml">
* <cmdi:CMD xmlns:cmdi="http://www.clarin.eu/cmd/" CMDVersion="1.1"> <!--
* content omitted --> </cmdi:CMD> </fcs:DataView> <!-- potential @pid attribute
* omitted --> <fcs:DataView type="application/x-cmdi+xml" ref=
* "http://repos.example.org/resources/4711/0815.cmdi" />
*/ | block_comment | nl | package org.ivdnt.fcs.results;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* This class is used to store FCS keywords in context (kwic) as part of the
* ResultSet (which is part of a FcsSearchResultSet = main result object)
*
* @author jesse
*
*/
public class Kwic {
// A Kwic (keyword in context) is a list of words in which a match was found
// so it consists of [a left context], [a match], and [a right context]
//
// The tokens of those 3 parts are stored together in lists, each of which
// represents one property.
// So, for a given token at position X, we can retrieve the value of a given
// property
// by accessing the corresponding list at the same position X
//
// (t.i. we have one sorted list for each single property, so there are as many
// lists
// as properties)
//
// To be able to recognize each part, the Kwic object has
// hitStart and hitEnd, which indicate the borders of the [match part]
// = start and end position of a keyword, within its context
private int hitStart;
private int hitEnd;
// default property
private String defaultProperty = "word";
// the list contains the names of all the properties contained in our Kwic
// object
private List<String> tokenPropertyNames = new ArrayList<>();
// this maps a property name to a sorted list of token properties
// (sorted, as the list represents the tokens on the result string)
private Map<String, List<String>> tokenProperties = new ConcurrentHashMap<>();
// metadata
private Map<String, String> metadata = new ConcurrentHashMap<>(); // considering the size of opensonar metadata,
// probably better to introduce separate
// document objects
// private Document document = null;
// -----------------------------------------------------------------------------------
// add a new property name to all tokens
public void addTokenProperty(String propertyName) {
// register the property name
// and
// add the property to all tokens
if (!this.tokenPropertyNames.contains(propertyName)) {
this.addTokenPropertyName(propertyName);
List<String> propertyValues = new ArrayList<>(this.size());
for (int i = 0; i < this.size(); i++) {
propertyValues.add(null);
}
this.setTokenProperties(propertyName, propertyValues);
}
}
// -----------------------------------------------------------------------------------
// getters
public void addTokenPropertyName(String pname) {
this.tokenPropertyNames.add(pname);
}
public void addTokenPropertyNames(Set<String> pnames) {
this.tokenPropertyNames.addAll(pnames);
}
public String get(String pname, int i) {
return getLayer(pname).get(i);
}
public String getDefaultProperty() {
return this.defaultProperty;
}
public int getHitEnd() {
return this.hitEnd;
}
public int getHitStart() {
return this.hitStart;
}
public List<String> getLayer(String propertyName) {
return this.tokenProperties.get(propertyName);
}
public URI getLayerURL(String pname) {
try {
return new URI("http://www.ivdnt.org/annotation-layers/" + pname);
} catch (Exception e) {
throw new NullPointerException("Unable to get layer URL for " + pname + ". " + e);
}
}
public Map<String, String> getMetadata() {
return this.metadata;
}
// synonym of getLayer
public List<String> getPropertyValues(String propertyName) {
return getLayer(propertyName);
}
public List<String> getTokenPropertyNames() {
return this.tokenPropertyNames;
}
public String getWord(int i) {
return this.tokenProperties.get(defaultProperty).get(i);
}
// -----------------------------------------------------------------------------------
// setters
public void setHitEnd(int hitEnd) {
this.hitEnd = hitEnd;
}
public void setHitStart(int hitStart) {
this.hitStart = hitStart;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
// set one property for all tokens at once
// eg. the pos-tag of all tokens of a sentence
public void setTokenProperties(String pname, List<String> properties) {
this.tokenProperties.put(pname, properties);
}
// modify the value of a property for token at position X
public void setTokenPropertyAt(String propertyName, String property, int index) {
List<String> propertyValues = this.getLayer(propertyName);
if (propertyValues.size() == 0)
propertyValues = new ArrayList<>(this.getTokenPropertyNames().size());
propertyValues.set(index, property);
this.setTokenProperties(propertyName, propertyValues);
}
public int size() {
return words().size();
}
public String toString() {
List<String> tokens = new ArrayList<String>();
List<String> words = words();
for (int i = 0; i < words.size(); i++) {
String p = (this.hitStart <= i && i <= this.hitEnd) ? ">>" : "";
tokens.add(p + words.get(i));
}
String s = String.format("Kwic(%d,%d):", this.hitStart, this.hitEnd);
return s + tokens.toString();
}
public Kwic translatePrefixes(Map<String, String> map) {
map.forEach((k, v) -> {
this.tokenProperties.put(v, this.tokenProperties.get(k));
this.tokenProperties.remove(k);
});
this.tokenPropertyNames = this.tokenPropertyNames.stream().map(p -> map.containsKey(p) ? map.get(p) : p)
.collect(Collectors.toList());
return this;
}
// -----------------------------------------------------------------------------------
public List<String> words() {
return this.tokenProperties.get(defaultProperty);
}
// -----------------------------------------------------------------------------------
}
/**
* Wat gaan we<SUF>*/
|
78476_8 | /*
* Copyright (C) 2014 The Android Open Source 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 news.androidtv.tvapprepo.fragments;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v17.leanback.app.BackgroundManager;
import android.support.v17.leanback.app.DetailsFragment;
import android.support.v17.leanback.widget.Action;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.ClassPresenterSelector;
import android.support.v17.leanback.widget.DetailsOverviewRow;
import android.support.v17.leanback.widget.DetailsOverviewRowPresenter;
import android.support.v17.leanback.widget.ImageCardView;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.OnItemViewClickedListener;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.RowPresenter;
import android.support.v17.leanback.widget.SparseArrayObjectAdapter;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.firebase.database.DatabaseError;
import java.io.File;
import news.androidtv.tvapprepo.R;
import news.androidtv.tvapprepo.Utils;
import news.androidtv.tvapprepo.activities.DetailsActivity;
import news.androidtv.tvapprepo.activities.MainActivity;
import news.androidtv.tvapprepo.download.ApkDownloadHelper;
import news.androidtv.tvapprepo.model.Apk;
import news.androidtv.tvapprepo.model.LeanbackShortcut;
import news.androidtv.tvapprepo.model.RepoDatabase;
import news.androidtv.tvapprepo.presenters.DetailsDescriptionPresenter;
import news.androidtv.tvapprepo.utils.PackageInstallerUtils;
import tv.puppetmaster.tinydl.PackageInstaller;
/*
* LeanbackDetailsFragment extends DetailsFragment, a Wrapper fragment for leanback details screens.
* It shows a detailed view of video and its meta plus related videos.
*/
public class AppDetailsFragment extends DetailsFragment {
private static final String TAG = AppDetailsFragment.class.getSimpleName();
private static final int ACTION_INSTALL = 11;
private static final int ACTION_UPDATE = 12;
private static final int ACTION_UNINSTALL = 13;
private static final int DETAIL_THUMB_WIDTH = 274;
private static final int DETAIL_THUMB_HEIGHT = 274;
private Apk mSelectedApk;
private ArrayObjectAdapter mAdapter;
private ClassPresenterSelector mPresenterSelector;
private BackgroundManager mBackgroundManager;
private Drawable mDefaultBackground;
private DisplayMetrics mMetrics;
private ApkDownloadHelper mApkDownloadHelper;
private PackageInstaller.DownloadListener mDownloadListener = new PackageInstaller.DownloadListener() {
@Override
public void onApkDownloaded(File downloadedApkFile) {
Log.d(TAG, "Downloaded " + downloadedApkFile.getAbsolutePath());
mApkDownloadHelper.install(downloadedApkFile);
}
@Override
public void onApkDownloadedNougat(final File downloadedApkFile) {
Log.d(TAG, "Downloaded " + downloadedApkFile.getAbsolutePath());
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
mApkDownloadHelper.install(downloadedApkFile);
}
}, 1000 * 5);
}
@Override
public void onFileDeleted(File deletedApkFile, boolean wasSuccessful) {
}
@Override
public void onProgressStarted() {
// Show a video ad
Toast.makeText(getActivity(), R.string.download_started, Toast.LENGTH_SHORT).show();
}
@Override
public void onProgressEnded() {
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate DetailsFragment");
super.onCreate(savedInstanceState);
prepareBackgroundManager();
mSelectedApk = new Apk.Builder(getActivity().getIntent()
.getStringExtra(DetailsActivity.APPLICATION)).build();
if (mSelectedApk != null) {
setupAdapter();
setupDetailsOverviewRow();
setupDetailsOverviewRowPresenter();
setupMovieListRow();
setupMovieListRowPresenter();
updateBackground(mSelectedApk.getBanner());
setOnItemViewClickedListener(new ItemViewClickedListener());
mApkDownloadHelper = new ApkDownloadHelper(getActivity());
RepoDatabase.getInstance().incrementApkViews(mSelectedApk);
mApkDownloadHelper.addListener(mDownloadListener);
} else {
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
Toast.makeText(getActivity(), R.string.no_app_selected, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onStop() {
super.onStop();
Log.d(TAG, "App activity stopped");
mApkDownloadHelper.destroy();
mApkDownloadHelper.removeListener(mDownloadListener);
}
private void prepareBackgroundManager() {
mBackgroundManager = BackgroundManager.getInstance(getActivity());
mBackgroundManager.attach(getActivity().getWindow());
mDefaultBackground = getResources().getDrawable(R.drawable.default_background);
mMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
}
protected void updateBackground(String uri) {
Glide.with(getActivity())
.load(uri)
.centerCrop()
.error(mDefaultBackground)
.into(new SimpleTarget<GlideDrawable>(mMetrics.widthPixels, mMetrics.heightPixels) {
@Override
public void onResourceReady(GlideDrawable resource,
GlideAnimation<? super GlideDrawable> glideAnimation) {
mBackgroundManager.setDrawable(resource);
}
});
}
private void setupAdapter() {
mPresenterSelector = new ClassPresenterSelector();
mAdapter = new ArrayObjectAdapter(mPresenterSelector);
setAdapter(mAdapter);
}
private void setupDetailsOverviewRow() {
Log.d(TAG, "doInBackground: " + mSelectedApk.toString());
final DetailsOverviewRow row = new DetailsOverviewRow(mSelectedApk);
row.setImageDrawable(getResources().getDrawable(R.drawable.default_background));
int width = Utils.convertDpToPixel(getActivity()
.getApplicationContext(), DETAIL_THUMB_WIDTH);
int height = Utils.convertDpToPixel(getActivity()
.getApplicationContext(), DETAIL_THUMB_HEIGHT);
Glide.with(getActivity())
.load(mSelectedApk.getIcon())
.centerCrop()
.error(R.drawable.default_background)
.into(new SimpleTarget<GlideDrawable>(width, height) {
@Override
public void onResourceReady(GlideDrawable resource,
GlideAnimation<? super GlideDrawable>
glideAnimation) {
Log.d(TAG, "details overview card image url ready: " + resource);
row.setImageDrawable(resource);
mAdapter.notifyArrayItemRangeChanged(0, mAdapter.size());
}
});
// See if this is already installed. If so, check if it can be updated.
// Offer an uninstall option.
// Add an install button.
SparseArrayObjectAdapter possibleActions = new SparseArrayObjectAdapter();
PackageManager packageManager = getActivity().getPackageManager();
try {
PackageInfo info = packageManager.getPackageInfo(mSelectedApk.getPackageName(), 0);
if (info.versionCode < mSelectedApk.getVersionCode()) {
possibleActions.set(ACTION_UPDATE,
new Action(ACTION_UPDATE, getString(R.string.update)));
}
possibleActions.set(ACTION_UNINSTALL,
new Action(ACTION_UNINSTALL, getString(R.string.uninstall)));
} catch (PackageManager.NameNotFoundException e) {
// App is not installed
possibleActions.set(ACTION_INSTALL,
new Action(ACTION_INSTALL, getString(R.string.install)));
}
row.setActionsAdapter(possibleActions);
mAdapter.add(row);
}
private void setupDetailsOverviewRowPresenter() {
// Set detail background and style.
DetailsOverviewRowPresenter detailsPresenter =
new DetailsOverviewRowPresenter(new DetailsDescriptionPresenter(getActivity()));
detailsPresenter.setBackgroundColor(getResources().getColor(R.color.selected_background));
detailsPresenter.setStyleLarge(true);
// Hook up transition element.
detailsPresenter.setSharedElementEnterTransition(getActivity(),
DetailsActivity.SHARED_ELEMENT_NAME);
mPresenterSelector.addClassPresenter(DetailsOverviewRow.class, detailsPresenter);
}
private void setupMovieListRow() {
}
private void setupMovieListRowPresenter() {
mPresenterSelector.addClassPresenter(ListRow.class, new ListRowPresenter());
}
private final class ItemViewClickedListener implements OnItemViewClickedListener {
@Override
public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Apk) {
Apk application = (Apk) item;
Log.d(TAG, "Item: " + item.toString());
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra(getResources().getString(R.string.apk_string), mSelectedApk.toString());
intent.putExtra(getResources().getString(R.string.should_start), true);
startActivity(intent);
Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
getActivity(),
((ImageCardView) itemViewHolder.view).getMainImageView(),
DetailsActivity.SHARED_ELEMENT_NAME).toBundle();
getActivity().startActivity(intent, bundle);
} else if (item instanceof Action) {
Log.d(TAG, "Item: " + item.toString());
Action action = (Action) item;
if (action.getId() == ACTION_INSTALL || action.getId() == ACTION_UPDATE) {
if (mSelectedApk.getDownloadCount() > 1) {
// Display picker
new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.dialog_theme))
.setTitle(R.string.title_apk_variants)
.setItems(mSelectedApk.getDownloadTitleArray(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
download(mSelectedApk.getDownloadUrlArray()[i]);
}
})
.show();
} else {
download(mSelectedApk.getDefaultDownloadUrl());
}
} else if (action.getId() == ACTION_UNINSTALL) {
if (mSelectedApk.getPackageName() == null) {
Toast.makeText(getActivity(), R.string.warn_null_package_name, Toast.LENGTH_SHORT).show();
} else {
PackageInstallerUtils.uninstallApp(getActivity(), mSelectedApk.getPackageName());
}
}
}
}
}
public void download(String url) {
RepoDatabase.getInstance().incrementApkDownloads(mSelectedApk);
mApkDownloadHelper.startDownload(url);
RepoDatabase.getLeanbackShortcut(mSelectedApk.getPackageName(),
new RepoDatabase.LeanbackShortcutCallback() {
@Override
public void onNoLeanbackShortcut() {
}
@Override
public void onLeanbackShortcut(LeanbackShortcut leanbackShortcut) {
mApkDownloadHelper.startDownload(leanbackShortcut.getDownload());
}
@Override
public void onDatabaseError(DatabaseError error) {
}
});
}
}
| ITVlab/TvAppRepo | app/src/main/java/news/androidtv/tvapprepo/fragments/AppDetailsFragment.java | 3,886 | // Hook up transition element.
| line_comment | nl | /*
* Copyright (C) 2014 The Android Open Source 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 news.androidtv.tvapprepo.fragments;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v17.leanback.app.BackgroundManager;
import android.support.v17.leanback.app.DetailsFragment;
import android.support.v17.leanback.widget.Action;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.ClassPresenterSelector;
import android.support.v17.leanback.widget.DetailsOverviewRow;
import android.support.v17.leanback.widget.DetailsOverviewRowPresenter;
import android.support.v17.leanback.widget.ImageCardView;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.OnItemViewClickedListener;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.RowPresenter;
import android.support.v17.leanback.widget.SparseArrayObjectAdapter;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.firebase.database.DatabaseError;
import java.io.File;
import news.androidtv.tvapprepo.R;
import news.androidtv.tvapprepo.Utils;
import news.androidtv.tvapprepo.activities.DetailsActivity;
import news.androidtv.tvapprepo.activities.MainActivity;
import news.androidtv.tvapprepo.download.ApkDownloadHelper;
import news.androidtv.tvapprepo.model.Apk;
import news.androidtv.tvapprepo.model.LeanbackShortcut;
import news.androidtv.tvapprepo.model.RepoDatabase;
import news.androidtv.tvapprepo.presenters.DetailsDescriptionPresenter;
import news.androidtv.tvapprepo.utils.PackageInstallerUtils;
import tv.puppetmaster.tinydl.PackageInstaller;
/*
* LeanbackDetailsFragment extends DetailsFragment, a Wrapper fragment for leanback details screens.
* It shows a detailed view of video and its meta plus related videos.
*/
public class AppDetailsFragment extends DetailsFragment {
private static final String TAG = AppDetailsFragment.class.getSimpleName();
private static final int ACTION_INSTALL = 11;
private static final int ACTION_UPDATE = 12;
private static final int ACTION_UNINSTALL = 13;
private static final int DETAIL_THUMB_WIDTH = 274;
private static final int DETAIL_THUMB_HEIGHT = 274;
private Apk mSelectedApk;
private ArrayObjectAdapter mAdapter;
private ClassPresenterSelector mPresenterSelector;
private BackgroundManager mBackgroundManager;
private Drawable mDefaultBackground;
private DisplayMetrics mMetrics;
private ApkDownloadHelper mApkDownloadHelper;
private PackageInstaller.DownloadListener mDownloadListener = new PackageInstaller.DownloadListener() {
@Override
public void onApkDownloaded(File downloadedApkFile) {
Log.d(TAG, "Downloaded " + downloadedApkFile.getAbsolutePath());
mApkDownloadHelper.install(downloadedApkFile);
}
@Override
public void onApkDownloadedNougat(final File downloadedApkFile) {
Log.d(TAG, "Downloaded " + downloadedApkFile.getAbsolutePath());
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
mApkDownloadHelper.install(downloadedApkFile);
}
}, 1000 * 5);
}
@Override
public void onFileDeleted(File deletedApkFile, boolean wasSuccessful) {
}
@Override
public void onProgressStarted() {
// Show a video ad
Toast.makeText(getActivity(), R.string.download_started, Toast.LENGTH_SHORT).show();
}
@Override
public void onProgressEnded() {
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate DetailsFragment");
super.onCreate(savedInstanceState);
prepareBackgroundManager();
mSelectedApk = new Apk.Builder(getActivity().getIntent()
.getStringExtra(DetailsActivity.APPLICATION)).build();
if (mSelectedApk != null) {
setupAdapter();
setupDetailsOverviewRow();
setupDetailsOverviewRowPresenter();
setupMovieListRow();
setupMovieListRowPresenter();
updateBackground(mSelectedApk.getBanner());
setOnItemViewClickedListener(new ItemViewClickedListener());
mApkDownloadHelper = new ApkDownloadHelper(getActivity());
RepoDatabase.getInstance().incrementApkViews(mSelectedApk);
mApkDownloadHelper.addListener(mDownloadListener);
} else {
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
Toast.makeText(getActivity(), R.string.no_app_selected, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onStop() {
super.onStop();
Log.d(TAG, "App activity stopped");
mApkDownloadHelper.destroy();
mApkDownloadHelper.removeListener(mDownloadListener);
}
private void prepareBackgroundManager() {
mBackgroundManager = BackgroundManager.getInstance(getActivity());
mBackgroundManager.attach(getActivity().getWindow());
mDefaultBackground = getResources().getDrawable(R.drawable.default_background);
mMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
}
protected void updateBackground(String uri) {
Glide.with(getActivity())
.load(uri)
.centerCrop()
.error(mDefaultBackground)
.into(new SimpleTarget<GlideDrawable>(mMetrics.widthPixels, mMetrics.heightPixels) {
@Override
public void onResourceReady(GlideDrawable resource,
GlideAnimation<? super GlideDrawable> glideAnimation) {
mBackgroundManager.setDrawable(resource);
}
});
}
private void setupAdapter() {
mPresenterSelector = new ClassPresenterSelector();
mAdapter = new ArrayObjectAdapter(mPresenterSelector);
setAdapter(mAdapter);
}
private void setupDetailsOverviewRow() {
Log.d(TAG, "doInBackground: " + mSelectedApk.toString());
final DetailsOverviewRow row = new DetailsOverviewRow(mSelectedApk);
row.setImageDrawable(getResources().getDrawable(R.drawable.default_background));
int width = Utils.convertDpToPixel(getActivity()
.getApplicationContext(), DETAIL_THUMB_WIDTH);
int height = Utils.convertDpToPixel(getActivity()
.getApplicationContext(), DETAIL_THUMB_HEIGHT);
Glide.with(getActivity())
.load(mSelectedApk.getIcon())
.centerCrop()
.error(R.drawable.default_background)
.into(new SimpleTarget<GlideDrawable>(width, height) {
@Override
public void onResourceReady(GlideDrawable resource,
GlideAnimation<? super GlideDrawable>
glideAnimation) {
Log.d(TAG, "details overview card image url ready: " + resource);
row.setImageDrawable(resource);
mAdapter.notifyArrayItemRangeChanged(0, mAdapter.size());
}
});
// See if this is already installed. If so, check if it can be updated.
// Offer an uninstall option.
// Add an install button.
SparseArrayObjectAdapter possibleActions = new SparseArrayObjectAdapter();
PackageManager packageManager = getActivity().getPackageManager();
try {
PackageInfo info = packageManager.getPackageInfo(mSelectedApk.getPackageName(), 0);
if (info.versionCode < mSelectedApk.getVersionCode()) {
possibleActions.set(ACTION_UPDATE,
new Action(ACTION_UPDATE, getString(R.string.update)));
}
possibleActions.set(ACTION_UNINSTALL,
new Action(ACTION_UNINSTALL, getString(R.string.uninstall)));
} catch (PackageManager.NameNotFoundException e) {
// App is not installed
possibleActions.set(ACTION_INSTALL,
new Action(ACTION_INSTALL, getString(R.string.install)));
}
row.setActionsAdapter(possibleActions);
mAdapter.add(row);
}
private void setupDetailsOverviewRowPresenter() {
// Set detail background and style.
DetailsOverviewRowPresenter detailsPresenter =
new DetailsOverviewRowPresenter(new DetailsDescriptionPresenter(getActivity()));
detailsPresenter.setBackgroundColor(getResources().getColor(R.color.selected_background));
detailsPresenter.setStyleLarge(true);
// Hook up<SUF>
detailsPresenter.setSharedElementEnterTransition(getActivity(),
DetailsActivity.SHARED_ELEMENT_NAME);
mPresenterSelector.addClassPresenter(DetailsOverviewRow.class, detailsPresenter);
}
private void setupMovieListRow() {
}
private void setupMovieListRowPresenter() {
mPresenterSelector.addClassPresenter(ListRow.class, new ListRowPresenter());
}
private final class ItemViewClickedListener implements OnItemViewClickedListener {
@Override
public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Apk) {
Apk application = (Apk) item;
Log.d(TAG, "Item: " + item.toString());
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra(getResources().getString(R.string.apk_string), mSelectedApk.toString());
intent.putExtra(getResources().getString(R.string.should_start), true);
startActivity(intent);
Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
getActivity(),
((ImageCardView) itemViewHolder.view).getMainImageView(),
DetailsActivity.SHARED_ELEMENT_NAME).toBundle();
getActivity().startActivity(intent, bundle);
} else if (item instanceof Action) {
Log.d(TAG, "Item: " + item.toString());
Action action = (Action) item;
if (action.getId() == ACTION_INSTALL || action.getId() == ACTION_UPDATE) {
if (mSelectedApk.getDownloadCount() > 1) {
// Display picker
new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.dialog_theme))
.setTitle(R.string.title_apk_variants)
.setItems(mSelectedApk.getDownloadTitleArray(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
download(mSelectedApk.getDownloadUrlArray()[i]);
}
})
.show();
} else {
download(mSelectedApk.getDefaultDownloadUrl());
}
} else if (action.getId() == ACTION_UNINSTALL) {
if (mSelectedApk.getPackageName() == null) {
Toast.makeText(getActivity(), R.string.warn_null_package_name, Toast.LENGTH_SHORT).show();
} else {
PackageInstallerUtils.uninstallApp(getActivity(), mSelectedApk.getPackageName());
}
}
}
}
}
public void download(String url) {
RepoDatabase.getInstance().incrementApkDownloads(mSelectedApk);
mApkDownloadHelper.startDownload(url);
RepoDatabase.getLeanbackShortcut(mSelectedApk.getPackageName(),
new RepoDatabase.LeanbackShortcutCallback() {
@Override
public void onNoLeanbackShortcut() {
}
@Override
public void onLeanbackShortcut(LeanbackShortcut leanbackShortcut) {
mApkDownloadHelper.startDownload(leanbackShortcut.getDownload());
}
@Override
public void onDatabaseError(DatabaseError error) {
}
});
}
}
|
32085_16 | /*
* 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 com.sun.opengl.impl.tessellator;
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);
}
}
| IUE/QGlobe | src/com/sun/opengl/impl/tessellator/Geom.java | 3,803 | /* Interpolate between o2 and d2 */ | block_comment | nl | /*
* 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 com.sun.opengl.impl.tessellator;
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<SUF>*/
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);
}
}
|
84220_17 | package com.example.aiui;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Objects;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import javafx.scene.transform.Scale;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class mainController implements Initializable {
User user;
data DB = new data();
public void setmainController(data DB, User user) {
this.DB = DB;
this.user = user;
}
private Stage stage;
private Scene scene;
private Parent root;
Gesprek DitGesprek;
gespreksManager Manager;
private ResourceBundle bundle = ResourceBundle.getBundle("com.example.aiui.English");
private boolean EnglishIsActive = true;
private static final double ZZOOM = 1.109375;
private static final double SMALL = 0.78125;
@FXML private ListView<String> chatList;
@FXML private Pane Base;
@FXML private Button darkmode;
@FXML private Button mode;
@FXML private Scale scale;
@FXML private Button Zoom;
@FXML private Button Minus;
@FXML private Pane achtergrond;
@FXML private Label OnderwerpLabel;
@FXML private Button showSettings;
@FXML private Button Submit;
@FXML private Button closeSettings;
@FXML private Pane settingspane;
boolean settings = false;
@FXML private Button setting_register;
@FXML private TextField input;
@FXML private Pane sidebar;
@FXML private Button edituser;
@FXML private Button language;
@FXML private Button advanced;
@FXML private Button lightmode;
@FXML private Button colormode1;
@FXML private Button colormode2;
@FXML private Button logUit;
@FXML private Label Titel;
@FXML private Label HisLabel;
private ObservableList<String> conversation;
private boolean FirstMessage = true;
public void Togglelang(ActionEvent event) { // voor taal switchen
if (EnglishIsActive) {
EnglishIsActive = false;
bundle = ResourceBundle.getBundle("com.example.aiui.Nederlands");
showSettings.setText(bundle.getString("Settings"));
input.setPromptText(bundle.getString("PromptText"));
Submit.setText(bundle.getString("Submit"));
closeSettings.setText(bundle.getString("closesettings"));
advanced.setText(bundle.getString("advanced"));
edituser.setText(bundle.getString("edituser"));
language.setText(bundle.getString("Taal"));
setting_register.setText(bundle.getString("settingsregister"));
} else {
EnglishIsActive = true;
bundle = ResourceBundle.getBundle("com.example.aiui.English");
showSettings.setText(bundle.getString("Settings"));
input.setPromptText(bundle.getString("PromptText"));
Submit.setText(bundle.getString("Submit"));
closeSettings.setText(bundle.getString("closesettings"));
advanced.setText(bundle.getString("advanced"));
edituser.setText(bundle.getString("edituser"));
language.setText(bundle.getString("Taal"));
setting_register.setText(bundle.getString("settingsregister"));
}
}
protected void LightMode() {
achtergrond.setStyle("-fx-background-color: linear-gradient(to right, #5bc3f0, #174694)");
GesprekOnderwerpen.setStyle(
"-fx-background-color: white; -fx-background-radius: 24px; -fx-text-fill: black;");
chatList.setStyle(
"-fx-background-color: white; -fx-background-radius: 24px; -fx-text-fill: black;");
settingspane.setStyle("-fx-background-color: white; -fx-background-radius: 24px;");
input.setStyle("-fx-background-color: white; -fx-text-fill: black");
Submit.setStyle("-fx-background-color: #5BC3F0");
showSettings.setStyle("-fx-background-color: #5BC3F0");
logUit.setStyle("-fx-background-color: #5BC3F0");
NieuweGesprek.setStyle("-fx-background-color: #5BC3F0");
setting_register.setStyle("-fx-background-color: #5BC3F0");
language.setStyle("-fx-background-color: #5BC3F0");
edituser.setStyle("-fx-background-color: #5BC3F0");
advanced.setStyle("-fx-background-color: #5BC3F0");
darkmode.setStyle("-fx-background-color: #5BC3F0");
lightmode.setStyle("-fx-background-color: #5BC3F0");
colormode1.setStyle("-fx-background-color: #5BC3F0");
colormode2.setStyle("-fx-background-color: #5BC3F0");
closeSettings.setStyle("-fx-background-color: #5BC3F0");
Zoom.setStyle("-fx-background-color: #5BC3F0");
Minus.setStyle("-fx-background-color: #5BC3F0");
}
protected void DarkMode() {
achtergrond.setStyle("-fx-background-color: black");
GesprekOnderwerpen.setStyle(
"-fx-background-color: #8a8a8a; -fx-background-radius: 24px; -fx-text-fill: white");
chatList.setStyle(
"-fx-background-color: #8a8a8a; -fx-background-radius: 24px; -fx-text-fill: white");
settingspane.setStyle("-fx-background-color: grey; -fx-background-radius: 24px;");
input.setStyle("-fx-background-color: darkgrey; -fx-text-fill: white");
Submit.setStyle("-fx-background-color: darkgrey");
showSettings.setStyle("-fx-background-color: darkgrey");
logUit.setStyle("-fx-background-color: darkgrey");
NieuweGesprek.setStyle("-fx-background-color: darkgrey");
setting_register.setStyle("-fx-background-color: darkgrey");
language.setStyle("-fx-background-color: darkgrey");
edituser.setStyle("-fx-background-color: darkgrey");
advanced.setStyle("-fx-background-color: darkgrey");
darkmode.setStyle("-fx-background-color: darkgrey");
lightmode.setStyle("-fx-background-color: darkgrey");
colormode1.setStyle("-fx-background-color: darkgrey");
colormode2.setStyle("-fx-background-color: darkgrey");
closeSettings.setStyle("-fx-background-color: darkgrey");
Zoom.setStyle("-fx-background-color: darkgrey");
Minus.setStyle("-fx-background-color: darkgrey");
}
protected void color1() {
achtergrond.setStyle("-fx-background-color: linear-gradient(to right, darkgreen, lime)");
settingspane.setStyle("-fx-background-color: darkgreen; -fx-background-radius: 24px;");
input.setStyle("-fx-background-color: darkgreen; -fx-text-fill: white");
GesprekOnderwerpen.setStyle(
"-fx-background-color: white; -fx-background-radius: 24px; -fx-text-fill: black");
chatList.setStyle(
"-fx-background-color: white; -fx-background-radius: 24px; -fx-text-fill: black");
Submit.setStyle("-fx-background-color: green");
showSettings.setStyle("-fx-background-color: green");
logUit.setStyle("-fx-background-color: green");
NieuweGesprek.setStyle("-fx-background-color: green");
setting_register.setStyle("-fx-background-color: green");
language.setStyle("-fx-background-color: green");
edituser.setStyle("-fx-background-color: green");
advanced.setStyle("-fx-background-color: green");
darkmode.setStyle("-fx-background-color: green");
lightmode.setStyle("-fx-background-color: green");
colormode1.setStyle("-fx-background-color: green");
colormode2.setStyle("-fx-background-color: green");
closeSettings.setStyle("-fx-background-color: green");
Zoom.setStyle("-fx-background-color: green");
Minus.setStyle("-fx-background-color: green");
}
protected void color2() {
achtergrond.setStyle("-fx-background-color: linear-gradient(to right, darkred, red)");
settingspane.setStyle("-fx-background-color: darkred; -fx-background-radius: 24px;");
GesprekOnderwerpen.setStyle(
"-fx-background-color: white; -fx-background-radius: 24px; -fx-text-fill: black");
chatList.setStyle(
"-fx-background-color: white; -fx-background-radius: 24px; -fx-text-fill: black");
input.setStyle("-fx-background-color: darkred; -fx-text-fill: white");
Submit.setStyle("-fx-background-color: red");
showSettings.setStyle("-fx-background-color: red");
logUit.setStyle("-fx-background-color: red");
NieuweGesprek.setStyle("-fx-background-color: red");
setting_register.setStyle("-fx-background-color: red");
language.setStyle("-fx-background-color: red");
edituser.setStyle("-fx-background-color: red");
advanced.setStyle("-fx-background-color: red");
darkmode.setStyle("-fx-background-color: red");
lightmode.setStyle("-fx-background-color: red");
colormode1.setStyle("-fx-background-color: red");
colormode2.setStyle("-fx-background-color: red");
closeSettings.setStyle("-fx-background-color: red");
Zoom.setStyle("-fx-background-color: red");
Minus.setStyle("-fx-background-color: red");
}
public void ThemaToepasser() {
if (ThemaBeheerder.isDarkMode()) {
LightMode();
} else if (ThemaBeheerder.isLightMode()) {
DarkMode();
} else if (ThemaBeheerder.isColorMode1()) {
color1();
} else if (ThemaBeheerder.isColorMode2()) {
color2();
}
}
@FXML
public void darkKlick() {
update(true, false, false, false);
}
@FXML
public void lightKlick() {
update(false, true, false, false);
}
@FXML
public void color1Klick() {
update(false, false, true, false);
}
@FXML
public void color2Klick() {
update(false, false, false, true);
}
@FXML
private void handleZoom() {
scale.setX(scale.getX() * ZZOOM);
scale.setY(scale.getY() * ZZOOM);
}
@FXML
private void handleMin() {
scale.setX(scale.getX() * SMALL);
scale.setY(scale.getY() * SMALL);
}
public void update(boolean darkmode, boolean lightmode, boolean colormode1, boolean colormode2) {
ThemaBeheerder.setDarkMode(darkmode);
ThemaBeheerder.setLightMode(lightmode);
ThemaBeheerder.setColorMode1(colormode1);
ThemaBeheerder.setColorMode2(colormode2);
// Apply color changes based on the selected theme
if (darkmode) {
DarkMode();
} else if (lightmode) {
LightMode();
} else if (colormode1) {
color1();
} else if (colormode2) {
color2();
}
}
@FXML
protected void displaySettings() {
settingspane.setVisible(!settings);
showSettings.setVisible(settings);
settings = !settings;
}
@FXML
public void setOnKeyPressed(ActionEvent Enter) {
// vind het juiste gesprek
DitGesprek = getGesprek();
// Maak het onderwerp aan voor het gesprek
String userMessage = input.getText();
if (DitGesprek.getGespreksData().isEmpty()) {
OnderwerpLabel.setText(userMessage);
DitGesprek.setOnderwerp(userMessage);
FirstMessage = false;
toevoegenGesprekAanGesprekkenLijst(DitGesprek);
}
// Add user's message to the chat list
String localInput = "User: " + userMessage;
chatList.getItems().add(localInput);
DitGesprek.getGespreksData().add(localInput);
// Generate an automatic response
String automaticResponse = DitGesprek.generateResponse(userMessage);
// Add the automatic response to the chat list
String localOutput = "AI: " + automaticResponse;
chatList.getItems().add(localOutput);
DitGesprek.getGespreksData().add(localOutput);
// Clear the input field
input.clear();
}
@FXML
protected void registerEmployee(ActionEvent event) throws IOException {
Stage stage = (Stage) setting_register.getScene().getWindow();
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("register.fxml"));
Parent root = fxmlLoader.load();
Stage popupStage = new Stage();
popupStage.initModality(Modality.APPLICATION_MODAL);
popupStage.initOwner(stage);
popupStage.setTitle("Register employee");
popupStage.setScene(new Scene(root));
// Access the controller of the loaded FXML file if needed
registrationController registrationController = fxmlLoader.getController();
registrationController.setregistrationController(DB);
registrationController.setStage();
// Show the popup window
popupStage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
@FXML
public void LogoutButton(ActionEvent event) throws IOException {
// Stap 1: Het gesprek opslaan
DitGesprek.saveConversation(conversation);
// Stap 2: Uitloggen en navigeren naar het startscherm
root = FXMLLoader.load(getClass().getResource("startLogin.fxml"));
stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
private void loadConversation() {
try {
// Lees het tekstbestand "conversation.txt"
BufferedReader reader = new BufferedReader(new FileReader("conversation.txt"));
String line;
while ((line = reader.readLine()) != null) {
// Voeg elk bericht toe aan de gesprekkenlijst
conversation.add(line);
}
reader.close();
System.out.println("Gesprek geladen.");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
ThemaToepasser();
scale = new Scale();
scale.setX(1.0);
scale.setY(1.0);
achtergrond.getTransforms().setAll(scale);
showSettings.setText(bundle.getString("Settings"));
input.setPromptText(bundle.getString("PromptText"));
// Submit.setText(bundle.getString("Submit"));
closeSettings.setText(bundle.getString("closesettings"));
advanced.setText(bundle.getString("advanced"));
edituser.setText(bundle.getString("edituser"));
language.setText(bundle.getString("Taal"));
setting_register.setText(bundle.getString("settingsregister"));
Gesprekken = new ArrayList<Gesprek>();
Gesprek EersteGesprek = new Gesprek();
Gesprekken.add(EersteGesprek);
}
// WIP
private ArrayList<Gesprek> Gesprekken;
private Gesprek LocaalGesprek;
private int GesprekId = 0;
private int gesprekidCounter = 0;
@FXML private ListView<String> GesprekOnderwerpen;
@FXML private Button NieuweGesprek;
public int GesprekIdCounter() {
int id = gesprekidCounter;
gesprekidCounter++;
return id;
}
public void NieuwGesprek() {
// maak een nieuw gesprek
Gesprek gesprek = Manager.newGesprek();
// clear het label
OnderwerpLabel.setText("");
// Voeg het gesprek toe aan de lijst met gesprekken
Gesprekken.add(gesprek);
// verander het id van de chat voor de klasse zodat de juiste chat wordt geladen
this.GesprekId = gesprek.getId();
//"open" een gesprek door de vorige text te verwijderen
chatList.getItems().clear();
}
public void SelecteerdChat() {
String SelectedChat = GesprekOnderwerpen.getSelectionModel().getSelectedItem();
for (Gesprek gesprek : Gesprekken) {
if (SelectedChat.equals(gesprek.getOnderwerp())) {
// Selecteer gesprek gebaseerd op onderwerp
Gesprek CurrentGesprek = gesprek;
this.GesprekId = CurrentGesprek.getId();
// Laad de nieuwe chat
ArrayList<String> gespreksData = CurrentGesprek.getGespreksData();
Laadchat(gespreksData);
OnderwerpLabel.setText(CurrentGesprek.getOnderwerp());
}
}
}
public void Laadchat(ArrayList<String> gespreksData) {
chatList.getItems().clear();
for (int i = 0; i < gespreksData.size(); i++) {
String str = gespreksData.get(i);
if (i % 2 == 0) {
chatList.getItems().add(str);
} else {
chatList.getItems().add(str);
}
}
}
public void toevoegenGesprekAanGesprekkenLijst(Gesprek gesprek) {
GesprekOnderwerpen.getItems().add(gesprek.getOnderwerp());
}
public Gesprek getGesprek() {
Gesprek DitGesprek = null;
for (Gesprek gesprek : Gesprekken) {
if (gesprek.getId() == GesprekId) {
DitGesprek = gesprek;
}
}
return DitGesprek;
}
public void WeizigOnderwerp() {
// weizig het onderwerp code
GesprekOnderwerpen.refresh();
}
@FXML
public void loguit(ActionEvent event) throws IOException {
root = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("startLogin.fxml")));
stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
} | IamDoom/AIUI | src/main/java/com/example/aiui/mainController.java | 5,546 | // verander het id van de chat voor de klasse zodat de juiste chat wordt geladen | line_comment | nl | package com.example.aiui;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Objects;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import javafx.scene.transform.Scale;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class mainController implements Initializable {
User user;
data DB = new data();
public void setmainController(data DB, User user) {
this.DB = DB;
this.user = user;
}
private Stage stage;
private Scene scene;
private Parent root;
Gesprek DitGesprek;
gespreksManager Manager;
private ResourceBundle bundle = ResourceBundle.getBundle("com.example.aiui.English");
private boolean EnglishIsActive = true;
private static final double ZZOOM = 1.109375;
private static final double SMALL = 0.78125;
@FXML private ListView<String> chatList;
@FXML private Pane Base;
@FXML private Button darkmode;
@FXML private Button mode;
@FXML private Scale scale;
@FXML private Button Zoom;
@FXML private Button Minus;
@FXML private Pane achtergrond;
@FXML private Label OnderwerpLabel;
@FXML private Button showSettings;
@FXML private Button Submit;
@FXML private Button closeSettings;
@FXML private Pane settingspane;
boolean settings = false;
@FXML private Button setting_register;
@FXML private TextField input;
@FXML private Pane sidebar;
@FXML private Button edituser;
@FXML private Button language;
@FXML private Button advanced;
@FXML private Button lightmode;
@FXML private Button colormode1;
@FXML private Button colormode2;
@FXML private Button logUit;
@FXML private Label Titel;
@FXML private Label HisLabel;
private ObservableList<String> conversation;
private boolean FirstMessage = true;
public void Togglelang(ActionEvent event) { // voor taal switchen
if (EnglishIsActive) {
EnglishIsActive = false;
bundle = ResourceBundle.getBundle("com.example.aiui.Nederlands");
showSettings.setText(bundle.getString("Settings"));
input.setPromptText(bundle.getString("PromptText"));
Submit.setText(bundle.getString("Submit"));
closeSettings.setText(bundle.getString("closesettings"));
advanced.setText(bundle.getString("advanced"));
edituser.setText(bundle.getString("edituser"));
language.setText(bundle.getString("Taal"));
setting_register.setText(bundle.getString("settingsregister"));
} else {
EnglishIsActive = true;
bundle = ResourceBundle.getBundle("com.example.aiui.English");
showSettings.setText(bundle.getString("Settings"));
input.setPromptText(bundle.getString("PromptText"));
Submit.setText(bundle.getString("Submit"));
closeSettings.setText(bundle.getString("closesettings"));
advanced.setText(bundle.getString("advanced"));
edituser.setText(bundle.getString("edituser"));
language.setText(bundle.getString("Taal"));
setting_register.setText(bundle.getString("settingsregister"));
}
}
protected void LightMode() {
achtergrond.setStyle("-fx-background-color: linear-gradient(to right, #5bc3f0, #174694)");
GesprekOnderwerpen.setStyle(
"-fx-background-color: white; -fx-background-radius: 24px; -fx-text-fill: black;");
chatList.setStyle(
"-fx-background-color: white; -fx-background-radius: 24px; -fx-text-fill: black;");
settingspane.setStyle("-fx-background-color: white; -fx-background-radius: 24px;");
input.setStyle("-fx-background-color: white; -fx-text-fill: black");
Submit.setStyle("-fx-background-color: #5BC3F0");
showSettings.setStyle("-fx-background-color: #5BC3F0");
logUit.setStyle("-fx-background-color: #5BC3F0");
NieuweGesprek.setStyle("-fx-background-color: #5BC3F0");
setting_register.setStyle("-fx-background-color: #5BC3F0");
language.setStyle("-fx-background-color: #5BC3F0");
edituser.setStyle("-fx-background-color: #5BC3F0");
advanced.setStyle("-fx-background-color: #5BC3F0");
darkmode.setStyle("-fx-background-color: #5BC3F0");
lightmode.setStyle("-fx-background-color: #5BC3F0");
colormode1.setStyle("-fx-background-color: #5BC3F0");
colormode2.setStyle("-fx-background-color: #5BC3F0");
closeSettings.setStyle("-fx-background-color: #5BC3F0");
Zoom.setStyle("-fx-background-color: #5BC3F0");
Minus.setStyle("-fx-background-color: #5BC3F0");
}
protected void DarkMode() {
achtergrond.setStyle("-fx-background-color: black");
GesprekOnderwerpen.setStyle(
"-fx-background-color: #8a8a8a; -fx-background-radius: 24px; -fx-text-fill: white");
chatList.setStyle(
"-fx-background-color: #8a8a8a; -fx-background-radius: 24px; -fx-text-fill: white");
settingspane.setStyle("-fx-background-color: grey; -fx-background-radius: 24px;");
input.setStyle("-fx-background-color: darkgrey; -fx-text-fill: white");
Submit.setStyle("-fx-background-color: darkgrey");
showSettings.setStyle("-fx-background-color: darkgrey");
logUit.setStyle("-fx-background-color: darkgrey");
NieuweGesprek.setStyle("-fx-background-color: darkgrey");
setting_register.setStyle("-fx-background-color: darkgrey");
language.setStyle("-fx-background-color: darkgrey");
edituser.setStyle("-fx-background-color: darkgrey");
advanced.setStyle("-fx-background-color: darkgrey");
darkmode.setStyle("-fx-background-color: darkgrey");
lightmode.setStyle("-fx-background-color: darkgrey");
colormode1.setStyle("-fx-background-color: darkgrey");
colormode2.setStyle("-fx-background-color: darkgrey");
closeSettings.setStyle("-fx-background-color: darkgrey");
Zoom.setStyle("-fx-background-color: darkgrey");
Minus.setStyle("-fx-background-color: darkgrey");
}
protected void color1() {
achtergrond.setStyle("-fx-background-color: linear-gradient(to right, darkgreen, lime)");
settingspane.setStyle("-fx-background-color: darkgreen; -fx-background-radius: 24px;");
input.setStyle("-fx-background-color: darkgreen; -fx-text-fill: white");
GesprekOnderwerpen.setStyle(
"-fx-background-color: white; -fx-background-radius: 24px; -fx-text-fill: black");
chatList.setStyle(
"-fx-background-color: white; -fx-background-radius: 24px; -fx-text-fill: black");
Submit.setStyle("-fx-background-color: green");
showSettings.setStyle("-fx-background-color: green");
logUit.setStyle("-fx-background-color: green");
NieuweGesprek.setStyle("-fx-background-color: green");
setting_register.setStyle("-fx-background-color: green");
language.setStyle("-fx-background-color: green");
edituser.setStyle("-fx-background-color: green");
advanced.setStyle("-fx-background-color: green");
darkmode.setStyle("-fx-background-color: green");
lightmode.setStyle("-fx-background-color: green");
colormode1.setStyle("-fx-background-color: green");
colormode2.setStyle("-fx-background-color: green");
closeSettings.setStyle("-fx-background-color: green");
Zoom.setStyle("-fx-background-color: green");
Minus.setStyle("-fx-background-color: green");
}
protected void color2() {
achtergrond.setStyle("-fx-background-color: linear-gradient(to right, darkred, red)");
settingspane.setStyle("-fx-background-color: darkred; -fx-background-radius: 24px;");
GesprekOnderwerpen.setStyle(
"-fx-background-color: white; -fx-background-radius: 24px; -fx-text-fill: black");
chatList.setStyle(
"-fx-background-color: white; -fx-background-radius: 24px; -fx-text-fill: black");
input.setStyle("-fx-background-color: darkred; -fx-text-fill: white");
Submit.setStyle("-fx-background-color: red");
showSettings.setStyle("-fx-background-color: red");
logUit.setStyle("-fx-background-color: red");
NieuweGesprek.setStyle("-fx-background-color: red");
setting_register.setStyle("-fx-background-color: red");
language.setStyle("-fx-background-color: red");
edituser.setStyle("-fx-background-color: red");
advanced.setStyle("-fx-background-color: red");
darkmode.setStyle("-fx-background-color: red");
lightmode.setStyle("-fx-background-color: red");
colormode1.setStyle("-fx-background-color: red");
colormode2.setStyle("-fx-background-color: red");
closeSettings.setStyle("-fx-background-color: red");
Zoom.setStyle("-fx-background-color: red");
Minus.setStyle("-fx-background-color: red");
}
public void ThemaToepasser() {
if (ThemaBeheerder.isDarkMode()) {
LightMode();
} else if (ThemaBeheerder.isLightMode()) {
DarkMode();
} else if (ThemaBeheerder.isColorMode1()) {
color1();
} else if (ThemaBeheerder.isColorMode2()) {
color2();
}
}
@FXML
public void darkKlick() {
update(true, false, false, false);
}
@FXML
public void lightKlick() {
update(false, true, false, false);
}
@FXML
public void color1Klick() {
update(false, false, true, false);
}
@FXML
public void color2Klick() {
update(false, false, false, true);
}
@FXML
private void handleZoom() {
scale.setX(scale.getX() * ZZOOM);
scale.setY(scale.getY() * ZZOOM);
}
@FXML
private void handleMin() {
scale.setX(scale.getX() * SMALL);
scale.setY(scale.getY() * SMALL);
}
public void update(boolean darkmode, boolean lightmode, boolean colormode1, boolean colormode2) {
ThemaBeheerder.setDarkMode(darkmode);
ThemaBeheerder.setLightMode(lightmode);
ThemaBeheerder.setColorMode1(colormode1);
ThemaBeheerder.setColorMode2(colormode2);
// Apply color changes based on the selected theme
if (darkmode) {
DarkMode();
} else if (lightmode) {
LightMode();
} else if (colormode1) {
color1();
} else if (colormode2) {
color2();
}
}
@FXML
protected void displaySettings() {
settingspane.setVisible(!settings);
showSettings.setVisible(settings);
settings = !settings;
}
@FXML
public void setOnKeyPressed(ActionEvent Enter) {
// vind het juiste gesprek
DitGesprek = getGesprek();
// Maak het onderwerp aan voor het gesprek
String userMessage = input.getText();
if (DitGesprek.getGespreksData().isEmpty()) {
OnderwerpLabel.setText(userMessage);
DitGesprek.setOnderwerp(userMessage);
FirstMessage = false;
toevoegenGesprekAanGesprekkenLijst(DitGesprek);
}
// Add user's message to the chat list
String localInput = "User: " + userMessage;
chatList.getItems().add(localInput);
DitGesprek.getGespreksData().add(localInput);
// Generate an automatic response
String automaticResponse = DitGesprek.generateResponse(userMessage);
// Add the automatic response to the chat list
String localOutput = "AI: " + automaticResponse;
chatList.getItems().add(localOutput);
DitGesprek.getGespreksData().add(localOutput);
// Clear the input field
input.clear();
}
@FXML
protected void registerEmployee(ActionEvent event) throws IOException {
Stage stage = (Stage) setting_register.getScene().getWindow();
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("register.fxml"));
Parent root = fxmlLoader.load();
Stage popupStage = new Stage();
popupStage.initModality(Modality.APPLICATION_MODAL);
popupStage.initOwner(stage);
popupStage.setTitle("Register employee");
popupStage.setScene(new Scene(root));
// Access the controller of the loaded FXML file if needed
registrationController registrationController = fxmlLoader.getController();
registrationController.setregistrationController(DB);
registrationController.setStage();
// Show the popup window
popupStage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
@FXML
public void LogoutButton(ActionEvent event) throws IOException {
// Stap 1: Het gesprek opslaan
DitGesprek.saveConversation(conversation);
// Stap 2: Uitloggen en navigeren naar het startscherm
root = FXMLLoader.load(getClass().getResource("startLogin.fxml"));
stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
private void loadConversation() {
try {
// Lees het tekstbestand "conversation.txt"
BufferedReader reader = new BufferedReader(new FileReader("conversation.txt"));
String line;
while ((line = reader.readLine()) != null) {
// Voeg elk bericht toe aan de gesprekkenlijst
conversation.add(line);
}
reader.close();
System.out.println("Gesprek geladen.");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
ThemaToepasser();
scale = new Scale();
scale.setX(1.0);
scale.setY(1.0);
achtergrond.getTransforms().setAll(scale);
showSettings.setText(bundle.getString("Settings"));
input.setPromptText(bundle.getString("PromptText"));
// Submit.setText(bundle.getString("Submit"));
closeSettings.setText(bundle.getString("closesettings"));
advanced.setText(bundle.getString("advanced"));
edituser.setText(bundle.getString("edituser"));
language.setText(bundle.getString("Taal"));
setting_register.setText(bundle.getString("settingsregister"));
Gesprekken = new ArrayList<Gesprek>();
Gesprek EersteGesprek = new Gesprek();
Gesprekken.add(EersteGesprek);
}
// WIP
private ArrayList<Gesprek> Gesprekken;
private Gesprek LocaalGesprek;
private int GesprekId = 0;
private int gesprekidCounter = 0;
@FXML private ListView<String> GesprekOnderwerpen;
@FXML private Button NieuweGesprek;
public int GesprekIdCounter() {
int id = gesprekidCounter;
gesprekidCounter++;
return id;
}
public void NieuwGesprek() {
// maak een nieuw gesprek
Gesprek gesprek = Manager.newGesprek();
// clear het label
OnderwerpLabel.setText("");
// Voeg het gesprek toe aan de lijst met gesprekken
Gesprekken.add(gesprek);
// verander het<SUF>
this.GesprekId = gesprek.getId();
//"open" een gesprek door de vorige text te verwijderen
chatList.getItems().clear();
}
public void SelecteerdChat() {
String SelectedChat = GesprekOnderwerpen.getSelectionModel().getSelectedItem();
for (Gesprek gesprek : Gesprekken) {
if (SelectedChat.equals(gesprek.getOnderwerp())) {
// Selecteer gesprek gebaseerd op onderwerp
Gesprek CurrentGesprek = gesprek;
this.GesprekId = CurrentGesprek.getId();
// Laad de nieuwe chat
ArrayList<String> gespreksData = CurrentGesprek.getGespreksData();
Laadchat(gespreksData);
OnderwerpLabel.setText(CurrentGesprek.getOnderwerp());
}
}
}
public void Laadchat(ArrayList<String> gespreksData) {
chatList.getItems().clear();
for (int i = 0; i < gespreksData.size(); i++) {
String str = gespreksData.get(i);
if (i % 2 == 0) {
chatList.getItems().add(str);
} else {
chatList.getItems().add(str);
}
}
}
public void toevoegenGesprekAanGesprekkenLijst(Gesprek gesprek) {
GesprekOnderwerpen.getItems().add(gesprek.getOnderwerp());
}
public Gesprek getGesprek() {
Gesprek DitGesprek = null;
for (Gesprek gesprek : Gesprekken) {
if (gesprek.getId() == GesprekId) {
DitGesprek = gesprek;
}
}
return DitGesprek;
}
public void WeizigOnderwerp() {
// weizig het onderwerp code
GesprekOnderwerpen.refresh();
}
@FXML
public void loguit(ActionEvent event) throws IOException {
root = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("startLogin.fxml")));
stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
} |
124982_5 | package dev.tilegame;
import dev.tilegame.Display.Display;
import dev.tilegame.gfx.Assets;
import dev.tilegame.gfx.ImageLoader;
import dev.tilegame.gfx.SpriteSheet;
import dev.tilegame.input.KeyManager;
import dev.tilegame.states.GameState;
import dev.tilegame.states.MenuState;
import dev.tilegame.states.State;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
public class Game implements Runnable {
private Display display;
public int width;
public int height;
public String title;
private boolean running;
private Thread thread;
private BufferStrategy bs; // zorgt voor het vlot tonen van de graphics || geen flickering
private Graphics g; // maakt het mogelijk om te tekenen op Canvas
//input
private KeyManager keyManager;
//states
private State gameState;
private State menuState;
public Game(String title, int width, int height){
this.width = width;
this.height = height;
this.title = title;
running = false;
keyManager = new KeyManager();
}
private void init(){
display = new Display(title,width,height);
display.getFrame().addKeyListener(keyManager);
Assets.init();
gameState = new GameState(this);
menuState = new MenuState(this);
State.setState(gameState);
}
private void tick(){
keyManager.tick();
if(gameState != null){
State.getState().tick();
}
}
/**
* renderd de grafische componenten
*/
private void render(){
bs = display.getCanvas().getBufferStrategy();
if(bs == null){
// aanmaken van bufferStrategy als deze nog niet bestaat
display.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
// leeg het scherm
g.clearRect(0,0,width,height);
// tekenen begin
if(gameState != null){
State.getState().render(g);
}
// einde tekenen
bs.show();
g.dispose();
}
@Override
public void run() {
init();
int fps = 60;
double timePerTick = 1000000000/fps;// 1 sec in nanosec gedeeld door aantal frames per seconde
double delta = 0;
long now;
long lastTime = System.nanoTime();
long timer = 0;
int ticks = 0;
// game loop
while(running){
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
timer += now - lastTime;
lastTime = now;
if(delta >= 1){
tick();
render();
ticks++;
delta--;
}
if(timer >= 1000000000){
System.out.println("ticks and frames: " + ticks);
ticks = 0;
timer = 0;
}
}
stop();
}
public KeyManager getKeyManager(){return keyManager;}
/**
* start de Thread bij het opstarten van het programma
*/
public synchronized void start(){
if(running){
return;
}
running = true;
thread = new Thread(this);
thread.start();
}
/**
* Stop de Thread op een veilige manier bij het afsluiten
*/
public synchronized void stop(){
if(!running){
return;
}
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| Ian-Gyssels/Simple_game | Simple game/src/dev/tilegame/Game.java | 1,020 | // 1 sec in nanosec gedeeld door aantal frames per seconde | line_comment | nl | package dev.tilegame;
import dev.tilegame.Display.Display;
import dev.tilegame.gfx.Assets;
import dev.tilegame.gfx.ImageLoader;
import dev.tilegame.gfx.SpriteSheet;
import dev.tilegame.input.KeyManager;
import dev.tilegame.states.GameState;
import dev.tilegame.states.MenuState;
import dev.tilegame.states.State;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
public class Game implements Runnable {
private Display display;
public int width;
public int height;
public String title;
private boolean running;
private Thread thread;
private BufferStrategy bs; // zorgt voor het vlot tonen van de graphics || geen flickering
private Graphics g; // maakt het mogelijk om te tekenen op Canvas
//input
private KeyManager keyManager;
//states
private State gameState;
private State menuState;
public Game(String title, int width, int height){
this.width = width;
this.height = height;
this.title = title;
running = false;
keyManager = new KeyManager();
}
private void init(){
display = new Display(title,width,height);
display.getFrame().addKeyListener(keyManager);
Assets.init();
gameState = new GameState(this);
menuState = new MenuState(this);
State.setState(gameState);
}
private void tick(){
keyManager.tick();
if(gameState != null){
State.getState().tick();
}
}
/**
* renderd de grafische componenten
*/
private void render(){
bs = display.getCanvas().getBufferStrategy();
if(bs == null){
// aanmaken van bufferStrategy als deze nog niet bestaat
display.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
// leeg het scherm
g.clearRect(0,0,width,height);
// tekenen begin
if(gameState != null){
State.getState().render(g);
}
// einde tekenen
bs.show();
g.dispose();
}
@Override
public void run() {
init();
int fps = 60;
double timePerTick = 1000000000/fps;// 1 sec<SUF>
double delta = 0;
long now;
long lastTime = System.nanoTime();
long timer = 0;
int ticks = 0;
// game loop
while(running){
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
timer += now - lastTime;
lastTime = now;
if(delta >= 1){
tick();
render();
ticks++;
delta--;
}
if(timer >= 1000000000){
System.out.println("ticks and frames: " + ticks);
ticks = 0;
timer = 0;
}
}
stop();
}
public KeyManager getKeyManager(){return keyManager;}
/**
* start de Thread bij het opstarten van het programma
*/
public synchronized void start(){
if(running){
return;
}
running = true;
thread = new Thread(this);
thread.start();
}
/**
* Stop de Thread op een veilige manier bij het afsluiten
*/
public synchronized void stop(){
if(!running){
return;
}
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
44720_18 | package org.panel;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
public class Panel extends LinearLayout {
private static final String TAG = "Panel";
/**
* Callback invoked when the panel is opened/closed.
*/
public static interface OnPanelListener {
/**
* Invoked when the panel becomes fully closed.
*/
public void onPanelClosed(Panel panel);
/**
* Invoked when the panel becomes fully opened.
*/
public void onPanelOpened(Panel panel);
}
private boolean mIsShrinking;
private int mPosition;
private int mDuration;
private boolean mLinearFlying;
private View mHandle;
private View mContent;
private Drawable mOpenedHandle;
private Drawable mClosedHandle;
private float mTrackX;
private float mTrackY;
private float mVelocity;
private OnPanelListener panelListener;
public static final int TOP = 0;
public static final int BOTTOM = 1;
public static final int LEFT = 2;
public static final int RIGHT = 3;
private enum State {
ABOUT_TO_ANIMATE,
ANIMATING,
READY,
TRACKING,
FLYING,
};
private State mState;
private Interpolator mInterpolator;
private GestureDetector mGestureDetector;
private int mContentHeight;
private int mContentWidth;
private int mOrientation;
private PanelOnGestureListener mGestureListener;
public Panel(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Panel);
mDuration = a.getInteger(R.styleable.Panel_animationDuration, 750); // duration defaults to 750 ms
mPosition = a.getInteger(R.styleable.Panel_position, BOTTOM); // position defaults to BOTTOM
mLinearFlying = a.getBoolean(R.styleable.Panel_linearFlying, false); // linearFlying defaults to false
mOpenedHandle = a.getDrawable(R.styleable.Panel_openedHandle);
mClosedHandle = a.getDrawable(R.styleable.Panel_closedHandle);
a.recycle();
mOrientation = (mPosition == TOP || mPosition == BOTTOM)? VERTICAL : HORIZONTAL;
setOrientation(mOrientation);
mState = State.READY;
mGestureListener = new PanelOnGestureListener();
mGestureDetector = new GestureDetector(mGestureListener);
mGestureDetector.setIsLongpressEnabled(false);
}
/**
* Sets the listener that receives a notification when the panel becomes open/close.
*
* @param onPanelListener The listener to be notified when the panel is opened/closed.
*/
public void setOnPanelListener(OnPanelListener onPanelListener) {
panelListener = onPanelListener;
}
/**
* Gets Panel's mHandle
*
* @return Panel's mHandle
*/
public View getHandle() {
return mHandle;
}
/**
* Gets Panel's mContent
*
* @return Panel's mContent
*/
public View getContent() {
return mContent;
}
/**
* Sets the acceleration curve for panel's animation.
*
* @param i The interpolator which defines the acceleration curve
*/
public void setInterpolator(Interpolator i) {
mInterpolator = i;
}
/**
* Set the opened state of Panel.
*
* @param open True if Panel is to be opened, false if Panel is to be closed.
* @param animate True if use animation, false otherwise.
*
*/
public void setOpen(boolean open, boolean animate) {
if (isOpen() ^ open) {
mIsShrinking = !open;
if (animate) {
mState = State.ABOUT_TO_ANIMATE;
if (!mIsShrinking) {
// this could make flicker so we test mState in dispatchDraw()
// to see if is equal to ABOUT_TO_ANIMATE
mContent.setVisibility(VISIBLE);
}
post(startAnimation);
} else {
mContent.setVisibility(open? VISIBLE : GONE);
postProcess();
}
}
}
/**
* Returns the opened status for Panel.
*
* @return True if Panel is opened, false otherwise.
*/
public boolean isOpen() {
return mContent.getVisibility() == VISIBLE;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mHandle = findViewById(R.id.panelHandle);
if (mHandle == null) {
throw new RuntimeException("Your Panel must have a View whose id attribute is 'R.id.panelHandle'");
}
mHandle.setOnTouchListener(touchListener);
mContent = findViewById(R.id.panelContent);
if (mContent == null) {
throw new RuntimeException("Your Panel must have a View whose id attribute is 'R.id.panelContent'");
}
// reposition children
removeView(mHandle);
removeView(mContent);
if (mPosition == TOP || mPosition == LEFT) {
addView(mContent);
addView(mHandle);
} else {
addView(mHandle);
addView(mContent);
}
if (mClosedHandle != null) {
mHandle.setBackgroundDrawable(mClosedHandle);
}
mContent.setVisibility(GONE);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
mContentWidth = mContent.getWidth();
mContentHeight = mContent.getHeight();
}
@Override
protected void dispatchDraw(Canvas canvas) {
// String name = getResources().getResourceEntryName(getId());
// Log.d(TAG, name + " ispatchDraw " + mState);
// this is why 'mState' was added:
// avoid flicker before animation start
if (mState == State.ABOUT_TO_ANIMATE && !mIsShrinking) {
int delta = mOrientation == VERTICAL? mContentHeight : mContentWidth;
if (mPosition == LEFT || mPosition == TOP) {
delta = -delta;
}
if (mOrientation == VERTICAL) {
canvas.translate(0, delta);
} else {
canvas.translate(delta, 0);
}
}
if (mState == State.TRACKING || mState == State.FLYING) {
canvas.translate(mTrackX, mTrackY);
}
super.dispatchDraw(canvas);
}
private float ensureRange(float v, int min, int max) {
v = Math.max(v, min);
v = Math.min(v, max);
return v;
}
OnTouchListener touchListener = new OnTouchListener() {
int initX;
int initY;
boolean setInitialPosition;
public boolean onTouch(View v, MotionEvent event) {
// Log.d(TAG, "state: " + mState + " x: " + event.getX() + " y: " + event.getY());
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
initX = 0;
initY = 0;
if (mContent.getVisibility() == GONE) {
// since we may not know content dimensions we use factors here
if (mOrientation == VERTICAL) {
initY = mPosition == TOP? -1 : 1;
} else {
initX = mPosition == LEFT? -1 : 1;
}
}
setInitialPosition = true;
} else {
if (setInitialPosition) {
// now we know content dimensions, so we multiply factors...
initX *= mContentWidth;
initY *= mContentHeight;
// ... and set initial panel's position
mGestureListener.setScroll(initX, initY);
setInitialPosition = false;
// for offsetLocation we have to invert values
initX = -initX;
initY = -initY;
}
// offset every ACTION_MOVE & ACTION_UP event
event.offsetLocation(initX, initY);
}
if (!mGestureDetector.onTouchEvent(event)) {
if (action == MotionEvent.ACTION_UP) {
// tup up after scrolling
post(startAnimation);
}
}
return false;
}
};
Runnable startAnimation = new Runnable() {
public void run() {
// this is why we post this Runnable couple of lines above:
// now its save to use mContent.getHeight() && mContent.getWidth()
TranslateAnimation animation;
int fromXDelta = 0, toXDelta = 0, fromYDelta = 0, toYDelta = 0;
if (mState == State.FLYING) {
mIsShrinking = (mPosition == TOP || mPosition == LEFT) ^ (mVelocity > 0);
}
int calculatedDuration;
if (mOrientation == VERTICAL) {
int height = mContentHeight;
if (!mIsShrinking) {
fromYDelta = mPosition == TOP? -height : height;
} else {
toYDelta = mPosition == TOP? -height : height;
}
if (mState == State.TRACKING) {
if (Math.abs(mTrackY - fromYDelta) < Math.abs(mTrackY - toYDelta)) {
mIsShrinking = !mIsShrinking;
toYDelta = fromYDelta;
}
fromYDelta = (int) mTrackY;
} else
if (mState == State.FLYING) {
fromYDelta = (int) mTrackY;
}
// for FLYING events we calculate animation duration based on flying velocity
// also for very high velocity make sure duration >= 20 ms
if (mState == State.FLYING && mLinearFlying) {
calculatedDuration = (int) (1000 * Math.abs((toYDelta - fromYDelta) / mVelocity));
calculatedDuration = Math.max(calculatedDuration, 20);
} else {
calculatedDuration = mDuration * Math.abs(toYDelta - fromYDelta) / mContentHeight;
}
} else {
int width = mContentWidth;
if (!mIsShrinking) {
fromXDelta = mPosition == LEFT? -width : width;
} else {
toXDelta = mPosition == LEFT? -width : width;
}
if (mState == State.TRACKING) {
if (Math.abs(mTrackX - fromXDelta) < Math.abs(mTrackX - toXDelta)) {
mIsShrinking = !mIsShrinking;
toXDelta = fromXDelta;
}
fromXDelta = (int) mTrackX;
} else
if (mState == State.FLYING) {
fromXDelta = (int) mTrackX;
}
// for FLYING events we calculate animation duration based on flying velocity
// also for very high velocity make sure duration >= 20 ms
if (mState == State.FLYING && mLinearFlying) {
calculatedDuration = (int) (1000 * Math.abs((toXDelta - fromXDelta) / mVelocity));
calculatedDuration = Math.max(calculatedDuration, 20);
} else {
calculatedDuration = mDuration * Math.abs(toXDelta - fromXDelta) / mContentWidth;
}
}
mTrackX = mTrackY = 0;
if (calculatedDuration == 0) {
mState = State.READY;
if (mIsShrinking) {
mContent.setVisibility(GONE);
}
postProcess();
return;
}
animation = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta);
animation.setDuration(calculatedDuration);
animation.setAnimationListener(animationListener);
if (mState == State.FLYING && mLinearFlying) {
animation.setInterpolator(new LinearInterpolator());
} else
if (mInterpolator != null) {
animation.setInterpolator(mInterpolator);
}
startAnimation(animation);
}
};
private AnimationListener animationListener = new AnimationListener() {
public void onAnimationEnd(Animation animation) {
mState = State.READY;
if (mIsShrinking) {
mContent.setVisibility(GONE);
}
postProcess();
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationStart(Animation animation) {
mState = State.ANIMATING;
}
};
private void postProcess() {
if (mIsShrinking && mClosedHandle != null) {
mHandle.setBackgroundDrawable(mClosedHandle);
} else
if (!mIsShrinking && mOpenedHandle != null) {
mHandle.setBackgroundDrawable(mOpenedHandle);
}
// invoke listener if any
if (panelListener != null) {
if (mIsShrinking) {
panelListener.onPanelClosed(Panel.this);
} else {
panelListener.onPanelOpened(Panel.this);
}
}
}
class PanelOnGestureListener implements OnGestureListener {
float scrollY;
float scrollX;
public void setScroll(int initScrollX, int initScrollY) {
scrollX = initScrollX;
scrollY = initScrollY;
}
public boolean onDown(MotionEvent e) {
scrollX = scrollY = 0;
if (mState != State.READY) {
// we are animating or just about to animate
return false;
}
mState = State.ABOUT_TO_ANIMATE;
mIsShrinking = mContent.getVisibility() == VISIBLE;
if (!mIsShrinking) {
// this could make flicker so we test mState in dispatchDraw()
// to see if is equal to ABOUT_TO_ANIMATE
mContent.setVisibility(VISIBLE);
}
return true;
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
mState = State.FLYING;
mVelocity = mOrientation == VERTICAL? velocityY : velocityX;
post(startAnimation);
return true;
}
public void onLongPress(MotionEvent e) {
// not used
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
mState = State.TRACKING;
float tmpY = 0, tmpX = 0;
if (mOrientation == VERTICAL) {
scrollY -= distanceY;
if (mPosition == TOP) {
tmpY = ensureRange(scrollY, -mContentHeight, 0);
} else {
tmpY = ensureRange(scrollY, 0, mContentHeight);
}
} else {
scrollX -= distanceX;
if (mPosition == LEFT) {
tmpX = ensureRange(scrollX, -mContentWidth, 0);
} else {
tmpX = ensureRange(scrollX, 0, mContentWidth);
}
}
if (tmpX != mTrackX || tmpY != mTrackY) {
mTrackX = tmpX;
mTrackY = tmpY;
invalidate();
}
return true;
}
public void onShowPress(MotionEvent e) {
// not used
}
public boolean onSingleTapUp(MotionEvent e) {
// simple tap: click
post(startAnimation);
return true;
}
}
}
| IanDarwin/Android-Cookbook-Examples | SlidingDrawer-Topdown/src/org/panel/Panel.java | 4,566 | // Log.d(TAG, "state: " + mState + " x: " + event.getX() + " y: " + event.getY()); | line_comment | nl | package org.panel;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
public class Panel extends LinearLayout {
private static final String TAG = "Panel";
/**
* Callback invoked when the panel is opened/closed.
*/
public static interface OnPanelListener {
/**
* Invoked when the panel becomes fully closed.
*/
public void onPanelClosed(Panel panel);
/**
* Invoked when the panel becomes fully opened.
*/
public void onPanelOpened(Panel panel);
}
private boolean mIsShrinking;
private int mPosition;
private int mDuration;
private boolean mLinearFlying;
private View mHandle;
private View mContent;
private Drawable mOpenedHandle;
private Drawable mClosedHandle;
private float mTrackX;
private float mTrackY;
private float mVelocity;
private OnPanelListener panelListener;
public static final int TOP = 0;
public static final int BOTTOM = 1;
public static final int LEFT = 2;
public static final int RIGHT = 3;
private enum State {
ABOUT_TO_ANIMATE,
ANIMATING,
READY,
TRACKING,
FLYING,
};
private State mState;
private Interpolator mInterpolator;
private GestureDetector mGestureDetector;
private int mContentHeight;
private int mContentWidth;
private int mOrientation;
private PanelOnGestureListener mGestureListener;
public Panel(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Panel);
mDuration = a.getInteger(R.styleable.Panel_animationDuration, 750); // duration defaults to 750 ms
mPosition = a.getInteger(R.styleable.Panel_position, BOTTOM); // position defaults to BOTTOM
mLinearFlying = a.getBoolean(R.styleable.Panel_linearFlying, false); // linearFlying defaults to false
mOpenedHandle = a.getDrawable(R.styleable.Panel_openedHandle);
mClosedHandle = a.getDrawable(R.styleable.Panel_closedHandle);
a.recycle();
mOrientation = (mPosition == TOP || mPosition == BOTTOM)? VERTICAL : HORIZONTAL;
setOrientation(mOrientation);
mState = State.READY;
mGestureListener = new PanelOnGestureListener();
mGestureDetector = new GestureDetector(mGestureListener);
mGestureDetector.setIsLongpressEnabled(false);
}
/**
* Sets the listener that receives a notification when the panel becomes open/close.
*
* @param onPanelListener The listener to be notified when the panel is opened/closed.
*/
public void setOnPanelListener(OnPanelListener onPanelListener) {
panelListener = onPanelListener;
}
/**
* Gets Panel's mHandle
*
* @return Panel's mHandle
*/
public View getHandle() {
return mHandle;
}
/**
* Gets Panel's mContent
*
* @return Panel's mContent
*/
public View getContent() {
return mContent;
}
/**
* Sets the acceleration curve for panel's animation.
*
* @param i The interpolator which defines the acceleration curve
*/
public void setInterpolator(Interpolator i) {
mInterpolator = i;
}
/**
* Set the opened state of Panel.
*
* @param open True if Panel is to be opened, false if Panel is to be closed.
* @param animate True if use animation, false otherwise.
*
*/
public void setOpen(boolean open, boolean animate) {
if (isOpen() ^ open) {
mIsShrinking = !open;
if (animate) {
mState = State.ABOUT_TO_ANIMATE;
if (!mIsShrinking) {
// this could make flicker so we test mState in dispatchDraw()
// to see if is equal to ABOUT_TO_ANIMATE
mContent.setVisibility(VISIBLE);
}
post(startAnimation);
} else {
mContent.setVisibility(open? VISIBLE : GONE);
postProcess();
}
}
}
/**
* Returns the opened status for Panel.
*
* @return True if Panel is opened, false otherwise.
*/
public boolean isOpen() {
return mContent.getVisibility() == VISIBLE;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mHandle = findViewById(R.id.panelHandle);
if (mHandle == null) {
throw new RuntimeException("Your Panel must have a View whose id attribute is 'R.id.panelHandle'");
}
mHandle.setOnTouchListener(touchListener);
mContent = findViewById(R.id.panelContent);
if (mContent == null) {
throw new RuntimeException("Your Panel must have a View whose id attribute is 'R.id.panelContent'");
}
// reposition children
removeView(mHandle);
removeView(mContent);
if (mPosition == TOP || mPosition == LEFT) {
addView(mContent);
addView(mHandle);
} else {
addView(mHandle);
addView(mContent);
}
if (mClosedHandle != null) {
mHandle.setBackgroundDrawable(mClosedHandle);
}
mContent.setVisibility(GONE);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
mContentWidth = mContent.getWidth();
mContentHeight = mContent.getHeight();
}
@Override
protected void dispatchDraw(Canvas canvas) {
// String name = getResources().getResourceEntryName(getId());
// Log.d(TAG, name + " ispatchDraw " + mState);
// this is why 'mState' was added:
// avoid flicker before animation start
if (mState == State.ABOUT_TO_ANIMATE && !mIsShrinking) {
int delta = mOrientation == VERTICAL? mContentHeight : mContentWidth;
if (mPosition == LEFT || mPosition == TOP) {
delta = -delta;
}
if (mOrientation == VERTICAL) {
canvas.translate(0, delta);
} else {
canvas.translate(delta, 0);
}
}
if (mState == State.TRACKING || mState == State.FLYING) {
canvas.translate(mTrackX, mTrackY);
}
super.dispatchDraw(canvas);
}
private float ensureRange(float v, int min, int max) {
v = Math.max(v, min);
v = Math.min(v, max);
return v;
}
OnTouchListener touchListener = new OnTouchListener() {
int initX;
int initY;
boolean setInitialPosition;
public boolean onTouch(View v, MotionEvent event) {
// Log.d(TAG, "state:<SUF>
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
initX = 0;
initY = 0;
if (mContent.getVisibility() == GONE) {
// since we may not know content dimensions we use factors here
if (mOrientation == VERTICAL) {
initY = mPosition == TOP? -1 : 1;
} else {
initX = mPosition == LEFT? -1 : 1;
}
}
setInitialPosition = true;
} else {
if (setInitialPosition) {
// now we know content dimensions, so we multiply factors...
initX *= mContentWidth;
initY *= mContentHeight;
// ... and set initial panel's position
mGestureListener.setScroll(initX, initY);
setInitialPosition = false;
// for offsetLocation we have to invert values
initX = -initX;
initY = -initY;
}
// offset every ACTION_MOVE & ACTION_UP event
event.offsetLocation(initX, initY);
}
if (!mGestureDetector.onTouchEvent(event)) {
if (action == MotionEvent.ACTION_UP) {
// tup up after scrolling
post(startAnimation);
}
}
return false;
}
};
Runnable startAnimation = new Runnable() {
public void run() {
// this is why we post this Runnable couple of lines above:
// now its save to use mContent.getHeight() && mContent.getWidth()
TranslateAnimation animation;
int fromXDelta = 0, toXDelta = 0, fromYDelta = 0, toYDelta = 0;
if (mState == State.FLYING) {
mIsShrinking = (mPosition == TOP || mPosition == LEFT) ^ (mVelocity > 0);
}
int calculatedDuration;
if (mOrientation == VERTICAL) {
int height = mContentHeight;
if (!mIsShrinking) {
fromYDelta = mPosition == TOP? -height : height;
} else {
toYDelta = mPosition == TOP? -height : height;
}
if (mState == State.TRACKING) {
if (Math.abs(mTrackY - fromYDelta) < Math.abs(mTrackY - toYDelta)) {
mIsShrinking = !mIsShrinking;
toYDelta = fromYDelta;
}
fromYDelta = (int) mTrackY;
} else
if (mState == State.FLYING) {
fromYDelta = (int) mTrackY;
}
// for FLYING events we calculate animation duration based on flying velocity
// also for very high velocity make sure duration >= 20 ms
if (mState == State.FLYING && mLinearFlying) {
calculatedDuration = (int) (1000 * Math.abs((toYDelta - fromYDelta) / mVelocity));
calculatedDuration = Math.max(calculatedDuration, 20);
} else {
calculatedDuration = mDuration * Math.abs(toYDelta - fromYDelta) / mContentHeight;
}
} else {
int width = mContentWidth;
if (!mIsShrinking) {
fromXDelta = mPosition == LEFT? -width : width;
} else {
toXDelta = mPosition == LEFT? -width : width;
}
if (mState == State.TRACKING) {
if (Math.abs(mTrackX - fromXDelta) < Math.abs(mTrackX - toXDelta)) {
mIsShrinking = !mIsShrinking;
toXDelta = fromXDelta;
}
fromXDelta = (int) mTrackX;
} else
if (mState == State.FLYING) {
fromXDelta = (int) mTrackX;
}
// for FLYING events we calculate animation duration based on flying velocity
// also for very high velocity make sure duration >= 20 ms
if (mState == State.FLYING && mLinearFlying) {
calculatedDuration = (int) (1000 * Math.abs((toXDelta - fromXDelta) / mVelocity));
calculatedDuration = Math.max(calculatedDuration, 20);
} else {
calculatedDuration = mDuration * Math.abs(toXDelta - fromXDelta) / mContentWidth;
}
}
mTrackX = mTrackY = 0;
if (calculatedDuration == 0) {
mState = State.READY;
if (mIsShrinking) {
mContent.setVisibility(GONE);
}
postProcess();
return;
}
animation = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta);
animation.setDuration(calculatedDuration);
animation.setAnimationListener(animationListener);
if (mState == State.FLYING && mLinearFlying) {
animation.setInterpolator(new LinearInterpolator());
} else
if (mInterpolator != null) {
animation.setInterpolator(mInterpolator);
}
startAnimation(animation);
}
};
private AnimationListener animationListener = new AnimationListener() {
public void onAnimationEnd(Animation animation) {
mState = State.READY;
if (mIsShrinking) {
mContent.setVisibility(GONE);
}
postProcess();
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationStart(Animation animation) {
mState = State.ANIMATING;
}
};
private void postProcess() {
if (mIsShrinking && mClosedHandle != null) {
mHandle.setBackgroundDrawable(mClosedHandle);
} else
if (!mIsShrinking && mOpenedHandle != null) {
mHandle.setBackgroundDrawable(mOpenedHandle);
}
// invoke listener if any
if (panelListener != null) {
if (mIsShrinking) {
panelListener.onPanelClosed(Panel.this);
} else {
panelListener.onPanelOpened(Panel.this);
}
}
}
class PanelOnGestureListener implements OnGestureListener {
float scrollY;
float scrollX;
public void setScroll(int initScrollX, int initScrollY) {
scrollX = initScrollX;
scrollY = initScrollY;
}
public boolean onDown(MotionEvent e) {
scrollX = scrollY = 0;
if (mState != State.READY) {
// we are animating or just about to animate
return false;
}
mState = State.ABOUT_TO_ANIMATE;
mIsShrinking = mContent.getVisibility() == VISIBLE;
if (!mIsShrinking) {
// this could make flicker so we test mState in dispatchDraw()
// to see if is equal to ABOUT_TO_ANIMATE
mContent.setVisibility(VISIBLE);
}
return true;
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
mState = State.FLYING;
mVelocity = mOrientation == VERTICAL? velocityY : velocityX;
post(startAnimation);
return true;
}
public void onLongPress(MotionEvent e) {
// not used
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
mState = State.TRACKING;
float tmpY = 0, tmpX = 0;
if (mOrientation == VERTICAL) {
scrollY -= distanceY;
if (mPosition == TOP) {
tmpY = ensureRange(scrollY, -mContentHeight, 0);
} else {
tmpY = ensureRange(scrollY, 0, mContentHeight);
}
} else {
scrollX -= distanceX;
if (mPosition == LEFT) {
tmpX = ensureRange(scrollX, -mContentWidth, 0);
} else {
tmpX = ensureRange(scrollX, 0, mContentWidth);
}
}
if (tmpX != mTrackX || tmpY != mTrackY) {
mTrackX = tmpX;
mTrackY = tmpY;
invalidate();
}
return true;
}
public void onShowPress(MotionEvent e) {
// not used
}
public boolean onSingleTapUp(MotionEvent e) {
// simple tap: click
post(startAnimation);
return true;
}
}
}
|
14017_0 | package alphareversi.commands.receive;
import alphareversi.commands.CommandParser;
import alphareversi.commands.RecvCommand;
import java.util.HashMap;
/**
* Created by Joost van Berkel on 3/24/2016.
* Resultaat van een zet ontvangen, bericht naar beide spelers.
* S: SVR GAME MOVE {PLAYER: "--speler--", DETAILS: "--reactie spel op zet--", MOVE:"--zet--"}
* Er is een zet gedaan, dit bericht geeft aan wie deze gezet heeft,
* wat de reactie van het spel erop is
*/
public class RecvGameMoveCommand extends RecvCommand {
private String player;
private String details;
private String move;
/**
* Parse string to create a filled RecvGamelistCommand.
* @param command string containing server message
*/
public RecvGameMoveCommand(String command) {
String[] parts = command.split(" ", 4);
this.setType(parts[0]);
this.setMethod(parts[1]);
this.setAction(parts[2]);
HashMap objects = CommandParser.parseObjectMap(parts[3]);
this.setPlayer((String) objects.get("PLAYER"));
this.setDetails((String) objects.get("DETAILS"));
this.setMove((String) objects.get("MOVE"));
}
public String getPlayer() {
return player;
}
public void setPlayer(String player) {
this.player = player;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getMove() {
return move;
}
public void setMove(String move) {
this.move = move;
}
}
| IcyPalm/AlphaReversi | src/alphareversi/commands/receive/RecvGameMoveCommand.java | 480 | /**
* Created by Joost van Berkel on 3/24/2016.
* Resultaat van een zet ontvangen, bericht naar beide spelers.
* S: SVR GAME MOVE {PLAYER: "--speler--", DETAILS: "--reactie spel op zet--", MOVE:"--zet--"}
* Er is een zet gedaan, dit bericht geeft aan wie deze gezet heeft,
* wat de reactie van het spel erop is
*/ | block_comment | nl | package alphareversi.commands.receive;
import alphareversi.commands.CommandParser;
import alphareversi.commands.RecvCommand;
import java.util.HashMap;
/**
* Created by Joost<SUF>*/
public class RecvGameMoveCommand extends RecvCommand {
private String player;
private String details;
private String move;
/**
* Parse string to create a filled RecvGamelistCommand.
* @param command string containing server message
*/
public RecvGameMoveCommand(String command) {
String[] parts = command.split(" ", 4);
this.setType(parts[0]);
this.setMethod(parts[1]);
this.setAction(parts[2]);
HashMap objects = CommandParser.parseObjectMap(parts[3]);
this.setPlayer((String) objects.get("PLAYER"));
this.setDetails((String) objects.get("DETAILS"));
this.setMove((String) objects.get("MOVE"));
}
public String getPlayer() {
return player;
}
public void setPlayer(String player) {
this.player = player;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getMove() {
return move;
}
public void setMove(String move) {
this.move = move;
}
}
|
131126_5 | package nl.ealse.ccnl.ledenadministratie.dd;
import java.math.BigDecimal;
import java.time.LocalDate;
import nl.ealse.ccnl.ledenadministratie.dd.model.AccountIdentification4Choice;
import nl.ealse.ccnl.ledenadministratie.dd.model.BranchAndFinancialInstitutionIdentification4;
import nl.ealse.ccnl.ledenadministratie.dd.model.CashAccount16;
import nl.ealse.ccnl.ledenadministratie.dd.model.DirectDebitTransactionInformation9;
import nl.ealse.ccnl.ledenadministratie.dd.model.FinancialInstitutionIdentification7;
import nl.ealse.ccnl.ledenadministratie.dd.model.GenericPersonIdentification1;
import nl.ealse.ccnl.ledenadministratie.dd.model.LocalInstrument2Choice;
import nl.ealse.ccnl.ledenadministratie.dd.model.Party6Choice;
import nl.ealse.ccnl.ledenadministratie.dd.model.PartyIdentification32;
import nl.ealse.ccnl.ledenadministratie.dd.model.PaymentInstructionInformation4;
import nl.ealse.ccnl.ledenadministratie.dd.model.PaymentMethod2Code;
import nl.ealse.ccnl.ledenadministratie.dd.model.PaymentTypeInformation20;
import nl.ealse.ccnl.ledenadministratie.dd.model.PersonIdentification5;
import nl.ealse.ccnl.ledenadministratie.dd.model.PersonIdentificationSchemeName1Choice;
import nl.ealse.ccnl.ledenadministratie.dd.model.SequenceType1Code;
import nl.ealse.ccnl.ledenadministratie.dd.model.ServiceLevel8Choice;
import nl.ealse.ccnl.ledenadministratie.excel.dd.BicResolver;
/**
* Bouwen crediteur zijde van de INCASSO
*
* @author Ealse
*
*/
public class PaymentInstructionInformationBuilder {
/**
* Het op te bouwen object
*/
private PaymentInstructionInformation4 paymentInstructionInformation =
new PaymentInstructionInformation4();
public PaymentInstructionInformationBuilder(IncassoProperties properties) {
init(properties);
}
/**
* Betaalinformatie toevoegen.
*
* @param paymentInformation - betaalinformatie
* @return builder
*/
public PaymentInstructionInformationBuilder metPaymentInformation(String paymentInformation) {
paymentInstructionInformation.setPmtInfId(paymentInformation);
return this;
}
/**
* Datum zetten waarop de INCASSO uitgevoerd moet worden.
*
* @param incassodatum - uitvoeringsdatum
* @return builder
*/
public PaymentInstructionInformationBuilder metIncassodatum(LocalDate incassodatum) {
paymentInstructionInformation.setReqdColltnDt(DateUtil.toXMLDate(incassodatum));
return this;
}
/**
* Debit transactie toevoegen.
*
* @param transactie - de toe te voegen transactie
* @return builder
*/
public PaymentInstructionInformationBuilder toevoegenDebitTransactie(
DirectDebitTransactionInformation9 transactie) {
paymentInstructionInformation.getDrctDbtTxInf().add(transactie);
return this;
}
/**
* Het totaal aantal van transacties toevoegen.
*
* @param aantalTransacties - totaal aantal transacties
* @return builder
*/
public PaymentInstructionInformationBuilder metAantalTransacties(Integer aantalTransacties) {
paymentInstructionInformation.setNbOfTxs(aantalTransacties.toString());
return this;
}
/**
* Het totaalbedrag van alle transacties toevoegen.
*
* @param somTransactieBedrag - totale transactiebedrag
* @return builder
*/
public PaymentInstructionInformationBuilder metSomTransactieBedrag(
BigDecimal somTransactieBedrag) {
paymentInstructionInformation.setCtrlSum(somTransactieBedrag);
return this;
}
public PaymentInstructionInformation4 build() {
return paymentInstructionInformation;
}
/**
* Vaste gegevens initiëren.
*/
private void init(IncassoProperties properties) {
paymentInstructionInformation.setBtchBookg(true);
paymentInstructionInformation.setPmtInfId(properties.getMessageId());
paymentInstructionInformation.setPmtMtd(PaymentMethod2Code.DD);
PaymentTypeInformation20 paymentTypeInformation20 = new PaymentTypeInformation20();
ServiceLevel8Choice serviceLevel8Choice = new ServiceLevel8Choice();
serviceLevel8Choice.setCd("SEPA");
paymentTypeInformation20.setSvcLvl(serviceLevel8Choice);
LocalInstrument2Choice localInstrument2Choice = new LocalInstrument2Choice();
localInstrument2Choice.setCd("CORE");
paymentTypeInformation20.setLclInstrm(localInstrument2Choice);
// paymentTypeInformation20.setSeqTp(SequenceType1Code.OOFF); // eenmalige INCASSO
paymentTypeInformation20.setSeqTp(SequenceType1Code.valueOf(properties.getMachtigingType()));
// paymentTypeInformation20.setSeqTp(SequenceType1Code.FRST); // eerste van een serie
// paymentTypeInformation20.setSeqTp(SequenceType1Code.RCUR); // herhaalde INCASSO
paymentInstructionInformation.setPmtTpInf(paymentTypeInformation20);
PartyIdentification32 creditor = new PartyIdentification32();
creditor.setNm(properties.getNaam());
paymentInstructionInformation.setCdtr(creditor);
CashAccount16 ibanRekening = new CashAccount16();
AccountIdentification4Choice ibanNummer = new AccountIdentification4Choice();
ibanNummer.setIBAN(properties.getIbanNummer());
ibanRekening.setId(ibanNummer);
paymentInstructionInformation.setCdtrAcct(ibanRekening);
BranchAndFinancialInstitutionIdentification4 bic =
new BranchAndFinancialInstitutionIdentification4();
FinancialInstitutionIdentification7 finId = new FinancialInstitutionIdentification7();
finId.setBIC(BicResolver.getBicCode(properties.getIbanNummer()));
bic.setFinInstnId(finId);
paymentInstructionInformation.setCdtrAgt(bic);
paymentInstructionInformation.setCdtrSchmeId(buildSchemaId(properties));
}
/**
* Incassant id deel opbouwen.
*
* @return opgebouwde Incassant Id informatie
*/
private PartyIdentification32 buildSchemaId(IncassoProperties properties) {
PartyIdentification32 schemaId = new PartyIdentification32();
schemaId.setNm(properties.getNaam());
Party6Choice id = new Party6Choice();
PersonIdentification5 personId = new PersonIdentification5();
id.setPrvtId(personId);
GenericPersonIdentification1 genId = new GenericPersonIdentification1();
personId.getOthr().add(genId);
genId.setId(properties.getIncassantId());
PersonIdentificationSchemeName1Choice schemaName = new PersonIdentificationSchemeName1Choice();
schemaName.setPrtry("SEPA");
genId.setSchmeNm(schemaName);
schemaId.setId(id);
return schemaId;
}
}
| IdelsTak/ledenadministratieCCNL | annual-ccnl/src/main/java/nl/ealse/ccnl/ledenadministratie/dd/PaymentInstructionInformationBuilder.java | 2,006 | /**
* Het totaal aantal van transacties toevoegen.
*
* @param aantalTransacties - totaal aantal transacties
* @return builder
*/ | block_comment | nl | package nl.ealse.ccnl.ledenadministratie.dd;
import java.math.BigDecimal;
import java.time.LocalDate;
import nl.ealse.ccnl.ledenadministratie.dd.model.AccountIdentification4Choice;
import nl.ealse.ccnl.ledenadministratie.dd.model.BranchAndFinancialInstitutionIdentification4;
import nl.ealse.ccnl.ledenadministratie.dd.model.CashAccount16;
import nl.ealse.ccnl.ledenadministratie.dd.model.DirectDebitTransactionInformation9;
import nl.ealse.ccnl.ledenadministratie.dd.model.FinancialInstitutionIdentification7;
import nl.ealse.ccnl.ledenadministratie.dd.model.GenericPersonIdentification1;
import nl.ealse.ccnl.ledenadministratie.dd.model.LocalInstrument2Choice;
import nl.ealse.ccnl.ledenadministratie.dd.model.Party6Choice;
import nl.ealse.ccnl.ledenadministratie.dd.model.PartyIdentification32;
import nl.ealse.ccnl.ledenadministratie.dd.model.PaymentInstructionInformation4;
import nl.ealse.ccnl.ledenadministratie.dd.model.PaymentMethod2Code;
import nl.ealse.ccnl.ledenadministratie.dd.model.PaymentTypeInformation20;
import nl.ealse.ccnl.ledenadministratie.dd.model.PersonIdentification5;
import nl.ealse.ccnl.ledenadministratie.dd.model.PersonIdentificationSchemeName1Choice;
import nl.ealse.ccnl.ledenadministratie.dd.model.SequenceType1Code;
import nl.ealse.ccnl.ledenadministratie.dd.model.ServiceLevel8Choice;
import nl.ealse.ccnl.ledenadministratie.excel.dd.BicResolver;
/**
* Bouwen crediteur zijde van de INCASSO
*
* @author Ealse
*
*/
public class PaymentInstructionInformationBuilder {
/**
* Het op te bouwen object
*/
private PaymentInstructionInformation4 paymentInstructionInformation =
new PaymentInstructionInformation4();
public PaymentInstructionInformationBuilder(IncassoProperties properties) {
init(properties);
}
/**
* Betaalinformatie toevoegen.
*
* @param paymentInformation - betaalinformatie
* @return builder
*/
public PaymentInstructionInformationBuilder metPaymentInformation(String paymentInformation) {
paymentInstructionInformation.setPmtInfId(paymentInformation);
return this;
}
/**
* Datum zetten waarop de INCASSO uitgevoerd moet worden.
*
* @param incassodatum - uitvoeringsdatum
* @return builder
*/
public PaymentInstructionInformationBuilder metIncassodatum(LocalDate incassodatum) {
paymentInstructionInformation.setReqdColltnDt(DateUtil.toXMLDate(incassodatum));
return this;
}
/**
* Debit transactie toevoegen.
*
* @param transactie - de toe te voegen transactie
* @return builder
*/
public PaymentInstructionInformationBuilder toevoegenDebitTransactie(
DirectDebitTransactionInformation9 transactie) {
paymentInstructionInformation.getDrctDbtTxInf().add(transactie);
return this;
}
/**
* Het totaal aantal<SUF>*/
public PaymentInstructionInformationBuilder metAantalTransacties(Integer aantalTransacties) {
paymentInstructionInformation.setNbOfTxs(aantalTransacties.toString());
return this;
}
/**
* Het totaalbedrag van alle transacties toevoegen.
*
* @param somTransactieBedrag - totale transactiebedrag
* @return builder
*/
public PaymentInstructionInformationBuilder metSomTransactieBedrag(
BigDecimal somTransactieBedrag) {
paymentInstructionInformation.setCtrlSum(somTransactieBedrag);
return this;
}
public PaymentInstructionInformation4 build() {
return paymentInstructionInformation;
}
/**
* Vaste gegevens initiëren.
*/
private void init(IncassoProperties properties) {
paymentInstructionInformation.setBtchBookg(true);
paymentInstructionInformation.setPmtInfId(properties.getMessageId());
paymentInstructionInformation.setPmtMtd(PaymentMethod2Code.DD);
PaymentTypeInformation20 paymentTypeInformation20 = new PaymentTypeInformation20();
ServiceLevel8Choice serviceLevel8Choice = new ServiceLevel8Choice();
serviceLevel8Choice.setCd("SEPA");
paymentTypeInformation20.setSvcLvl(serviceLevel8Choice);
LocalInstrument2Choice localInstrument2Choice = new LocalInstrument2Choice();
localInstrument2Choice.setCd("CORE");
paymentTypeInformation20.setLclInstrm(localInstrument2Choice);
// paymentTypeInformation20.setSeqTp(SequenceType1Code.OOFF); // eenmalige INCASSO
paymentTypeInformation20.setSeqTp(SequenceType1Code.valueOf(properties.getMachtigingType()));
// paymentTypeInformation20.setSeqTp(SequenceType1Code.FRST); // eerste van een serie
// paymentTypeInformation20.setSeqTp(SequenceType1Code.RCUR); // herhaalde INCASSO
paymentInstructionInformation.setPmtTpInf(paymentTypeInformation20);
PartyIdentification32 creditor = new PartyIdentification32();
creditor.setNm(properties.getNaam());
paymentInstructionInformation.setCdtr(creditor);
CashAccount16 ibanRekening = new CashAccount16();
AccountIdentification4Choice ibanNummer = new AccountIdentification4Choice();
ibanNummer.setIBAN(properties.getIbanNummer());
ibanRekening.setId(ibanNummer);
paymentInstructionInformation.setCdtrAcct(ibanRekening);
BranchAndFinancialInstitutionIdentification4 bic =
new BranchAndFinancialInstitutionIdentification4();
FinancialInstitutionIdentification7 finId = new FinancialInstitutionIdentification7();
finId.setBIC(BicResolver.getBicCode(properties.getIbanNummer()));
bic.setFinInstnId(finId);
paymentInstructionInformation.setCdtrAgt(bic);
paymentInstructionInformation.setCdtrSchmeId(buildSchemaId(properties));
}
/**
* Incassant id deel opbouwen.
*
* @return opgebouwde Incassant Id informatie
*/
private PartyIdentification32 buildSchemaId(IncassoProperties properties) {
PartyIdentification32 schemaId = new PartyIdentification32();
schemaId.setNm(properties.getNaam());
Party6Choice id = new Party6Choice();
PersonIdentification5 personId = new PersonIdentification5();
id.setPrvtId(personId);
GenericPersonIdentification1 genId = new GenericPersonIdentification1();
personId.getOthr().add(genId);
genId.setId(properties.getIncassantId());
PersonIdentificationSchemeName1Choice schemaName = new PersonIdentificationSchemeName1Choice();
schemaName.setPrtry("SEPA");
genId.setSchmeNm(schemaName);
schemaId.setId(id);
return schemaId;
}
}
|
55362_0 | package main.application;
/**
* De schimmel F. ellipsoidea wordt erg groot. De fibonacci reeks bepaald het aantal
* centimeters dat de schimmel dagelijks in diameter toeneemt.
* Bereken de omtrek van de schimmel na 1000 dagen groeien.
* Antwoord in centimeters en gebruik de wetenschappelijke notatie,
* rond af op 4 cijfers achter de komma, bijvoorbeeld: 1.0903E+231
*/
public class VraagQuattro {
public static void main(String[] args) {
double a = 0;
double b = 1;
double c = 0;
double d = 2;
for (int i = 3; i <= 1000; i++) {
c = a + b;
d += c;
a = b;
b = c;
}
System.out.println(formatToString(d*Math.PI));
//Answer is: 2.2094E+209
}
private static String formatToString(double d) {
String num = Double.toString(d);
String [] decimal = num.split("\\.");
String [] eNum = num.split("E");
String output = decimal[0] + ".";
char c[] = decimal[1].toCharArray();
for (int i = 0; i < 4; i++){
output += c[i];
}
output += "E+" + eNum[1];
return output;
}
} | Igoranze/Martyrs-mega-project-list | tweakers-devv-contest/src/main/application/VraagQuattro.java | 396 | /**
* De schimmel F. ellipsoidea wordt erg groot. De fibonacci reeks bepaald het aantal
* centimeters dat de schimmel dagelijks in diameter toeneemt.
* Bereken de omtrek van de schimmel na 1000 dagen groeien.
* Antwoord in centimeters en gebruik de wetenschappelijke notatie,
* rond af op 4 cijfers achter de komma, bijvoorbeeld: 1.0903E+231
*/ | block_comment | nl | package main.application;
/**
* De schimmel F.<SUF>*/
public class VraagQuattro {
public static void main(String[] args) {
double a = 0;
double b = 1;
double c = 0;
double d = 2;
for (int i = 3; i <= 1000; i++) {
c = a + b;
d += c;
a = b;
b = c;
}
System.out.println(formatToString(d*Math.PI));
//Answer is: 2.2094E+209
}
private static String formatToString(double d) {
String num = Double.toString(d);
String [] decimal = num.split("\\.");
String [] eNum = num.split("E");
String output = decimal[0] + ".";
char c[] = decimal[1].toCharArray();
for (int i = 0; i < 4; i++){
output += c[i];
}
output += "E+" + eNum[1];
return output;
}
} |
100666_1 | import org.apache.commons.math3.complex.Complex;
import org.apache.commons.math3.transform.DftNormalization;
import org.apache.commons.math3.transform.FastFourierTransformer;
import org.apache.commons.math3.transform.TransformType;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.*;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AudioProcessor {
public static void main(String[] args) {
File audioFile = new File("RecordAudio.wav");
try {
// Open het audiobestand
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
// Bepaal een buffergrootte
int bufferSize = 4096;
byte[] audioData = new byte[bufferSize];
int bytesRead;
// Lees de audiogegevens in de array
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((bytesRead = audioStream.read(audioData, 0, bufferSize)) != -1) {
byteArrayOutputStream.write(audioData, 0, bytesRead);
}
byte[] audioDataArray = byteArrayOutputStream.toByteArray();
System.out.println("Audiogegevens gelezen: " + audioDataArray.length + " bytes");
// Voer Fourier-transformatie uit met Apache Commons Math
double[] audioSamples = new double[audioDataArray.length / 2]; // 2 wegen de stero geluid
for (int i = 0; i < audioSamples.length; i++) {
audioSamples[i] = (double)((audioDataArray[i * 2] & 0xFF) | (audioDataArray[i * 2 + 1] << 8)) / 32768.0;
}
// Calculate the next power of 2 for the length of audioSamples
int powerOf2Length = 1;
while (powerOf2Length < audioSamples.length) {
powerOf2Length *= 2;
}
// Pad the audio data with zeros to the next power of 2
double[] paddedAudioSamples = new double[powerOf2Length];
System.arraycopy(audioSamples, 0, paddedAudioSamples, 0, audioSamples.length);
// Voer de Fourier-transformatie uit op het opgevulde audioSamples
FastFourierTransformer transformer = new FastFourierTransformer(DftNormalization.STANDARD);
Complex[] complexSamples = transformer.transform(paddedAudioSamples, TransformType.FORWARD);
int[] positiveIntSamples = new int[complexSamples.length];
for (int i = 0; i < complexSamples.length; i++) {
complexSamples[i] = Complex.valueOf(complexSamples[i].abs()); // Ensure the value is positive
}
System.out.println(positiveIntSamples.length);
// Save the complexSamples to a text file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("complexSamples.txt"))) {
for (Complex complex : complexSamples) {
writer.write(complex.getReal() + " " + complex.getImaginary() + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
// Nu heb je de frequentiegegevens in de complexSamples-array en kun je verdere verwerking uitvoeren.
// Sluit het audiobestand
audioStream.close();
} catch (UnsupportedAudioFileException | IOException e) {
e.printStackTrace();
}
}
}
| IhabSaf/AudioAnalyzer | AudioProcessor.java | 996 | // Bepaal een buffergrootte
| line_comment | nl | import org.apache.commons.math3.complex.Complex;
import org.apache.commons.math3.transform.DftNormalization;
import org.apache.commons.math3.transform.FastFourierTransformer;
import org.apache.commons.math3.transform.TransformType;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.*;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AudioProcessor {
public static void main(String[] args) {
File audioFile = new File("RecordAudio.wav");
try {
// Open het audiobestand
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
// Bepaal een<SUF>
int bufferSize = 4096;
byte[] audioData = new byte[bufferSize];
int bytesRead;
// Lees de audiogegevens in de array
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((bytesRead = audioStream.read(audioData, 0, bufferSize)) != -1) {
byteArrayOutputStream.write(audioData, 0, bytesRead);
}
byte[] audioDataArray = byteArrayOutputStream.toByteArray();
System.out.println("Audiogegevens gelezen: " + audioDataArray.length + " bytes");
// Voer Fourier-transformatie uit met Apache Commons Math
double[] audioSamples = new double[audioDataArray.length / 2]; // 2 wegen de stero geluid
for (int i = 0; i < audioSamples.length; i++) {
audioSamples[i] = (double)((audioDataArray[i * 2] & 0xFF) | (audioDataArray[i * 2 + 1] << 8)) / 32768.0;
}
// Calculate the next power of 2 for the length of audioSamples
int powerOf2Length = 1;
while (powerOf2Length < audioSamples.length) {
powerOf2Length *= 2;
}
// Pad the audio data with zeros to the next power of 2
double[] paddedAudioSamples = new double[powerOf2Length];
System.arraycopy(audioSamples, 0, paddedAudioSamples, 0, audioSamples.length);
// Voer de Fourier-transformatie uit op het opgevulde audioSamples
FastFourierTransformer transformer = new FastFourierTransformer(DftNormalization.STANDARD);
Complex[] complexSamples = transformer.transform(paddedAudioSamples, TransformType.FORWARD);
int[] positiveIntSamples = new int[complexSamples.length];
for (int i = 0; i < complexSamples.length; i++) {
complexSamples[i] = Complex.valueOf(complexSamples[i].abs()); // Ensure the value is positive
}
System.out.println(positiveIntSamples.length);
// Save the complexSamples to a text file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("complexSamples.txt"))) {
for (Complex complex : complexSamples) {
writer.write(complex.getReal() + " " + complex.getImaginary() + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
// Nu heb je de frequentiegegevens in de complexSamples-array en kun je verdere verwerking uitvoeren.
// Sluit het audiobestand
audioStream.close();
} catch (UnsupportedAudioFileException | IOException e) {
e.printStackTrace();
}
}
}
|
206460_5 | package simulation.src.main.java;
import java.util.ArrayList;
class War {
private ArrayList<Integer> deck;
public War(ArrayList<Integer> deck) {
this.deck = deck;
}
public int drawCard(ArrayList<Integer> stack) {
int myCard;
myCard= stack.get(0);
return myCard;
}
public int simulateGame() {
/// ...
int score = 0;
ArrayList<ArrayList<Integer>> A$B = card_delen(deck);
ArrayList<Integer> A = A$B.get(0); //Lijst van speler A
ArrayList<Integer> B = A$B.get(1); //Lijst van speler B.
boolean simulating = true;
while (simulating){
if(A.isEmpty()){return -1;}
if(B.isEmpty()){return 1;}
if(A.isEmpty() && B.isEmpty()){return 0;}
if(drawCard(A) > drawCard(B)){
A.add(B.get(0));
A.add(A.get(0));
B.remove(0);
A.remove(0);
}
else if(drawCard(A) < drawCard(B)){
B.add(B.get(0));
B.add(A.get(0));
A.remove(0);
B.remove(0);
}
else if(drawCard(A) == drawCard(B)){
//verklaar oorlog
int cards = 3;
while (true){
if(A.size() < cards){return -1;}
if(B.size() < cards){return 1;}
if(A.size() < cards && B.size() <cards){return 0;}
if(A.get(cards) > B.get(cards)){
for(int x=0; x < cards; x++){
A.add(B.get(0));
A.add(A.get(0));
B.remove(0);
A.remove(0);
}
break;
}
else if(A.get(cards) < B.get(cards)){
for(int x=0; x < cards; x++){
B.add(B.get(0));
B.add(A.get(0));
B.remove(0);
A.remove(0);
}
break;
}
else if(A.get(cards) == B.get(cards)){
cards += 4;
}
}
}
}
return score;
}
public static int findWinner(ArrayList<Integer> deck) {
War w = new War(deck);
return w.simulateGame();
}
@Override
public String toString() {
return
this.deck.toString();
}
public ArrayList<ArrayList<Integer>>card_delen(ArrayList<Integer> deck) {
/**
* Deze mothode deelt de deck door 2 players A en B, maakt list of lists daarin list[0] is A en List[1] is B
*/
ArrayList<ArrayList<Integer>> players = new ArrayList<ArrayList<Integer>>(); // list of lists
ArrayList<Integer> A = new ArrayList<>();
ArrayList<Integer> B = new ArrayList<>();
for (int ind = 0; ind < deck.size(); ind++) {
if (ind % 2 == 0){
A.add(deck.get(ind)); //Even nummer van de index voor A
} else {
B.add(deck.get(ind)); // Odd nummer van de index voor B
}
}
players.add(A);
players.add(B);
return players;
}
public static void main(String[] args) {
ArrayList<Integer> arl = new ArrayList<Integer>();
arl.add(1);
arl.add(22);
arl.add(-2);
System.out.println("Arraylist contains: " + arl.toString());
// print the result
}
} | IhabSaf/War-card-game-Simulation- | War.java | 1,113 | // Odd nummer van de index voor B | line_comment | nl | package simulation.src.main.java;
import java.util.ArrayList;
class War {
private ArrayList<Integer> deck;
public War(ArrayList<Integer> deck) {
this.deck = deck;
}
public int drawCard(ArrayList<Integer> stack) {
int myCard;
myCard= stack.get(0);
return myCard;
}
public int simulateGame() {
/// ...
int score = 0;
ArrayList<ArrayList<Integer>> A$B = card_delen(deck);
ArrayList<Integer> A = A$B.get(0); //Lijst van speler A
ArrayList<Integer> B = A$B.get(1); //Lijst van speler B.
boolean simulating = true;
while (simulating){
if(A.isEmpty()){return -1;}
if(B.isEmpty()){return 1;}
if(A.isEmpty() && B.isEmpty()){return 0;}
if(drawCard(A) > drawCard(B)){
A.add(B.get(0));
A.add(A.get(0));
B.remove(0);
A.remove(0);
}
else if(drawCard(A) < drawCard(B)){
B.add(B.get(0));
B.add(A.get(0));
A.remove(0);
B.remove(0);
}
else if(drawCard(A) == drawCard(B)){
//verklaar oorlog
int cards = 3;
while (true){
if(A.size() < cards){return -1;}
if(B.size() < cards){return 1;}
if(A.size() < cards && B.size() <cards){return 0;}
if(A.get(cards) > B.get(cards)){
for(int x=0; x < cards; x++){
A.add(B.get(0));
A.add(A.get(0));
B.remove(0);
A.remove(0);
}
break;
}
else if(A.get(cards) < B.get(cards)){
for(int x=0; x < cards; x++){
B.add(B.get(0));
B.add(A.get(0));
B.remove(0);
A.remove(0);
}
break;
}
else if(A.get(cards) == B.get(cards)){
cards += 4;
}
}
}
}
return score;
}
public static int findWinner(ArrayList<Integer> deck) {
War w = new War(deck);
return w.simulateGame();
}
@Override
public String toString() {
return
this.deck.toString();
}
public ArrayList<ArrayList<Integer>>card_delen(ArrayList<Integer> deck) {
/**
* Deze mothode deelt de deck door 2 players A en B, maakt list of lists daarin list[0] is A en List[1] is B
*/
ArrayList<ArrayList<Integer>> players = new ArrayList<ArrayList<Integer>>(); // list of lists
ArrayList<Integer> A = new ArrayList<>();
ArrayList<Integer> B = new ArrayList<>();
for (int ind = 0; ind < deck.size(); ind++) {
if (ind % 2 == 0){
A.add(deck.get(ind)); //Even nummer van de index voor A
} else {
B.add(deck.get(ind)); // Odd nummer<SUF>
}
}
players.add(A);
players.add(B);
return players;
}
public static void main(String[] args) {
ArrayList<Integer> arl = new ArrayList<Integer>();
arl.add(1);
arl.add(22);
arl.add(-2);
System.out.println("Arraylist contains: " + arl.toString());
// print the result
}
} |
169500_0 | import java.util.ArrayList;
public class Route {
private Locatie van, naar;
private ArrayList<Verbindingsstuk> verbindingsstukken = new ArrayList<Verbindingsstuk>();
public Route (Locatie l1, Locatie l2) {
van = l1;
naar = l2;
}
public int berekenReistijd() {
// TO DO: implementeer deze methode
int reistijd = 0;
for(Verbindingsstuk v : verbindingsstukken) {
reistijd += v.berekenReistijd();
}
return reistijd;
}
public void voegToe(Verbindingsstuk v) {
verbindingsstukken.add(v);
}
public String toString() {
String routeAlsTekst = "" + van;
for (Verbindingsstuk v: verbindingsstukken) {
routeAlsTekst += " => " + v.getEinde();
}
return routeAlsTekst;
}
} | IkBenDeSjaak/OOSE | OOAD/5 - Design Class Diagrams/5.2.2 - A2B/A2B/src/Route.java | 275 | // TO DO: implementeer deze methode | line_comment | nl | import java.util.ArrayList;
public class Route {
private Locatie van, naar;
private ArrayList<Verbindingsstuk> verbindingsstukken = new ArrayList<Verbindingsstuk>();
public Route (Locatie l1, Locatie l2) {
van = l1;
naar = l2;
}
public int berekenReistijd() {
// TO DO:<SUF>
int reistijd = 0;
for(Verbindingsstuk v : verbindingsstukken) {
reistijd += v.berekenReistijd();
}
return reistijd;
}
public void voegToe(Verbindingsstuk v) {
verbindingsstukken.add(v);
}
public String toString() {
String routeAlsTekst = "" + van;
for (Verbindingsstuk v: verbindingsstukken) {
routeAlsTekst += " => " + v.getEinde();
}
return routeAlsTekst;
}
} |
173723_17 | /*
* 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 org.apache.commons.validator.routines;
import org.apache.commons.validator.routines.checkdigit.CheckDigit;
import org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
/**
* Perform credit card validations.
*
* <p>
* By default, all supported card types are allowed. You can specify which
* cards should pass validation by configuring the validation options. For
* example,
* </p>
*
* <pre>
* <code>CreditCardValidator ccv = new CreditCardValidator(CreditCardValidator.AMEX + CreditCardValidator.VISA);</code>
* </pre>
*
* <p>
* configures the validator to only pass American Express and Visa cards.
* If a card type is not directly supported by this class, you can implement
* the CreditCardType interface and pass an instance into the
* <code>addAllowedCardType</code> method.
* </p>
*
* <p>
* For a similar implementation in Perl, reference Sean M. Burke's
* <a href="http://www.speech.cs.cmu.edu/~sburke/pub/luhn_lib.html">script</a>.
* More information can be found in Michael Gilleland's essay
* <a href="http://web.archive.org/web/20120614072656/http://www.merriampark.com/anatomycc.htm">Anatomy of Credit Card Numbers</a>.
* </p>
*
* @version $Revision: 1739207 $
* @since Validator 1.4
*/
public class CreditCardValidator implements Serializable {
private static final long serialVersionUID = 5955978921148959496L;
/**
* Option specifying that no cards are allowed. This is useful if
* you want only custom card types to validate so you turn off the
* default cards with this option.
*
* <pre>
* <code>
* CreditCardValidator v = new CreditCardValidator(CreditCardValidator.NONE);
* v.addAllowedCardType(customType);
* v.isValid(aCardNumber);
* </code>
* </pre>
*/
public static final long NONE = 0;
/**
* Option specifying that American Express cards are allowed.
*/
public static final long AMEX = 1 << 0;
/**
* Option specifying that Visa cards are allowed.
*/
public static final long VISA = 1 << 1;
/**
* Option specifying that Mastercard cards are allowed.
*/
public static final long MASTERCARD = 1 << 2;
/**
* Option specifying that Discover cards are allowed.
*/
public static final long DISCOVER = 1 << 3; // CHECKSTYLE IGNORE MagicNumber
/**
* Option specifying that Diners cards are allowed.
*/
public static final long DINERS = 1 << 4; // CHECKSTYLE IGNORE MagicNumber
/**
* Option specifying that VPay (Visa) cards are allowed.
* @since 1.5.0
*/
public static final long VPAY = 1 << 5; // CHECKSTYLE IGNORE MagicNumber
/**
* Option specifying that Mastercard cards (pre Oct 2016 only) are allowed.
* @deprecated for use until Oct 2016 only
*/
@Deprecated
public static final long MASTERCARD_PRE_OCT2016 = 1 << 6; // CHECKSTYLE IGNORE MagicNumber
/**
* The CreditCardTypes that are allowed to pass validation.
*/
private final List<CodeValidator> cardTypes = new ArrayList<CodeValidator>();
/**
* Luhn checkdigit validator for the card numbers.
*/
private static final CheckDigit LUHN_VALIDATOR = LuhnCheckDigit.LUHN_CHECK_DIGIT;
/** American Express (Amex) Card Validator */
public static final CodeValidator AMEX_VALIDATOR = new CodeValidator("^(3[47]\\d{13})$", LUHN_VALIDATOR);
/** Diners Card Validator */
public static final CodeValidator DINERS_VALIDATOR = new CodeValidator("^(30[0-5]\\d{11}|3095\\d{10}|36\\d{12}|3[8-9]\\d{12})$", LUHN_VALIDATOR);
/** Discover Card regular expressions */
private static final RegexValidator DISCOVER_REGEX = new RegexValidator(new String[] {"^(6011\\d{12})$", "^(64[4-9]\\d{13})$", "^(65\\d{14})$"});
/** Discover Card Validator */
public static final CodeValidator DISCOVER_VALIDATOR = new CodeValidator(DISCOVER_REGEX, LUHN_VALIDATOR);
/** Mastercard regular expressions */
private static final RegexValidator MASTERCARD_REGEX = new RegexValidator(
new String[] {
"^(5[1-5]\\d{14})$", // 51 - 55 (pre Oct 2016)
// valid from October 2016
"^(2221\\d{12})$", // 222100 - 222199
"^(222[2-9]\\d{12})$",// 222200 - 222999
"^(22[3-9]\\d{13})$", // 223000 - 229999
"^(2[3-6]\\d{14})$", // 230000 - 269999
"^(27[01]\\d{13})$", // 270000 - 271999
"^(2720\\d{12})$", // 272000 - 272099
});
/** Mastercard Card Validator */
public static final CodeValidator MASTERCARD_VALIDATOR = new CodeValidator(MASTERCARD_REGEX, LUHN_VALIDATOR);
/**
* Mastercard Card Validator (pre Oct 2016)
* @deprecated for use until Oct 2016 only
*/
@Deprecated
public static final CodeValidator MASTERCARD_VALIDATOR_PRE_OCT2016 = new CodeValidator("^(5[1-5]\\d{14})$", LUHN_VALIDATOR);
/** Visa Card Validator */
public static final CodeValidator VISA_VALIDATOR = new CodeValidator("^(4)(\\d{12}|\\d{15})$", LUHN_VALIDATOR);
/** VPay (Visa) Card Validator
* @since 1.5.0
*/
public static final CodeValidator VPAY_VALIDATOR = new CodeValidator("^(4)(\\d{12,18})$", LUHN_VALIDATOR);
/**
* Create a new CreditCardValidator with default options.
* The default options are:
* AMEX, VISA, MASTERCARD and DISCOVER
*/
public CreditCardValidator() {
this(AMEX + VISA + MASTERCARD + DISCOVER);
}
/**
* Create a new CreditCardValidator with the specified options.
* @param options Pass in
* CreditCardValidator.VISA + CreditCardValidator.AMEX to specify that
* those are the only valid card types.
*/
public CreditCardValidator(long options) {
super();
if (isOn(options, VISA)) {
this.cardTypes.add(VISA_VALIDATOR);
}
if (isOn(options, VPAY)) {
this.cardTypes.add(VPAY_VALIDATOR);
}
if (isOn(options, AMEX)) {
this.cardTypes.add(AMEX_VALIDATOR);
}
if (isOn(options, MASTERCARD)) {
this.cardTypes.add(MASTERCARD_VALIDATOR);
}
if (isOn(options, MASTERCARD_PRE_OCT2016)) {
this.cardTypes.add(MASTERCARD_VALIDATOR_PRE_OCT2016);
}
if (isOn(options, DISCOVER)) {
this.cardTypes.add(DISCOVER_VALIDATOR);
}
if (isOn(options, DINERS)) {
this.cardTypes.add(DINERS_VALIDATOR);
}
}
/**
* Create a new CreditCardValidator with the specified {@link CodeValidator}s.
* @param creditCardValidators Set of valid code validators
*/
public CreditCardValidator(CodeValidator[] creditCardValidators) {
if (creditCardValidators == null) {
throw new IllegalArgumentException("Card validators are missing");
}
Collections.addAll(cardTypes, creditCardValidators);
}
/**
* Checks if the field is a valid credit card number.
* @param card The card number to validate.
* @return Whether the card number is valid.
*/
public boolean isValid(String card) {
if (card == null || card.length() == 0) {
return false;
}
for (CodeValidator cardType : cardTypes) {
if (cardType.isValid(card)) {
return true;
}
}
return false;
}
/**
* Checks if the field is a valid credit card number.
* @param card The card number to validate.
* @return The card number if valid or <code>null</code>
* if invalid.
*/
public Object validate(String card) {
if (card == null || card.length() == 0) {
return null;
}
Object result = null;
for (CodeValidator cardType : cardTypes) {
result = cardType.validate(card);
if (result != null) {
return result;
}
}
return null;
}
/**
* Tests whether the given flag is on. If the flag is not a power of 2
* (ie. 3) this tests whether the combination of flags is on.
*
* @param options The options specified.
* @param flag Flag value to check.
*
* @return whether the specified flag value is on.
*/
private boolean isOn(long options, long flag) {
return (options & flag) > 0;
}
}
| Ilhasoft/data-binding-validator | library/src/main/java/org/apache/commons/validator/routines/CreditCardValidator.java | 2,862 | /** Diners Card Validator */ | block_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 org.apache.commons.validator.routines;
import org.apache.commons.validator.routines.checkdigit.CheckDigit;
import org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
/**
* Perform credit card validations.
*
* <p>
* By default, all supported card types are allowed. You can specify which
* cards should pass validation by configuring the validation options. For
* example,
* </p>
*
* <pre>
* <code>CreditCardValidator ccv = new CreditCardValidator(CreditCardValidator.AMEX + CreditCardValidator.VISA);</code>
* </pre>
*
* <p>
* configures the validator to only pass American Express and Visa cards.
* If a card type is not directly supported by this class, you can implement
* the CreditCardType interface and pass an instance into the
* <code>addAllowedCardType</code> method.
* </p>
*
* <p>
* For a similar implementation in Perl, reference Sean M. Burke's
* <a href="http://www.speech.cs.cmu.edu/~sburke/pub/luhn_lib.html">script</a>.
* More information can be found in Michael Gilleland's essay
* <a href="http://web.archive.org/web/20120614072656/http://www.merriampark.com/anatomycc.htm">Anatomy of Credit Card Numbers</a>.
* </p>
*
* @version $Revision: 1739207 $
* @since Validator 1.4
*/
public class CreditCardValidator implements Serializable {
private static final long serialVersionUID = 5955978921148959496L;
/**
* Option specifying that no cards are allowed. This is useful if
* you want only custom card types to validate so you turn off the
* default cards with this option.
*
* <pre>
* <code>
* CreditCardValidator v = new CreditCardValidator(CreditCardValidator.NONE);
* v.addAllowedCardType(customType);
* v.isValid(aCardNumber);
* </code>
* </pre>
*/
public static final long NONE = 0;
/**
* Option specifying that American Express cards are allowed.
*/
public static final long AMEX = 1 << 0;
/**
* Option specifying that Visa cards are allowed.
*/
public static final long VISA = 1 << 1;
/**
* Option specifying that Mastercard cards are allowed.
*/
public static final long MASTERCARD = 1 << 2;
/**
* Option specifying that Discover cards are allowed.
*/
public static final long DISCOVER = 1 << 3; // CHECKSTYLE IGNORE MagicNumber
/**
* Option specifying that Diners cards are allowed.
*/
public static final long DINERS = 1 << 4; // CHECKSTYLE IGNORE MagicNumber
/**
* Option specifying that VPay (Visa) cards are allowed.
* @since 1.5.0
*/
public static final long VPAY = 1 << 5; // CHECKSTYLE IGNORE MagicNumber
/**
* Option specifying that Mastercard cards (pre Oct 2016 only) are allowed.
* @deprecated for use until Oct 2016 only
*/
@Deprecated
public static final long MASTERCARD_PRE_OCT2016 = 1 << 6; // CHECKSTYLE IGNORE MagicNumber
/**
* The CreditCardTypes that are allowed to pass validation.
*/
private final List<CodeValidator> cardTypes = new ArrayList<CodeValidator>();
/**
* Luhn checkdigit validator for the card numbers.
*/
private static final CheckDigit LUHN_VALIDATOR = LuhnCheckDigit.LUHN_CHECK_DIGIT;
/** American Express (Amex) Card Validator */
public static final CodeValidator AMEX_VALIDATOR = new CodeValidator("^(3[47]\\d{13})$", LUHN_VALIDATOR);
/** Diners Card Validator<SUF>*/
public static final CodeValidator DINERS_VALIDATOR = new CodeValidator("^(30[0-5]\\d{11}|3095\\d{10}|36\\d{12}|3[8-9]\\d{12})$", LUHN_VALIDATOR);
/** Discover Card regular expressions */
private static final RegexValidator DISCOVER_REGEX = new RegexValidator(new String[] {"^(6011\\d{12})$", "^(64[4-9]\\d{13})$", "^(65\\d{14})$"});
/** Discover Card Validator */
public static final CodeValidator DISCOVER_VALIDATOR = new CodeValidator(DISCOVER_REGEX, LUHN_VALIDATOR);
/** Mastercard regular expressions */
private static final RegexValidator MASTERCARD_REGEX = new RegexValidator(
new String[] {
"^(5[1-5]\\d{14})$", // 51 - 55 (pre Oct 2016)
// valid from October 2016
"^(2221\\d{12})$", // 222100 - 222199
"^(222[2-9]\\d{12})$",// 222200 - 222999
"^(22[3-9]\\d{13})$", // 223000 - 229999
"^(2[3-6]\\d{14})$", // 230000 - 269999
"^(27[01]\\d{13})$", // 270000 - 271999
"^(2720\\d{12})$", // 272000 - 272099
});
/** Mastercard Card Validator */
public static final CodeValidator MASTERCARD_VALIDATOR = new CodeValidator(MASTERCARD_REGEX, LUHN_VALIDATOR);
/**
* Mastercard Card Validator (pre Oct 2016)
* @deprecated for use until Oct 2016 only
*/
@Deprecated
public static final CodeValidator MASTERCARD_VALIDATOR_PRE_OCT2016 = new CodeValidator("^(5[1-5]\\d{14})$", LUHN_VALIDATOR);
/** Visa Card Validator */
public static final CodeValidator VISA_VALIDATOR = new CodeValidator("^(4)(\\d{12}|\\d{15})$", LUHN_VALIDATOR);
/** VPay (Visa) Card Validator
* @since 1.5.0
*/
public static final CodeValidator VPAY_VALIDATOR = new CodeValidator("^(4)(\\d{12,18})$", LUHN_VALIDATOR);
/**
* Create a new CreditCardValidator with default options.
* The default options are:
* AMEX, VISA, MASTERCARD and DISCOVER
*/
public CreditCardValidator() {
this(AMEX + VISA + MASTERCARD + DISCOVER);
}
/**
* Create a new CreditCardValidator with the specified options.
* @param options Pass in
* CreditCardValidator.VISA + CreditCardValidator.AMEX to specify that
* those are the only valid card types.
*/
public CreditCardValidator(long options) {
super();
if (isOn(options, VISA)) {
this.cardTypes.add(VISA_VALIDATOR);
}
if (isOn(options, VPAY)) {
this.cardTypes.add(VPAY_VALIDATOR);
}
if (isOn(options, AMEX)) {
this.cardTypes.add(AMEX_VALIDATOR);
}
if (isOn(options, MASTERCARD)) {
this.cardTypes.add(MASTERCARD_VALIDATOR);
}
if (isOn(options, MASTERCARD_PRE_OCT2016)) {
this.cardTypes.add(MASTERCARD_VALIDATOR_PRE_OCT2016);
}
if (isOn(options, DISCOVER)) {
this.cardTypes.add(DISCOVER_VALIDATOR);
}
if (isOn(options, DINERS)) {
this.cardTypes.add(DINERS_VALIDATOR);
}
}
/**
* Create a new CreditCardValidator with the specified {@link CodeValidator}s.
* @param creditCardValidators Set of valid code validators
*/
public CreditCardValidator(CodeValidator[] creditCardValidators) {
if (creditCardValidators == null) {
throw new IllegalArgumentException("Card validators are missing");
}
Collections.addAll(cardTypes, creditCardValidators);
}
/**
* Checks if the field is a valid credit card number.
* @param card The card number to validate.
* @return Whether the card number is valid.
*/
public boolean isValid(String card) {
if (card == null || card.length() == 0) {
return false;
}
for (CodeValidator cardType : cardTypes) {
if (cardType.isValid(card)) {
return true;
}
}
return false;
}
/**
* Checks if the field is a valid credit card number.
* @param card The card number to validate.
* @return The card number if valid or <code>null</code>
* if invalid.
*/
public Object validate(String card) {
if (card == null || card.length() == 0) {
return null;
}
Object result = null;
for (CodeValidator cardType : cardTypes) {
result = cardType.validate(card);
if (result != null) {
return result;
}
}
return null;
}
/**
* Tests whether the given flag is on. If the flag is not a power of 2
* (ie. 3) this tests whether the combination of flags is on.
*
* @param options The options specified.
* @param flag Flag value to check.
*
* @return whether the specified flag value is on.
*/
private boolean isOn(long options, long flag) {
return (options & flag) > 0;
}
}
|
52471_0 | package nl.workshophub.workshophubeindopdrachtbackend.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/*
CORS (Cross Origin Resource Sharing is een instelling die zorgt dat de frontend en de backend met elkaar kunnen
communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080).
De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten.
In deze applictie staat alsnog wel boven elke klasse ter demonstratie.
Vergeet niet om in de security config ook de ".cors()" optie aan te zetten.
*/
@Configuration
public class GlobalCorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
}
};
}
} | IlsevNierop/WorkshopHub_Eindopdracht_Back-End | src/main/java/nl/workshophub/workshophubeindopdrachtbackend/config/GlobalCorsConfiguration.java | 342 | /*
CORS (Cross Origin Resource Sharing is een instelling die zorgt dat de frontend en de backend met elkaar kunnen
communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080).
De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten.
In deze applictie staat alsnog wel boven elke klasse ter demonstratie.
Vergeet niet om in de security config ook de ".cors()" optie aan te zetten.
*/ | block_comment | nl | package nl.workshophub.workshophubeindopdrachtbackend.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/*
CORS (Cross Origin<SUF>*/
@Configuration
public class GlobalCorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
}
};
}
} |
128465_8 | package com.dismas.imaya.gatekeeper;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.dismas.imaya.gatekeeper.Database.DBhelper;
import com.dismas.imaya.gatekeeper.Database.SQLController;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Button button;
// Spinner element
Spinner spinner;
private SQLController dbController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonExit();
dbController = new SQLController(this);
dbController.open();
//insert data into sqlite database
dbController.insert("O'Neill, Jack", "Colonel", "SGC General", "android.resource://com.dismas.imaya.gatekeeper/drawable/jackoneill", "21/02/1949", "5.7", "78KG", "Gate A", "44553A9A");
dbController.insert("George S. Hammond", "SGC Major General", "Commander-in-Chief", "android.resource://com.dismas.imaya.gatekeeper/drawable/georgehammond", "09/12/1959", "6.3", "85KG", "Gate B", "E14351D5");
dbController.insert("Samantha Carter", "Captain", "SGC Commander of the Daedalus-class ship", "android.resource://com.dismas.imaya.gatekeeper/drawable/samanthacarter", "12/02/1960", "5.5", "60KG", "Gate B", "D47C379A");
dbController.insert("Cameron Mitchell", "Colonel", "Stargate Command", "android.resource://com.dismas.imaya.gatekeeper/drawable/cameronmitchel", "11/12/1970", "5.6", "78KG", "Data Centre", "445E369A");
dbController.insert("Ann Siyanoi", "Captian", "Cadet", "img_url", "21/02/1989", "6.0", "80KG", "Conference", "654U455P");
dbController.insert("Christiana Mandy", "Officer Cadet", "Cadet", "img_url", "21/10/1969", "5.9", "70KG", "Data Centre", "987G789V");
dbController.insert("Olive Wanjiku", "Commandant", "Cadet", "img_url", "03/11/1989", "6.1", "73KG", "Gate B", "357X753V");
dbController.insert("Job Maroro", "Marshal", "Field", "img_url", "21/02/1990", "5.7", "70KG", "Gate A", "159S951K");
dbController.insert("Anthony Kamau", "Officer Cadet", "Health", "img_url", "21/04/1991", "5.8", "78KG", "Conference", "254Z451M");
dbController.insert("Maryann Nashipai", "Officer Cadet", "Store", "img_url", "21/02/1989", "6.0", "72KG", "Gate A", "014J123G");
// Spinner element
spinner = (Spinner) findViewById(R.id.spinner);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data from database
loadSpinnerData();
}
public void addListenerOnButtonExit() {
final Context context = this;
button = (Button) findViewById(R.id.exit);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
// database handler
DBhelper db = new DBhelper(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllAreas();
Set<String> hs = new HashSet<>();
hs.addAll(lables);
lables.clear();
lables.addAll(hs);
//this is for custom spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
R.layout.spinner_item, lables);
// Drop down layout style - list view with radio button for default provided by android
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//this for a custom spinner
dataAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
final String label = parent.getItemAtPosition(position).toString();
final Context context = this;
button = (Button) findViewById(R.id.verify);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(context, VerifyActivity.class);
intent.putExtra("label", label);
startActivity(intent);
//finish();
}
});
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
| ImayaDismas/android-projects | GateKeeper/app/src/main/java/com/dismas/imaya/gatekeeper/MainActivity.java | 1,618 | // Spinner Drop down elements | line_comment | nl | package com.dismas.imaya.gatekeeper;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.dismas.imaya.gatekeeper.Database.DBhelper;
import com.dismas.imaya.gatekeeper.Database.SQLController;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Button button;
// Spinner element
Spinner spinner;
private SQLController dbController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonExit();
dbController = new SQLController(this);
dbController.open();
//insert data into sqlite database
dbController.insert("O'Neill, Jack", "Colonel", "SGC General", "android.resource://com.dismas.imaya.gatekeeper/drawable/jackoneill", "21/02/1949", "5.7", "78KG", "Gate A", "44553A9A");
dbController.insert("George S. Hammond", "SGC Major General", "Commander-in-Chief", "android.resource://com.dismas.imaya.gatekeeper/drawable/georgehammond", "09/12/1959", "6.3", "85KG", "Gate B", "E14351D5");
dbController.insert("Samantha Carter", "Captain", "SGC Commander of the Daedalus-class ship", "android.resource://com.dismas.imaya.gatekeeper/drawable/samanthacarter", "12/02/1960", "5.5", "60KG", "Gate B", "D47C379A");
dbController.insert("Cameron Mitchell", "Colonel", "Stargate Command", "android.resource://com.dismas.imaya.gatekeeper/drawable/cameronmitchel", "11/12/1970", "5.6", "78KG", "Data Centre", "445E369A");
dbController.insert("Ann Siyanoi", "Captian", "Cadet", "img_url", "21/02/1989", "6.0", "80KG", "Conference", "654U455P");
dbController.insert("Christiana Mandy", "Officer Cadet", "Cadet", "img_url", "21/10/1969", "5.9", "70KG", "Data Centre", "987G789V");
dbController.insert("Olive Wanjiku", "Commandant", "Cadet", "img_url", "03/11/1989", "6.1", "73KG", "Gate B", "357X753V");
dbController.insert("Job Maroro", "Marshal", "Field", "img_url", "21/02/1990", "5.7", "70KG", "Gate A", "159S951K");
dbController.insert("Anthony Kamau", "Officer Cadet", "Health", "img_url", "21/04/1991", "5.8", "78KG", "Conference", "254Z451M");
dbController.insert("Maryann Nashipai", "Officer Cadet", "Store", "img_url", "21/02/1989", "6.0", "72KG", "Gate A", "014J123G");
// Spinner element
spinner = (Spinner) findViewById(R.id.spinner);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data from database
loadSpinnerData();
}
public void addListenerOnButtonExit() {
final Context context = this;
button = (Button) findViewById(R.id.exit);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
// database handler
DBhelper db = new DBhelper(getApplicationContext());
// Spinner Drop<SUF>
List<String> lables = db.getAllAreas();
Set<String> hs = new HashSet<>();
hs.addAll(lables);
lables.clear();
lables.addAll(hs);
//this is for custom spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
R.layout.spinner_item, lables);
// Drop down layout style - list view with radio button for default provided by android
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//this for a custom spinner
dataAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
final String label = parent.getItemAtPosition(position).toString();
final Context context = this;
button = (Button) findViewById(R.id.verify);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(context, VerifyActivity.class);
intent.putExtra("label", label);
startActivity(intent);
//finish();
}
});
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
|
76292_29 | /**
* This Java Class is part of the Impro-Visor Application
*
* Copyright (C) 2014-2016 Robert Keller and Harvey Mudd College
*
* Impro-Visor 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.
*
* Impro-Visor 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 Impro-Visor; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package imp.themeWeaver;
import imp.data.MelodyPart;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import static imp.Constants.BEAT;
import imp.data.Part;
import imp.data.Unit;
import polya.Polylist;
import polya.PolylistEnum;
/**
*
* @author Nava Dallal
*/
public class Theme {
MelodyPart melody;
String name;
int ThemeLength;
int serial;
int numDiscriminators = 0;
String discriminator[] = new String[maxDiscriminators];
static int maxDiscriminators = 2;
int discriminatorOffset[] = new int[maxDiscriminators];
//construct a Theme from a MelodyPart
public Theme(MelodyPart melody)
{
this.melody = melody;
this.ThemeLength = melody.size() / BEAT;
}
private static LinkedHashMap<String, Theme> allThemes = new LinkedHashMap<String, Theme>();
private static ArrayList<Theme> orderedThemes = null;
//create Theme from name and MelodyPart
public static Theme makeTheme(String name, MelodyPart theme) {
Theme newTheme = new Theme(theme);
newTheme.name = name;
newTheme.ThemeLength = theme.size() /BEAT;
// newTheme.ThemeLength = theme.getUnitList();
// for (int i = 0; i < theme.getUnitList().size(); i++){
// Note note = (Note)theme.getUnitList().get(i);
// note.getNoteLength();
return newTheme;
}
//get name of a Theme
String getName() { return name; }
// get the string of notes in a theme
Polylist getNotes()
{
return Polylist.list(melodyToString(melody));
}
//Convert a MelodyPart to a String
public static String melodyToString(MelodyPart melody){
Part.PartIterator i = melody.iterator(); //iterate over lick
String theme = ""; //set theme as empty to start
while (i.hasNext()) //while you can still iterate through the lick
{
Unit unit = i.next();
if (unit != null) //if next isn't empty
{
theme += unit.toLeadsheet() + " "; //add it to the theme
}
}
return theme;
}
//Convert a Theme to a Polylist
public Polylist ThemetoPolylist(Theme theme){
return Polylist.list("theme", Polylist.list("name", theme.name), Polylist.list("notes", theme.melodyToString(theme.melody)));
}
//construct a Theme from a Polylist
public Theme(Polylist list) {
Polylist nameList = (Polylist)list.second(); //get Polylist of the name
Polylist nameTheme = nameList.rest(); //just get the name
PolylistEnum nameElements = nameTheme.elements(); //set the name of the Theme
String nameString = "";
while (nameElements.hasMoreElements()) { //while there are more notes
Object current = nameElements.nextElement();//get next note
String currentString = current.toString(); //convert it to String
nameString += currentString + " "; //add the note to the melodyString
// System.out.println(nameString);
}
this.name = nameString;
Polylist melodyList = (Polylist)list.last(); //get polylist of the melody
Polylist melodyNotes = (Polylist)melodyList.rest(); //get the notes in a polylist
PolylistEnum melodyElements = melodyNotes.elements(); //get the notes as elements
//To get the notes of the theme in a string:
String melodyString = "";
while (melodyElements.hasMoreElements()) { //while there are more notes
Object current = melodyElements.nextElement();//get next note
String currentString = current.toString(); //convert it to String
melodyString += currentString + " "; //add the note to the melodyString
// System.out.println(melodyString);
}
MelodyPart melody = new MelodyPart(melodyString); //create a MelodyPart of the string
this.melody = melody; //set the melody to the melody of the theme
}
public void showForm(java.io.PrintStream out) {
out.println(toString());
}
@Override
public String toString()
{
return "(theme "
+ "(name " + getName()
+ ")(notes " + melodyToString(melody)
+ "))";
}
}
| Impro-Visor/Impro-Visor | src/imp/themeWeaver/Theme.java | 1,516 | //get next note | line_comment | nl | /**
* This Java Class is part of the Impro-Visor Application
*
* Copyright (C) 2014-2016 Robert Keller and Harvey Mudd College
*
* Impro-Visor 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.
*
* Impro-Visor 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 Impro-Visor; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package imp.themeWeaver;
import imp.data.MelodyPart;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import static imp.Constants.BEAT;
import imp.data.Part;
import imp.data.Unit;
import polya.Polylist;
import polya.PolylistEnum;
/**
*
* @author Nava Dallal
*/
public class Theme {
MelodyPart melody;
String name;
int ThemeLength;
int serial;
int numDiscriminators = 0;
String discriminator[] = new String[maxDiscriminators];
static int maxDiscriminators = 2;
int discriminatorOffset[] = new int[maxDiscriminators];
//construct a Theme from a MelodyPart
public Theme(MelodyPart melody)
{
this.melody = melody;
this.ThemeLength = melody.size() / BEAT;
}
private static LinkedHashMap<String, Theme> allThemes = new LinkedHashMap<String, Theme>();
private static ArrayList<Theme> orderedThemes = null;
//create Theme from name and MelodyPart
public static Theme makeTheme(String name, MelodyPart theme) {
Theme newTheme = new Theme(theme);
newTheme.name = name;
newTheme.ThemeLength = theme.size() /BEAT;
// newTheme.ThemeLength = theme.getUnitList();
// for (int i = 0; i < theme.getUnitList().size(); i++){
// Note note = (Note)theme.getUnitList().get(i);
// note.getNoteLength();
return newTheme;
}
//get name of a Theme
String getName() { return name; }
// get the string of notes in a theme
Polylist getNotes()
{
return Polylist.list(melodyToString(melody));
}
//Convert a MelodyPart to a String
public static String melodyToString(MelodyPart melody){
Part.PartIterator i = melody.iterator(); //iterate over lick
String theme = ""; //set theme as empty to start
while (i.hasNext()) //while you can still iterate through the lick
{
Unit unit = i.next();
if (unit != null) //if next isn't empty
{
theme += unit.toLeadsheet() + " "; //add it to the theme
}
}
return theme;
}
//Convert a Theme to a Polylist
public Polylist ThemetoPolylist(Theme theme){
return Polylist.list("theme", Polylist.list("name", theme.name), Polylist.list("notes", theme.melodyToString(theme.melody)));
}
//construct a Theme from a Polylist
public Theme(Polylist list) {
Polylist nameList = (Polylist)list.second(); //get Polylist of the name
Polylist nameTheme = nameList.rest(); //just get the name
PolylistEnum nameElements = nameTheme.elements(); //set the name of the Theme
String nameString = "";
while (nameElements.hasMoreElements()) { //while there are more notes
Object current = nameElements.nextElement();//get next note
String currentString = current.toString(); //convert it to String
nameString += currentString + " "; //add the note to the melodyString
// System.out.println(nameString);
}
this.name = nameString;
Polylist melodyList = (Polylist)list.last(); //get polylist of the melody
Polylist melodyNotes = (Polylist)melodyList.rest(); //get the notes in a polylist
PolylistEnum melodyElements = melodyNotes.elements(); //get the notes as elements
//To get the notes of the theme in a string:
String melodyString = "";
while (melodyElements.hasMoreElements()) { //while there are more notes
Object current = melodyElements.nextElement();//get next<SUF>
String currentString = current.toString(); //convert it to String
melodyString += currentString + " "; //add the note to the melodyString
// System.out.println(melodyString);
}
MelodyPart melody = new MelodyPart(melodyString); //create a MelodyPart of the string
this.melody = melody; //set the melody to the melody of the theme
}
public void showForm(java.io.PrintStream out) {
out.println(toString());
}
@Override
public String toString()
{
return "(theme "
+ "(name " + getName()
+ ")(notes " + melodyToString(melody)
+ "))";
}
}
|
34147_17 | /*
* Copyright (C) 2016 Dienst voor het kadaster en de openbare registers
*
* This file is part of Imvertor.
*
* Imvertor 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.
*
* Imvertor 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 Imvertor. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.imvertor.common.file;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.XMLTestCase;
import org.custommonkey.xmlunit.XMLUnit;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import net.sf.saxon.xpath.XPathFactoryImpl;
import nl.imvertor.common.Configurator;
import nl.imvertor.common.Transformer;
import nl.imvertor.common.xsl.extensions.ImvertorCompareXML;
/**
* An XmlFile represents an XmlFile on the file system.
*
* The XmlFile is an AnyFile and therefore does not access the chain environment.
*
* @author arjan
*
*/
public class XmlFile extends AnyFile implements ErrorHandler {
private static final long serialVersionUID = -4351737187940152153L;
protected static final Logger logger = Logger.getLogger(XmlFile.class);
static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
protected static final String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces";
protected static final String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";
protected static final String SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema";
protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
protected static final String EXTERNAL_PARAMETER_ENTITIES_ID = "http://xml.org/sax/features/external-parameter-entities";
protected static final String EXTERNAL_GENERAL_ENTITIES_ID = "http://xml.org/sax/features/external-general-entities";
protected static final String IGNORE_DTD_FEATURE_ID = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; // http://www.isocra.com/2006/05/making-xerces-ignore-a-dtd/
protected static final String LEXICAL_HANDLER_PROPERTY_ID = "http://xml.org/sax/properties/lexical-handler";
protected static final String DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser";
protected static final int WFCODE_OKAY = 0;
protected static final int WFCODE_WARNING = 1;
protected static final int WFCODE_ERROR = 2;
protected static final int WFCODE_FATAL = 3;
// parameters die de verwerking van het XML file bepalen
public boolean namespace = true; // namespace aware?
public boolean validate = false; // valideren?
public boolean xinclude = true; // herken xinclude statements?
public boolean schema = false; // zoek naar schema bij valideren?
public boolean schemacheck = false; // schema ook checken?
public boolean dtd = false; // zoek naar dtd bij valideren?
public boolean auto = false; // automagically determine how to parse this file?
public boolean external = false; // externe entiteiten ophalen?
public boolean inquiry = false; // zoek alleen maar naar informatie over dit file?
private Document dom = null;
private int wfcode = WFCODE_OKAY; // a code indicating the Wellformedness of the XML file.
private Vector<String> messages = new Vector<String>();
public static void main(String[] args) {
//XmlFile file = new XmlFile("D:\\projects\\arjan\\Java development\\CommonHandlers\\sandbox\\EHcache\\config\\ehcache.xml");
XmlFile file = new XmlFile("D:\\projects\\validprojects\\Kadaster-Imvertor\\Imvertor-OS-work\\default\\comply\\template\\xl\\worksheets\\sheet1.xml");
System.out.println(file.isValid());
file.getMessages();
}
public XmlFile(String pathname) {
super(pathname);
}
public XmlFile(File file) {
super(file.getAbsolutePath());
}
public XmlFile(File folder, String filename) {
super(folder,filename);
}
public String getFileType() {
return "XML";
}
/**
* Lees een file in naar een DOM Document.
*
* @param file
* @return
* @throws Exception
*/
public Document toDocument() throws Exception {
Document d = buildDom();
return d;
}
/**
* Zet een Document weg als file. Transformeer middels het XSLT file. Als
* XSLT file is "", identity transform.
*
* @param doc
* @param xsltfile
* @param parms
* @throws Exception
*/
public void fromDocument(Document doc) throws Exception {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("XML 3.0 LS 3.0");
if (impl == null) {
System.out.println("No DOMImplementation found !");
System.exit(0);
}
LSSerializer serializer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
output.setEncoding("UTF-8");
output.setByteStream(new FileOutputStream(this));
serializer.write(doc, output);
}
/**
* Build a DOM Document representation of this XML file.
*
* @return
* @throws Exception
*/
private Document buildDom() throws Exception {
return this.buildDom(this);
}
/**
* Build a DOM Document representation of some external XML file.
*
* @return
* @throws Exception
*/
private Document buildDom(File file) throws Exception {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
InputSource in = new InputSource(file.getAbsolutePath());
docFactory.setValidating(validate);
docFactory.setXIncludeAware(xinclude);
docFactory.setFeature(VALIDATION_FEATURE_ID, validate);
docFactory.setFeature(NAMESPACES_FEATURE_ID, namespace);
docFactory.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schema);
docFactory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemacheck);
docFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_ID, external);
docFactory.setFeature(EXTERNAL_PARAMETER_ENTITIES_ID, external);
DocumentBuilder db = docFactory.newDocumentBuilder();
return db.parse(in);
}
public Document getDom() throws Exception {
if (dom == null)
return buildDom(this);
else
return dom;
}
/**
* Benader de inhoud dmv. een Xpath expressie. Geef het laatste item die aan het criterium voldoet af als String.
*
* @param outfile
* @param xslFilePath
* @throws Exception
*/
public String xpath(String expression, HashMap<String, String> parms) throws Exception {
return (String) xpathToObject(expression, parms, XPathConstants.STRING);
}
/**
* Benader de inhoud dmv. een Xpath expressie.
*
* @param outfile
* @param xslFilePath
* @throws Exception
*/
public Object xpathToObject(String expression, HashMap<String, String> parms, QName returnType) throws Exception {
if (dom == null) dom = this.buildDom();
XPathFactoryImpl xpf = new XPathFactoryImpl();
XPath xpe = xpf.newXPath();
XPathExpression find = xpe.compile(expression);
return find.evaluate(dom, returnType);
}
public String xpath(String expression) throws Exception {
return xpath(expression,new HashMap<String,String>());
}
/**
* Transform the XML file to a canonical form
*
* @param outfile
* @param xslFile
* @param parms
* @throws Exception
*/
public void fileToCanonicalFile(XmlFile outfile) throws Exception {
logger.debug("Canonizing " + this.getCanonicalPath());
if (dom == null) dom = this.buildDom();
outfile.fromDocument(dom);
}
public boolean isWellFormed() {
messages.removeAllElements();
try {
wfcode = WFCODE_OKAY;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(this);
builder.parse(new InputSource(this.getCanonicalPath()));
} catch (Exception e) {
wfcode = WFCODE_FATAL;
}
return wfcode < WFCODE_ERROR;
}
public boolean isValid() {
messages.removeAllElements();
try {
wfcode = WFCODE_OKAY;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
factory.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(this);
builder.parse(new InputSource(this.getCanonicalPath()));
} catch (Exception e) {
wfcode = WFCODE_FATAL;
}
return wfcode < WFCODE_ERROR;
}
public Vector<String> getMessages() {
return messages;
}
/**
* Compare this control file to the passed test file, store result in file. Return true if files are the same.
*
* Difference types are listed as constants in
* <a href="http://xmlunit.sourceforge.net/api/org/custommonkey/xmlunit/DifferenceConstants.html">here</a>
*
* @param controlXmlPath
* @param testXmlPath
* @param resultPath
* @return
* @throws Exception
*/
public boolean xmlUnitCompareXML(XmlFile testXmlFile, XmlFile resultFile) throws Exception {
XmlFile controlXmlFile = this;
XMLUnit.setCompareUnmatched(false);
XMLTestCase testcase = new Case(this.getName());
DetailedDiff myDiff = new DetailedDiff(testcase.compareXML(controlXmlFile.getContent(), testXmlFile.getContent()));
@SuppressWarnings("unchecked")
List<Difference> allDifferences = myDiff.getAllDifferences();
Iterator<Difference> it = allDifferences.iterator();
String analysis = "<diffs>";
while (it.hasNext()) {
Difference d = it.next();
analysis += "<diff"
+ " desc=\"" + safe(d.getDescription()) + "\""
+ ">";
analysis += "<ctrl"
+ " path=\"" + d.getControlNodeDetail().getXpathLocation() + "\""
+ " value=\"" + safe(d.getControlNodeDetail().getValue()) + "\""
+ "/>";
analysis += "<test"
+ " path=\"" + d.getTestNodeDetail().getXpathLocation() + "\""
+ " value=\"" + safe(d.getTestNodeDetail().getValue()) + "\""
+ "/>";
analysis += "</diff>";
}
analysis += "</diffs>";
resultFile.setContent(analysis);
return (allDifferences.size() == 0) ? true: false;
}
/**
* Replace special characters in XML string.
*
* @param s
* @return
*/
private String safe(String s) {
s = StringUtils.replace(s,"&","&");
s = StringUtils.replace(s,"<","<");
s = StringUtils.replace(s,">",">");
s = StringUtils.replace(s,"\"",""");
return s;
}
/**
* Introduce the XmlFile class as a valid JUnit TestCase class.
*
* @author arjan
*
*/
private class Case extends XMLTestCase {
public Case(String name) {
super(name);
}
}
@Override
public void error(SAXParseException exception) throws SAXException {
messages.add(exception.getMessage());
wfcode = WFCODE_ERROR;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
messages.add(exception.getMessage());
wfcode = WFCODE_FATAL;
}
@Override
public void warning(SAXParseException exception) throws SAXException {
messages.add(exception.getMessage());
wfcode = WFCODE_WARNING;
}
public static String xmlescape(String s) {
s = s.replace("&", "&");
s = s.replace("<", "<");
return s;
}
/**
* See IM-147 Documentatie release ondersteunen.
*
* This method compares the current XML file to any other XML file. Results are written to a listing XML file.
*
* This XML file is the control XML file, and is compared to test XML file.
*
* @return
* @throws Exception
*/
public boolean compare(XmlFile testXmlFile, Configurator configurator) throws Exception {
String compareLabel = configurator.getParm("system", "compare-label");
// create a transformer
Transformer transformer = new Transformer();
transformer.setExtensionFunction(new ImvertorCompareXML());
Boolean valid = true;
//TODO Duplicate, redundant?
XmlFile ctrlNameFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_CONTROL_NAME_FILE")); // imvertor.20.docrelease.1.1.compare-control-name.xml
XmlFile testNameFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_TEST_NAME_FILE")); // imvertor.20.docrelease.1.2.compare-test-name.xml
XmlFile infoConfig = new XmlFile(configurator.getParm("properties","IMVERTOR_COMPARE_CONFIG")); // Imvert-compare-config.xml
// This transformer will pass regular XML parameters to the stylesheet.
// This is because the compare core code is not part of the Imvertor framework, but developed separately.
// We therefore do not use the XMLConfiguration approach here.
transformer.setXslParm("identify-construct-by-function", "name"); // the name of the construct is the only identifier
//TODO name of id??
transformer.setXslParm("info-config", infoConfig.toURI().toString());
transformer.setXslParm("info-ctrlpath", this.getCanonicalPath());
transformer.setXslParm("info-testpath", "(test path)");
transformer.setXslParm("compare-label", compareLabel);
// determine temporary files
XmlFile controlModelFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_CONTROL_MODEL_FILE")); // imvertor.20.docrelease.1.1.compare-control-model.xml
XmlFile testModelFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_TEST_MODEL_FILE")); // imvertor.20.docrelease.1.2.compare-test-model.xml
XmlFile controlSimpleFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_CONTROL_SIMPLE_FILE")); // imvertor.20.docrelease.1.1.compare-control-simple.xml
XmlFile testSimpleFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_TEST_SIMPLE_FILE")); // imvertor.20.docrelease.1.2.compare-test-simple.xml
XmlFile diffXml = new XmlFile(configurator.getParm("properties","WORK_COMPARE_DIFF_FILE")); // imvertor.20.docrelease.2.compare-diff.xml
XmlFile listingXml = new XmlFile(configurator.getParm("properties","WORK_COMPARE_LISTING_FILE")); // imvertor.20.docrelease.3.compare-listing.xml
XslFile tempXsl = new XslFile(configurator.getParm("properties","COMPARE_GENERATED_XSLPATH"));
//clean
XslFile cleanerXsl = new XslFile(configurator.getParm("properties","IMVERTOR_COMPARE_CLEAN_XSLPATH"));
XslFile simpleXsl = new XslFile(configurator.getParm("properties","IMVERTOR_COMPARE_SIMPLE_XSLPATH"));
valid = valid && transformer.transform(this,controlModelFile,cleanerXsl);
valid = valid && transformer.transform(testXmlFile,testModelFile,cleanerXsl);
// simplify
transformer.setXslParm("ctrl-name-mapping-filepath", ctrlNameFile.toURI().toString()); // file:/D:/.../Imvertor-OS-work/imvert/imvertor.20.compare-control-name.xml
transformer.setXslParm("test-name-mapping-filepath", testNameFile.toURI().toString());
transformer.setXslParm("comparison-role", "ctrl");
valid = valid && transformer.transform(controlModelFile,controlSimpleFile,simpleXsl);
transformer.setXslParm("comparison-role", "test");
valid = valid && transformer.transform(testModelFile,testSimpleFile,simpleXsl);
// compare
XslFile compareXsl = new XslFile(configurator.getParm("properties","COMPARE_GENERATOR_XSLPATH"));
transformer.setXslParm("ctrl-filepath", controlSimpleFile.getCanonicalPath());
transformer.setXslParm("test-filepath", testSimpleFile.getCanonicalPath());
transformer.setXslParm("diff-filepath", diffXml.getCanonicalPath());
valid = valid && transformer.transform(controlSimpleFile, tempXsl, compareXsl);
// create listing
XslFile listingXsl = new XslFile(configurator.getParm("properties","IMVERTOR_COMPARE_LISTING_XSLPATH"));
valid = valid && transformer.transform(controlSimpleFile,listingXml,listingXsl);
// get the number of differences found
int differences = ((NodeList) listingXml.xpathToObject("/*/*",null,XPathConstants.NODESET)).getLength();
configurator.setParm("appinfo", "compare-differences-" + compareLabel, differences);
// Build report
boolean result = valid && (differences == 0);
return result;
}
}
| Imvertor/Imvertor | src/nl/imvertor/common/file/XmlFile.java | 5,997 | /**
* Benader de inhoud dmv. een Xpath expressie. Geef het laatste item die aan het criterium voldoet af als String.
*
* @param outfile
* @param xslFilePath
* @throws Exception
*/ | block_comment | nl | /*
* Copyright (C) 2016 Dienst voor het kadaster en de openbare registers
*
* This file is part of Imvertor.
*
* Imvertor 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.
*
* Imvertor 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 Imvertor. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.imvertor.common.file;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.XMLTestCase;
import org.custommonkey.xmlunit.XMLUnit;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import net.sf.saxon.xpath.XPathFactoryImpl;
import nl.imvertor.common.Configurator;
import nl.imvertor.common.Transformer;
import nl.imvertor.common.xsl.extensions.ImvertorCompareXML;
/**
* An XmlFile represents an XmlFile on the file system.
*
* The XmlFile is an AnyFile and therefore does not access the chain environment.
*
* @author arjan
*
*/
public class XmlFile extends AnyFile implements ErrorHandler {
private static final long serialVersionUID = -4351737187940152153L;
protected static final Logger logger = Logger.getLogger(XmlFile.class);
static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
protected static final String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces";
protected static final String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";
protected static final String SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema";
protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
protected static final String EXTERNAL_PARAMETER_ENTITIES_ID = "http://xml.org/sax/features/external-parameter-entities";
protected static final String EXTERNAL_GENERAL_ENTITIES_ID = "http://xml.org/sax/features/external-general-entities";
protected static final String IGNORE_DTD_FEATURE_ID = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; // http://www.isocra.com/2006/05/making-xerces-ignore-a-dtd/
protected static final String LEXICAL_HANDLER_PROPERTY_ID = "http://xml.org/sax/properties/lexical-handler";
protected static final String DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser";
protected static final int WFCODE_OKAY = 0;
protected static final int WFCODE_WARNING = 1;
protected static final int WFCODE_ERROR = 2;
protected static final int WFCODE_FATAL = 3;
// parameters die de verwerking van het XML file bepalen
public boolean namespace = true; // namespace aware?
public boolean validate = false; // valideren?
public boolean xinclude = true; // herken xinclude statements?
public boolean schema = false; // zoek naar schema bij valideren?
public boolean schemacheck = false; // schema ook checken?
public boolean dtd = false; // zoek naar dtd bij valideren?
public boolean auto = false; // automagically determine how to parse this file?
public boolean external = false; // externe entiteiten ophalen?
public boolean inquiry = false; // zoek alleen maar naar informatie over dit file?
private Document dom = null;
private int wfcode = WFCODE_OKAY; // a code indicating the Wellformedness of the XML file.
private Vector<String> messages = new Vector<String>();
public static void main(String[] args) {
//XmlFile file = new XmlFile("D:\\projects\\arjan\\Java development\\CommonHandlers\\sandbox\\EHcache\\config\\ehcache.xml");
XmlFile file = new XmlFile("D:\\projects\\validprojects\\Kadaster-Imvertor\\Imvertor-OS-work\\default\\comply\\template\\xl\\worksheets\\sheet1.xml");
System.out.println(file.isValid());
file.getMessages();
}
public XmlFile(String pathname) {
super(pathname);
}
public XmlFile(File file) {
super(file.getAbsolutePath());
}
public XmlFile(File folder, String filename) {
super(folder,filename);
}
public String getFileType() {
return "XML";
}
/**
* Lees een file in naar een DOM Document.
*
* @param file
* @return
* @throws Exception
*/
public Document toDocument() throws Exception {
Document d = buildDom();
return d;
}
/**
* Zet een Document weg als file. Transformeer middels het XSLT file. Als
* XSLT file is "", identity transform.
*
* @param doc
* @param xsltfile
* @param parms
* @throws Exception
*/
public void fromDocument(Document doc) throws Exception {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("XML 3.0 LS 3.0");
if (impl == null) {
System.out.println("No DOMImplementation found !");
System.exit(0);
}
LSSerializer serializer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
output.setEncoding("UTF-8");
output.setByteStream(new FileOutputStream(this));
serializer.write(doc, output);
}
/**
* Build a DOM Document representation of this XML file.
*
* @return
* @throws Exception
*/
private Document buildDom() throws Exception {
return this.buildDom(this);
}
/**
* Build a DOM Document representation of some external XML file.
*
* @return
* @throws Exception
*/
private Document buildDom(File file) throws Exception {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
InputSource in = new InputSource(file.getAbsolutePath());
docFactory.setValidating(validate);
docFactory.setXIncludeAware(xinclude);
docFactory.setFeature(VALIDATION_FEATURE_ID, validate);
docFactory.setFeature(NAMESPACES_FEATURE_ID, namespace);
docFactory.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schema);
docFactory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemacheck);
docFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_ID, external);
docFactory.setFeature(EXTERNAL_PARAMETER_ENTITIES_ID, external);
DocumentBuilder db = docFactory.newDocumentBuilder();
return db.parse(in);
}
public Document getDom() throws Exception {
if (dom == null)
return buildDom(this);
else
return dom;
}
/**
* Benader de inhoud<SUF>*/
public String xpath(String expression, HashMap<String, String> parms) throws Exception {
return (String) xpathToObject(expression, parms, XPathConstants.STRING);
}
/**
* Benader de inhoud dmv. een Xpath expressie.
*
* @param outfile
* @param xslFilePath
* @throws Exception
*/
public Object xpathToObject(String expression, HashMap<String, String> parms, QName returnType) throws Exception {
if (dom == null) dom = this.buildDom();
XPathFactoryImpl xpf = new XPathFactoryImpl();
XPath xpe = xpf.newXPath();
XPathExpression find = xpe.compile(expression);
return find.evaluate(dom, returnType);
}
public String xpath(String expression) throws Exception {
return xpath(expression,new HashMap<String,String>());
}
/**
* Transform the XML file to a canonical form
*
* @param outfile
* @param xslFile
* @param parms
* @throws Exception
*/
public void fileToCanonicalFile(XmlFile outfile) throws Exception {
logger.debug("Canonizing " + this.getCanonicalPath());
if (dom == null) dom = this.buildDom();
outfile.fromDocument(dom);
}
public boolean isWellFormed() {
messages.removeAllElements();
try {
wfcode = WFCODE_OKAY;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(this);
builder.parse(new InputSource(this.getCanonicalPath()));
} catch (Exception e) {
wfcode = WFCODE_FATAL;
}
return wfcode < WFCODE_ERROR;
}
public boolean isValid() {
messages.removeAllElements();
try {
wfcode = WFCODE_OKAY;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
factory.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(this);
builder.parse(new InputSource(this.getCanonicalPath()));
} catch (Exception e) {
wfcode = WFCODE_FATAL;
}
return wfcode < WFCODE_ERROR;
}
public Vector<String> getMessages() {
return messages;
}
/**
* Compare this control file to the passed test file, store result in file. Return true if files are the same.
*
* Difference types are listed as constants in
* <a href="http://xmlunit.sourceforge.net/api/org/custommonkey/xmlunit/DifferenceConstants.html">here</a>
*
* @param controlXmlPath
* @param testXmlPath
* @param resultPath
* @return
* @throws Exception
*/
public boolean xmlUnitCompareXML(XmlFile testXmlFile, XmlFile resultFile) throws Exception {
XmlFile controlXmlFile = this;
XMLUnit.setCompareUnmatched(false);
XMLTestCase testcase = new Case(this.getName());
DetailedDiff myDiff = new DetailedDiff(testcase.compareXML(controlXmlFile.getContent(), testXmlFile.getContent()));
@SuppressWarnings("unchecked")
List<Difference> allDifferences = myDiff.getAllDifferences();
Iterator<Difference> it = allDifferences.iterator();
String analysis = "<diffs>";
while (it.hasNext()) {
Difference d = it.next();
analysis += "<diff"
+ " desc=\"" + safe(d.getDescription()) + "\""
+ ">";
analysis += "<ctrl"
+ " path=\"" + d.getControlNodeDetail().getXpathLocation() + "\""
+ " value=\"" + safe(d.getControlNodeDetail().getValue()) + "\""
+ "/>";
analysis += "<test"
+ " path=\"" + d.getTestNodeDetail().getXpathLocation() + "\""
+ " value=\"" + safe(d.getTestNodeDetail().getValue()) + "\""
+ "/>";
analysis += "</diff>";
}
analysis += "</diffs>";
resultFile.setContent(analysis);
return (allDifferences.size() == 0) ? true: false;
}
/**
* Replace special characters in XML string.
*
* @param s
* @return
*/
private String safe(String s) {
s = StringUtils.replace(s,"&","&");
s = StringUtils.replace(s,"<","<");
s = StringUtils.replace(s,">",">");
s = StringUtils.replace(s,"\"",""");
return s;
}
/**
* Introduce the XmlFile class as a valid JUnit TestCase class.
*
* @author arjan
*
*/
private class Case extends XMLTestCase {
public Case(String name) {
super(name);
}
}
@Override
public void error(SAXParseException exception) throws SAXException {
messages.add(exception.getMessage());
wfcode = WFCODE_ERROR;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
messages.add(exception.getMessage());
wfcode = WFCODE_FATAL;
}
@Override
public void warning(SAXParseException exception) throws SAXException {
messages.add(exception.getMessage());
wfcode = WFCODE_WARNING;
}
public static String xmlescape(String s) {
s = s.replace("&", "&");
s = s.replace("<", "<");
return s;
}
/**
* See IM-147 Documentatie release ondersteunen.
*
* This method compares the current XML file to any other XML file. Results are written to a listing XML file.
*
* This XML file is the control XML file, and is compared to test XML file.
*
* @return
* @throws Exception
*/
public boolean compare(XmlFile testXmlFile, Configurator configurator) throws Exception {
String compareLabel = configurator.getParm("system", "compare-label");
// create a transformer
Transformer transformer = new Transformer();
transformer.setExtensionFunction(new ImvertorCompareXML());
Boolean valid = true;
//TODO Duplicate, redundant?
XmlFile ctrlNameFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_CONTROL_NAME_FILE")); // imvertor.20.docrelease.1.1.compare-control-name.xml
XmlFile testNameFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_TEST_NAME_FILE")); // imvertor.20.docrelease.1.2.compare-test-name.xml
XmlFile infoConfig = new XmlFile(configurator.getParm("properties","IMVERTOR_COMPARE_CONFIG")); // Imvert-compare-config.xml
// This transformer will pass regular XML parameters to the stylesheet.
// This is because the compare core code is not part of the Imvertor framework, but developed separately.
// We therefore do not use the XMLConfiguration approach here.
transformer.setXslParm("identify-construct-by-function", "name"); // the name of the construct is the only identifier
//TODO name of id??
transformer.setXslParm("info-config", infoConfig.toURI().toString());
transformer.setXslParm("info-ctrlpath", this.getCanonicalPath());
transformer.setXslParm("info-testpath", "(test path)");
transformer.setXslParm("compare-label", compareLabel);
// determine temporary files
XmlFile controlModelFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_CONTROL_MODEL_FILE")); // imvertor.20.docrelease.1.1.compare-control-model.xml
XmlFile testModelFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_TEST_MODEL_FILE")); // imvertor.20.docrelease.1.2.compare-test-model.xml
XmlFile controlSimpleFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_CONTROL_SIMPLE_FILE")); // imvertor.20.docrelease.1.1.compare-control-simple.xml
XmlFile testSimpleFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_TEST_SIMPLE_FILE")); // imvertor.20.docrelease.1.2.compare-test-simple.xml
XmlFile diffXml = new XmlFile(configurator.getParm("properties","WORK_COMPARE_DIFF_FILE")); // imvertor.20.docrelease.2.compare-diff.xml
XmlFile listingXml = new XmlFile(configurator.getParm("properties","WORK_COMPARE_LISTING_FILE")); // imvertor.20.docrelease.3.compare-listing.xml
XslFile tempXsl = new XslFile(configurator.getParm("properties","COMPARE_GENERATED_XSLPATH"));
//clean
XslFile cleanerXsl = new XslFile(configurator.getParm("properties","IMVERTOR_COMPARE_CLEAN_XSLPATH"));
XslFile simpleXsl = new XslFile(configurator.getParm("properties","IMVERTOR_COMPARE_SIMPLE_XSLPATH"));
valid = valid && transformer.transform(this,controlModelFile,cleanerXsl);
valid = valid && transformer.transform(testXmlFile,testModelFile,cleanerXsl);
// simplify
transformer.setXslParm("ctrl-name-mapping-filepath", ctrlNameFile.toURI().toString()); // file:/D:/.../Imvertor-OS-work/imvert/imvertor.20.compare-control-name.xml
transformer.setXslParm("test-name-mapping-filepath", testNameFile.toURI().toString());
transformer.setXslParm("comparison-role", "ctrl");
valid = valid && transformer.transform(controlModelFile,controlSimpleFile,simpleXsl);
transformer.setXslParm("comparison-role", "test");
valid = valid && transformer.transform(testModelFile,testSimpleFile,simpleXsl);
// compare
XslFile compareXsl = new XslFile(configurator.getParm("properties","COMPARE_GENERATOR_XSLPATH"));
transformer.setXslParm("ctrl-filepath", controlSimpleFile.getCanonicalPath());
transformer.setXslParm("test-filepath", testSimpleFile.getCanonicalPath());
transformer.setXslParm("diff-filepath", diffXml.getCanonicalPath());
valid = valid && transformer.transform(controlSimpleFile, tempXsl, compareXsl);
// create listing
XslFile listingXsl = new XslFile(configurator.getParm("properties","IMVERTOR_COMPARE_LISTING_XSLPATH"));
valid = valid && transformer.transform(controlSimpleFile,listingXml,listingXsl);
// get the number of differences found
int differences = ((NodeList) listingXml.xpathToObject("/*/*",null,XPathConstants.NODESET)).getLength();
configurator.setParm("appinfo", "compare-differences-" + compareLabel, differences);
// Build report
boolean result = valid && (differences == 0);
return result;
}
}
|
53303_7 | /*
* Copyright (C) 2016 Dienst voor het kadaster en de openbare registers
*
* This file is part of Imvertor.
*
* Imvertor 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.
*
* Imvertor 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 Imvertor. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.imvertor.EpCompiler;
import java.io.IOException;
import org.apache.log4j.Logger;
import nl.imvertor.common.Configurator;
import nl.imvertor.common.Step;
import nl.imvertor.common.Transformer;
import nl.imvertor.common.exceptions.ConfiguratorException;
import nl.imvertor.common.file.AnyFile;
import nl.imvertor.common.file.AnyFolder;
import nl.imvertor.common.file.XmlFile;
// see also https://github.com/Imvertor/Imvertor-Maven/issues/56
public class EpCompiler extends Step {
protected static final Logger logger = Logger.getLogger(EpCompiler.class);
public static final String STEP_NAME = "EpCompiler";
public static final String VC_IDENTIFIER = "$Id: $";
/**
* run the main translation
*/
public boolean run() throws Exception{
// set up the configuration for this step
configurator.setActiveStepName(STEP_NAME);
prepare();
runner.info(logger,"Compiling EP");
generate();
configurator.setStepDone(STEP_NAME);
// save any changes to the work configuration for report and future steps
configurator.save();
report();
return runner.succeeds();
}
/**
* Generate EP file suited for Kadaster and OGC Json schema.
*
* @throws Exception
*/
public boolean generate() throws Exception {
// create a transformer
Transformer transformer = new Transformer();
boolean succeeds = true;
runner.debug(logger,"CHAIN","Generating EP");
String epSchema = (requiresMIM() ? "EP2.xsd" : "EP.xsd");
transformer.setXslParm("ep-schema-path","xsd/" + epSchema);
// Create EP
if (requiresMIM()) {
// check of MIM resultaat beschikbaar is
succeeds = succeeds && AnyFile.exists(configurator.getXParm("properties/WORK_MIMFORMAT_XMLPATH",false));
// verwerk MIM naar EP
succeeds = succeeds && transformer.transformStep("properties/WORK_MIMFORMAT_XMLPATH","properties/WORK_EP_XMLPATH_PRE", "properties/IMVERTOR_EP2_XSLPATH_PRE");
succeeds = succeeds && transformer.transformStep("properties/WORK_EP_XMLPATH_PRE","properties/WORK_EP_XMLPATH_CORE", "properties/IMVERTOR_EP2_XSLPATH_CORE");
succeeds = succeeds && transformer.transformStep("properties/WORK_EP_XMLPATH_CORE","properties/WORK_EP_XMLPATH_FINAL", "properties/IMVERTOR_EP2_XSLPATH_POST");
} else
succeeds = succeeds && transformer.transformStep("properties/WORK_EMBELLISH_FILE","properties/WORK_EP_XMLPATH_FINAL", "properties/IMVERTOR_EP_XSLPATH");
// if this succeeds, copy the EP schema to the app and validate
if (succeeds) {
AnyFolder workAppFolder = new AnyFolder(Configurator.getInstance().getXParm("system/work-app-folder-path"));
XmlFile resultEpFile = new XmlFile(configurator.getXParm("properties/WORK_EP_XMLPATH_FINAL"));
XmlFile targetEpFile = new XmlFile(workAppFolder.getCanonicalPath() + "/ep/ep.xml"); // TODO nette naam, bepaald door gebruiker oid.
resultEpFile.copyFile(targetEpFile);
XmlFile managedSchemaFile = new XmlFile(Configurator.getInstance().getBaseFolder().getCanonicalPath() + "/etc/xsd/EP/" + epSchema);
XmlFile targetSchemaFile = new XmlFile(workAppFolder.getCanonicalPath() + "/ep/xsd/" + epSchema);
managedSchemaFile.copyFile(targetSchemaFile);
// Debug: test if EP is okay
succeeds = succeeds && resultEpFile.isValid();
}
configurator.setXParm("system/ep-schema-created",succeeds);
configurator.setXParm("system/ep-schema-version",requiresMIM() ? "2" : "1"); // when MIM based, generated EP version 2
return succeeds;
}
public static Boolean requiresMIM() throws IOException, ConfiguratorException {
// bepaal of hier de MIM schema variant moet worden gebruikt
String jsonschemasource = Configurator.getInstance().getXParm("cli/jsonschemasource",false);
return (jsonschemasource == null || jsonschemasource.equals("MIM"));
}
}
| Imvertor/Imvertor-Maven | src/main/java/nl/imvertor/EpCompiler/EpCompiler.java | 1,599 | // check of MIM resultaat beschikbaar is
| line_comment | nl | /*
* Copyright (C) 2016 Dienst voor het kadaster en de openbare registers
*
* This file is part of Imvertor.
*
* Imvertor 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.
*
* Imvertor 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 Imvertor. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.imvertor.EpCompiler;
import java.io.IOException;
import org.apache.log4j.Logger;
import nl.imvertor.common.Configurator;
import nl.imvertor.common.Step;
import nl.imvertor.common.Transformer;
import nl.imvertor.common.exceptions.ConfiguratorException;
import nl.imvertor.common.file.AnyFile;
import nl.imvertor.common.file.AnyFolder;
import nl.imvertor.common.file.XmlFile;
// see also https://github.com/Imvertor/Imvertor-Maven/issues/56
public class EpCompiler extends Step {
protected static final Logger logger = Logger.getLogger(EpCompiler.class);
public static final String STEP_NAME = "EpCompiler";
public static final String VC_IDENTIFIER = "$Id: $";
/**
* run the main translation
*/
public boolean run() throws Exception{
// set up the configuration for this step
configurator.setActiveStepName(STEP_NAME);
prepare();
runner.info(logger,"Compiling EP");
generate();
configurator.setStepDone(STEP_NAME);
// save any changes to the work configuration for report and future steps
configurator.save();
report();
return runner.succeeds();
}
/**
* Generate EP file suited for Kadaster and OGC Json schema.
*
* @throws Exception
*/
public boolean generate() throws Exception {
// create a transformer
Transformer transformer = new Transformer();
boolean succeeds = true;
runner.debug(logger,"CHAIN","Generating EP");
String epSchema = (requiresMIM() ? "EP2.xsd" : "EP.xsd");
transformer.setXslParm("ep-schema-path","xsd/" + epSchema);
// Create EP
if (requiresMIM()) {
// check of<SUF>
succeeds = succeeds && AnyFile.exists(configurator.getXParm("properties/WORK_MIMFORMAT_XMLPATH",false));
// verwerk MIM naar EP
succeeds = succeeds && transformer.transformStep("properties/WORK_MIMFORMAT_XMLPATH","properties/WORK_EP_XMLPATH_PRE", "properties/IMVERTOR_EP2_XSLPATH_PRE");
succeeds = succeeds && transformer.transformStep("properties/WORK_EP_XMLPATH_PRE","properties/WORK_EP_XMLPATH_CORE", "properties/IMVERTOR_EP2_XSLPATH_CORE");
succeeds = succeeds && transformer.transformStep("properties/WORK_EP_XMLPATH_CORE","properties/WORK_EP_XMLPATH_FINAL", "properties/IMVERTOR_EP2_XSLPATH_POST");
} else
succeeds = succeeds && transformer.transformStep("properties/WORK_EMBELLISH_FILE","properties/WORK_EP_XMLPATH_FINAL", "properties/IMVERTOR_EP_XSLPATH");
// if this succeeds, copy the EP schema to the app and validate
if (succeeds) {
AnyFolder workAppFolder = new AnyFolder(Configurator.getInstance().getXParm("system/work-app-folder-path"));
XmlFile resultEpFile = new XmlFile(configurator.getXParm("properties/WORK_EP_XMLPATH_FINAL"));
XmlFile targetEpFile = new XmlFile(workAppFolder.getCanonicalPath() + "/ep/ep.xml"); // TODO nette naam, bepaald door gebruiker oid.
resultEpFile.copyFile(targetEpFile);
XmlFile managedSchemaFile = new XmlFile(Configurator.getInstance().getBaseFolder().getCanonicalPath() + "/etc/xsd/EP/" + epSchema);
XmlFile targetSchemaFile = new XmlFile(workAppFolder.getCanonicalPath() + "/ep/xsd/" + epSchema);
managedSchemaFile.copyFile(targetSchemaFile);
// Debug: test if EP is okay
succeeds = succeeds && resultEpFile.isValid();
}
configurator.setXParm("system/ep-schema-created",succeeds);
configurator.setXParm("system/ep-schema-version",requiresMIM() ? "2" : "1"); // when MIM based, generated EP version 2
return succeeds;
}
public static Boolean requiresMIM() throws IOException, ConfiguratorException {
// bepaal of hier de MIM schema variant moet worden gebruikt
String jsonschemasource = Configurator.getInstance().getXParm("cli/jsonschemasource",false);
return (jsonschemasource == null || jsonschemasource.equals("MIM"));
}
}
|
57131_23 | /*
* 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.indooratlas.android.sdk.examples.ar.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.TrackingState;
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;
/** Renders the detected AR planes. */
public class PlaneRenderer {
private static final String TAG = PlaneRenderer.class.getSimpleName();
// Shader names.
private static final String VERTEX_SHADER_NAME = "shaders/plane.vert";
private static final String FRAGMENT_SHADER_NAME = "shaders/plane.frag";
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 planeProgram;
private final int[] textures = new int[1];
private int planeXZPositionAlphaAttribute;
private int planeModelUniform;
private int planeNormalUniform;
private int planeModelViewProjectionUniform;
private int textureUniform;
private int lineColorUniform;
private int dotColorUniform;
private int gridControlUniform;
private int planeUvMatrixUniform;
private FloatBuffer vertexBuffer =
ByteBuffer.allocateDirect(INITIAL_VERTEX_BUFFER_SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
private ShortBuffer indexBuffer =
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 final float[] modelMatrix = new float[16];
private final float[] modelViewMatrix = new float[16];
private final float[] modelViewProjectionMatrix = new float[16];
private final float[] planeColor = new float[] {1f, 1f, 1f, 1f};
private final float[] planeAngleUvMatrix =
new float[4]; // 2x2 rotation matrix applied to uv coords.
private final Map<Plane, Integer> planeIndexMap = new HashMap<>();
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 {
int vertexShader =
ShaderUtil.loadGLShader(TAG, context, GLES20.GL_VERTEX_SHADER, VERTEX_SHADER_NAME);
int passthroughShader =
ShaderUtil.loadGLShader(TAG, context, GLES20.GL_FRAGMENT_SHADER, FRAGMENT_SHADER_NAME);
planeProgram = GLES20.glCreateProgram();
GLES20.glAttachShader(planeProgram, vertexShader);
GLES20.glAttachShader(planeProgram, passthroughShader);
GLES20.glLinkProgram(planeProgram);
GLES20.glUseProgram(planeProgram);
ShaderUtil.checkGLError(TAG, "Program creation");
// Read the texture.
Bitmap textureBitmap =
BitmapFactory.decodeStream(context.getAssets().open(gridDistanceTextureName));
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glGenTextures(textures.length, textures, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[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");
planeXZPositionAlphaAttribute = GLES20.glGetAttribLocation(planeProgram, "a_XZPositionAlpha");
planeModelUniform = GLES20.glGetUniformLocation(planeProgram, "u_Model");
planeNormalUniform = GLES20.glGetUniformLocation(planeProgram, "u_Normal");
planeModelViewProjectionUniform =
GLES20.glGetUniformLocation(planeProgram, "u_ModelViewProjection");
textureUniform = GLES20.glGetUniformLocation(planeProgram, "u_Texture");
lineColorUniform = GLES20.glGetUniformLocation(planeProgram, "u_lineColor");
dotColorUniform = GLES20.glGetUniformLocation(planeProgram, "u_dotColor");
gridControlUniform = GLES20.glGetUniformLocation(planeProgram, "u_gridControl");
planeUvMatrixUniform = GLES20.glGetUniformLocation(planeProgram, "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, modelMatrix, 0, 16);
if (boundary == null) {
vertexBuffer.limit(0);
indexBuffer.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 (vertexBuffer.capacity() < numVertices * COORDS_PER_VERTEX) {
int size = vertexBuffer.capacity();
while (size < numVertices * COORDS_PER_VERTEX) {
size *= 2;
}
vertexBuffer =
ByteBuffer.allocateDirect(BYTES_PER_FLOAT * size)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
}
vertexBuffer.rewind();
vertexBuffer.limit(numVertices * COORDS_PER_VERTEX);
if (indexBuffer.capacity() < numIndices) {
int size = indexBuffer.capacity();
while (size < numIndices) {
size *= 2;
}
indexBuffer =
ByteBuffer.allocateDirect(BYTES_PER_SHORT * size)
.order(ByteOrder.nativeOrder())
.asShortBuffer();
}
indexBuffer.rewind();
indexBuffer.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();
vertexBuffer.put(x);
vertexBuffer.put(z);
vertexBuffer.put(0.0f);
vertexBuffer.put(x * xScale);
vertexBuffer.put(z * zScale);
vertexBuffer.put(1.0f);
}
// step 1, perimeter
indexBuffer.put((short) ((boundaryVertices - 1) * 2));
for (int i = 0; i < boundaryVertices; ++i) {
indexBuffer.put((short) (i * 2));
indexBuffer.put((short) (i * 2 + 1));
}
indexBuffer.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) {
indexBuffer.put((short) ((boundaryVertices - 1 - i) * 2 + 1));
indexBuffer.put((short) (i * 2 + 1));
}
if (boundaryVertices % 2 != 0) {
indexBuffer.put((short) ((boundaryVertices / 2) * 2 + 1));
}
}
private void draw(float[] cameraView, float[] cameraPerspective, float[] planeNormal) {
// Build the ModelView and ModelViewProjection matrices
// for calculating cube position and light.
Matrix.multiplyMM(modelViewMatrix, 0, cameraView, 0, modelMatrix, 0);
Matrix.multiplyMM(modelViewProjectionMatrix, 0, cameraPerspective, 0, modelViewMatrix, 0);
// Set the position of the plane
vertexBuffer.rewind();
GLES20.glVertexAttribPointer(
planeXZPositionAlphaAttribute,
COORDS_PER_VERTEX,
GLES20.GL_FLOAT,
false,
BYTES_PER_FLOAT * COORDS_PER_VERTEX,
vertexBuffer);
// Set the Model and ModelViewProjection matrices in the shader.
GLES20.glUniformMatrix4fv(planeModelUniform, 1, false, modelMatrix, 0);
GLES20.glUniform3f(planeNormalUniform, planeNormal[0], planeNormal[1], planeNormal[2]);
GLES20.glUniformMatrix4fv(
planeModelViewProjectionUniform, 1, false, modelViewProjectionMatrix, 0);
indexBuffer.rewind();
GLES20.glDrawElements(
GLES20.GL_TRIANGLE_STRIP, indexBuffer.limit(), GLES20.GL_UNSIGNED_SHORT, indexBuffer);
ShaderUtil.checkGLError(TAG, "Drawing plane");
}
static class SortablePlane {
final float distance;
final Plane plane;
SortablePlane(float distance, Plane plane) {
this.distance = distance;
this.plane = 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<>();
for (Plane plane : allPlanes) {
if (plane.getTrackingState() != TrackingState.TRACKING || plane.getSubsumedBy() != null) {
continue;
}
float distance = calculateDistanceToPlane(plane.getCenterPose(), cameraPose);
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.distance, b.distance);
}
});
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(planeProgram);
// Attach the texture.
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);
GLES20.glUniform1i(textureUniform, 0);
// Shared fragment uniforms.
GLES20.glUniform4fv(gridControlUniform, 1, GRID_CONTROL, 0);
// Enable vertex arrays
GLES20.glEnableVertexAttribArray(planeXZPositionAlphaAttribute);
ShaderUtil.checkGLError(TAG, "Setting up to draw planes");
for (SortablePlane sortedPlane : sortedPlanes) {
Plane plane = sortedPlane.plane;
float[] planeMatrix = new float[16];
plane.getCenterPose().toMatrix(planeMatrix, 0);
float[] normal = new float[3];
// Get transformed Y axis of plane's coordinate system.
plane.getCenterPose().getTransformedAxis(1, 1.0f, normal, 0);
updatePlaneParameters(
planeMatrix, plane.getExtentX(), plane.getExtentZ(), plane.getPolygon());
// Get plane index. Keep a map to assign same indices to same planes.
Integer planeIndex = planeIndexMap.get(plane);
if (planeIndex == null) {
planeIndex = planeIndexMap.size();
planeIndexMap.put(plane, planeIndex);
}
// Set plane color.
GLES20.glUniform4fv(lineColorUniform, 1, planeColor, 0);
GLES20.glUniform4fv(dotColorUniform, 1, planeColor, 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;
planeAngleUvMatrix[0] = +(float) Math.cos(angleRadians) * uScale;
planeAngleUvMatrix[1] = -(float) Math.sin(angleRadians) * vScale;
planeAngleUvMatrix[2] = +(float) Math.sin(angleRadians) * uScale;
planeAngleUvMatrix[3] = +(float) Math.cos(angleRadians) * vScale;
GLES20.glUniformMatrix2fv(planeUvMatrixUniform, 1, false, planeAngleUvMatrix, 0);
draw(cameraView, cameraPerspective, normal);
}
// Clean up the state we set
GLES20.glDisableVertexAttribArray(planeXZPositionAlphaAttribute);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
GLES20.glDisable(GLES20.GL_BLEND);
GLES20.glDepthMask(true);
GLES20.glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
ShaderUtil.checkGLError(TAG, "Cleaning up after drawing planes");
}
// Calculate the normal distance to plane from cameraPose, the given planePose should have y axis
// parallel to plane's normal, for example plane's center pose or hit test pose.
public static float calculateDistanceToPlane(Pose planePose, Pose cameraPose) {
float[] normal = new float[3];
float cameraX = cameraPose.tx();
float cameraY = cameraPose.ty();
float cameraZ = cameraPose.tz();
// Get transformed Y axis of plane's coordinate system.
planePose.getTransformedAxis(1, 1.0f, normal, 0);
// Compute dot product of plane's normal with vector from camera to plane center.
return (cameraX - planePose.tx()) * normal[0]
+ (cameraY - planePose.ty()) * normal[1]
+ (cameraZ - planePose.tz()) * normal[2];
}
}
| IndoorAtlas/android-sdk-examples | Basic/src/arCore/java/com/indooratlas/android/sdk/examples/ar/rendering/PlaneRenderer.java | 5,611 | // 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.indooratlas.android.sdk.examples.ar.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.TrackingState;
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;
/** Renders the detected AR planes. */
public class PlaneRenderer {
private static final String TAG = PlaneRenderer.class.getSimpleName();
// Shader names.
private static final String VERTEX_SHADER_NAME = "shaders/plane.vert";
private static final String FRAGMENT_SHADER_NAME = "shaders/plane.frag";
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 planeProgram;
private final int[] textures = new int[1];
private int planeXZPositionAlphaAttribute;
private int planeModelUniform;
private int planeNormalUniform;
private int planeModelViewProjectionUniform;
private int textureUniform;
private int lineColorUniform;
private int dotColorUniform;
private int gridControlUniform;
private int planeUvMatrixUniform;
private FloatBuffer vertexBuffer =
ByteBuffer.allocateDirect(INITIAL_VERTEX_BUFFER_SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
private ShortBuffer indexBuffer =
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 final float[] modelMatrix = new float[16];
private final float[] modelViewMatrix = new float[16];
private final float[] modelViewProjectionMatrix = new float[16];
private final float[] planeColor = new float[] {1f, 1f, 1f, 1f};
private final float[] planeAngleUvMatrix =
new float[4]; // 2x2 rotation matrix applied to uv coords.
private final Map<Plane, Integer> planeIndexMap = new HashMap<>();
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 {
int vertexShader =
ShaderUtil.loadGLShader(TAG, context, GLES20.GL_VERTEX_SHADER, VERTEX_SHADER_NAME);
int passthroughShader =
ShaderUtil.loadGLShader(TAG, context, GLES20.GL_FRAGMENT_SHADER, FRAGMENT_SHADER_NAME);
planeProgram = GLES20.glCreateProgram();
GLES20.glAttachShader(planeProgram, vertexShader);
GLES20.glAttachShader(planeProgram, passthroughShader);
GLES20.glLinkProgram(planeProgram);
GLES20.glUseProgram(planeProgram);
ShaderUtil.checkGLError(TAG, "Program creation");
// Read the texture.
Bitmap textureBitmap =
BitmapFactory.decodeStream(context.getAssets().open(gridDistanceTextureName));
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glGenTextures(textures.length, textures, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[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");
planeXZPositionAlphaAttribute = GLES20.glGetAttribLocation(planeProgram, "a_XZPositionAlpha");
planeModelUniform = GLES20.glGetUniformLocation(planeProgram, "u_Model");
planeNormalUniform = GLES20.glGetUniformLocation(planeProgram, "u_Normal");
planeModelViewProjectionUniform =
GLES20.glGetUniformLocation(planeProgram, "u_ModelViewProjection");
textureUniform = GLES20.glGetUniformLocation(planeProgram, "u_Texture");
lineColorUniform = GLES20.glGetUniformLocation(planeProgram, "u_lineColor");
dotColorUniform = GLES20.glGetUniformLocation(planeProgram, "u_dotColor");
gridControlUniform = GLES20.glGetUniformLocation(planeProgram, "u_gridControl");
planeUvMatrixUniform = GLES20.glGetUniformLocation(planeProgram, "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, modelMatrix, 0, 16);
if (boundary == null) {
vertexBuffer.limit(0);
indexBuffer.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 (vertexBuffer.capacity() < numVertices * COORDS_PER_VERTEX) {
int size = vertexBuffer.capacity();
while (size < numVertices * COORDS_PER_VERTEX) {
size *= 2;
}
vertexBuffer =
ByteBuffer.allocateDirect(BYTES_PER_FLOAT * size)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
}
vertexBuffer.rewind();
vertexBuffer.limit(numVertices * COORDS_PER_VERTEX);
if (indexBuffer.capacity() < numIndices) {
int size = indexBuffer.capacity();
while (size < numIndices) {
size *= 2;
}
indexBuffer =
ByteBuffer.allocateDirect(BYTES_PER_SHORT * size)
.order(ByteOrder.nativeOrder())
.asShortBuffer();
}
indexBuffer.rewind();
indexBuffer.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();
vertexBuffer.put(x);
vertexBuffer.put(z);
vertexBuffer.put(0.0f);
vertexBuffer.put(x * xScale);
vertexBuffer.put(z * zScale);
vertexBuffer.put(1.0f);
}
// step 1, perimeter
indexBuffer.put((short) ((boundaryVertices - 1) * 2));
for (int i = 0; i < boundaryVertices; ++i) {
indexBuffer.put((short) (i * 2));
indexBuffer.put((short) (i * 2 + 1));
}
indexBuffer.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) {
indexBuffer.put((short) ((boundaryVertices - 1 - i) * 2 + 1));
indexBuffer.put((short) (i * 2 + 1));
}
if (boundaryVertices % 2 != 0) {
indexBuffer.put((short) ((boundaryVertices / 2) * 2 + 1));
}
}
private void draw(float[] cameraView, float[] cameraPerspective, float[] planeNormal) {
// Build the ModelView and ModelViewProjection matrices
// for calculating cube position and light.
Matrix.multiplyMM(modelViewMatrix, 0, cameraView, 0, modelMatrix, 0);
Matrix.multiplyMM(modelViewProjectionMatrix, 0, cameraPerspective, 0, modelViewMatrix, 0);
// Set the position of the plane
vertexBuffer.rewind();
GLES20.glVertexAttribPointer(
planeXZPositionAlphaAttribute,
COORDS_PER_VERTEX,
GLES20.GL_FLOAT,
false,
BYTES_PER_FLOAT * COORDS_PER_VERTEX,
vertexBuffer);
// Set the Model and ModelViewProjection matrices in the shader.
GLES20.glUniformMatrix4fv(planeModelUniform, 1, false, modelMatrix, 0);
GLES20.glUniform3f(planeNormalUniform, planeNormal[0], planeNormal[1], planeNormal[2]);
GLES20.glUniformMatrix4fv(
planeModelViewProjectionUniform, 1, false, modelViewProjectionMatrix, 0);
indexBuffer.rewind();
GLES20.glDrawElements(
GLES20.GL_TRIANGLE_STRIP, indexBuffer.limit(), GLES20.GL_UNSIGNED_SHORT, indexBuffer);
ShaderUtil.checkGLError(TAG, "Drawing plane");
}
static class SortablePlane {
final float distance;
final Plane plane;
SortablePlane(float distance, Plane plane) {
this.distance = distance;
this.plane = 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<>();
for (Plane plane : allPlanes) {
if (plane.getTrackingState() != TrackingState.TRACKING || plane.getSubsumedBy() != null) {
continue;
}
float distance = calculateDistanceToPlane(plane.getCenterPose(), cameraPose);
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.distance, b.distance);
}
});
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(planeProgram);
// Attach the texture.
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);
GLES20.glUniform1i(textureUniform, 0);
// Shared fragment uniforms.
GLES20.glUniform4fv(gridControlUniform, 1, GRID_CONTROL, 0);
// Enable vertex arrays
GLES20.glEnableVertexAttribArray(planeXZPositionAlphaAttribute);
ShaderUtil.checkGLError(TAG, "Setting up to draw planes");
for (SortablePlane sortedPlane : sortedPlanes) {
Plane plane = sortedPlane.plane;
float[] planeMatrix = new float[16];
plane.getCenterPose().toMatrix(planeMatrix, 0);
float[] normal = new float[3];
// Get transformed Y axis of plane's coordinate system.
plane.getCenterPose().getTransformedAxis(1, 1.0f, normal, 0);
updatePlaneParameters(
planeMatrix, plane.getExtentX(), plane.getExtentZ(), plane.getPolygon());
// Get plane index. Keep a map to assign same indices to same planes.
Integer planeIndex = planeIndexMap.get(plane);
if (planeIndex == null) {
planeIndex = planeIndexMap.size();
planeIndexMap.put(plane, planeIndex);
}
// Set plane color.
GLES20.glUniform4fv(lineColorUniform, 1, planeColor, 0);
GLES20.glUniform4fv(dotColorUniform, 1, planeColor, 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;
planeAngleUvMatrix[0] = +(float) Math.cos(angleRadians) * uScale;
planeAngleUvMatrix[1] = -(float) Math.sin(angleRadians) * vScale;
planeAngleUvMatrix[2] = +(float) Math.sin(angleRadians) * uScale;
planeAngleUvMatrix[3] = +(float) Math.cos(angleRadians) * vScale;
GLES20.glUniformMatrix2fv(planeUvMatrixUniform, 1, false, planeAngleUvMatrix, 0);
draw(cameraView, cameraPerspective, normal);
}
// Clean up the state we set
GLES20.glDisableVertexAttribArray(planeXZPositionAlphaAttribute);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
GLES20.glDisable(GLES20.GL_BLEND);
GLES20.glDepthMask(true);
GLES20.glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
ShaderUtil.checkGLError(TAG, "Cleaning up after drawing planes");
}
// Calculate the normal distance to plane from cameraPose, the given planePose should have y axis
// parallel to plane's normal, for example plane's center pose or hit test pose.
public static float calculateDistanceToPlane(Pose planePose, Pose cameraPose) {
float[] normal = new float[3];
float cameraX = cameraPose.tx();
float cameraY = cameraPose.ty();
float cameraZ = cameraPose.tz();
// Get transformed Y axis of plane's coordinate system.
planePose.getTransformedAxis(1, 1.0f, normal, 0);
// Compute dot product of plane's normal with vector from camera to plane center.
return (cameraX - planePose.tx()) * normal[0]
+ (cameraY - planePose.ty()) * normal[1]
+ (cameraZ - planePose.tz()) * normal[2];
}
}
|
20491_3 | package domein;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import util.EdelsteenSoort;
import util.TaalHelper;
public class Spel {
private List<Speler> spelers;
private Speler startSpeler;
private OntwikkelingskaartRepository okr;
private EdeleRepository er;
private EdelsteenAantal diamantAantal, smaragdAantal, saffierAantal, onyxAantal, robijnAantal;
private Speler huidigeSpeler;
private List<Ontwikkelingskaart> niveau1, niveau2, niveau3, niveau1Zichtbaar, niveau2Zichtbaar, niveau3Zichtbaar;
private List<Edele> edelen, beschikbareEdelenSpeler = new ArrayList<>();
private List<Edele> edeleInSpel;
private List<Speler> winnaars;
private static final int prestigePunten =15;// 50
public Spel() {
okr = new OntwikkelingskaartRepository();
er = new EdeleRepository();
spelers = new ArrayList<>();
}
public void meldAan(Speler sp){
spelers.add(sp);
}
public void shuffleOntwikkelingsKaarten() {
niveau1 = okr.geefKaartenNiveau1();
Collections.shuffle(niveau1);
niveau2 = okr.geefKaartenNiveau2();
Collections.shuffle(niveau2);
niveau3 = okr.geefKaartenNiveau3();
Collections.shuffle(niveau3);
}
public void shuffleEdelen() {
edelen= er.geefEdelen();
Collections.shuffle(edelen);
}
public void geefKaartenAantalSpelers() {
if(spelers.size() == 2) {
edeleInSpel = new ArrayList<>();
diamantAantal = new EdelsteenAantal(4,EdelsteenSoort.DIAMANT);
smaragdAantal = new EdelsteenAantal(4,EdelsteenSoort.SMARAGD);
robijnAantal = new EdelsteenAantal(4,EdelsteenSoort.ROBIJN);
saffierAantal = new EdelsteenAantal(4,EdelsteenSoort.SAFFIER);
onyxAantal = new EdelsteenAantal(4,EdelsteenSoort.ONYX);
for(int i = 0; i < 3; i++) {
edeleInSpel.add(edelen.get(i));
}
}
if(spelers.size() == 3) {
edeleInSpel = new ArrayList<>();
diamantAantal = new EdelsteenAantal(5,EdelsteenSoort.DIAMANT);
smaragdAantal = new EdelsteenAantal(5,EdelsteenSoort.SMARAGD);
robijnAantal = new EdelsteenAantal(5,EdelsteenSoort.ROBIJN);
saffierAantal = new EdelsteenAantal(5,EdelsteenSoort.SAFFIER);
onyxAantal = new EdelsteenAantal(5,EdelsteenSoort.ONYX);
for(int i = 0; i < 4; i++) {
edeleInSpel.add(edelen.get(i));
}
}
if(spelers.size() == 4) {
edeleInSpel = new ArrayList<>();
diamantAantal = new EdelsteenAantal(7,EdelsteenSoort.DIAMANT);
smaragdAantal = new EdelsteenAantal(7,EdelsteenSoort.SMARAGD);
robijnAantal = new EdelsteenAantal(7,EdelsteenSoort.ROBIJN);
saffierAantal = new EdelsteenAantal(7,EdelsteenSoort.SAFFIER);
onyxAantal = new EdelsteenAantal(7,EdelsteenSoort.ONYX);
for(int i = 0; i < 5; i++) {
edeleInSpel.add(edelen.get(i));
}
}
}
public void maakZichtbareOntwikkelingskaarten() {
niveau1Zichtbaar = new ArrayList<>();
niveau2Zichtbaar = new ArrayList<>();
niveau3Zichtbaar = new ArrayList<>();
for(int i =0;i<4;i++) {
niveau1Zichtbaar.add(niveau1.remove(0));
niveau2Zichtbaar.add(niveau2.remove(0));
niveau3Zichtbaar.add(niveau3.remove(0));
}
}
public List<Edele> controleerMogelijkheidTotEdelen() {
int aantalSoortenEdelstenen ;
int aantalJuisteBonusen ;
List<Edele> tmpLijstEdelenSpeler = new ArrayList<>();
for(int i = 0; i < edeleInSpel.size(); i++) { //per in edelen in spel
aantalJuisteBonusen = 0; // opnieuw op 0 zetten anders blijft het optellen -> foute edelen geven
aantalSoortenEdelstenen = edeleInSpel.get(i).getKosten().size();
for(EdelsteenAantal kost : edeleInSpel.get(i).getKosten())// per kost
for(EdelsteenAantal bonus : huidigeSpeler.getBonussen())// per bonus
if(kost.getSoort().equals(bonus.getSoort()))
if(kost.getAantal() <= bonus.getAantal())
aantalJuisteBonusen++;
if(aantalJuisteBonusen == aantalSoortenEdelstenen) {
tmpLijstEdelenSpeler.add(edeleInSpel.get(i));
}
}
return tmpLijstEdelenSpeler;
}
public void koopKaartNiveau1(int index) {
// krijgt index binnen van kaartnummer
// index kaart uit lijst zichtbare kaarten halen
// deze kaart in huidigeSpeler.ontwikkelingskaartenInBezit
if(kanKaartGekochtWorden(niveau1Zichtbaar.get(index))) {
if(niveau1.size()!=0) {
// fiches uit bezit speler halen
for(EdelsteenAantal kost : niveau1Zichtbaar.get(index).getKosten()) {
huidigeSpeler.verwijderEdelsteenfiches(kost.getSoort(), kost.getAantal());
fichesTerugSpel(kost);
}
huidigeSpeler.voegOntwikkelingskaartToe(niveau1Zichtbaar.remove(index));
niveau1Zichtbaar.add(index,niveau1.remove(0));
}
}
}
public void koopKaartNiveau2(int index) {
if(kanKaartGekochtWorden(niveau2Zichtbaar.get(index))) {
if(niveau2.size()!=0) {
for(EdelsteenAantal kost : niveau2Zichtbaar.get(index).getKosten()) {
huidigeSpeler.verwijderEdelsteenfiches(kost.getSoort(), kost.getAantal());
fichesTerugSpel(kost);
}
huidigeSpeler.voegOntwikkelingskaartToe(niveau2Zichtbaar.remove(index));
niveau2Zichtbaar.add(index,niveau2.remove(0));
}
}
}
public void koopKaartNiveau3(int index) {
if(kanKaartGekochtWorden(niveau3Zichtbaar.get(index))) {
if(niveau3.size()!=0) {
for(EdelsteenAantal kost : niveau3Zichtbaar.get(index).getKosten()) {
huidigeSpeler.verwijderEdelsteenfiches(kost.getSoort(), kost.getAantal());
fichesTerugSpel(kost);
}
huidigeSpeler.voegOntwikkelingskaartToe(niveau3Zichtbaar.remove(index));
niveau3Zichtbaar.add(index,niveau3.remove(0));
}
}
}
private void fichesTerugSpel(EdelsteenAantal fiche) {
switch(fiche.getSoort()) {
case DIAMANT -> diamantAantal.setAantal(diamantAantal.getAantal() + fiche.getAantal());
case ONYX -> onyxAantal.setAantal(onyxAantal.getAantal() + fiche.getAantal());
case ROBIJN -> robijnAantal.setAantal(robijnAantal.getAantal() + fiche.getAantal());
case SAFFIER -> saffierAantal.setAantal(saffierAantal.getAantal() + fiche.getAantal());
case SMARAGD -> smaragdAantal.setAantal(smaragdAantal.getAantal() + fiche.getAantal());
}
}
private void fichesUitSpel(EdelsteenAantal fiche) {
switch(fiche.getSoort()) {
case DIAMANT -> diamantAantal.setAantal(diamantAantal.getAantal() - fiche.getAantal());
case ONYX -> onyxAantal.setAantal(onyxAantal.getAantal() - fiche.getAantal());
case ROBIJN -> robijnAantal.setAantal(robijnAantal.getAantal() - fiche.getAantal());
case SAFFIER -> saffierAantal.setAantal(saffierAantal.getAantal() - fiche.getAantal());
case SMARAGD -> smaragdAantal.setAantal(smaragdAantal.getAantal() - fiche.getAantal());
}
}
private boolean kanKaartGekochtWorden(Ontwikkelingskaart k) {
int aantalSoortenEdelstenen = k.getKosten().size();
int aantalGoed = 0;
for(EdelsteenAantal kost : k.getKosten())
for(EdelsteenAantal inBezit : huidigeSpeler.getEdelsteenfichesInBezit())
if(kost.getSoort().equals(inBezit.getSoort()))
if(kost.getAantal() <= inBezit.getAantal())
aantalGoed++;
if(aantalGoed == aantalSoortenEdelstenen)
return true;
throw new IllegalArgumentException(TaalHelper.getText("kanKaartGekochtWorden"));//rb.getString("kanKaartGekochtWorden")
}
public void neemEdelsteenAantal(EdelsteenAantal fiche) {
switch(fiche.getSoort()) {
case DIAMANT -> controleerAantal(diamantAantal.getAantal(), fiche.getSoort());
case ONYX -> controleerAantal(onyxAantal.getAantal(), fiche.getSoort());
case ROBIJN -> controleerAantal(robijnAantal.getAantal(), fiche.getSoort());
case SAFFIER -> controleerAantal(saffierAantal.getAantal(), fiche.getSoort());
case SMARAGD -> controleerAantal(smaragdAantal.getAantal(), fiche.getSoort());
}
huidigeSpeler.voegEdelsteenficheToe(fiche);
}
public void voegTmpLijstFichesToeAanPermLijst() {
List<EdelsteenAantal> lijst = huidigeSpeler.getTmpFicheLijst();
for(int i = 0; i < lijst.size(); i++) {
fichesUitSpel(lijst.get(i));
}
huidigeSpeler.voegTmpLijstFichesToeAanPermLijst();
}
public void verwijder1FicheUitTmpLijst(EdelsteenAantal fiche) {
huidigeSpeler.verwijder1FicheUitTmpLijst(fiche);
}
private void controleerAantal(int aantal, EdelsteenSoort soort) {
if(aantal == 0)
throw new IllegalArgumentException(String.format(TaalHelper.getText("controleerAantal"), soort.name().toLowerCase()));
}
public boolean controleerHoeveelheidFichesNemen(EdelsteenAantal fiche) {
List<EdelsteenAantal> tmpLijst = huidigeSpeler.getTmpFicheLijst();
if(tmpLijst.size() == 3)
return false;
else {
for(int i = 0; i < tmpLijst.size(); i++) {
EdelsteenAantal spelerFiche = tmpLijst.get(i);
if(spelerFiche.getSoort().equals(fiche.getSoort())) {
if(spelerFiche.getAantal() == 2)
throw new IllegalArgumentException(TaalHelper.getText("controleerHoeveelheidFichesNemen1"));
if(aantalInSpel(fiche.getSoort()) < 4)
throw new IllegalArgumentException(TaalHelper.getText("controleerHoeveelheidFichesNemen2"));
else if(tmpLijst.size() == 2)
throw new IllegalArgumentException(TaalHelper.getText("controleerHoeveelheidFichesNemen3"));
huidigeSpeler.voegTmpFicheToe(fiche);
return true;
}
huidigeSpeler.voegTmpFicheToe(fiche);
return true;
}
}
huidigeSpeler.voegTmpFicheToe(fiche);
return true;
}
private int aantalInSpel(EdelsteenSoort soort) {
return switch(soort) {
case DIAMANT -> diamantAantal.getAantal();
case ONYX -> onyxAantal.getAantal();
case ROBIJN -> robijnAantal.getAantal();
case SAFFIER -> saffierAantal.getAantal();
case SMARAGD -> smaragdAantal.getAantal();
};
}
public boolean controleerAlTweeGelijkeFichesGekozen() {
List<EdelsteenAantal> tmpLijst = huidigeSpeler.getTmpFicheLijst();
if(tmpLijst.get(0).getSoort().equals(tmpLijst.get(1).getSoort())) {
return true;
}
return false;
}
public List<Ontwikkelingskaart> getNiveau1Zichtbaar() {
return niveau1Zichtbaar;
}
public List<Ontwikkelingskaart> getNiveau2Zichtbaar() {
return niveau2Zichtbaar;
}
public List<Ontwikkelingskaart> getNiveau3Zichtbaar() {
return niveau3Zichtbaar;
}
public List<Speler> getSpelers() {
return spelers;
}
public List<Edele> getEdeleInSpel() {
return edeleInSpel;
}
public List<Ontwikkelingskaart> getNiveau1() {
return niveau1;
}
public List<Ontwikkelingskaart> getNiveau2() {
return niveau2;
}
public List<Ontwikkelingskaart> getNiveau3() {
return niveau3;
}
public EdelsteenAantal getDiamantAantal() {
return diamantAantal;
}
public EdelsteenAantal getOnyxAantal() {
return onyxAantal;
}
public EdelsteenAantal getRobijnAantal() {
return robijnAantal;
}
public EdelsteenAantal getSaffierAantal() {
return saffierAantal;
}
public EdelsteenAantal getSmaragdAantal() {
return smaragdAantal;
}
public Speler getHuidigeSpeler() {
return huidigeSpeler;
}
public Speler getStartSpeler() {
return startSpeler;
}
public List<Speler> getWinnaars() {
return winnaars;
}
public List<Edele> getBeschikbareEdelenSpeler() {
return beschikbareEdelenSpeler;
}
public List<EdelsteenAantal> getTmpLijstSpeler() {
return huidigeSpeler.getTmpFicheLijst();
}
public boolean isEindeSpel() {
for(Speler speler: spelers) {
if(speler.getTotaalAantalPrestigePunten() >= prestigePunten) {
bepaalWinnaar();
return true;
}
}
return false;
}
private void bepaalWinnaar() {
int maxPrestigepunten=Integer.MIN_VALUE;
int minAantalOwk=Integer.MAX_VALUE;
winnaars = new ArrayList<>();
for(Speler speler:spelers) {
if(speler.getTotaalAantalPrestigePunten() >= prestigePunten) {
if(speler.getTotaalAantalPrestigePunten() == maxPrestigepunten) {
if(speler.getOntwikkelingskaartenInBezit().size() < minAantalOwk) {
minAantalOwk = speler.getOntwikkelingskaartenInBezit().size();
for(int i=0; i < winnaars.size(); i++) {
if(winnaars.get(i).getOntwikkelingskaartenInBezit().size() > minAantalOwk)
winnaars.remove(i);
}
winnaars.add(speler);
}
else if(speler.getOntwikkelingskaartenInBezit().size() == minAantalOwk) {
winnaars.add(speler);
}
}
else if(speler.getTotaalAantalPrestigePunten()> maxPrestigepunten) {
maxPrestigepunten=speler.getTotaalAantalPrestigePunten();
for(int i=0; i < winnaars.size(); i++) {
if(winnaars.get(i).getTotaalAantalPrestigePunten() < maxPrestigepunten)
winnaars.remove(i);
}
winnaars.add(speler);
}
}
}
}
public void isStartSpeler() {
int jongsteJaar=Integer.MIN_VALUE;
startSpeler=spelers.get(0);
for(Speler speler:spelers) {
if(speler.getGeboortejaar() == jongsteJaar) {
if(speler.getGebruikersnaam().length() > startSpeler.getGebruikersnaam().length()) {
jongsteJaar=speler.getGeboortejaar();
startSpeler=speler;
}
else if(speler.getGebruikersnaam().length() == startSpeler.getGebruikersnaam().length()) {
String str1 = speler.getGebruikersnaam();
String str2 = startSpeler.getGebruikersnaam();
int result;
do {
result = str1.compareToIgnoreCase(str2);
if(result > 0) // 1
startSpeler = speler;
}while(result <= 0);
}
}
else if(speler.getGeboortejaar()>jongsteJaar) {
jongsteJaar=speler.getGeboortejaar();
startSpeler=speler;
}
}
startSpeler.isStartspeler(true);
startSpeler.isAanDeBeurt(true);
huidigeSpeler = startSpeler;
}
public List<Speler> updateIsAanDeBeurt(List<Speler> tmpSpelerLijst) {
if(tmpSpelerLijst.contains(startSpeler)) {
tmpSpelerLijst.remove(huidigeSpeler);
return tmpSpelerLijst;
}
boolean klaar = false;
while(!klaar) {
if(tmpSpelerLijst.size()!=1) {
for(int i = 0; i < spelers.size(); i++) {
String naam = spelers.get(i).getGebruikersnaam();
if(tmpSpelerLijst.get(0).getGebruikersnaam().equals(naam)) {
huidigeSpeler.isAanDeBeurt(false);
tmpSpelerLijst.remove(huidigeSpeler);
huidigeSpeler = tmpSpelerLijst.get(0);
huidigeSpeler.isAanDeBeurt(true);
klaar = true;
}
if(klaar)break;
}
}
else if(tmpSpelerLijst.size() == 1) {
huidigeSpeler.isAanDeBeurt(false);
tmpSpelerLijst.remove(huidigeSpeler);
huidigeSpeler = tmpSpelerLijst.get(0);
huidigeSpeler.isAanDeBeurt(true);
klaar = true;
}
}
return tmpSpelerLijst;
}
public void resetSpelers() {
isStartSpeler();
for(Speler s : spelers) {
if(!s.geefisStartSpeler()) {
s.isAanDeBeurt(false);
}
}
}
} | IndraVanWynendaele/splendor | src/domein/Spel.java | 6,337 | // index kaart uit lijst zichtbare kaarten halen | line_comment | nl | package domein;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import util.EdelsteenSoort;
import util.TaalHelper;
public class Spel {
private List<Speler> spelers;
private Speler startSpeler;
private OntwikkelingskaartRepository okr;
private EdeleRepository er;
private EdelsteenAantal diamantAantal, smaragdAantal, saffierAantal, onyxAantal, robijnAantal;
private Speler huidigeSpeler;
private List<Ontwikkelingskaart> niveau1, niveau2, niveau3, niveau1Zichtbaar, niveau2Zichtbaar, niveau3Zichtbaar;
private List<Edele> edelen, beschikbareEdelenSpeler = new ArrayList<>();
private List<Edele> edeleInSpel;
private List<Speler> winnaars;
private static final int prestigePunten =15;// 50
public Spel() {
okr = new OntwikkelingskaartRepository();
er = new EdeleRepository();
spelers = new ArrayList<>();
}
public void meldAan(Speler sp){
spelers.add(sp);
}
public void shuffleOntwikkelingsKaarten() {
niveau1 = okr.geefKaartenNiveau1();
Collections.shuffle(niveau1);
niveau2 = okr.geefKaartenNiveau2();
Collections.shuffle(niveau2);
niveau3 = okr.geefKaartenNiveau3();
Collections.shuffle(niveau3);
}
public void shuffleEdelen() {
edelen= er.geefEdelen();
Collections.shuffle(edelen);
}
public void geefKaartenAantalSpelers() {
if(spelers.size() == 2) {
edeleInSpel = new ArrayList<>();
diamantAantal = new EdelsteenAantal(4,EdelsteenSoort.DIAMANT);
smaragdAantal = new EdelsteenAantal(4,EdelsteenSoort.SMARAGD);
robijnAantal = new EdelsteenAantal(4,EdelsteenSoort.ROBIJN);
saffierAantal = new EdelsteenAantal(4,EdelsteenSoort.SAFFIER);
onyxAantal = new EdelsteenAantal(4,EdelsteenSoort.ONYX);
for(int i = 0; i < 3; i++) {
edeleInSpel.add(edelen.get(i));
}
}
if(spelers.size() == 3) {
edeleInSpel = new ArrayList<>();
diamantAantal = new EdelsteenAantal(5,EdelsteenSoort.DIAMANT);
smaragdAantal = new EdelsteenAantal(5,EdelsteenSoort.SMARAGD);
robijnAantal = new EdelsteenAantal(5,EdelsteenSoort.ROBIJN);
saffierAantal = new EdelsteenAantal(5,EdelsteenSoort.SAFFIER);
onyxAantal = new EdelsteenAantal(5,EdelsteenSoort.ONYX);
for(int i = 0; i < 4; i++) {
edeleInSpel.add(edelen.get(i));
}
}
if(spelers.size() == 4) {
edeleInSpel = new ArrayList<>();
diamantAantal = new EdelsteenAantal(7,EdelsteenSoort.DIAMANT);
smaragdAantal = new EdelsteenAantal(7,EdelsteenSoort.SMARAGD);
robijnAantal = new EdelsteenAantal(7,EdelsteenSoort.ROBIJN);
saffierAantal = new EdelsteenAantal(7,EdelsteenSoort.SAFFIER);
onyxAantal = new EdelsteenAantal(7,EdelsteenSoort.ONYX);
for(int i = 0; i < 5; i++) {
edeleInSpel.add(edelen.get(i));
}
}
}
public void maakZichtbareOntwikkelingskaarten() {
niveau1Zichtbaar = new ArrayList<>();
niveau2Zichtbaar = new ArrayList<>();
niveau3Zichtbaar = new ArrayList<>();
for(int i =0;i<4;i++) {
niveau1Zichtbaar.add(niveau1.remove(0));
niveau2Zichtbaar.add(niveau2.remove(0));
niveau3Zichtbaar.add(niveau3.remove(0));
}
}
public List<Edele> controleerMogelijkheidTotEdelen() {
int aantalSoortenEdelstenen ;
int aantalJuisteBonusen ;
List<Edele> tmpLijstEdelenSpeler = new ArrayList<>();
for(int i = 0; i < edeleInSpel.size(); i++) { //per in edelen in spel
aantalJuisteBonusen = 0; // opnieuw op 0 zetten anders blijft het optellen -> foute edelen geven
aantalSoortenEdelstenen = edeleInSpel.get(i).getKosten().size();
for(EdelsteenAantal kost : edeleInSpel.get(i).getKosten())// per kost
for(EdelsteenAantal bonus : huidigeSpeler.getBonussen())// per bonus
if(kost.getSoort().equals(bonus.getSoort()))
if(kost.getAantal() <= bonus.getAantal())
aantalJuisteBonusen++;
if(aantalJuisteBonusen == aantalSoortenEdelstenen) {
tmpLijstEdelenSpeler.add(edeleInSpel.get(i));
}
}
return tmpLijstEdelenSpeler;
}
public void koopKaartNiveau1(int index) {
// krijgt index binnen van kaartnummer
// index kaart<SUF>
// deze kaart in huidigeSpeler.ontwikkelingskaartenInBezit
if(kanKaartGekochtWorden(niveau1Zichtbaar.get(index))) {
if(niveau1.size()!=0) {
// fiches uit bezit speler halen
for(EdelsteenAantal kost : niveau1Zichtbaar.get(index).getKosten()) {
huidigeSpeler.verwijderEdelsteenfiches(kost.getSoort(), kost.getAantal());
fichesTerugSpel(kost);
}
huidigeSpeler.voegOntwikkelingskaartToe(niveau1Zichtbaar.remove(index));
niveau1Zichtbaar.add(index,niveau1.remove(0));
}
}
}
public void koopKaartNiveau2(int index) {
if(kanKaartGekochtWorden(niveau2Zichtbaar.get(index))) {
if(niveau2.size()!=0) {
for(EdelsteenAantal kost : niveau2Zichtbaar.get(index).getKosten()) {
huidigeSpeler.verwijderEdelsteenfiches(kost.getSoort(), kost.getAantal());
fichesTerugSpel(kost);
}
huidigeSpeler.voegOntwikkelingskaartToe(niveau2Zichtbaar.remove(index));
niveau2Zichtbaar.add(index,niveau2.remove(0));
}
}
}
public void koopKaartNiveau3(int index) {
if(kanKaartGekochtWorden(niveau3Zichtbaar.get(index))) {
if(niveau3.size()!=0) {
for(EdelsteenAantal kost : niveau3Zichtbaar.get(index).getKosten()) {
huidigeSpeler.verwijderEdelsteenfiches(kost.getSoort(), kost.getAantal());
fichesTerugSpel(kost);
}
huidigeSpeler.voegOntwikkelingskaartToe(niveau3Zichtbaar.remove(index));
niveau3Zichtbaar.add(index,niveau3.remove(0));
}
}
}
private void fichesTerugSpel(EdelsteenAantal fiche) {
switch(fiche.getSoort()) {
case DIAMANT -> diamantAantal.setAantal(diamantAantal.getAantal() + fiche.getAantal());
case ONYX -> onyxAantal.setAantal(onyxAantal.getAantal() + fiche.getAantal());
case ROBIJN -> robijnAantal.setAantal(robijnAantal.getAantal() + fiche.getAantal());
case SAFFIER -> saffierAantal.setAantal(saffierAantal.getAantal() + fiche.getAantal());
case SMARAGD -> smaragdAantal.setAantal(smaragdAantal.getAantal() + fiche.getAantal());
}
}
private void fichesUitSpel(EdelsteenAantal fiche) {
switch(fiche.getSoort()) {
case DIAMANT -> diamantAantal.setAantal(diamantAantal.getAantal() - fiche.getAantal());
case ONYX -> onyxAantal.setAantal(onyxAantal.getAantal() - fiche.getAantal());
case ROBIJN -> robijnAantal.setAantal(robijnAantal.getAantal() - fiche.getAantal());
case SAFFIER -> saffierAantal.setAantal(saffierAantal.getAantal() - fiche.getAantal());
case SMARAGD -> smaragdAantal.setAantal(smaragdAantal.getAantal() - fiche.getAantal());
}
}
private boolean kanKaartGekochtWorden(Ontwikkelingskaart k) {
int aantalSoortenEdelstenen = k.getKosten().size();
int aantalGoed = 0;
for(EdelsteenAantal kost : k.getKosten())
for(EdelsteenAantal inBezit : huidigeSpeler.getEdelsteenfichesInBezit())
if(kost.getSoort().equals(inBezit.getSoort()))
if(kost.getAantal() <= inBezit.getAantal())
aantalGoed++;
if(aantalGoed == aantalSoortenEdelstenen)
return true;
throw new IllegalArgumentException(TaalHelper.getText("kanKaartGekochtWorden"));//rb.getString("kanKaartGekochtWorden")
}
public void neemEdelsteenAantal(EdelsteenAantal fiche) {
switch(fiche.getSoort()) {
case DIAMANT -> controleerAantal(diamantAantal.getAantal(), fiche.getSoort());
case ONYX -> controleerAantal(onyxAantal.getAantal(), fiche.getSoort());
case ROBIJN -> controleerAantal(robijnAantal.getAantal(), fiche.getSoort());
case SAFFIER -> controleerAantal(saffierAantal.getAantal(), fiche.getSoort());
case SMARAGD -> controleerAantal(smaragdAantal.getAantal(), fiche.getSoort());
}
huidigeSpeler.voegEdelsteenficheToe(fiche);
}
public void voegTmpLijstFichesToeAanPermLijst() {
List<EdelsteenAantal> lijst = huidigeSpeler.getTmpFicheLijst();
for(int i = 0; i < lijst.size(); i++) {
fichesUitSpel(lijst.get(i));
}
huidigeSpeler.voegTmpLijstFichesToeAanPermLijst();
}
public void verwijder1FicheUitTmpLijst(EdelsteenAantal fiche) {
huidigeSpeler.verwijder1FicheUitTmpLijst(fiche);
}
private void controleerAantal(int aantal, EdelsteenSoort soort) {
if(aantal == 0)
throw new IllegalArgumentException(String.format(TaalHelper.getText("controleerAantal"), soort.name().toLowerCase()));
}
public boolean controleerHoeveelheidFichesNemen(EdelsteenAantal fiche) {
List<EdelsteenAantal> tmpLijst = huidigeSpeler.getTmpFicheLijst();
if(tmpLijst.size() == 3)
return false;
else {
for(int i = 0; i < tmpLijst.size(); i++) {
EdelsteenAantal spelerFiche = tmpLijst.get(i);
if(spelerFiche.getSoort().equals(fiche.getSoort())) {
if(spelerFiche.getAantal() == 2)
throw new IllegalArgumentException(TaalHelper.getText("controleerHoeveelheidFichesNemen1"));
if(aantalInSpel(fiche.getSoort()) < 4)
throw new IllegalArgumentException(TaalHelper.getText("controleerHoeveelheidFichesNemen2"));
else if(tmpLijst.size() == 2)
throw new IllegalArgumentException(TaalHelper.getText("controleerHoeveelheidFichesNemen3"));
huidigeSpeler.voegTmpFicheToe(fiche);
return true;
}
huidigeSpeler.voegTmpFicheToe(fiche);
return true;
}
}
huidigeSpeler.voegTmpFicheToe(fiche);
return true;
}
private int aantalInSpel(EdelsteenSoort soort) {
return switch(soort) {
case DIAMANT -> diamantAantal.getAantal();
case ONYX -> onyxAantal.getAantal();
case ROBIJN -> robijnAantal.getAantal();
case SAFFIER -> saffierAantal.getAantal();
case SMARAGD -> smaragdAantal.getAantal();
};
}
public boolean controleerAlTweeGelijkeFichesGekozen() {
List<EdelsteenAantal> tmpLijst = huidigeSpeler.getTmpFicheLijst();
if(tmpLijst.get(0).getSoort().equals(tmpLijst.get(1).getSoort())) {
return true;
}
return false;
}
public List<Ontwikkelingskaart> getNiveau1Zichtbaar() {
return niveau1Zichtbaar;
}
public List<Ontwikkelingskaart> getNiveau2Zichtbaar() {
return niveau2Zichtbaar;
}
public List<Ontwikkelingskaart> getNiveau3Zichtbaar() {
return niveau3Zichtbaar;
}
public List<Speler> getSpelers() {
return spelers;
}
public List<Edele> getEdeleInSpel() {
return edeleInSpel;
}
public List<Ontwikkelingskaart> getNiveau1() {
return niveau1;
}
public List<Ontwikkelingskaart> getNiveau2() {
return niveau2;
}
public List<Ontwikkelingskaart> getNiveau3() {
return niveau3;
}
public EdelsteenAantal getDiamantAantal() {
return diamantAantal;
}
public EdelsteenAantal getOnyxAantal() {
return onyxAantal;
}
public EdelsteenAantal getRobijnAantal() {
return robijnAantal;
}
public EdelsteenAantal getSaffierAantal() {
return saffierAantal;
}
public EdelsteenAantal getSmaragdAantal() {
return smaragdAantal;
}
public Speler getHuidigeSpeler() {
return huidigeSpeler;
}
public Speler getStartSpeler() {
return startSpeler;
}
public List<Speler> getWinnaars() {
return winnaars;
}
public List<Edele> getBeschikbareEdelenSpeler() {
return beschikbareEdelenSpeler;
}
public List<EdelsteenAantal> getTmpLijstSpeler() {
return huidigeSpeler.getTmpFicheLijst();
}
public boolean isEindeSpel() {
for(Speler speler: spelers) {
if(speler.getTotaalAantalPrestigePunten() >= prestigePunten) {
bepaalWinnaar();
return true;
}
}
return false;
}
private void bepaalWinnaar() {
int maxPrestigepunten=Integer.MIN_VALUE;
int minAantalOwk=Integer.MAX_VALUE;
winnaars = new ArrayList<>();
for(Speler speler:spelers) {
if(speler.getTotaalAantalPrestigePunten() >= prestigePunten) {
if(speler.getTotaalAantalPrestigePunten() == maxPrestigepunten) {
if(speler.getOntwikkelingskaartenInBezit().size() < minAantalOwk) {
minAantalOwk = speler.getOntwikkelingskaartenInBezit().size();
for(int i=0; i < winnaars.size(); i++) {
if(winnaars.get(i).getOntwikkelingskaartenInBezit().size() > minAantalOwk)
winnaars.remove(i);
}
winnaars.add(speler);
}
else if(speler.getOntwikkelingskaartenInBezit().size() == minAantalOwk) {
winnaars.add(speler);
}
}
else if(speler.getTotaalAantalPrestigePunten()> maxPrestigepunten) {
maxPrestigepunten=speler.getTotaalAantalPrestigePunten();
for(int i=0; i < winnaars.size(); i++) {
if(winnaars.get(i).getTotaalAantalPrestigePunten() < maxPrestigepunten)
winnaars.remove(i);
}
winnaars.add(speler);
}
}
}
}
public void isStartSpeler() {
int jongsteJaar=Integer.MIN_VALUE;
startSpeler=spelers.get(0);
for(Speler speler:spelers) {
if(speler.getGeboortejaar() == jongsteJaar) {
if(speler.getGebruikersnaam().length() > startSpeler.getGebruikersnaam().length()) {
jongsteJaar=speler.getGeboortejaar();
startSpeler=speler;
}
else if(speler.getGebruikersnaam().length() == startSpeler.getGebruikersnaam().length()) {
String str1 = speler.getGebruikersnaam();
String str2 = startSpeler.getGebruikersnaam();
int result;
do {
result = str1.compareToIgnoreCase(str2);
if(result > 0) // 1
startSpeler = speler;
}while(result <= 0);
}
}
else if(speler.getGeboortejaar()>jongsteJaar) {
jongsteJaar=speler.getGeboortejaar();
startSpeler=speler;
}
}
startSpeler.isStartspeler(true);
startSpeler.isAanDeBeurt(true);
huidigeSpeler = startSpeler;
}
public List<Speler> updateIsAanDeBeurt(List<Speler> tmpSpelerLijst) {
if(tmpSpelerLijst.contains(startSpeler)) {
tmpSpelerLijst.remove(huidigeSpeler);
return tmpSpelerLijst;
}
boolean klaar = false;
while(!klaar) {
if(tmpSpelerLijst.size()!=1) {
for(int i = 0; i < spelers.size(); i++) {
String naam = spelers.get(i).getGebruikersnaam();
if(tmpSpelerLijst.get(0).getGebruikersnaam().equals(naam)) {
huidigeSpeler.isAanDeBeurt(false);
tmpSpelerLijst.remove(huidigeSpeler);
huidigeSpeler = tmpSpelerLijst.get(0);
huidigeSpeler.isAanDeBeurt(true);
klaar = true;
}
if(klaar)break;
}
}
else if(tmpSpelerLijst.size() == 1) {
huidigeSpeler.isAanDeBeurt(false);
tmpSpelerLijst.remove(huidigeSpeler);
huidigeSpeler = tmpSpelerLijst.get(0);
huidigeSpeler.isAanDeBeurt(true);
klaar = true;
}
}
return tmpSpelerLijst;
}
public void resetSpelers() {
isStartSpeler();
for(Speler s : spelers) {
if(!s.geefisStartSpeler()) {
s.isAanDeBeurt(false);
}
}
}
} |
70050_1 | package be.vlaanderen.vip.magda.client;
import be.vlaanderen.vip.magda.client.diensten.subject.SubjectIdentificationNumber;
import be.vlaanderen.vip.magda.client.domeinservice.MagdaRegistrationInfo;
import jakarta.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.UUID;
/**
* The common part of a request to a MAGDA service. Has subclasses for specific service/versions.
* <p>
* Contains:
* <ul>
* <li>correlationId: unique correlation ID of the request</li>
* <li>requestId: unique ID of the request</li>
* <li>registration: registration code that can be resolved by a MagdaHoedanigService to obtain registration info (defaults to code "default" if not specified)</li>
* </ul>
*/
@Getter
@EqualsAndHashCode
public abstract class MagdaRequest {
protected abstract static class Builder<SELF extends Builder<SELF>> {
private String registration;
@SuppressWarnings("unchecked")
public SELF registration(String registration) {
this.registration = registration;
return (SELF) this;
}
protected String getRegistration() {
return Objects.toString(registration, DEFAULT_REGISTRATION);
}
}
public static final String DEFAULT_REGISTRATION = "default";
@Setter
private UUID correlationId;
private final UUID requestId = UUID.randomUUID();
@NotNull
private final String registration;
protected MagdaRequest(@NotNull String registration) {
this.registration = registration;
}
public abstract MagdaServiceIdentification magdaServiceIdentification();
public abstract SubjectIdentificationNumber getSubject();
public MagdaDocument toMagdaDocument(MagdaRegistrationInfo magdaRegistrationInfo) {
var serviceId = magdaServiceIdentification();
var document = Objects.requireNonNull(MagdaDocument.fromResource(MagdaDocument.class, "/templates/" + serviceId.getName() + "/" + serviceId.getVersion() + "/template.xml"));
fillIn(document, magdaRegistrationInfo);
return document;
}
protected void fillInCommonFields(MagdaDocument request, MagdaRegistrationInfo magdaRegistrationInfo) {
request.setValue("//Referte", getRequestId().toString());
request.setValue(getSubject().getXPathExpression(), getSubject().getValue());
final var now = Instant.now();
var ldt = LocalDateTime.ofInstant(now, ZoneId.of("Europe/Brussels"));
var dateFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
var today = ldt.format(dateFormatter);
request.setValue("//Context/Bericht/Tijdstip/Datum", today);
// Hardcoded 000 milliseconden wordt door alle Magda services aanvaard
// Afwezigheid van milliseconden of milliseconden <> 000 wordt door sommige services geweigerd
var timeFormat = DateTimeFormatter.ofPattern("HH:mm:ss");
var time = ldt.format(timeFormat) + ".000";
request.setValue("//Context/Bericht/Tijdstip/Tijd", time);
request.setValue("//Context/Bericht/Afzender/Identificatie", magdaRegistrationInfo.getIdentification());
var hoedanigheidscode = magdaRegistrationInfo.getHoedanigheidscode();
if(hoedanigheidscode.isEmpty()) {
request.removeNode("//Context/Bericht/Afzender/Hoedanigheid");
} else {
request.setValue("//Context/Bericht/Afzender/Hoedanigheid", hoedanigheidscode.get());
}
}
protected abstract void fillIn(MagdaDocument request, MagdaRegistrationInfo magdaRegistrationInfo);
} | Informatievlaanderen/MAGDA-Mock | interfaces/src/main/java/be/vlaanderen/vip/magda/client/MagdaRequest.java | 1,034 | // Hardcoded 000 milliseconden wordt door alle Magda services aanvaard | line_comment | nl | package be.vlaanderen.vip.magda.client;
import be.vlaanderen.vip.magda.client.diensten.subject.SubjectIdentificationNumber;
import be.vlaanderen.vip.magda.client.domeinservice.MagdaRegistrationInfo;
import jakarta.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.UUID;
/**
* The common part of a request to a MAGDA service. Has subclasses for specific service/versions.
* <p>
* Contains:
* <ul>
* <li>correlationId: unique correlation ID of the request</li>
* <li>requestId: unique ID of the request</li>
* <li>registration: registration code that can be resolved by a MagdaHoedanigService to obtain registration info (defaults to code "default" if not specified)</li>
* </ul>
*/
@Getter
@EqualsAndHashCode
public abstract class MagdaRequest {
protected abstract static class Builder<SELF extends Builder<SELF>> {
private String registration;
@SuppressWarnings("unchecked")
public SELF registration(String registration) {
this.registration = registration;
return (SELF) this;
}
protected String getRegistration() {
return Objects.toString(registration, DEFAULT_REGISTRATION);
}
}
public static final String DEFAULT_REGISTRATION = "default";
@Setter
private UUID correlationId;
private final UUID requestId = UUID.randomUUID();
@NotNull
private final String registration;
protected MagdaRequest(@NotNull String registration) {
this.registration = registration;
}
public abstract MagdaServiceIdentification magdaServiceIdentification();
public abstract SubjectIdentificationNumber getSubject();
public MagdaDocument toMagdaDocument(MagdaRegistrationInfo magdaRegistrationInfo) {
var serviceId = magdaServiceIdentification();
var document = Objects.requireNonNull(MagdaDocument.fromResource(MagdaDocument.class, "/templates/" + serviceId.getName() + "/" + serviceId.getVersion() + "/template.xml"));
fillIn(document, magdaRegistrationInfo);
return document;
}
protected void fillInCommonFields(MagdaDocument request, MagdaRegistrationInfo magdaRegistrationInfo) {
request.setValue("//Referte", getRequestId().toString());
request.setValue(getSubject().getXPathExpression(), getSubject().getValue());
final var now = Instant.now();
var ldt = LocalDateTime.ofInstant(now, ZoneId.of("Europe/Brussels"));
var dateFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
var today = ldt.format(dateFormatter);
request.setValue("//Context/Bericht/Tijdstip/Datum", today);
// Hardcoded 000<SUF>
// Afwezigheid van milliseconden of milliseconden <> 000 wordt door sommige services geweigerd
var timeFormat = DateTimeFormatter.ofPattern("HH:mm:ss");
var time = ldt.format(timeFormat) + ".000";
request.setValue("//Context/Bericht/Tijdstip/Tijd", time);
request.setValue("//Context/Bericht/Afzender/Identificatie", magdaRegistrationInfo.getIdentification());
var hoedanigheidscode = magdaRegistrationInfo.getHoedanigheidscode();
if(hoedanigheidscode.isEmpty()) {
request.removeNode("//Context/Bericht/Afzender/Hoedanigheid");
} else {
request.setValue("//Context/Bericht/Afzender/Hoedanigheid", hoedanigheidscode.get());
}
}
protected abstract void fillIn(MagdaDocument request, MagdaRegistrationInfo magdaRegistrationInfo);
} |
172133_1 | package Game;
import Framework.AI.BotInterface;
import Framework.Config;
import Framework.Dialogs.ConnectionDialog;
import Framework.Dialogs.DialogEvents;
import Framework.Dialogs.DialogInterface;
import Framework.Game.GameLogicInterface;
import Framework.GameStart;
import Framework.Networking.Connection;
import Framework.Networking.ConnectionInterface;
import Framework.Networking.NetworkEvents;
import Framework.Networking.Response.*;
import Framework.Networking.SimulatedConnection;
import Game.Controllers.BaseController;
import Game.Controllers.DialogEventsController;
import Game.Controllers.NetworkEventsController;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
/**
* Created by peterzen on 2017-03-23.
* Part of the othello project.
*/
public class StartGame extends Application implements GameStart {
private Stage stage;
private Scene scene;
private static ConnectionInterface conn;
private static ConnectionInterface oldConn;
private static final NetworkEvents networkEventHandler = new NetworkEventsController();
private final static DialogEvents dialogEventsController = new DialogEventsController();
private final static BaseController baseController = new BaseController();
public static void main(String[] args) {
launch(args);
}
public StartGame(Stage stage, Scene scene) throws IOException {
// Scene meegegeven die weer wordt vervangen door updateGameScene method. --> dus, is dit nodig?
this.stage = stage;
this.scene = scene;
// setup and save the connection
String host;
int port;
try {
host = Config.get("network", "host");
port = Integer.parseInt(Config.get("network", "port"));
setConnection(host, port);
} catch (Exception e) {
DialogInterface networkDialog = new ConnectionDialog(getDialogEventsController());
Platform.runLater(networkDialog::display);
}
if (!stage.isShowing()) {
stage.show();
}
// update and show the GUI
updateGameScene();
this.start();
}
public static void setConnection(String host, int port) {
try {
conn = new Connection(host, port, networkEventHandler);
} catch (Exception e) {
DialogInterface networkDialog = new ConnectionDialog(StartGame.getDialogEventsController());
Platform.runLater(networkDialog::display);
}
}
public static DialogEvents getDialogEventsController() {
return dialogEventsController;
}
public void updateGameScene() throws IOException {
// Load view
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Framework/GUI/fxml/View.fxml"));
fxmlLoader.setController(getBaseController());
Parent root = fxmlLoader.load();
Scene gameScene = new Scene(root);
this.scene = gameScene;
Platform.runLater(() -> this.stage.setScene(gameScene));
}
public static BaseController getBaseController() {
return baseController;
}
public StartGame() {
// This constructor only exists to support stand-alone starting
}
@Override
public void start() {
// when started from either the framework or standalone
// @DEBUG: challengeAcceptedResponse
// Response challengeResponse = new OurTurnResponse("");
// challengeResponse.executeCallback();
}
@Override
public void start(Stage stage) throws Exception {
// when being started standalone
new StartGame(stage, null);
}
public static ConnectionInterface getConn() {
return conn;
}
public static void toggleConnection() throws IOException {
ConnectionInterface tempConn;
if (conn instanceof Connection && oldConn == null) {
GameLogicInterface gameLogic = getBaseController().getBoardController().getGameLogic();
BotInterface bot = getBaseController().getBoardController().getAI();
oldConn = new SimulatedConnection("Reversi", gameLogic, bot, networkEventHandler);
}
// swaperoo: swap the Simulated and real Connection objects around
tempConn = conn;
conn = oldConn;
oldConn = tempConn;
System.out.println("now using: " + conn);
System.out.println("before we used: " + oldConn);
}
}
| Iniedergeval-Cool/othello | src/Game/StartGame.java | 1,140 | // Scene meegegeven die weer wordt vervangen door updateGameScene method. --> dus, is dit nodig? | line_comment | nl | package Game;
import Framework.AI.BotInterface;
import Framework.Config;
import Framework.Dialogs.ConnectionDialog;
import Framework.Dialogs.DialogEvents;
import Framework.Dialogs.DialogInterface;
import Framework.Game.GameLogicInterface;
import Framework.GameStart;
import Framework.Networking.Connection;
import Framework.Networking.ConnectionInterface;
import Framework.Networking.NetworkEvents;
import Framework.Networking.Response.*;
import Framework.Networking.SimulatedConnection;
import Game.Controllers.BaseController;
import Game.Controllers.DialogEventsController;
import Game.Controllers.NetworkEventsController;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
/**
* Created by peterzen on 2017-03-23.
* Part of the othello project.
*/
public class StartGame extends Application implements GameStart {
private Stage stage;
private Scene scene;
private static ConnectionInterface conn;
private static ConnectionInterface oldConn;
private static final NetworkEvents networkEventHandler = new NetworkEventsController();
private final static DialogEvents dialogEventsController = new DialogEventsController();
private final static BaseController baseController = new BaseController();
public static void main(String[] args) {
launch(args);
}
public StartGame(Stage stage, Scene scene) throws IOException {
// Scene meegegeven<SUF>
this.stage = stage;
this.scene = scene;
// setup and save the connection
String host;
int port;
try {
host = Config.get("network", "host");
port = Integer.parseInt(Config.get("network", "port"));
setConnection(host, port);
} catch (Exception e) {
DialogInterface networkDialog = new ConnectionDialog(getDialogEventsController());
Platform.runLater(networkDialog::display);
}
if (!stage.isShowing()) {
stage.show();
}
// update and show the GUI
updateGameScene();
this.start();
}
public static void setConnection(String host, int port) {
try {
conn = new Connection(host, port, networkEventHandler);
} catch (Exception e) {
DialogInterface networkDialog = new ConnectionDialog(StartGame.getDialogEventsController());
Platform.runLater(networkDialog::display);
}
}
public static DialogEvents getDialogEventsController() {
return dialogEventsController;
}
public void updateGameScene() throws IOException {
// Load view
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Framework/GUI/fxml/View.fxml"));
fxmlLoader.setController(getBaseController());
Parent root = fxmlLoader.load();
Scene gameScene = new Scene(root);
this.scene = gameScene;
Platform.runLater(() -> this.stage.setScene(gameScene));
}
public static BaseController getBaseController() {
return baseController;
}
public StartGame() {
// This constructor only exists to support stand-alone starting
}
@Override
public void start() {
// when started from either the framework or standalone
// @DEBUG: challengeAcceptedResponse
// Response challengeResponse = new OurTurnResponse("");
// challengeResponse.executeCallback();
}
@Override
public void start(Stage stage) throws Exception {
// when being started standalone
new StartGame(stage, null);
}
public static ConnectionInterface getConn() {
return conn;
}
public static void toggleConnection() throws IOException {
ConnectionInterface tempConn;
if (conn instanceof Connection && oldConn == null) {
GameLogicInterface gameLogic = getBaseController().getBoardController().getGameLogic();
BotInterface bot = getBaseController().getBoardController().getAI();
oldConn = new SimulatedConnection("Reversi", gameLogic, bot, networkEventHandler);
}
// swaperoo: swap the Simulated and real Connection objects around
tempConn = conn;
conn = oldConn;
oldConn = tempConn;
System.out.println("now using: " + conn);
System.out.println("before we used: " + oldConn);
}
}
|
66549_3 | package Game.Models;
import Framework.AI.BotInterface;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class AI implements BotInterface {
private TTTGame TTTGame;
private HashMap<String, Integer> possibleTurns;
private char player;
private int[] lastMove = new int[2];
public AI(TTTGame TTTGame, char player) {
this.TTTGame = TTTGame;
this.possibleTurns = new HashMap<>();
this.player = player;
}
public char getPlayer() {
return this.player;
}
public int[] doTurn(char[][] board) {
//check de open vakjes.
//dan: check of de andere gebruiker kan winnen met een van de open vakjes.
//zoja: geef dat vakje een score van 10. Sla op in mogelijke zet array
//Check per vakje of de AI kan winnen ná het zetten van het vakje. Zoja: geef score van 5 aan dat vakje
//Anders: geef score -1
int score;
for(int y = 0; y < board.length; y++) {
for(int x = 0; x < board[y].length; x++) {
if(board[y][x] == ' ') {
score = this.getScore(y, x, board);
this.possibleTurns.put("" + y + x, score);
}
else {
this.possibleTurns.put("" + y + x, -1);
}
}
}
System.out.println(this.possibleTurns);
this.placeTurn();
// Return this turns AI move [0:x, 1:y]
return this.lastMove;
}
private int getScore(int y, int x, char[][] board) {
//board[y][x] = this.player;
//check if I can win with this position
if(this.checkIfICanWin(y, x, board)) {
board[y][x] = ' ';
return 5;
}
//check if the other player can win with this position
if(this.checkIfOtherCanWin(y, x, board)) {
board[y][x] = ' ';
return 10;
}
board[y][x] = ' ';
//check if I can with after placing this position
return 0;
}
private boolean checkIfICanWin(int y, int x, char[][] testBoard) {
testBoard[y][x] = this.player;
return (testBoard[y][0] == this.player && testBoard[y][1] == this.player && testBoard[y][2] == this.player) ||
(testBoard[0][x] == this.player && testBoard[1][x] == this.player && testBoard[2][x] == this.player) ||
(testBoard[0][0] == this.player && testBoard[1][1] == this.player && testBoard[2][2] == this.player) ||
(testBoard[0][2] == this.player && testBoard[1][1] == this.player && testBoard[2][0] == this.player);
}
private boolean checkIfOtherCanWin(int y, int x, char[][] testBoard) {
char player = this.oppositePlayer();
testBoard[y][x] = player;
System.out.println("Huidige speler AI: " + this.player + ", andere speler: " + player);
return (testBoard[y][0] == player && testBoard[y][1] == player && testBoard[y][2] == player) ||
(testBoard[0][x] == player && testBoard[1][x] == player && testBoard[2][x] == player) ||
(testBoard[0][0] == player && testBoard[1][1] == player && testBoard[2][2] == player) ||
(testBoard[0][2] == player && testBoard[1][1] == player && testBoard[2][0] == player);
}
private void placeTurn() {
//Initialize the biggest key-value pair
Map.Entry<String, Integer> biggest = null;
//Loop through all key-value pairs in the possible turns (all potential positions)
for (Map.Entry<String, Integer> entry : this.possibleTurns.entrySet())
{
//If a value is bigger than the current iteration, replace the former key-value pair with this new one.
//The biggest key-value pair has the higest priority
if (biggest == null || entry.getValue().compareTo(biggest.getValue()) > 0)
{
biggest = entry;
}
}
//Get the current playing board
char[][] newBoard = this.TTTGame.getBoard();
//Subtract the x value from the key
int y = Integer.valueOf(biggest.getKey().split("")[0]);
//subtract the y value from the key
int x = Integer.valueOf(biggest.getKey().split("")[1]);
//make a new board where the AI placed his turn
if(newBoard[y][x] == ' ') {
newBoard[y][x] = this.player;
}
// use this to return the last AI move
this.lastMove[0] = x;
this.lastMove[1] = y;
System.out.println(this.lastMove[1]+""+this.lastMove[0]);
//Replace the tic-tac-toe board with the board where the AI placed his turn
this.TTTGame.setBoard(newBoard);
}
private char oppositePlayer() {
if(this.player == 'O') {
return 'X';
}
return 'O';
}
}
| Iniedergeval-Cool/tictactoe | src/Game/Models/AI.java | 1,548 | //Check per vakje of de AI kan winnen ná het zetten van het vakje. Zoja: geef score van 5 aan dat vakje | line_comment | nl | package Game.Models;
import Framework.AI.BotInterface;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class AI implements BotInterface {
private TTTGame TTTGame;
private HashMap<String, Integer> possibleTurns;
private char player;
private int[] lastMove = new int[2];
public AI(TTTGame TTTGame, char player) {
this.TTTGame = TTTGame;
this.possibleTurns = new HashMap<>();
this.player = player;
}
public char getPlayer() {
return this.player;
}
public int[] doTurn(char[][] board) {
//check de open vakjes.
//dan: check of de andere gebruiker kan winnen met een van de open vakjes.
//zoja: geef dat vakje een score van 10. Sla op in mogelijke zet array
//Check per<SUF>
//Anders: geef score -1
int score;
for(int y = 0; y < board.length; y++) {
for(int x = 0; x < board[y].length; x++) {
if(board[y][x] == ' ') {
score = this.getScore(y, x, board);
this.possibleTurns.put("" + y + x, score);
}
else {
this.possibleTurns.put("" + y + x, -1);
}
}
}
System.out.println(this.possibleTurns);
this.placeTurn();
// Return this turns AI move [0:x, 1:y]
return this.lastMove;
}
private int getScore(int y, int x, char[][] board) {
//board[y][x] = this.player;
//check if I can win with this position
if(this.checkIfICanWin(y, x, board)) {
board[y][x] = ' ';
return 5;
}
//check if the other player can win with this position
if(this.checkIfOtherCanWin(y, x, board)) {
board[y][x] = ' ';
return 10;
}
board[y][x] = ' ';
//check if I can with after placing this position
return 0;
}
private boolean checkIfICanWin(int y, int x, char[][] testBoard) {
testBoard[y][x] = this.player;
return (testBoard[y][0] == this.player && testBoard[y][1] == this.player && testBoard[y][2] == this.player) ||
(testBoard[0][x] == this.player && testBoard[1][x] == this.player && testBoard[2][x] == this.player) ||
(testBoard[0][0] == this.player && testBoard[1][1] == this.player && testBoard[2][2] == this.player) ||
(testBoard[0][2] == this.player && testBoard[1][1] == this.player && testBoard[2][0] == this.player);
}
private boolean checkIfOtherCanWin(int y, int x, char[][] testBoard) {
char player = this.oppositePlayer();
testBoard[y][x] = player;
System.out.println("Huidige speler AI: " + this.player + ", andere speler: " + player);
return (testBoard[y][0] == player && testBoard[y][1] == player && testBoard[y][2] == player) ||
(testBoard[0][x] == player && testBoard[1][x] == player && testBoard[2][x] == player) ||
(testBoard[0][0] == player && testBoard[1][1] == player && testBoard[2][2] == player) ||
(testBoard[0][2] == player && testBoard[1][1] == player && testBoard[2][0] == player);
}
private void placeTurn() {
//Initialize the biggest key-value pair
Map.Entry<String, Integer> biggest = null;
//Loop through all key-value pairs in the possible turns (all potential positions)
for (Map.Entry<String, Integer> entry : this.possibleTurns.entrySet())
{
//If a value is bigger than the current iteration, replace the former key-value pair with this new one.
//The biggest key-value pair has the higest priority
if (biggest == null || entry.getValue().compareTo(biggest.getValue()) > 0)
{
biggest = entry;
}
}
//Get the current playing board
char[][] newBoard = this.TTTGame.getBoard();
//Subtract the x value from the key
int y = Integer.valueOf(biggest.getKey().split("")[0]);
//subtract the y value from the key
int x = Integer.valueOf(biggest.getKey().split("")[1]);
//make a new board where the AI placed his turn
if(newBoard[y][x] == ' ') {
newBoard[y][x] = this.player;
}
// use this to return the last AI move
this.lastMove[0] = x;
this.lastMove[1] = y;
System.out.println(this.lastMove[1]+""+this.lastMove[0]);
//Replace the tic-tac-toe board with the board where the AI placed his turn
this.TTTGame.setBoard(newBoard);
}
private char oppositePlayer() {
if(this.player == 'O') {
return 'X';
}
return 'O';
}
}
|
15081_46 | // Copyright (c) 2014 Tom Zhou<[email protected]>
package com.iwebpp.node.http;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.ArrayList;
import java.util.List;
import com.iwebpp.node.HttpParser;
import com.iwebpp.node.NodeContext;
import com.iwebpp.node.net.AbstractSocket;
public abstract class IncomingParser
extends HttpParser {
private final static String TAG = "IncomingParser";
protected AbstractSocket socket;
protected IncomingMessage incoming;
protected CharsetDecoder decoder;
protected String [] fields_; ///[32]; // header fields
protected String [] values_; ///[32]; // header values
protected String url_;
protected String status_message_;
protected int num_fields_;
protected int num_values_;
protected boolean have_flushed_;
protected ByteBuffer current_buffer_;
protected int maxHeaderPairs;
protected List<String> _headers;
protected String _url;
private NodeContext context;
protected IncomingParser(NodeContext ctx, http_parser_type type, AbstractSocket socket) {
super(type, socket);
this.context = ctx;
// TODO Auto-generated constructor stub
this.decoder = Charset.forName("utf-8").newDecoder();
this.socket = socket;
this._headers = new ArrayList<String>();
this._url = "";
this.fields_ = new String[32];
this.values_ = new String[32];
this.url_ = "";
this.status_message_ = "";
this.num_fields_ = this.num_values_ = 0;
this.have_flushed_ = false;
this.current_buffer_ = null;
}
private IncomingParser(){super(null, null);}
protected void Init(http_parser_type type) {
super.reset(type);
_headers.clear();
_url = "";
url_ = "";
status_message_ = "";
num_fields_ = 0;
num_values_ = 0;
have_flushed_ = false;
current_buffer_ = null;
}
// spill headers and request path to JS land
protected void Flush() {
parserOnHeaders(CreateHeaders(), url_);
///if (r.IsEmpty())
/// got_exception_ = true;
url_ = "";
have_flushed_ = true;
}
protected List<String> CreateHeaders() {
// num_values_ is either -1 or the entry # of the last header
// so num_values_ == 0 means there's a single header
List<String> headers = new ArrayList<String>();
for (int i = 0; i < this.num_values_; i ++) {
headers.add(this.fields_[i]);
headers.add(this.values_[i]);
}
return headers;
}
public void Pause(boolean should_pause) {
pause(should_pause);
}
public void Reinitialize(http_parser_type type) {
Init(type);
}
public int Finish() throws Exception {
int rv = execute(null);
if (rv != 0) {
http_errno err = HTTP_PARSER_ERRNO();
throw new Exception(err.desc());
}
return rv;
}
// var bytesParsed = parser->execute(buffer);
public int Execute(ByteBuffer buffer_obj) throws Exception {
int buffer_len = buffer_obj.capacity();
// This is a hack to get the current_buffer to the callbacks with the least
// amount of overhead. Nothing else will run while http_parser_execute()
// runs, therefore this pointer can be set and used for the execution.
current_buffer_ = buffer_obj;
int nparsed = execute(current_buffer_);
// Unassign the 'buffer_' variable
current_buffer_.clear();
// If there was a parse error in one of the callbacks
// TODO(bnoordhuis) What if there is an error on EOF?
if (!isUpgrade() && nparsed != buffer_len) {
// TBD...
///http_errno err = HTTP_PARSER_ERRNO();
///throw new Exception(err.desc());
return -1;
}
return nparsed;
}
// Only called in the slow case where slow means
// that the request headers were either fragmented
// across multiple TCP packets or too large to be
// processed in a single run. This method is also
// called to process trailing http headers.
protected void parserOnHeaders(List<String> headers, String url) {
debug(TAG, "parserOnHeaders ");
// Once we exceeded headers limit - stop collecting them
if (this.maxHeaderPairs <= 0 ||
this._headers.size() < this.maxHeaderPairs) {
///this._headers = this._headers.concat(headers);
this._headers.addAll(headers);
}
this._url += url != null ? url : "";
}
// info.headers and info.url are set only if .onHeaders()
// has not been called for this request.
//
// info.url is not set for response parsers but that's not
// applicable here since all our parsers are request parsers.
///function parserOnHeadersComplete(info) {
protected boolean parserOnHeadersComplete(parseInfo info) throws Exception {
///debug('parserOnHeadersComplete', info);
debug(TAG, "parserOnHeadersComplete "+info);
///var parser = this;
List<String> headers = info.headers;
String url = info.url;
if (null == headers || headers.isEmpty()) {
headers = _headers;
_headers.clear();
}
if (null==url || ""==url) {
url = _url;
_url = "";
}
/*parser.incoming = new IncomingMessage(parser.socket);
parser.incoming.httpVersionMajor = info.versionMajor;
parser.incoming.httpVersionMinor = info.versionMinor;
parser.incoming.httpVersion = info.versionMajor + '.' + info.versionMinor;
parser.incoming.url = url;
*/
// TBD...
this.incoming = new IncomingMessage(context, (AbstractSocket)super.getData());
this.incoming.setHttpVersionMajor(info.versionMajor);
this.incoming.setHttpVersionMinor(info.versionMinor);
this.incoming.httpVersion(info.versionMajor + "." + info.versionMinor);
this.incoming.url(url);
///var n = headers.length;
int n = headers.size();
// If parser.maxHeaderPairs <= 0 - assume that there're no limit
if (maxHeaderPairs > 0) {
n = Math.min(n, maxHeaderPairs);
}
incoming._addHeaderLines(headers, n);
if (super.getType() == http_parser_type.HTTP_REQUEST/*isNumber(info.method)*/) {
// server only
incoming.setMethod(info.method.desc()) ;
} else {
// client only
incoming.setStatusCode(info.statusCode);
incoming.setStatusMessage(info.statusMessage);
}
incoming.setUpgrade(info.upgrade);
boolean skipBody = false; // response to HEAD or CONNECT
if (!info.upgrade) {
// For upgraded connections and CONNECT method request,
// we'll emit this after parser.execute
// so that we can capture the first part of the new protocol
skipBody = onIncoming(incoming, info.shouldKeepAlive);
}
return skipBody;
}
// POJO bean
protected class parseInfo {
public boolean shouldKeepAlive;
public boolean upgrade;
public http_method method;
public String url;
public List<String> headers;
public int statusCode;
public String statusMessage;
public int versionMajor;
public int versionMinor;
}
protected abstract boolean onIncoming(IncomingMessage incoming, boolean shouldKeepAlive) throws Exception;
// XXX This is a mess.
// TODO: http.Parser should be a Writable emits request/response events.
///function parserOnBody(b, start, len) {
protected void parserOnBody(ByteBuffer b) throws Exception {
debug(TAG, "parserOnBody ");
IncomingParser parser = this;
IncomingMessage stream = parser.incoming;
// if the stream has already been removed, then drop it.
if (null==stream)
return;
AbstractSocket socket = stream.socket();
int len = b == null ? 0 : b.capacity();
// pretend this was the result of a stream._read call.
if (len > 0 && !stream.is_dumped()) {
///var slice = b.slice(start, start + len);
boolean ret = stream.push(b, null);
if (!ret)
IncomingMessage.readStop(socket);
}
}
///function parserOnMessageComplete() {
protected void parserOnMessageComplete() throws Exception {
debug(TAG, "parserOnMessageComplete ");
IncomingParser parser = this;
IncomingMessage stream = parser.incoming;
if (stream!=null) {
stream.setComplete(true);
// Emit any trailing headers.
List<String> headers = parser._headers;
if (headers!=null && !headers.isEmpty()) {
stream._addHeaderLines(headers, headers.size());
_headers.clear();
_url = "";
}
if (!stream.isUpgrade())
// For upgraded connections, also emit this after parser.execute
stream.push(null, null);
}
if (stream!=null && 0==stream.get_pendings().size()) {
// For emit end event
stream.push(null, null);
}
// force to read the next incoming message
IncomingMessage.readStart(parser.socket);
}
@Override
protected int on_message_begin() throws Exception {
num_fields_ = num_values_ = 0;
url_ = "";
status_message_ = "";
return 0;
}
@Override
protected int on_url(ByteBuffer url) throws Exception {
url_ = decoder.decode(url).toString();
return 0;
}
@Override
protected int on_status(ByteBuffer status) throws Exception {
status_message_ = decoder.decode(status).toString();
return 0;
}
@Override
protected int on_header_field(ByteBuffer field) throws Exception {
if (num_fields_ == num_values_) {
// start of new field name
num_fields_++;
///if (num_fields_ == ARRAY_SIZE(fields_)) {
if (num_fields_ == fields_.length) {
// ran out of space - flush to javascript land
Flush();
num_fields_ = 1;
num_values_ = 0;
}
fields_[num_fields_ - 1] = "";
}
///assert(num_fields_ < static_cast<int>(ARRAY_SIZE(fields_)));
assert(num_fields_ < fields_.length);
assert(num_fields_ == num_values_ + 1);
fields_[num_fields_ - 1] = decoder.decode(field).toString();
return 0;
}
@Override
protected int on_header_value(ByteBuffer value) throws Exception {
if (num_values_ != num_fields_) {
// start of new header value
num_values_++;
values_[num_values_ - 1] = "";
}
assert(num_values_ < values_.length);
assert(num_values_ == num_fields_);
values_[num_values_ - 1] = decoder.decode(value).toString();
return 0;
}
@Override
protected int on_headers_complete() throws Exception {
///Local<Object> message_info = Object::New(env()->isolate());
parseInfo message_info = new parseInfo();
if (have_flushed_) {
// Slow case, flush remaining headers.
Flush();
} else {
// Fast case, pass headers and URL to JS land.
message_info.headers = CreateHeaders();
if (getType() == http_parser_type.HTTP_REQUEST)
message_info.url = url_;
}
num_fields_ = num_values_ = 0;
// METHOD
if (getType() == http_parser_type.HTTP_REQUEST) {
message_info.method = getMethod();
}
// STATUS
if (getType() == http_parser_type.HTTP_RESPONSE) {
message_info.statusCode = getStatus_code();
message_info.statusMessage = status_message_;
}
// VERSION
message_info.versionMajor = super.getHttp_major();
message_info.versionMinor = super.getHttp_minor();
message_info.shouldKeepAlive = super.http_should_keep_alive();
message_info.upgrade = super.isUpgrade();
return parserOnHeadersComplete(message_info) ? 1 : 0;
}
@Override
protected int on_body(ByteBuffer body) throws Exception {
parserOnBody(body);
return 0;
}
@Override
protected int on_message_complete() throws Exception {
if (num_fields_ > 0)
Flush(); // Flush trailing http headers.
parserOnMessageComplete();
return 0;
}
// Free the parser and also break any links that it
// might have to any other things.
// TODO: All parser data should be attached to a
// single object, so that it can be easily cleaned
// up by doing `parser.data = {}`, which should
// be done in FreeList.free. `parsers.free(parser)`
// should be all that is needed.
public static void freeParser(IncomingParser parser, Object req) {
if (parser != null) {
parser._headers.clear();
///parser.onIncoming = null;
if (parser.socket != null)
parser.socket.setParser(null);
parser.socket = null;
parser.incoming = null;
///parsers.free(parser);
parser = null;
}
if (req != null) {
if (req instanceof IncomingMessage)
((IncomingMessage)req).setParser(null);
if (req instanceof ClientRequest)
((ClientRequest)req).setParser(null);
}
}
}
| InstantWebP2P/node-android | app/src/main/java/com/iwebpp/node/http/IncomingParser.java | 3,842 | // For emit end event | line_comment | nl | // Copyright (c) 2014 Tom Zhou<[email protected]>
package com.iwebpp.node.http;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.ArrayList;
import java.util.List;
import com.iwebpp.node.HttpParser;
import com.iwebpp.node.NodeContext;
import com.iwebpp.node.net.AbstractSocket;
public abstract class IncomingParser
extends HttpParser {
private final static String TAG = "IncomingParser";
protected AbstractSocket socket;
protected IncomingMessage incoming;
protected CharsetDecoder decoder;
protected String [] fields_; ///[32]; // header fields
protected String [] values_; ///[32]; // header values
protected String url_;
protected String status_message_;
protected int num_fields_;
protected int num_values_;
protected boolean have_flushed_;
protected ByteBuffer current_buffer_;
protected int maxHeaderPairs;
protected List<String> _headers;
protected String _url;
private NodeContext context;
protected IncomingParser(NodeContext ctx, http_parser_type type, AbstractSocket socket) {
super(type, socket);
this.context = ctx;
// TODO Auto-generated constructor stub
this.decoder = Charset.forName("utf-8").newDecoder();
this.socket = socket;
this._headers = new ArrayList<String>();
this._url = "";
this.fields_ = new String[32];
this.values_ = new String[32];
this.url_ = "";
this.status_message_ = "";
this.num_fields_ = this.num_values_ = 0;
this.have_flushed_ = false;
this.current_buffer_ = null;
}
private IncomingParser(){super(null, null);}
protected void Init(http_parser_type type) {
super.reset(type);
_headers.clear();
_url = "";
url_ = "";
status_message_ = "";
num_fields_ = 0;
num_values_ = 0;
have_flushed_ = false;
current_buffer_ = null;
}
// spill headers and request path to JS land
protected void Flush() {
parserOnHeaders(CreateHeaders(), url_);
///if (r.IsEmpty())
/// got_exception_ = true;
url_ = "";
have_flushed_ = true;
}
protected List<String> CreateHeaders() {
// num_values_ is either -1 or the entry # of the last header
// so num_values_ == 0 means there's a single header
List<String> headers = new ArrayList<String>();
for (int i = 0; i < this.num_values_; i ++) {
headers.add(this.fields_[i]);
headers.add(this.values_[i]);
}
return headers;
}
public void Pause(boolean should_pause) {
pause(should_pause);
}
public void Reinitialize(http_parser_type type) {
Init(type);
}
public int Finish() throws Exception {
int rv = execute(null);
if (rv != 0) {
http_errno err = HTTP_PARSER_ERRNO();
throw new Exception(err.desc());
}
return rv;
}
// var bytesParsed = parser->execute(buffer);
public int Execute(ByteBuffer buffer_obj) throws Exception {
int buffer_len = buffer_obj.capacity();
// This is a hack to get the current_buffer to the callbacks with the least
// amount of overhead. Nothing else will run while http_parser_execute()
// runs, therefore this pointer can be set and used for the execution.
current_buffer_ = buffer_obj;
int nparsed = execute(current_buffer_);
// Unassign the 'buffer_' variable
current_buffer_.clear();
// If there was a parse error in one of the callbacks
// TODO(bnoordhuis) What if there is an error on EOF?
if (!isUpgrade() && nparsed != buffer_len) {
// TBD...
///http_errno err = HTTP_PARSER_ERRNO();
///throw new Exception(err.desc());
return -1;
}
return nparsed;
}
// Only called in the slow case where slow means
// that the request headers were either fragmented
// across multiple TCP packets or too large to be
// processed in a single run. This method is also
// called to process trailing http headers.
protected void parserOnHeaders(List<String> headers, String url) {
debug(TAG, "parserOnHeaders ");
// Once we exceeded headers limit - stop collecting them
if (this.maxHeaderPairs <= 0 ||
this._headers.size() < this.maxHeaderPairs) {
///this._headers = this._headers.concat(headers);
this._headers.addAll(headers);
}
this._url += url != null ? url : "";
}
// info.headers and info.url are set only if .onHeaders()
// has not been called for this request.
//
// info.url is not set for response parsers but that's not
// applicable here since all our parsers are request parsers.
///function parserOnHeadersComplete(info) {
protected boolean parserOnHeadersComplete(parseInfo info) throws Exception {
///debug('parserOnHeadersComplete', info);
debug(TAG, "parserOnHeadersComplete "+info);
///var parser = this;
List<String> headers = info.headers;
String url = info.url;
if (null == headers || headers.isEmpty()) {
headers = _headers;
_headers.clear();
}
if (null==url || ""==url) {
url = _url;
_url = "";
}
/*parser.incoming = new IncomingMessage(parser.socket);
parser.incoming.httpVersionMajor = info.versionMajor;
parser.incoming.httpVersionMinor = info.versionMinor;
parser.incoming.httpVersion = info.versionMajor + '.' + info.versionMinor;
parser.incoming.url = url;
*/
// TBD...
this.incoming = new IncomingMessage(context, (AbstractSocket)super.getData());
this.incoming.setHttpVersionMajor(info.versionMajor);
this.incoming.setHttpVersionMinor(info.versionMinor);
this.incoming.httpVersion(info.versionMajor + "." + info.versionMinor);
this.incoming.url(url);
///var n = headers.length;
int n = headers.size();
// If parser.maxHeaderPairs <= 0 - assume that there're no limit
if (maxHeaderPairs > 0) {
n = Math.min(n, maxHeaderPairs);
}
incoming._addHeaderLines(headers, n);
if (super.getType() == http_parser_type.HTTP_REQUEST/*isNumber(info.method)*/) {
// server only
incoming.setMethod(info.method.desc()) ;
} else {
// client only
incoming.setStatusCode(info.statusCode);
incoming.setStatusMessage(info.statusMessage);
}
incoming.setUpgrade(info.upgrade);
boolean skipBody = false; // response to HEAD or CONNECT
if (!info.upgrade) {
// For upgraded connections and CONNECT method request,
// we'll emit this after parser.execute
// so that we can capture the first part of the new protocol
skipBody = onIncoming(incoming, info.shouldKeepAlive);
}
return skipBody;
}
// POJO bean
protected class parseInfo {
public boolean shouldKeepAlive;
public boolean upgrade;
public http_method method;
public String url;
public List<String> headers;
public int statusCode;
public String statusMessage;
public int versionMajor;
public int versionMinor;
}
protected abstract boolean onIncoming(IncomingMessage incoming, boolean shouldKeepAlive) throws Exception;
// XXX This is a mess.
// TODO: http.Parser should be a Writable emits request/response events.
///function parserOnBody(b, start, len) {
protected void parserOnBody(ByteBuffer b) throws Exception {
debug(TAG, "parserOnBody ");
IncomingParser parser = this;
IncomingMessage stream = parser.incoming;
// if the stream has already been removed, then drop it.
if (null==stream)
return;
AbstractSocket socket = stream.socket();
int len = b == null ? 0 : b.capacity();
// pretend this was the result of a stream._read call.
if (len > 0 && !stream.is_dumped()) {
///var slice = b.slice(start, start + len);
boolean ret = stream.push(b, null);
if (!ret)
IncomingMessage.readStop(socket);
}
}
///function parserOnMessageComplete() {
protected void parserOnMessageComplete() throws Exception {
debug(TAG, "parserOnMessageComplete ");
IncomingParser parser = this;
IncomingMessage stream = parser.incoming;
if (stream!=null) {
stream.setComplete(true);
// Emit any trailing headers.
List<String> headers = parser._headers;
if (headers!=null && !headers.isEmpty()) {
stream._addHeaderLines(headers, headers.size());
_headers.clear();
_url = "";
}
if (!stream.isUpgrade())
// For upgraded connections, also emit this after parser.execute
stream.push(null, null);
}
if (stream!=null && 0==stream.get_pendings().size()) {
// For emit<SUF>
stream.push(null, null);
}
// force to read the next incoming message
IncomingMessage.readStart(parser.socket);
}
@Override
protected int on_message_begin() throws Exception {
num_fields_ = num_values_ = 0;
url_ = "";
status_message_ = "";
return 0;
}
@Override
protected int on_url(ByteBuffer url) throws Exception {
url_ = decoder.decode(url).toString();
return 0;
}
@Override
protected int on_status(ByteBuffer status) throws Exception {
status_message_ = decoder.decode(status).toString();
return 0;
}
@Override
protected int on_header_field(ByteBuffer field) throws Exception {
if (num_fields_ == num_values_) {
// start of new field name
num_fields_++;
///if (num_fields_ == ARRAY_SIZE(fields_)) {
if (num_fields_ == fields_.length) {
// ran out of space - flush to javascript land
Flush();
num_fields_ = 1;
num_values_ = 0;
}
fields_[num_fields_ - 1] = "";
}
///assert(num_fields_ < static_cast<int>(ARRAY_SIZE(fields_)));
assert(num_fields_ < fields_.length);
assert(num_fields_ == num_values_ + 1);
fields_[num_fields_ - 1] = decoder.decode(field).toString();
return 0;
}
@Override
protected int on_header_value(ByteBuffer value) throws Exception {
if (num_values_ != num_fields_) {
// start of new header value
num_values_++;
values_[num_values_ - 1] = "";
}
assert(num_values_ < values_.length);
assert(num_values_ == num_fields_);
values_[num_values_ - 1] = decoder.decode(value).toString();
return 0;
}
@Override
protected int on_headers_complete() throws Exception {
///Local<Object> message_info = Object::New(env()->isolate());
parseInfo message_info = new parseInfo();
if (have_flushed_) {
// Slow case, flush remaining headers.
Flush();
} else {
// Fast case, pass headers and URL to JS land.
message_info.headers = CreateHeaders();
if (getType() == http_parser_type.HTTP_REQUEST)
message_info.url = url_;
}
num_fields_ = num_values_ = 0;
// METHOD
if (getType() == http_parser_type.HTTP_REQUEST) {
message_info.method = getMethod();
}
// STATUS
if (getType() == http_parser_type.HTTP_RESPONSE) {
message_info.statusCode = getStatus_code();
message_info.statusMessage = status_message_;
}
// VERSION
message_info.versionMajor = super.getHttp_major();
message_info.versionMinor = super.getHttp_minor();
message_info.shouldKeepAlive = super.http_should_keep_alive();
message_info.upgrade = super.isUpgrade();
return parserOnHeadersComplete(message_info) ? 1 : 0;
}
@Override
protected int on_body(ByteBuffer body) throws Exception {
parserOnBody(body);
return 0;
}
@Override
protected int on_message_complete() throws Exception {
if (num_fields_ > 0)
Flush(); // Flush trailing http headers.
parserOnMessageComplete();
return 0;
}
// Free the parser and also break any links that it
// might have to any other things.
// TODO: All parser data should be attached to a
// single object, so that it can be easily cleaned
// up by doing `parser.data = {}`, which should
// be done in FreeList.free. `parsers.free(parser)`
// should be all that is needed.
public static void freeParser(IncomingParser parser, Object req) {
if (parser != null) {
parser._headers.clear();
///parser.onIncoming = null;
if (parser.socket != null)
parser.socket.setParser(null);
parser.socket = null;
parser.incoming = null;
///parsers.free(parser);
parser = null;
}
if (req != null) {
if (req instanceof IncomingMessage)
((IncomingMessage)req).setParser(null);
if (req instanceof ClientRequest)
((ClientRequest)req).setParser(null);
}
}
}
|
181882_0 | package me.kyllian.netflixstatistix.controllers;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import me.kyllian.netflixstatistix.NetflixStatistix;
import me.kyllian.netflixstatistix.models.PercentagePerEpisodeModel;
import me.kyllian.netflixstatistix.post.PostBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class PercentagePerEpisodeController extends Controller implements Initializable {
//Voor een geselecteerde account en serie, geef per aflevering het gemiddeld
//bekeken percentage van de totale tijdsduur.
@FXML
private TableView<PercentagePerEpisodeModel> table;
@FXML
private TableColumn<PercentagePerEpisodeModel, String> tableSerie;
@FXML
private TableColumn<PercentagePerEpisodeModel, Integer> tableEpisode;
@FXML
private TableColumn<PercentagePerEpisodeModel, Integer> tableAverageTime;
@Override
public void initialize(URL location, ResourceBundle resources) {
tableSerie.setCellValueFactory(new PropertyValueFactory<>("Serie"));
tableEpisode.setCellValueFactory(new PropertyValueFactory<>("Episode"));
tableAverageTime.setCellValueFactory(new PropertyValueFactory<>("AverageTime"));
new PostBuilder()
.withIdentifier("averageTime")
.post(this);
}
@Override
public void handleResponse(String response) {
List<PercentagePerEpisodeModel> percentagePerEpisodeModels = new ArrayList<>();
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i != array.length(); i++) {
JSONObject data = array.getJSONObject(i);
percentagePerEpisodeModels.add(new PercentagePerEpisodeModel(data.getString("name_serie"), data.getInt("episode_id"), data.getInt("average")));
}
} catch (JSONException exception) {
System.out.println("Error reading JSON from server");
exception.printStackTrace();
}
table.setItems(FXCollections.observableArrayList(percentagePerEpisodeModels));
}
public void back() {
try {
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("view/statistic.fxml"));
root.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
NetflixStatistix.parentWindow.getScene().setRoot(root);
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
| InstantlyMoist/NetflixStatistix | src/main/java/me/kyllian/netflixstatistix/controllers/PercentagePerEpisodeController.java | 834 | //Voor een geselecteerde account en serie, geef per aflevering het gemiddeld | line_comment | nl | package me.kyllian.netflixstatistix.controllers;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import me.kyllian.netflixstatistix.NetflixStatistix;
import me.kyllian.netflixstatistix.models.PercentagePerEpisodeModel;
import me.kyllian.netflixstatistix.post.PostBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class PercentagePerEpisodeController extends Controller implements Initializable {
//Voor een<SUF>
//bekeken percentage van de totale tijdsduur.
@FXML
private TableView<PercentagePerEpisodeModel> table;
@FXML
private TableColumn<PercentagePerEpisodeModel, String> tableSerie;
@FXML
private TableColumn<PercentagePerEpisodeModel, Integer> tableEpisode;
@FXML
private TableColumn<PercentagePerEpisodeModel, Integer> tableAverageTime;
@Override
public void initialize(URL location, ResourceBundle resources) {
tableSerie.setCellValueFactory(new PropertyValueFactory<>("Serie"));
tableEpisode.setCellValueFactory(new PropertyValueFactory<>("Episode"));
tableAverageTime.setCellValueFactory(new PropertyValueFactory<>("AverageTime"));
new PostBuilder()
.withIdentifier("averageTime")
.post(this);
}
@Override
public void handleResponse(String response) {
List<PercentagePerEpisodeModel> percentagePerEpisodeModels = new ArrayList<>();
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i != array.length(); i++) {
JSONObject data = array.getJSONObject(i);
percentagePerEpisodeModels.add(new PercentagePerEpisodeModel(data.getString("name_serie"), data.getInt("episode_id"), data.getInt("average")));
}
} catch (JSONException exception) {
System.out.println("Error reading JSON from server");
exception.printStackTrace();
}
table.setItems(FXCollections.observableArrayList(percentagePerEpisodeModels));
}
public void back() {
try {
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("view/statistic.fxml"));
root.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
NetflixStatistix.parentWindow.getScene().setRoot(root);
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
|
131214_126 | package main;
import controllers.CustomerController;
import controllers.ProductController;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.stage.Stage;
import screens.*;
import java.text.NumberFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
public class ATDProgram extends Application {
private Stage mainStage;
private Tab stockAdministration;
private Tab serviceScreen;
private Tab invoiceScreen;
private Tab financesScreen;
private Tab parkingScreen;
private Scene mainScene;
@Deprecated private final Stock stock = new Stock();
private final ArrayList<MaintenanceSession> maintenanceSessions = new ArrayList<>();
private final ArrayList<Invoice> receipts = new ArrayList<>();
@Deprecated private final ArrayList<Customer> customers = new ArrayList<>();
private final ArrayList<Mechanic> mechanics = new ArrayList<>();
@Deprecated private final ArrayList<Order> orders = new ArrayList<>();
@Deprecated private final ArrayList<ProductSupplier> suppliers = new ArrayList<>();
private final ArrayList<ParkingSpace> parkingSpaces = new ArrayList<>();
private final ArrayList<Reservation> reservations = new ArrayList<>();
private final static NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("nl", "NL"));
@Override
public void start(Stage stage) throws Exception {
mainStage = stage;
nf.setCurrency(Currency.getInstance("EUR"));
// addContent();
//create tabs and add content
TabPane tabsScreen = new TabPane();
Tab customerAdministration = new Tab("Klanten");
customerAdministration.setClosable(false);
customerAdministration.setContent(new CustomerScreen(this));
stockAdministration = new Tab("Voorraad");
stockAdministration.setClosable(false);
stockAdministration.setContent(new StockScreen(this));
serviceScreen = new Tab("Onderhoud");
serviceScreen.setClosable(false);
serviceScreen.setContent(new MaintenanceScreen(this));
invoiceScreen = new Tab("Facturen");
invoiceScreen.setClosable(false);
invoiceScreen.setContent(new InvoiceScreen(this));
financesScreen = new Tab("Financien");
financesScreen.setClosable(false);
financesScreen.setContent(new FinancesScreen(this));
parkingScreen = new Tab("Parkeren");
parkingScreen.setClosable(false);
parkingScreen.setContent(new ParkingScreen(this));
tabsScreen.getTabs().addAll(financesScreen, invoiceScreen, customerAdministration, stockAdministration, serviceScreen, parkingScreen);
tabsScreen.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
((screens.Screen) newValue.getContent()).refreshList();
});
// Create Mainscreen
mainScene = new Scene(tabsScreen);
mainScene.getStylesheets().add("application.css");
stage.setScene(mainScene);
stage.setTitle("AutoTotaalDienst");
stage.sizeToScene();
stage.setResizable(false);
stage.show();
}
@Deprecated
public ArrayList<Customer> getCustomers() {
return customers;
}
@Deprecated
public List<Customer> getRemindList(boolean Maintenace) {
ArrayList<Customer> remindables = new ArrayList<>();
for (Customer customer : customers) {
if (Maintenace) {
if (customer.getLastMaintenance().isBefore(
LocalDate.now().minusMonths(6))) {
remindables.add(customer);
}
} else {
if (customer.getLastVisit().isBefore(
LocalDate.now().minusMonths(2))) {
remindables.add(customer);
}
}
}
return remindables;
}
public ArrayList<Reservation> getReservations() {
return reservations;
}
public void addorRemoveReservations(Reservation reservation, boolean remove) {
if (remove) reservations.remove(reservation);
else reservations.add(reservation);
}
@Deprecated
public void addorRemoveCustomer(Customer customer, boolean remove) {
if (remove) customers.remove(customer);
else customers.add(customer);
}
@Deprecated
public ArrayList<Product> getProducts() {
return stock.getAllProducts();
}
@Deprecated
public void addorRemoveproduct(Product product, boolean remove) {
if (remove) stock.removeProduct(product);
else stock.newProduct(product);
}
@Deprecated
public ArrayList<Order> getOrders() {
return orders;
}
@Deprecated
public void addorRemoveOrder(Order order, boolean remove) {
if (remove) orders.remove(order);
else orders.add(order);
}
@Deprecated
public ArrayList<ProductSupplier> getSuppliers() {
return suppliers;
}
@Deprecated
public void addorRemoveSupplier(ProductSupplier supplier, boolean remove) {
if (remove) suppliers.remove(supplier);
else suppliers.add(supplier);
}
public ArrayList<Mechanic> getMechanics() {
return mechanics;
}
private void addorRemoveMechanic(Mechanic mechanic, boolean remove) {
if (remove) mechanics.remove(mechanic);
else mechanics.add(mechanic);
}
public ArrayList<Invoice> getInvoices() {
return receipts;
}
public void addorRemoveInvoice(Invoice receipt, boolean remove) {
if (remove) receipts.remove(receipt);
else receipts.add(receipt);
}
public ArrayList<MaintenanceSession> getMaintenanceSessions() {
return maintenanceSessions;
}
public ArrayList<ParkingSpace> getParkingSpaces() {
return parkingSpaces;
}
public void addorRemoveMaintenanceSessions(MaintenanceSession maintenanceSession, boolean remove) {
if (remove) maintenanceSessions.remove(maintenanceSession);
else maintenanceSessions.add(maintenanceSession);
}
public static String convert(double price) {
return nf.format(price);
}
public static boolean periodIsOverlapping(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
return (!start1.isAfter(end2)) && (!start2.isAfter(end1));
}
// private void addContent() {
// for (int i = 0; i < 20; i++) {
// parkingSpaces.add(new ParkingSpace(i));
// }
// addorRemoveCustomer(new Customer("Jorrit Meulenbeld", "Utrecht",
// "NL35 INGB 0008 8953 57", LocalDate.parse("1990-08-25"), "[email protected]",
// "3552AZ", "0636114939", "Omloop 48", false), false);
// addorRemoveCustomer(new Customer("Mark Havekes", "De Meern", "n.v.t.", LocalDate.parse("1990-05-31"),
// "[email protected]", "3453MC", "0302801265",
// "De Drecht 32", false), false);
// addorRemoveCustomer(new Customer("Taoufik Abou", "Utrecht",
// "NL35 INGB 0001 1234 56", LocalDate.parse("1997-08-08"), "[email protected]",
// "3550AA", "0612345678", "Mijnstraat 123", false), false);
// addorRemoveCustomer(new Customer("Oussama Aalili", "Utrecht", "n.v.t.", LocalDate.parse("1995-08-25"),
// "[email protected]", "3563CR", "0690874563",
// "Drielenbrochdreef 11", false), false);
// addorRemoveCustomer(new Customer("Jantje Bont", "Utrecht",
// "NL35 INGB 0128 4553 66", LocalDate.parse("1980-09-07"), "[email protected]",
// "3535AA", "0656789032", "Walstraat 123", false), false);
// addorRemoveCustomer(new Customer("Kees Jansma", "Dordrecht", "n.v.t.", LocalDate.parse("1970-07-12"),
// "[email protected]", "3400BB", "0678324211",
// "Kiboltstraat 12", false), false);
// addorRemoveCustomer(new Customer("Jeroen van der Boom", "Vianen",
// "NL35 ABNA 0056 8953 57", LocalDate.parse("1989-08-25"), "[email protected]",
// "3552AZ", "0636114939", "Jeroenstraat 11", false), false);
// addorRemoveCustomer(new Customer("Frans Bouwer", "Maastricht", "n.v.t.", LocalDate.parse("1975-05-31"),
// "[email protected]", "3451AC", "0690324576",
// "Franslaan 89", false), false);
// addorRemoveCustomer(new Customer("Ali Bouali", "Nieuwegein",
// "NL35 ABNA 0067 8953 57", LocalDate.parse("1945-08-25"), "[email protected]",
// "3560AZ", "0690125467", "Groteneusdreef 10", false), false);
// addorRemoveCustomer(new Customer("Jan Shit", "Amsterdam", "n.v.t.", LocalDate.parse("1965-05-31"),
// "[email protected]", "3745BC", "0301234567",
// "Wallendreef 34", false), false);
// addorRemoveCustomer(new Customer("Arjen Robben", "Groningen",
// "NL35 INGB 0208 5953 55", LocalDate.parse("1978-01-30"), "[email protected]",
// "2544AZ", "0637124999", "kalekop 11", false), false);
// addorRemoveCustomer(new Customer("Robin van Persie", "Rotterdam", "n.v.t.", LocalDate.parse("1979-05-31"),
// "[email protected]", "3853MC", "0672831215",
// "", false), false);
// addorRemoveCustomer(new Customer("Wesley Sneijder", "Utrecht",
// "NL35 INGB 0031 1134 78", LocalDate.parse("1987-08-08"), "[email protected]",
// "3230AA", "0622375668", "Ondiepstraat 11", false), false);
// addorRemoveCustomer(new Customer("Klaas-Jan Huntelaar", "Abcoude", "n.v.t.", LocalDate.parse("1989-08-25"),
// "[email protected]", "3134CR", "0620174413",
// "schalkestraat 11", false), false);
// addorRemoveCustomer(new Customer("Memphis Depay", "Leiden",
// "NL35 INGB 0118 4253 56", LocalDate.parse("1990-09-07"), "[email protected]",
// "3333AA", "0645769232", "wcstraat 13", false), false);
// addorRemoveCustomer(new Customer("Daley Blind", "Amsterdam", "n.v.t.", LocalDate.parse("1991-07-12"),
// "[email protected]", "3441BB", "0678624321",
// "Kilostraat 12", false), false);
// addorRemoveCustomer(new Customer("Tim Krul", "Vianen",
// "NL65 ABNA 0156 8653 51", LocalDate.parse("1989-08-25"), "[email protected]",
// "3553AZ", "0616113931", "mexicostraat 11", false), false);
// addorRemoveCustomer(new Customer(" Bas Dost", "Den Haag", "n.v.t.", LocalDate.parse("1975-05-31"),
// "[email protected]", "3451AC", "0690324576",
// "Englandlaan 89", false), false);
// addorRemoveCustomer(new Customer("Leo Messi", "Nieuwegein",
// "NL23 ABNA 0267 8153 37", LocalDate.parse("1988-08-25"), "[email protected]",
// "3564AZ", "0690421467", "Kleineneusdreef 10", false), false);
// addorRemoveCustomer(new Customer("Andre Hazes", "Amsterdam", "n.v.t.", LocalDate.parse("1957-05-31"),
// "[email protected]", "3715BC", "0621234167",
// "legendedreef 12", false), false);
//
//
// customers.get(0).add(new Car("volkswagen", "13-LOL-3"));
// customers.get(1).add(new Car("porsche", "14-LAL-5"));
// customers.get(2).add(new Car("ferrari", "15-LIL-6"));
// customers.get(3).add(new Car("mercedes", "16-LEL-9"));
// customers.get(4).add(new Car("bmw", "17-LQL-1"));
// customers.get(5).add(new Car("nissan", "18-POL-2"));
// customers.get(6).add(new Car("opel", "18-LVL-8"));
// customers.get(7).add(new Car("renault", "15-WOL-1"));
// customers.get(8).add(new Car("audi", "24-QOL-9"));
// customers.get(9).add(new Car("lamborgini", "03-TOL-3"));
// customers.get(10).add(new Car("volkswagen", "93-TOL-3"));
// customers.get(11).add(new Car("porsche", "43-TOL-3"));
// customers.get(12).add(new Car("ferrari", "23-TOL-3"));
// customers.get(13).add(new Car("mercedes", "83-TOL-3"));
// customers.get(14).add(new Car("bmw", "33-TOL-3"));
// customers.get(15).add(new Car("opel", "13-TOL-3"));
// customers.get(16).add(new Car("renault", "33-TOL-3"));
// customers.get(17).add(new Car("audi", "12-TOL-3"));
// customers.get(18).add(new Car("lamborgini", "50-TOL-3"));
// customers.get(19).add(new Car("volkswagen", "59-TOL-3"));
// customers.get(1).add(new Car("lamborgini", "58-TOL-3"));
// customers.get(1).add(new Car("porsche", "57-TOL-3"));
// customers.get(2).add(new Car("lamborgini", "52-TOL-3"));
// customers.get(3).add(new Car("lamborgini", "56-TOL-3"));
// customers.get(4).add(new Car("lamborgini", "55-TOL-3"));
// customers.get(5).add(new Car("lamborgini", "54-TOL-3"));
// customers.get(6).add(new Car("lamborgini", "04-TOL-3"));
//
//
// customers.get(0).setLastMaintenance(LocalDate.now().minusMonths(7));
// customers.get(0).setLastVisit(LocalDate.now().minusMonths(1));
// customers.get(1).setLastMaintenance(LocalDate.now().minusMonths(4));
// customers.get(1).setLastVisit(LocalDate.now().minusMonths(3));
// addorRemoveMechanic(new Mechanic(1, "Jaap", 15.0), false);
// addorRemoveMechanic(new Mechanic(2, "Hans", 12.5), false);
// addorRemoveMechanic(new Mechanic(3, "Sjaak", 10.0), false);
// addorRemoveMechanic(new Mechanic(4, "Piet", 15.0), false);
// addorRemoveInvoice(new Invoice(), false);
// addorRemoveInvoice(new Invoice(), false);
// addorRemoveMaintenanceSessions(new MaintenanceSession("13-LOL-3", stock, LocalDate.now()), false);
// addorRemoveMaintenanceSessions(new MaintenanceSession("65-RGB-1", stock, LocalDate.now().plusDays(4)), false);
// addorRemoveSupplier(new ProductSupplier("Cheapo BV", "Hoevelaan 2", "7853OQ", "Den Haag"), false);
// addorRemoveSupplier(new ProductSupplier("Banden BV", "Hamburgerstraat 10", "4198KW", "Utrecht"), false);
// addorRemoveSupplier(new ProductSupplier("Peugeot", "Parijslaan", "2353PL", "Amsterdam"), false);
// addorRemoveSupplier(new ProductSupplier("Mercedes", "Berlijnstraat 45", "5462KY", "Rotterdam"), false);
// addorRemoveSupplier(new ProductSupplier("Shell", "Hoevenlaan 99", "1337AF", "Eindhoven"), false);
// addorRemoveproduct(new Part("Uitlaat", 5, 5, 20, 22, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Band klein", 7, 10, 60, 100, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Accu", 80, 85, 180, 220, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Airco", 70, 100, 200, 230, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Band groot", 50, 50, 25, 52, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Velgen klein", 9, 10, 60, 120, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Velgen groot", 20, 27, 20, 22, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Besturingsysteem", 4, 10, 110, 250, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Brandstofsysteem", 30, 50, 60, 80, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Dashboard", 15, 20, 60, 100, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Schakelaar", 20, 20, 20, 35, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Kabels", 78, 80, 6, 12, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Filter", 40, 50, 20, 22, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Bekleding", 26, 30, 40, 100, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Interieur", 50, 50, 250, 320, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Motor", 70, 75, 300, 400, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Ophanging", 10, 15, 75, 88, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Onderstel", 7, 10, 60, 100, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Remmen", 50, 65, 80, 120, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Aandrijving", 20, 25, 60, 100, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Ruiten", 40, 50, 20, 40, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Toebehoren Ruiten", 40, 50, 20, 40, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Spiegels", 25, 30, 20, 32, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Transmissie en toebehoren", 50, 60, 30, 40, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Transmissie", 25, 30, 220, 332, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Lampen", 35, 40, 2, 5, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Koplamp voor", 35, 40, 20, 42, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Koplamp achter", 35, 40, 60, 90, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Autosleutel", 5, 20, 15, 25, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Winterband groot", 20, 10, 60, 100, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Winterband klein", 20, 5, 50, 90, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Sneeuwketting groot", 20, 15, 60, 100, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Sneeuwketting klein", 20, 15, 50, 90, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Schroeven extra groot", 8, 10, 5, 10, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Schroeven groot", 8, 10, 4, 8, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Schroeven middelmaat", 8, 3, 6, 100, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Schroeven klein", 8, 10, 2, 4, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Schroeven extra klein", 8, 10, 1, 2, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Radio duur", 10, 20, 50, 75, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Radio normaal", 7, 10, 30, 55, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Radio goedkoop", 5, 5, 15, 20, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Radio extra goedkoop", 7, 10, 10, 15, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Velgen extra duur", 20, 20, 30, 62, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Besturingsysteem duur", 20, 30, 150, 250, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Brandstofsysteem duur", 20, 40, 200, 350, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Dashboard classic", 7, 10, 60, 100, suppliers.get(1)), false);
// addorRemoveproduct(new Part("doekjes", 5, 5, 1, 3, suppliers.get(2)), false);
// addorRemoveproduct(new Part("ververs olie", 150, 200, 6, 10, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Reiningmiddel", 150, 200, 2, 5, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Schoonmaakmiddel", 200, 300, 3, 6, suppliers.get(1)), false);
// addorRemoveproduct(new Fuel("Diesel", 300, 200, 1, 1.19, suppliers.get(4)), false);
// addorRemoveproduct(new Fuel("Euro95", 275, 150, 1.11, 1.52, suppliers.get(4)), false);
// addorRemoveproduct(new Fuel("Euro98", 271, 250, 1, 1.69, suppliers.get(4)), false);
// addorRemoveproduct(new Fuel("Lpg", 275, 150, 1.11, 1.12, suppliers.get(4)), false);
// addorRemoveproduct(new Fuel("Electriteit", 300, 200, 1, 2.19, suppliers.get(4)), false);
// addorRemoveproduct(new Fuel("Waterstof", 275, 150, 1.11, 8.62, suppliers.get(4)), false);
// addorRemoveReservations(new Reservation(LocalDate.parse("2015-03-29"), LocalDate.parse("2015-04-20"), "13-edm-1", parkingSpaces.get(0)), false);
// addorRemoveReservations(new Reservation(LocalDate.parse("2015-04-01"), LocalDate.parse("2015-04-04"), "69-lmr-7", parkingSpaces.get(1)), false);
// addorRemoveReservations(new Reservation(LocalDate.parse("2015-04-04"), LocalDate.parse("2015-04-09"), "31-dos-3", parkingSpaces.get(2)), false);
// }
public static void main(String[] args) {
launch();
}
@Deprecated
public Stock getStock() {
return stock;
}
public Stage getStage() {
return mainStage;
}
}
| InteNs/themaopdracht_3 | Themaopdracht/src/main/ATDProgram.java | 7,147 | // addorRemoveproduct(new Part("Transmissie en toebehoren", 50, 60, 30, 40, suppliers.get(3)), false); | line_comment | nl | package main;
import controllers.CustomerController;
import controllers.ProductController;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.stage.Stage;
import screens.*;
import java.text.NumberFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
public class ATDProgram extends Application {
private Stage mainStage;
private Tab stockAdministration;
private Tab serviceScreen;
private Tab invoiceScreen;
private Tab financesScreen;
private Tab parkingScreen;
private Scene mainScene;
@Deprecated private final Stock stock = new Stock();
private final ArrayList<MaintenanceSession> maintenanceSessions = new ArrayList<>();
private final ArrayList<Invoice> receipts = new ArrayList<>();
@Deprecated private final ArrayList<Customer> customers = new ArrayList<>();
private final ArrayList<Mechanic> mechanics = new ArrayList<>();
@Deprecated private final ArrayList<Order> orders = new ArrayList<>();
@Deprecated private final ArrayList<ProductSupplier> suppliers = new ArrayList<>();
private final ArrayList<ParkingSpace> parkingSpaces = new ArrayList<>();
private final ArrayList<Reservation> reservations = new ArrayList<>();
private final static NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("nl", "NL"));
@Override
public void start(Stage stage) throws Exception {
mainStage = stage;
nf.setCurrency(Currency.getInstance("EUR"));
// addContent();
//create tabs and add content
TabPane tabsScreen = new TabPane();
Tab customerAdministration = new Tab("Klanten");
customerAdministration.setClosable(false);
customerAdministration.setContent(new CustomerScreen(this));
stockAdministration = new Tab("Voorraad");
stockAdministration.setClosable(false);
stockAdministration.setContent(new StockScreen(this));
serviceScreen = new Tab("Onderhoud");
serviceScreen.setClosable(false);
serviceScreen.setContent(new MaintenanceScreen(this));
invoiceScreen = new Tab("Facturen");
invoiceScreen.setClosable(false);
invoiceScreen.setContent(new InvoiceScreen(this));
financesScreen = new Tab("Financien");
financesScreen.setClosable(false);
financesScreen.setContent(new FinancesScreen(this));
parkingScreen = new Tab("Parkeren");
parkingScreen.setClosable(false);
parkingScreen.setContent(new ParkingScreen(this));
tabsScreen.getTabs().addAll(financesScreen, invoiceScreen, customerAdministration, stockAdministration, serviceScreen, parkingScreen);
tabsScreen.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
((screens.Screen) newValue.getContent()).refreshList();
});
// Create Mainscreen
mainScene = new Scene(tabsScreen);
mainScene.getStylesheets().add("application.css");
stage.setScene(mainScene);
stage.setTitle("AutoTotaalDienst");
stage.sizeToScene();
stage.setResizable(false);
stage.show();
}
@Deprecated
public ArrayList<Customer> getCustomers() {
return customers;
}
@Deprecated
public List<Customer> getRemindList(boolean Maintenace) {
ArrayList<Customer> remindables = new ArrayList<>();
for (Customer customer : customers) {
if (Maintenace) {
if (customer.getLastMaintenance().isBefore(
LocalDate.now().minusMonths(6))) {
remindables.add(customer);
}
} else {
if (customer.getLastVisit().isBefore(
LocalDate.now().minusMonths(2))) {
remindables.add(customer);
}
}
}
return remindables;
}
public ArrayList<Reservation> getReservations() {
return reservations;
}
public void addorRemoveReservations(Reservation reservation, boolean remove) {
if (remove) reservations.remove(reservation);
else reservations.add(reservation);
}
@Deprecated
public void addorRemoveCustomer(Customer customer, boolean remove) {
if (remove) customers.remove(customer);
else customers.add(customer);
}
@Deprecated
public ArrayList<Product> getProducts() {
return stock.getAllProducts();
}
@Deprecated
public void addorRemoveproduct(Product product, boolean remove) {
if (remove) stock.removeProduct(product);
else stock.newProduct(product);
}
@Deprecated
public ArrayList<Order> getOrders() {
return orders;
}
@Deprecated
public void addorRemoveOrder(Order order, boolean remove) {
if (remove) orders.remove(order);
else orders.add(order);
}
@Deprecated
public ArrayList<ProductSupplier> getSuppliers() {
return suppliers;
}
@Deprecated
public void addorRemoveSupplier(ProductSupplier supplier, boolean remove) {
if (remove) suppliers.remove(supplier);
else suppliers.add(supplier);
}
public ArrayList<Mechanic> getMechanics() {
return mechanics;
}
private void addorRemoveMechanic(Mechanic mechanic, boolean remove) {
if (remove) mechanics.remove(mechanic);
else mechanics.add(mechanic);
}
public ArrayList<Invoice> getInvoices() {
return receipts;
}
public void addorRemoveInvoice(Invoice receipt, boolean remove) {
if (remove) receipts.remove(receipt);
else receipts.add(receipt);
}
public ArrayList<MaintenanceSession> getMaintenanceSessions() {
return maintenanceSessions;
}
public ArrayList<ParkingSpace> getParkingSpaces() {
return parkingSpaces;
}
public void addorRemoveMaintenanceSessions(MaintenanceSession maintenanceSession, boolean remove) {
if (remove) maintenanceSessions.remove(maintenanceSession);
else maintenanceSessions.add(maintenanceSession);
}
public static String convert(double price) {
return nf.format(price);
}
public static boolean periodIsOverlapping(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
return (!start1.isAfter(end2)) && (!start2.isAfter(end1));
}
// private void addContent() {
// for (int i = 0; i < 20; i++) {
// parkingSpaces.add(new ParkingSpace(i));
// }
// addorRemoveCustomer(new Customer("Jorrit Meulenbeld", "Utrecht",
// "NL35 INGB 0008 8953 57", LocalDate.parse("1990-08-25"), "[email protected]",
// "3552AZ", "0636114939", "Omloop 48", false), false);
// addorRemoveCustomer(new Customer("Mark Havekes", "De Meern", "n.v.t.", LocalDate.parse("1990-05-31"),
// "[email protected]", "3453MC", "0302801265",
// "De Drecht 32", false), false);
// addorRemoveCustomer(new Customer("Taoufik Abou", "Utrecht",
// "NL35 INGB 0001 1234 56", LocalDate.parse("1997-08-08"), "[email protected]",
// "3550AA", "0612345678", "Mijnstraat 123", false), false);
// addorRemoveCustomer(new Customer("Oussama Aalili", "Utrecht", "n.v.t.", LocalDate.parse("1995-08-25"),
// "[email protected]", "3563CR", "0690874563",
// "Drielenbrochdreef 11", false), false);
// addorRemoveCustomer(new Customer("Jantje Bont", "Utrecht",
// "NL35 INGB 0128 4553 66", LocalDate.parse("1980-09-07"), "[email protected]",
// "3535AA", "0656789032", "Walstraat 123", false), false);
// addorRemoveCustomer(new Customer("Kees Jansma", "Dordrecht", "n.v.t.", LocalDate.parse("1970-07-12"),
// "[email protected]", "3400BB", "0678324211",
// "Kiboltstraat 12", false), false);
// addorRemoveCustomer(new Customer("Jeroen van der Boom", "Vianen",
// "NL35 ABNA 0056 8953 57", LocalDate.parse("1989-08-25"), "[email protected]",
// "3552AZ", "0636114939", "Jeroenstraat 11", false), false);
// addorRemoveCustomer(new Customer("Frans Bouwer", "Maastricht", "n.v.t.", LocalDate.parse("1975-05-31"),
// "[email protected]", "3451AC", "0690324576",
// "Franslaan 89", false), false);
// addorRemoveCustomer(new Customer("Ali Bouali", "Nieuwegein",
// "NL35 ABNA 0067 8953 57", LocalDate.parse("1945-08-25"), "[email protected]",
// "3560AZ", "0690125467", "Groteneusdreef 10", false), false);
// addorRemoveCustomer(new Customer("Jan Shit", "Amsterdam", "n.v.t.", LocalDate.parse("1965-05-31"),
// "[email protected]", "3745BC", "0301234567",
// "Wallendreef 34", false), false);
// addorRemoveCustomer(new Customer("Arjen Robben", "Groningen",
// "NL35 INGB 0208 5953 55", LocalDate.parse("1978-01-30"), "[email protected]",
// "2544AZ", "0637124999", "kalekop 11", false), false);
// addorRemoveCustomer(new Customer("Robin van Persie", "Rotterdam", "n.v.t.", LocalDate.parse("1979-05-31"),
// "[email protected]", "3853MC", "0672831215",
// "", false), false);
// addorRemoveCustomer(new Customer("Wesley Sneijder", "Utrecht",
// "NL35 INGB 0031 1134 78", LocalDate.parse("1987-08-08"), "[email protected]",
// "3230AA", "0622375668", "Ondiepstraat 11", false), false);
// addorRemoveCustomer(new Customer("Klaas-Jan Huntelaar", "Abcoude", "n.v.t.", LocalDate.parse("1989-08-25"),
// "[email protected]", "3134CR", "0620174413",
// "schalkestraat 11", false), false);
// addorRemoveCustomer(new Customer("Memphis Depay", "Leiden",
// "NL35 INGB 0118 4253 56", LocalDate.parse("1990-09-07"), "[email protected]",
// "3333AA", "0645769232", "wcstraat 13", false), false);
// addorRemoveCustomer(new Customer("Daley Blind", "Amsterdam", "n.v.t.", LocalDate.parse("1991-07-12"),
// "[email protected]", "3441BB", "0678624321",
// "Kilostraat 12", false), false);
// addorRemoveCustomer(new Customer("Tim Krul", "Vianen",
// "NL65 ABNA 0156 8653 51", LocalDate.parse("1989-08-25"), "[email protected]",
// "3553AZ", "0616113931", "mexicostraat 11", false), false);
// addorRemoveCustomer(new Customer(" Bas Dost", "Den Haag", "n.v.t.", LocalDate.parse("1975-05-31"),
// "[email protected]", "3451AC", "0690324576",
// "Englandlaan 89", false), false);
// addorRemoveCustomer(new Customer("Leo Messi", "Nieuwegein",
// "NL23 ABNA 0267 8153 37", LocalDate.parse("1988-08-25"), "[email protected]",
// "3564AZ", "0690421467", "Kleineneusdreef 10", false), false);
// addorRemoveCustomer(new Customer("Andre Hazes", "Amsterdam", "n.v.t.", LocalDate.parse("1957-05-31"),
// "[email protected]", "3715BC", "0621234167",
// "legendedreef 12", false), false);
//
//
// customers.get(0).add(new Car("volkswagen", "13-LOL-3"));
// customers.get(1).add(new Car("porsche", "14-LAL-5"));
// customers.get(2).add(new Car("ferrari", "15-LIL-6"));
// customers.get(3).add(new Car("mercedes", "16-LEL-9"));
// customers.get(4).add(new Car("bmw", "17-LQL-1"));
// customers.get(5).add(new Car("nissan", "18-POL-2"));
// customers.get(6).add(new Car("opel", "18-LVL-8"));
// customers.get(7).add(new Car("renault", "15-WOL-1"));
// customers.get(8).add(new Car("audi", "24-QOL-9"));
// customers.get(9).add(new Car("lamborgini", "03-TOL-3"));
// customers.get(10).add(new Car("volkswagen", "93-TOL-3"));
// customers.get(11).add(new Car("porsche", "43-TOL-3"));
// customers.get(12).add(new Car("ferrari", "23-TOL-3"));
// customers.get(13).add(new Car("mercedes", "83-TOL-3"));
// customers.get(14).add(new Car("bmw", "33-TOL-3"));
// customers.get(15).add(new Car("opel", "13-TOL-3"));
// customers.get(16).add(new Car("renault", "33-TOL-3"));
// customers.get(17).add(new Car("audi", "12-TOL-3"));
// customers.get(18).add(new Car("lamborgini", "50-TOL-3"));
// customers.get(19).add(new Car("volkswagen", "59-TOL-3"));
// customers.get(1).add(new Car("lamborgini", "58-TOL-3"));
// customers.get(1).add(new Car("porsche", "57-TOL-3"));
// customers.get(2).add(new Car("lamborgini", "52-TOL-3"));
// customers.get(3).add(new Car("lamborgini", "56-TOL-3"));
// customers.get(4).add(new Car("lamborgini", "55-TOL-3"));
// customers.get(5).add(new Car("lamborgini", "54-TOL-3"));
// customers.get(6).add(new Car("lamborgini", "04-TOL-3"));
//
//
// customers.get(0).setLastMaintenance(LocalDate.now().minusMonths(7));
// customers.get(0).setLastVisit(LocalDate.now().minusMonths(1));
// customers.get(1).setLastMaintenance(LocalDate.now().minusMonths(4));
// customers.get(1).setLastVisit(LocalDate.now().minusMonths(3));
// addorRemoveMechanic(new Mechanic(1, "Jaap", 15.0), false);
// addorRemoveMechanic(new Mechanic(2, "Hans", 12.5), false);
// addorRemoveMechanic(new Mechanic(3, "Sjaak", 10.0), false);
// addorRemoveMechanic(new Mechanic(4, "Piet", 15.0), false);
// addorRemoveInvoice(new Invoice(), false);
// addorRemoveInvoice(new Invoice(), false);
// addorRemoveMaintenanceSessions(new MaintenanceSession("13-LOL-3", stock, LocalDate.now()), false);
// addorRemoveMaintenanceSessions(new MaintenanceSession("65-RGB-1", stock, LocalDate.now().plusDays(4)), false);
// addorRemoveSupplier(new ProductSupplier("Cheapo BV", "Hoevelaan 2", "7853OQ", "Den Haag"), false);
// addorRemoveSupplier(new ProductSupplier("Banden BV", "Hamburgerstraat 10", "4198KW", "Utrecht"), false);
// addorRemoveSupplier(new ProductSupplier("Peugeot", "Parijslaan", "2353PL", "Amsterdam"), false);
// addorRemoveSupplier(new ProductSupplier("Mercedes", "Berlijnstraat 45", "5462KY", "Rotterdam"), false);
// addorRemoveSupplier(new ProductSupplier("Shell", "Hoevenlaan 99", "1337AF", "Eindhoven"), false);
// addorRemoveproduct(new Part("Uitlaat", 5, 5, 20, 22, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Band klein", 7, 10, 60, 100, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Accu", 80, 85, 180, 220, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Airco", 70, 100, 200, 230, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Band groot", 50, 50, 25, 52, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Velgen klein", 9, 10, 60, 120, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Velgen groot", 20, 27, 20, 22, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Besturingsysteem", 4, 10, 110, 250, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Brandstofsysteem", 30, 50, 60, 80, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Dashboard", 15, 20, 60, 100, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Schakelaar", 20, 20, 20, 35, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Kabels", 78, 80, 6, 12, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Filter", 40, 50, 20, 22, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Bekleding", 26, 30, 40, 100, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Interieur", 50, 50, 250, 320, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Motor", 70, 75, 300, 400, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Ophanging", 10, 15, 75, 88, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Onderstel", 7, 10, 60, 100, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Remmen", 50, 65, 80, 120, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Aandrijving", 20, 25, 60, 100, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Ruiten", 40, 50, 20, 40, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Toebehoren Ruiten", 40, 50, 20, 40, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Spiegels", 25, 30, 20, 32, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Transmissie<SUF>
// addorRemoveproduct(new Part("Transmissie", 25, 30, 220, 332, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Lampen", 35, 40, 2, 5, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Koplamp voor", 35, 40, 20, 42, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Koplamp achter", 35, 40, 60, 90, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Autosleutel", 5, 20, 15, 25, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Winterband groot", 20, 10, 60, 100, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Winterband klein", 20, 5, 50, 90, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Sneeuwketting groot", 20, 15, 60, 100, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Sneeuwketting klein", 20, 15, 50, 90, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Schroeven extra groot", 8, 10, 5, 10, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Schroeven groot", 8, 10, 4, 8, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Schroeven middelmaat", 8, 3, 6, 100, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Schroeven klein", 8, 10, 2, 4, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Schroeven extra klein", 8, 10, 1, 2, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Radio duur", 10, 20, 50, 75, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Radio normaal", 7, 10, 30, 55, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Radio goedkoop", 5, 5, 15, 20, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Radio extra goedkoop", 7, 10, 10, 15, suppliers.get(1)), false);
// addorRemoveproduct(new Part("Velgen extra duur", 20, 20, 30, 62, suppliers.get(2)), false);
// addorRemoveproduct(new Part("Besturingsysteem duur", 20, 30, 150, 250, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Brandstofsysteem duur", 20, 40, 200, 350, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Dashboard classic", 7, 10, 60, 100, suppliers.get(1)), false);
// addorRemoveproduct(new Part("doekjes", 5, 5, 1, 3, suppliers.get(2)), false);
// addorRemoveproduct(new Part("ververs olie", 150, 200, 6, 10, suppliers.get(3)), false);
// addorRemoveproduct(new Part("Reiningmiddel", 150, 200, 2, 5, suppliers.get(0)), false);
// addorRemoveproduct(new Part("Schoonmaakmiddel", 200, 300, 3, 6, suppliers.get(1)), false);
// addorRemoveproduct(new Fuel("Diesel", 300, 200, 1, 1.19, suppliers.get(4)), false);
// addorRemoveproduct(new Fuel("Euro95", 275, 150, 1.11, 1.52, suppliers.get(4)), false);
// addorRemoveproduct(new Fuel("Euro98", 271, 250, 1, 1.69, suppliers.get(4)), false);
// addorRemoveproduct(new Fuel("Lpg", 275, 150, 1.11, 1.12, suppliers.get(4)), false);
// addorRemoveproduct(new Fuel("Electriteit", 300, 200, 1, 2.19, suppliers.get(4)), false);
// addorRemoveproduct(new Fuel("Waterstof", 275, 150, 1.11, 8.62, suppliers.get(4)), false);
// addorRemoveReservations(new Reservation(LocalDate.parse("2015-03-29"), LocalDate.parse("2015-04-20"), "13-edm-1", parkingSpaces.get(0)), false);
// addorRemoveReservations(new Reservation(LocalDate.parse("2015-04-01"), LocalDate.parse("2015-04-04"), "69-lmr-7", parkingSpaces.get(1)), false);
// addorRemoveReservations(new Reservation(LocalDate.parse("2015-04-04"), LocalDate.parse("2015-04-09"), "31-dos-3", parkingSpaces.get(2)), false);
// }
public static void main(String[] args) {
launch();
}
@Deprecated
public Stock getStock() {
return stock;
}
public Stage getStage() {
return mainStage;
}
}
|
132221_10 | /**
* Copyright 2014 Internet2
*
* 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.
*/
/*
* @author Chris Hyzer
*/
package edu.internet2.middleware.grouper.changeLog.esb.consumer;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import edu.internet2.middleware.grouper.Group;
import edu.internet2.middleware.grouper.GroupFinder;
import edu.internet2.middleware.grouper.GrouperSession;
import edu.internet2.middleware.grouper.Member;
import edu.internet2.middleware.grouper.MemberFinder;
import edu.internet2.middleware.grouper.Membership;
import edu.internet2.middleware.grouper.MembershipFinder;
import edu.internet2.middleware.grouper.Stem;
import edu.internet2.middleware.grouper.Stem.Scope;
import edu.internet2.middleware.grouper.attr.AttributeDef;
import edu.internet2.middleware.grouper.attr.AttributeDefName;
import edu.internet2.middleware.grouper.attr.assign.AttributeAssign;
import edu.internet2.middleware.grouper.attr.finder.AttributeDefNameFinder;
import edu.internet2.middleware.grouper.cfg.GrouperConfig;
import edu.internet2.middleware.grouper.changeLog.ChangeLogConsumerBase;
import edu.internet2.middleware.grouper.changeLog.ChangeLogEntry;
import edu.internet2.middleware.grouper.changeLog.ChangeLogLabels;
import edu.internet2.middleware.grouper.changeLog.ChangeLogProcessorMetadata;
import edu.internet2.middleware.grouper.changeLog.ChangeLogType;
import edu.internet2.middleware.grouper.exception.GrouperSessionException;
import edu.internet2.middleware.grouper.membership.MembershipResult;
import edu.internet2.middleware.grouper.membership.MembershipType;
import edu.internet2.middleware.grouper.misc.CompositeType;
import edu.internet2.middleware.grouper.misc.GrouperSessionHandler;
import edu.internet2.middleware.grouper.permissions.role.Role;
import edu.internet2.middleware.grouper.rules.RuleCheck;
import edu.internet2.middleware.grouper.rules.RuleCheckType;
import edu.internet2.middleware.grouper.rules.RuleDefinition;
import edu.internet2.middleware.grouper.rules.RuleEngine;
import edu.internet2.middleware.grouper.rules.RuleIfCondition;
import edu.internet2.middleware.grouper.rules.RuleIfConditionEnum;
import edu.internet2.middleware.grouper.rules.RuleThenEnum;
import edu.internet2.middleware.grouper.rules.beans.RulesBean;
import edu.internet2.middleware.grouper.rules.beans.RulesMembershipBean;
import edu.internet2.middleware.grouper.rules.beans.RulesPermissionBean;
import edu.internet2.middleware.grouper.util.GrouperUtil;
import edu.internet2.middleware.subject.Source;
import edu.internet2.middleware.subject.Subject;
import edu.internet2.middleware.subject.provider.SourceManager;
/**
* Class to dispatch individual events for rules
* @author mchyzer
*/
public class RuleConsumer extends ChangeLogConsumerBase {
/**
* process events based on event type. This is the category__action
*
*/
private static enum RuleEventType {
/** add membership event */
membership__addMembership {
/**
* @see RuleEventType#processEvent(ChangeLogType, ChangeLogEntry, RulesBean)
*/
@Override
public void processEvent(ChangeLogType changeLogType,
ChangeLogEntry changeLogEntry, RulesBean rulesBean) {
//fire rules directly connected to this membership flat delete
RuleEngine.fireRule(RuleCheckType.flattenedMembershipAdd, rulesBean);
//fire rules related to add in stem
RuleEngine.fireRule(RuleCheckType.flattenedMembershipAddInFolder, rulesBean);
}
/**
* @see RuleEventType#setupRulesBean(ChangeLogType, ChangeLogEntry, GrouperSession)
*/
@Override
public RulesBean setupRulesBean(ChangeLogType changeLogType,
ChangeLogEntry changeLogEntry, GrouperSession grouperSession) {
return setupRulesBeanMembership(changeLogType, changeLogEntry, grouperSession);
}
/**
* @see RuleEventType#shouldProcess(ChangeLogType, ChangeLogEntry)
*/
@Override
public boolean shouldProcess(ChangeLogType changeLogType,
ChangeLogEntry changeLogEntry) {
return shouldProcessMembership(changeLogType, changeLogEntry);
}
},
/** delete membership event */
membership__deleteMembership {
/**
* @see RuleEventType#processEvent(ChangeLogType, ChangeLogEntry, RulesBean)
*/
@Override
public void processEvent(ChangeLogType changeLogType,
ChangeLogEntry changeLogEntry, RulesBean rulesBean) {
//fire rules directly connected to this membership flat delete
RuleEngine.fireRule(RuleCheckType.flattenedMembershipRemove, rulesBean);
//fire rules related to membership flat delete in folder
RuleEngine.fireRule(RuleCheckType.flattenedMembershipRemoveInFolder, rulesBean);
fixVetoIfNotInFolder(rulesBean.getGroup(), rulesBean.getSubject(), rulesBean.getSubjectSourceId());
}
/**
* @see RuleEventType#setupRulesBean(ChangeLogType, ChangeLogEntry, GrouperSession)
*/
@Override
public RulesBean setupRulesBean(ChangeLogType changeLogType,
ChangeLogEntry changeLogEntry, GrouperSession grouperSession) {
return setupRulesBeanMembership(changeLogType, changeLogEntry, grouperSession);
}
/**
* @see RuleEventType#shouldProcess(ChangeLogType, ChangeLogEntry)
*/
@Override
public boolean shouldProcess(ChangeLogType changeLogType,
ChangeLogEntry changeLogEntry) {
return shouldProcessMembership(changeLogType, changeLogEntry);
}
};
/**
* if this record should be processed
* @param changeLogType
* @param changeLogEntry
* @return true if the record should be processed
*/
public abstract boolean shouldProcess(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry);
/**
* setup a rules bean, this will be called in the context of a root session
* @param changeLogType
* @param changeLogEntry
* @param grouperSession
* @return the rules bean
*/
public abstract RulesBean setupRulesBean(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry, GrouperSession grouperSession);
/**
* process an event which matches the category and type
* @param changeLogType
* @param changeLogEntry
* @param rulesBean
*/
public abstract void processEvent(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry, RulesBean rulesBean);
/**
* do a case-insensitive matching
*
* @param string
* @param exceptionOnNull will not allow null or blank entries
* @param exceptionIfInvalid true if there should be an exception if invalid
* @return the enum or null or exception if not found
*/
public static RuleConsumer.RuleEventType valueOfIgnoreCase(String string, boolean exceptionOnNull, boolean exceptionIfInvalid) {
return GrouperUtil.enumValueOfIgnoreCase(RuleConsumer.RuleEventType.class,
string, exceptionOnNull, exceptionIfInvalid);
}
};
/** */
private static final Log LOG = GrouperUtil.getLog(RuleConsumer.class);
public static boolean shouldContinueFixVetoIfNotInFolder(final RuleDefinition definition) {
RuleCheck ruleCheck = definition.getCheck();
RuleIfCondition ifCondition = definition.getIfCondition();
if (ruleCheck.checkTypeEnum() == RuleCheckType.subjectAssignInStem &&
ifCondition.ifConditionEnum() == RuleIfConditionEnum.groupHasNoEnabledMembership &&
definition.getAttributeAssignType().getOwnerStem() != null &&
definition.getThen().thenEnum() == RuleThenEnum.veto) {
return true;
}
return false;
}
public static void fixVetoIfNotInFolder(final Group group, final Subject subject, final String subjectSourceId) {
Set<RuleDefinition> definitions = RuleEngine.ruleEngine().getRuleDefinitions();
for (RuleDefinition definition: definitions) {
if (!shouldContinueFixVetoIfNotInFolder(definition)) {
continue;
}
if (!GrouperConfig.retrieveConfig().propertyValueBoolean("grouperRuleChangeLog_GRP_2143_Remove_memberships_from_restricted_stem_when_removed_from_dependent_group", true)) {
return;
}
String ownerId = definition.getIfCondition().getIfOwnerId();
boolean shouldContinue = false;
if (StringUtils.equals(ownerId, group.getId())) {
shouldContinue = true;
}
if (!shouldContinue) {
String ownerName = definition.getIfCondition().getIfOwnerName();
if (StringUtils.equals(ownerName, group.getName())) {
shouldContinue = true;
}
}
if (!shouldContinue) {
continue;
}
final Stem ownerStem = definition.getAttributeAssignType().getOwnerStem();
String checkStemScope = definition.getCheck().getCheckStemScope();
final Scope scope = StringUtils.isNotBlank(checkStemScope) ? Scope.valueOfIgnoreCase(checkStemScope, true): Scope.SUB;
GrouperSession.internal_callbackRootGrouperSession(new GrouperSessionHandler() {
@Override
public Object callback(GrouperSession grouperSession) throws GrouperSessionException {
Member member = MemberFinder.findBySubject(grouperSession, subject, false);
if (group.hasMember(member.getSubject())) {
return null;
}
Set<Source> sources = null;
if (subjectSourceId != null) {
sources = new HashSet<Source>();
Source source = SourceManager.getInstance().getSource(subjectSourceId);
sources.add(source);
}
MembershipResult membershipResult = new MembershipFinder().assignFindAllFields(true)
.addMemberId(member.getId())
.assignMembershipType(MembershipType.IMMEDIATE)
.assignSources(sources)
.assignStem(ownerStem)
.assignStemScope(scope)
.assignEnabled(null)
.findMembershipResult();
Set<Object[]> membershipsOwnersMembers = membershipResult.getMembershipsOwnersMembers();
for (Object[] objects: membershipsOwnersMembers) {
Membership membership = (Membership) objects[0];
membership.delete();
}
return null;
}
});
}
}
/**
* @see ChangeLogConsumerBase#processChangeLogEntries(List, ChangeLogProcessorMetadata)
*/
@Override
public long processChangeLogEntries(
List<ChangeLogEntry> changeLogEntryList,
ChangeLogProcessorMetadata changeLogProcessorMetadata) {
long currentId = -1;
//try catch so we can track that we made some progress
try {
for (final ChangeLogEntry changeLogEntry : changeLogEntryList) {
final ChangeLogType changeLogType = changeLogEntry.getChangeLogType();
currentId = changeLogEntry.getSequenceNumber();
if (LOG.isDebugEnabled()) {
LOG.debug("Processing event number " + currentId + ", "
+ changeLogType.getChangeLogCategory() + ", " + changeLogType.getActionName());
}
String enumKey = changeLogType.getChangeLogCategory() + "__" + changeLogType.getActionName();
final RuleEventType ruleEventType = RuleEventType.valueOfIgnoreCase(enumKey, false, false);
if (ruleEventType != null) {
if (!ruleEventType.shouldProcess(changeLogType, changeLogEntry)) {
continue;
}
GrouperSession theGrouperSession = GrouperSession.startRootSession(false);
RulesBean rulesBean = null;
try {
rulesBean = (RulesBean)GrouperSession.callbackGrouperSession(theGrouperSession, new GrouperSessionHandler() {
public Object callback(GrouperSession grouperSession) throws GrouperSessionException {
return ruleEventType.setupRulesBean(changeLogType, changeLogEntry, grouperSession);
}
});
} finally {
GrouperSession.stopQuietly(theGrouperSession);
}
if (rulesBean != null) {
ruleEventType.processEvent(changeLogType, changeLogEntry, rulesBean);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Unsupported event " + changeLogType.getChangeLogCategory() + ", "
+ changeLogType.getActionName() + ", " + changeLogEntry.getSequenceNumber());
}
}
}
//we successfully processed this record
} catch (Exception e) {
LOG.error("problem", e);
changeLogProcessorMetadata.registerProblem(e, "Error processing record " + currentId, currentId);
//we made it to this -1
return currentId - 1;
}
if (currentId == -1) {
throw new RuntimeException("Couldn't process any records");
}
return currentId;
}
/**
*
* @param changeLogType
* @param changeLogEntry
* @return true if should process, false if not
*/
private static boolean shouldProcessMembership(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry) {
String fieldId = changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_DELETE.fieldId);
//lets only do members list for now
if (!StringUtils.equals(fieldId, Group.getDefaultList().getUuid())) {
return false;
}
//must be flattened
String membershipType = changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_DELETE.membershipType);
if (!StringUtils.equals("flattened", membershipType)) {
return false;
}
return true;
}
/**
*
* @param changeLogType
* @param changeLogEntry
* @return true if should process, false if not
*/
private static boolean shouldProcessPermission(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry) {
// There is no more flattened...
// //must be flattened
// String permissionType = changeLogEntry.retrieveValueForLabel("permissionType");
//
// if (!StringUtils.equals("flattened", permissionType)) {
// return false;
// }
String memberId = changeLogEntry.retrieveValueForLabel("memberId");
//if this is assigned to a role, and not a user, skip it
if (StringUtils.isBlank(memberId)) {
return false;
}
return true;
}
/**
*
* @param changeLogType
* @param changeLogEntry
* @param grouperSession
* @return the rules bean
*/
private static RulesBean setupRulesBeanMembership(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry, GrouperSession grouperSession) {
String memberId = changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_DELETE.memberId);
Member member = MemberFinder.findByUuid(grouperSession, memberId, true);
if (member == null) {
return null;
}
Subject subject = member.getSubject();
String groupId = changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_DELETE.groupId);
Group group = GroupFinder.findByUuid(grouperSession, groupId, false);
if (group == null) {
return null;
}
RulesMembershipBean rulesMembershipBean = new RulesMembershipBean(member, group, subject);
return rulesMembershipBean;
}
/**
*
* @param changeLogType
* @param changeLogEntry
* @param grouperSession
* @return the rules bean
*/
private static RulesBean setupRulesBeanPermission(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry, GrouperSession grouperSession) {
AttributeAssign attributeAssign = null;
// CH this went away, not in change log anymore...
// String attributeAssignId = changeLogEntry.retrieveValueForLabel("attributeAssignId");
//
// AttributeAssign attributeAssign = AttributeAssignFinder.findById(attributeAssignId, false);
// if (attributeAssign == null) {
// return null;
// }
String memberId = changeLogEntry.retrieveValueForLabel("memberId");
Member member = MemberFinder.findByUuid(grouperSession, memberId, false);
if (member == null) {
return null;
}
Role role = null;
// CH this went away, not in change log anymore...
// String roleId = changeLogEntry.retrieveValueForLabel("roleId");
//
// Role role = GroupFinder.findByUuid(grouperSession, roleId, false);
//
// if (role == null) {
// return null;
// }
String attributeDefNameId = changeLogEntry.retrieveValueForLabel("attributeDefNameId");
AttributeDefName attributeDefName = AttributeDefNameFinder.findById(attributeDefNameId, false);
if (attributeDefName == null) {
return null;
}
AttributeDef attributeDef = attributeDefName.getAttributeDef();
String action = changeLogEntry.retrieveValueForLabel("action");
RulesPermissionBean rulesPermissionBean = new RulesPermissionBean(attributeAssign, role, member, attributeDefName, attributeDef, action);
return rulesPermissionBean;
}
}
| Internet2/grouper | grouper/src/grouper/edu/internet2/middleware/grouper/changeLog/esb/consumer/RuleConsumer.java | 5,428 | /** delete membership event */ | block_comment | nl | /**
* Copyright 2014 Internet2
*
* 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.
*/
/*
* @author Chris Hyzer
*/
package edu.internet2.middleware.grouper.changeLog.esb.consumer;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import edu.internet2.middleware.grouper.Group;
import edu.internet2.middleware.grouper.GroupFinder;
import edu.internet2.middleware.grouper.GrouperSession;
import edu.internet2.middleware.grouper.Member;
import edu.internet2.middleware.grouper.MemberFinder;
import edu.internet2.middleware.grouper.Membership;
import edu.internet2.middleware.grouper.MembershipFinder;
import edu.internet2.middleware.grouper.Stem;
import edu.internet2.middleware.grouper.Stem.Scope;
import edu.internet2.middleware.grouper.attr.AttributeDef;
import edu.internet2.middleware.grouper.attr.AttributeDefName;
import edu.internet2.middleware.grouper.attr.assign.AttributeAssign;
import edu.internet2.middleware.grouper.attr.finder.AttributeDefNameFinder;
import edu.internet2.middleware.grouper.cfg.GrouperConfig;
import edu.internet2.middleware.grouper.changeLog.ChangeLogConsumerBase;
import edu.internet2.middleware.grouper.changeLog.ChangeLogEntry;
import edu.internet2.middleware.grouper.changeLog.ChangeLogLabels;
import edu.internet2.middleware.grouper.changeLog.ChangeLogProcessorMetadata;
import edu.internet2.middleware.grouper.changeLog.ChangeLogType;
import edu.internet2.middleware.grouper.exception.GrouperSessionException;
import edu.internet2.middleware.grouper.membership.MembershipResult;
import edu.internet2.middleware.grouper.membership.MembershipType;
import edu.internet2.middleware.grouper.misc.CompositeType;
import edu.internet2.middleware.grouper.misc.GrouperSessionHandler;
import edu.internet2.middleware.grouper.permissions.role.Role;
import edu.internet2.middleware.grouper.rules.RuleCheck;
import edu.internet2.middleware.grouper.rules.RuleCheckType;
import edu.internet2.middleware.grouper.rules.RuleDefinition;
import edu.internet2.middleware.grouper.rules.RuleEngine;
import edu.internet2.middleware.grouper.rules.RuleIfCondition;
import edu.internet2.middleware.grouper.rules.RuleIfConditionEnum;
import edu.internet2.middleware.grouper.rules.RuleThenEnum;
import edu.internet2.middleware.grouper.rules.beans.RulesBean;
import edu.internet2.middleware.grouper.rules.beans.RulesMembershipBean;
import edu.internet2.middleware.grouper.rules.beans.RulesPermissionBean;
import edu.internet2.middleware.grouper.util.GrouperUtil;
import edu.internet2.middleware.subject.Source;
import edu.internet2.middleware.subject.Subject;
import edu.internet2.middleware.subject.provider.SourceManager;
/**
* Class to dispatch individual events for rules
* @author mchyzer
*/
public class RuleConsumer extends ChangeLogConsumerBase {
/**
* process events based on event type. This is the category__action
*
*/
private static enum RuleEventType {
/** add membership event */
membership__addMembership {
/**
* @see RuleEventType#processEvent(ChangeLogType, ChangeLogEntry, RulesBean)
*/
@Override
public void processEvent(ChangeLogType changeLogType,
ChangeLogEntry changeLogEntry, RulesBean rulesBean) {
//fire rules directly connected to this membership flat delete
RuleEngine.fireRule(RuleCheckType.flattenedMembershipAdd, rulesBean);
//fire rules related to add in stem
RuleEngine.fireRule(RuleCheckType.flattenedMembershipAddInFolder, rulesBean);
}
/**
* @see RuleEventType#setupRulesBean(ChangeLogType, ChangeLogEntry, GrouperSession)
*/
@Override
public RulesBean setupRulesBean(ChangeLogType changeLogType,
ChangeLogEntry changeLogEntry, GrouperSession grouperSession) {
return setupRulesBeanMembership(changeLogType, changeLogEntry, grouperSession);
}
/**
* @see RuleEventType#shouldProcess(ChangeLogType, ChangeLogEntry)
*/
@Override
public boolean shouldProcess(ChangeLogType changeLogType,
ChangeLogEntry changeLogEntry) {
return shouldProcessMembership(changeLogType, changeLogEntry);
}
},
/** delete membership event<SUF>*/
membership__deleteMembership {
/**
* @see RuleEventType#processEvent(ChangeLogType, ChangeLogEntry, RulesBean)
*/
@Override
public void processEvent(ChangeLogType changeLogType,
ChangeLogEntry changeLogEntry, RulesBean rulesBean) {
//fire rules directly connected to this membership flat delete
RuleEngine.fireRule(RuleCheckType.flattenedMembershipRemove, rulesBean);
//fire rules related to membership flat delete in folder
RuleEngine.fireRule(RuleCheckType.flattenedMembershipRemoveInFolder, rulesBean);
fixVetoIfNotInFolder(rulesBean.getGroup(), rulesBean.getSubject(), rulesBean.getSubjectSourceId());
}
/**
* @see RuleEventType#setupRulesBean(ChangeLogType, ChangeLogEntry, GrouperSession)
*/
@Override
public RulesBean setupRulesBean(ChangeLogType changeLogType,
ChangeLogEntry changeLogEntry, GrouperSession grouperSession) {
return setupRulesBeanMembership(changeLogType, changeLogEntry, grouperSession);
}
/**
* @see RuleEventType#shouldProcess(ChangeLogType, ChangeLogEntry)
*/
@Override
public boolean shouldProcess(ChangeLogType changeLogType,
ChangeLogEntry changeLogEntry) {
return shouldProcessMembership(changeLogType, changeLogEntry);
}
};
/**
* if this record should be processed
* @param changeLogType
* @param changeLogEntry
* @return true if the record should be processed
*/
public abstract boolean shouldProcess(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry);
/**
* setup a rules bean, this will be called in the context of a root session
* @param changeLogType
* @param changeLogEntry
* @param grouperSession
* @return the rules bean
*/
public abstract RulesBean setupRulesBean(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry, GrouperSession grouperSession);
/**
* process an event which matches the category and type
* @param changeLogType
* @param changeLogEntry
* @param rulesBean
*/
public abstract void processEvent(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry, RulesBean rulesBean);
/**
* do a case-insensitive matching
*
* @param string
* @param exceptionOnNull will not allow null or blank entries
* @param exceptionIfInvalid true if there should be an exception if invalid
* @return the enum or null or exception if not found
*/
public static RuleConsumer.RuleEventType valueOfIgnoreCase(String string, boolean exceptionOnNull, boolean exceptionIfInvalid) {
return GrouperUtil.enumValueOfIgnoreCase(RuleConsumer.RuleEventType.class,
string, exceptionOnNull, exceptionIfInvalid);
}
};
/** */
private static final Log LOG = GrouperUtil.getLog(RuleConsumer.class);
public static boolean shouldContinueFixVetoIfNotInFolder(final RuleDefinition definition) {
RuleCheck ruleCheck = definition.getCheck();
RuleIfCondition ifCondition = definition.getIfCondition();
if (ruleCheck.checkTypeEnum() == RuleCheckType.subjectAssignInStem &&
ifCondition.ifConditionEnum() == RuleIfConditionEnum.groupHasNoEnabledMembership &&
definition.getAttributeAssignType().getOwnerStem() != null &&
definition.getThen().thenEnum() == RuleThenEnum.veto) {
return true;
}
return false;
}
public static void fixVetoIfNotInFolder(final Group group, final Subject subject, final String subjectSourceId) {
Set<RuleDefinition> definitions = RuleEngine.ruleEngine().getRuleDefinitions();
for (RuleDefinition definition: definitions) {
if (!shouldContinueFixVetoIfNotInFolder(definition)) {
continue;
}
if (!GrouperConfig.retrieveConfig().propertyValueBoolean("grouperRuleChangeLog_GRP_2143_Remove_memberships_from_restricted_stem_when_removed_from_dependent_group", true)) {
return;
}
String ownerId = definition.getIfCondition().getIfOwnerId();
boolean shouldContinue = false;
if (StringUtils.equals(ownerId, group.getId())) {
shouldContinue = true;
}
if (!shouldContinue) {
String ownerName = definition.getIfCondition().getIfOwnerName();
if (StringUtils.equals(ownerName, group.getName())) {
shouldContinue = true;
}
}
if (!shouldContinue) {
continue;
}
final Stem ownerStem = definition.getAttributeAssignType().getOwnerStem();
String checkStemScope = definition.getCheck().getCheckStemScope();
final Scope scope = StringUtils.isNotBlank(checkStemScope) ? Scope.valueOfIgnoreCase(checkStemScope, true): Scope.SUB;
GrouperSession.internal_callbackRootGrouperSession(new GrouperSessionHandler() {
@Override
public Object callback(GrouperSession grouperSession) throws GrouperSessionException {
Member member = MemberFinder.findBySubject(grouperSession, subject, false);
if (group.hasMember(member.getSubject())) {
return null;
}
Set<Source> sources = null;
if (subjectSourceId != null) {
sources = new HashSet<Source>();
Source source = SourceManager.getInstance().getSource(subjectSourceId);
sources.add(source);
}
MembershipResult membershipResult = new MembershipFinder().assignFindAllFields(true)
.addMemberId(member.getId())
.assignMembershipType(MembershipType.IMMEDIATE)
.assignSources(sources)
.assignStem(ownerStem)
.assignStemScope(scope)
.assignEnabled(null)
.findMembershipResult();
Set<Object[]> membershipsOwnersMembers = membershipResult.getMembershipsOwnersMembers();
for (Object[] objects: membershipsOwnersMembers) {
Membership membership = (Membership) objects[0];
membership.delete();
}
return null;
}
});
}
}
/**
* @see ChangeLogConsumerBase#processChangeLogEntries(List, ChangeLogProcessorMetadata)
*/
@Override
public long processChangeLogEntries(
List<ChangeLogEntry> changeLogEntryList,
ChangeLogProcessorMetadata changeLogProcessorMetadata) {
long currentId = -1;
//try catch so we can track that we made some progress
try {
for (final ChangeLogEntry changeLogEntry : changeLogEntryList) {
final ChangeLogType changeLogType = changeLogEntry.getChangeLogType();
currentId = changeLogEntry.getSequenceNumber();
if (LOG.isDebugEnabled()) {
LOG.debug("Processing event number " + currentId + ", "
+ changeLogType.getChangeLogCategory() + ", " + changeLogType.getActionName());
}
String enumKey = changeLogType.getChangeLogCategory() + "__" + changeLogType.getActionName();
final RuleEventType ruleEventType = RuleEventType.valueOfIgnoreCase(enumKey, false, false);
if (ruleEventType != null) {
if (!ruleEventType.shouldProcess(changeLogType, changeLogEntry)) {
continue;
}
GrouperSession theGrouperSession = GrouperSession.startRootSession(false);
RulesBean rulesBean = null;
try {
rulesBean = (RulesBean)GrouperSession.callbackGrouperSession(theGrouperSession, new GrouperSessionHandler() {
public Object callback(GrouperSession grouperSession) throws GrouperSessionException {
return ruleEventType.setupRulesBean(changeLogType, changeLogEntry, grouperSession);
}
});
} finally {
GrouperSession.stopQuietly(theGrouperSession);
}
if (rulesBean != null) {
ruleEventType.processEvent(changeLogType, changeLogEntry, rulesBean);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Unsupported event " + changeLogType.getChangeLogCategory() + ", "
+ changeLogType.getActionName() + ", " + changeLogEntry.getSequenceNumber());
}
}
}
//we successfully processed this record
} catch (Exception e) {
LOG.error("problem", e);
changeLogProcessorMetadata.registerProblem(e, "Error processing record " + currentId, currentId);
//we made it to this -1
return currentId - 1;
}
if (currentId == -1) {
throw new RuntimeException("Couldn't process any records");
}
return currentId;
}
/**
*
* @param changeLogType
* @param changeLogEntry
* @return true if should process, false if not
*/
private static boolean shouldProcessMembership(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry) {
String fieldId = changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_DELETE.fieldId);
//lets only do members list for now
if (!StringUtils.equals(fieldId, Group.getDefaultList().getUuid())) {
return false;
}
//must be flattened
String membershipType = changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_DELETE.membershipType);
if (!StringUtils.equals("flattened", membershipType)) {
return false;
}
return true;
}
/**
*
* @param changeLogType
* @param changeLogEntry
* @return true if should process, false if not
*/
private static boolean shouldProcessPermission(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry) {
// There is no more flattened...
// //must be flattened
// String permissionType = changeLogEntry.retrieveValueForLabel("permissionType");
//
// if (!StringUtils.equals("flattened", permissionType)) {
// return false;
// }
String memberId = changeLogEntry.retrieveValueForLabel("memberId");
//if this is assigned to a role, and not a user, skip it
if (StringUtils.isBlank(memberId)) {
return false;
}
return true;
}
/**
*
* @param changeLogType
* @param changeLogEntry
* @param grouperSession
* @return the rules bean
*/
private static RulesBean setupRulesBeanMembership(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry, GrouperSession grouperSession) {
String memberId = changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_DELETE.memberId);
Member member = MemberFinder.findByUuid(grouperSession, memberId, true);
if (member == null) {
return null;
}
Subject subject = member.getSubject();
String groupId = changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_DELETE.groupId);
Group group = GroupFinder.findByUuid(grouperSession, groupId, false);
if (group == null) {
return null;
}
RulesMembershipBean rulesMembershipBean = new RulesMembershipBean(member, group, subject);
return rulesMembershipBean;
}
/**
*
* @param changeLogType
* @param changeLogEntry
* @param grouperSession
* @return the rules bean
*/
private static RulesBean setupRulesBeanPermission(ChangeLogType changeLogType, ChangeLogEntry changeLogEntry, GrouperSession grouperSession) {
AttributeAssign attributeAssign = null;
// CH this went away, not in change log anymore...
// String attributeAssignId = changeLogEntry.retrieveValueForLabel("attributeAssignId");
//
// AttributeAssign attributeAssign = AttributeAssignFinder.findById(attributeAssignId, false);
// if (attributeAssign == null) {
// return null;
// }
String memberId = changeLogEntry.retrieveValueForLabel("memberId");
Member member = MemberFinder.findByUuid(grouperSession, memberId, false);
if (member == null) {
return null;
}
Role role = null;
// CH this went away, not in change log anymore...
// String roleId = changeLogEntry.retrieveValueForLabel("roleId");
//
// Role role = GroupFinder.findByUuid(grouperSession, roleId, false);
//
// if (role == null) {
// return null;
// }
String attributeDefNameId = changeLogEntry.retrieveValueForLabel("attributeDefNameId");
AttributeDefName attributeDefName = AttributeDefNameFinder.findById(attributeDefNameId, false);
if (attributeDefName == null) {
return null;
}
AttributeDef attributeDef = attributeDefName.getAttributeDef();
String action = changeLogEntry.retrieveValueForLabel("action");
RulesPermissionBean rulesPermissionBean = new RulesPermissionBean(attributeAssign, role, member, attributeDefName, attributeDef, action);
return rulesPermissionBean;
}
}
|
131135_1 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.pepsoft.worldpainter.importing;
import org.pepsoft.util.MathUtils;
import org.pepsoft.util.ProgressReceiver;
import org.pepsoft.worldpainter.Dimension;
import org.pepsoft.worldpainter.Terrain;
import org.pepsoft.worldpainter.Tile;
import org.pepsoft.worldpainter.biomeschemes.Minecraft1_13Biomes;
import org.pepsoft.worldpainter.history.HistoryEntry;
import org.pepsoft.worldpainter.layers.Annotations;
import org.pepsoft.worldpainter.layers.Biome;
import org.pepsoft.worldpainter.layers.Layer;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
import static org.pepsoft.worldpainter.Constants.TILE_SIZE;
import static org.pepsoft.worldpainter.Constants.TILE_SIZE_BITS;
import static org.pepsoft.worldpainter.importing.MaskImporter.InputType.SIXTEEN_BIT_GREY_SCALE;
/**
*
* @author pepijn
*/
public class MaskImporter {
public MaskImporter(Dimension dimension, File imageFile, List<Layer> allLayers) throws IOException {
this(dimension, imageFile, ImageIO.read(imageFile), allLayers);
}
public MaskImporter(Dimension dimension, File imageFile, BufferedImage image, List<Layer> allLayers) {
this.dimension = dimension;
this.imageFile = imageFile;
this.image = image;
this.allLayers = allLayers;
int sampleSize = image.getSampleModel().getSampleSize(0);
if (sampleSize == 1) {
inputType = InputType.ONE_BIT_GRAY_SCALE;
} else if (image.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_GRAY) {
if (sampleSize == 8) {
inputType = InputType.EIGHT_BIT_GREY_SCALE;
} else if (sampleSize == 16) {
inputType = InputType.SIXTEEN_BIT_GREY_SCALE;
} else {
inputType = InputType.UNSUPPORTED;
}
} else {
inputType = InputType.COLOUR;
}
switch (inputType) {
case ONE_BIT_GRAY_SCALE:
imageLowValue = 0;
imageHighValue = 1;
break;
case EIGHT_BIT_GREY_SCALE:
case SIXTEEN_BIT_GREY_SCALE:
final int width = image.getWidth(), height = image.getHeight();
final Raster raster = image.getRaster();
int imageLowValue = Integer.MAX_VALUE, imageHighValue = Integer.MIN_VALUE;
outer: for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int value = raster.getSample(x, y, 0);
if (value < imageLowValue) {
imageLowValue = value;
}
if (value > imageHighValue) {
imageHighValue = value;
}
if ((imageLowValue == 0) && ((inputType == SIXTEEN_BIT_GREY_SCALE) ? (imageHighValue == 65535) : (imageHighValue == 255))) {
// Lowest and highest possible values found; no
// point in looking any further!
break outer;
}
}
}
this.imageLowValue = imageLowValue;
this.imageHighValue = imageHighValue;
break;
default:
this.imageLowValue = -1;
this.imageHighValue = -1;
break;
}
}
public void doImport(ProgressReceiver progressReceiver) throws ProgressReceiver.OperationCancelled {
if ((! applyToTerrain) && (applyToLayer == null)) {
throw new IllegalStateException("Target not set");
}
if (mapping == null) {
throw new IllegalStateException("Mapping not set");
}
if ((mapping == Mapping.THRESHOLD) && (threshold == -1)) {
throw new IllegalStateException("Threshold not set");
}
final int maxValue;
switch (inputType) {
case ONE_BIT_GRAY_SCALE:
maxValue = 1;
break;
case EIGHT_BIT_GREY_SCALE:
maxValue = 255;
break;
case SIXTEEN_BIT_GREY_SCALE:
maxValue = 65535;
break;
default:
maxValue = 0;
break;
}
final Random random = new Random(dimension.getSeed() + xOffset * 31 + yOffset);
// Scale the mask, if necessary
final BufferedImage scaledImage;
if (scale == 100) {
// No scaling necessary
scaledImage = image;
} else {
final int newWidth = image.getWidth() * scale / 100, newHeight = image.getHeight() * scale / 100;
if (image.getColorModel() instanceof IndexColorModel) {
scaledImage = new BufferedImage(newWidth, newHeight, image.getType(), (IndexColorModel) image.getColorModel());
} else {
scaledImage = new BufferedImage(newWidth, newHeight, image.getType());
}
Graphics2D g2 = scaledImage.createGraphics();
try {
if (mapping == Mapping.FULL_RANGE) {
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
}
g2.drawImage(image, 0, 0, newWidth, newHeight, null);
} finally {
g2.dispose();
}
}
image = null; // The original image is no longer necessary, so allow it to be garbage collected to make more space available for the import
// Create the appropriate mapping logic
abstract class Applicator {
void setTile(Tile tile) {
this.tile = tile;
}
abstract void apply(int x, int y, int value);
Tile tile;
}
final Applicator applicator;
final String aspect;
switch (inputType) {
case ONE_BIT_GRAY_SCALE:
if (removeExistingLayer) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
tile.setBitLayerValue(applyToLayer, x, y, value != 0);
}
};
} else {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if (value != 0) {
tile.setBitLayerValue(applyToLayer, x, y, true);
}
}
};
}
aspect = "layer " + applyToLayer.getName();
break;
case EIGHT_BIT_GREY_SCALE:
case SIXTEEN_BIT_GREY_SCALE:
switch (mapping) {
case ONE_TO_ONE:
if (applyToTerrain) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
tile.setTerrain(x, y, Terrain.VALUES[value]);
}
};
aspect = "terrain";
} else {
final int defaultValue = applyToLayer.getDefaultValue();
if (removeExistingLayer) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if ((value != defaultValue)
|| (tile.getLayerValue(applyToLayer, x, y) != defaultValue)) {
tile.setLayerValue(applyToLayer, x, y, value);
}
}
};
} else {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if ((value != defaultValue) && (value > tile.getLayerValue(applyToLayer, x, y))) {
tile.setLayerValue(applyToLayer, x, y, value);
}
}
};
}
aspect = "layer " + applyToLayer.getName();
}
break;
case DITHERING:
if (removeExistingLayer) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
boolean layerValue = (value > 0) && (random.nextInt(limit) <= value);
if (layerValue || (tile.getBitLayerValue(applyToLayer, x, y))) {
tile.setBitLayerValue(applyToLayer, x, y, layerValue);
}
}
private final int limit = maxValue + 1;
};
} else {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if ((value > 0) && (random.nextInt(limit) <= value)) {
tile.setBitLayerValue(applyToLayer, x, y, true);
}
}
private final int limit = maxValue + 1;
};
}
aspect = "layer " + applyToLayer.getName();
break;
case THRESHOLD:
if (removeExistingLayer) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
boolean layerValue = value >= threshold;
if (layerValue || tile.getBitLayerValue(applyToLayer, x, y)) {
tile.setBitLayerValue(applyToLayer, x, y, layerValue);
}
}
};
} else {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if (value >= threshold) {
tile.setBitLayerValue(applyToLayer, x, y, true);
}
}
};
}
aspect = "layer " + applyToLayer.getName();
break;
case FULL_RANGE:
final int layerLimit;
if (applyToLayer.getDataSize() == Layer.DataSize.NIBBLE) {
layerLimit = 16;
} else if (applyToLayer.getDataSize() == Layer.DataSize.BYTE) {
layerLimit = 256;
} else {
throw new IllegalArgumentException();
}
final int defaultValue = applyToLayer.getDefaultValue();
if (removeExistingLayer) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
int layerValue = value * layerLimit / limit;
if ((layerValue != defaultValue) || (tile.getLayerValue(applyToLayer, x, y) != defaultValue)) {
tile.setLayerValue(applyToLayer, x, y, layerValue);
}
}
private final int limit = maxValue + 1;
};
} else {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
int layerValue = value * layerLimit / limit;
if ((layerValue != defaultValue) && (layerValue > tile.getLayerValue(applyToLayer, x, y))) {
tile.setLayerValue(applyToLayer, x, y, layerValue);
}
}
private final int limit = maxValue + 1;
};
}
aspect = "layer " + applyToLayer.getName();
break;
default:
throw new IllegalArgumentException("Don't know how to apply this combo");
}
break;
case COLOUR:
if (removeExistingLayer) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if (((value >> 24) & 0xff) > 0x7f) {
tile.setLayerValue(Annotations.INSTANCE, x, y, COLOUR_ANNOTATION_MAPPING[((value >> 12) & 0xf00) | ((value >> 8) & 0xf0) | ((value >> 4) & 0xf)]);
} else if (tile.getLayerValue(Annotations.INSTANCE, x, y) != 0) {
tile.setLayerValue(Annotations.INSTANCE, x, y, 0);
}
}
};
} else {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if (((value >> 24) & 0xff) > 0x7f) {
tile.setLayerValue(Annotations.INSTANCE, x, y, COLOUR_ANNOTATION_MAPPING[((value >> 12) & 0xf00) | ((value >> 8) & 0xf0) | ((value >> 4) & 0xf)]);
}
}
};
}
aspect = "annotations";
break;
default:
throw new IllegalArgumentException("Don't know how to apply this combo");
}
if (dimension.getWorld() != null) {
dimension.getWorld().addHistoryEntry(HistoryEntry.WORLD_MASK_IMPORTED_TO_DIMENSION, dimension.getName(), imageFile, aspect);
}
// Apply the mask tile by tile
final int width = scaledImage.getWidth(), height = scaledImage.getHeight();
final int tileX1 = xOffset >> TILE_SIZE_BITS, tileX2 = (xOffset + width - 1) >> TILE_SIZE_BITS;
final int tileY1 = yOffset >> TILE_SIZE_BITS, tileY2 = (yOffset + height- 1) >> TILE_SIZE_BITS;
final int noOfTiles = (tileX2 - tileX1 + 1) * (tileY2 - tileY1 + 1);
int tileCount = 0;
for (int tileX = tileX1; tileX <= tileX2; tileX++) {
for (int tileY = tileY1; tileY <= tileY2; tileY++) {
final Tile tile = dimension.getTile(tileX, tileY);
if (tile == null) {
tileCount++;
if (progressReceiver != null) {
progressReceiver.setProgress((float) tileCount / noOfTiles);
}
continue;
}
tile.inhibitEvents();
try {
final int tileOffsetX = (tileX << TILE_SIZE_BITS) - xOffset, tileOffsetY = (tileY << TILE_SIZE_BITS) - yOffset;
final Raster raster = scaledImage.getRaster();
applicator.setTile(tile);
if (inputType == InputType.COLOUR) {
for (int xInTile = 0; xInTile < TILE_SIZE; xInTile++) {
for (int yInTile = 0; yInTile < TILE_SIZE; yInTile++) {
final int imageX = tileOffsetX + xInTile, imageY = tileOffsetY + yInTile;
if ((imageX >= 0) && (imageX < width) && (imageY >= 0) && (imageY < height)) {
applicator.apply(xInTile, yInTile, scaledImage.getRGB(imageX, imageY));
}
}
}
} else {
for (int xInTile = 0; xInTile < TILE_SIZE; xInTile++) {
for (int yInTile = 0; yInTile < TILE_SIZE; yInTile++) {
final int imageX = tileOffsetX + xInTile, imageY = tileOffsetY + yInTile;
if ((imageX >= 0) && (imageX < width) && (imageY >= 0) && (imageY < height)) {
applicator.apply(xInTile, yInTile, raster.getSample(imageX, imageY, 0));
}
}
}
}
} finally {
tile.releaseEvents();
}
tileCount++;
if (progressReceiver != null) {
progressReceiver.setProgress((float) tileCount / noOfTiles);
}
}
}
}
public InputType getInputType() {
return inputType;
}
public boolean isSupported() {
return inputType != InputType.UNSUPPORTED;
}
/**
* @return Whether this image type can be mapped to the terrain.
*/
public boolean isTerrainPossible() {
// Only gray scale images with at least 8 bits can be mapped to the
// terrain. Possible in the future we will support mapping colours to
// the terrain, but not yet.
return (inputType == InputType.EIGHT_BIT_GREY_SCALE || inputType == InputType.SIXTEEN_BIT_GREY_SCALE)
&& (imageHighValue < Terrain.VALUES.length);
}
// TODO: dithered en threshold ook ondersteunen voor terrain en continue layers - mappen op één waarde
// of beter nog: generieke mapping mode bouwen
/**
* @return The list of layers to which this image type can be mapped. May be
* empty.
*/
public List<Layer> getPossibleLayers() {
List<Layer> possibleLayers = new ArrayList<>(allLayers.size());
for (Layer layer: allLayers) {
if (layer.equals(Annotations.INSTANCE)) {
// Annotations are a special case; since they are coloured we
// support importing a colour image as annotations
if (((inputType == InputType.EIGHT_BIT_GREY_SCALE || inputType == InputType.SIXTEEN_BIT_GREY_SCALE) && (imageHighValue < 16)) || inputType == InputType.COLOUR) {
possibleLayers.add(layer);
}
} else if (layer.equals(Biome.INSTANCE)) {
// Biomes are a discrete layer which can only be mapped one on one
if ((inputType == InputType.EIGHT_BIT_GREY_SCALE || inputType == InputType.SIXTEEN_BIT_GREY_SCALE) && (imageHighValue <= Minecraft1_13Biomes.HIGHEST_BIOME_ID )) {
possibleLayers.add(layer);
}
} else if (layer.getDataSize() == Layer.DataSize.BIT || layer.getDataSize() == Layer.DataSize.BIT_PER_CHUNK) {
// 8 or 16 bit masks can be applied by either dithering or applying a threshold
if (inputType == InputType.ONE_BIT_GRAY_SCALE || inputType == InputType.EIGHT_BIT_GREY_SCALE || inputType == InputType.SIXTEEN_BIT_GREY_SCALE) {
possibleLayers.add(layer);
}
} else {
// Continuous layers need a gray scale mask
if (inputType == InputType.EIGHT_BIT_GREY_SCALE || inputType == InputType.SIXTEEN_BIT_GREY_SCALE) {
possibleLayers.add(layer);
}
}
}
return possibleLayers;
}
public Layer getApplyToLayer() {
return applyToLayer;
}
public void setApplyToLayer(Layer applyToLayer) {
if ((applyToLayer != null) && (! getPossibleLayers().contains(applyToLayer))) {
throw new IllegalArgumentException("This image type cannot be applied to the specified layer");
}
this.applyToLayer = applyToLayer;
if (applyToLayer != null) {
applyToTerrain = false;
}
}
public boolean isApplyToTerrain() {
return applyToTerrain;
}
public void setApplyToTerrain(boolean applyToTerrain) {
if (applyToTerrain && (! isTerrainPossible())) {
throw new IllegalArgumentException("This image type cannot be applied to the terrain");
}
this.applyToTerrain = applyToTerrain;
if (applyToTerrain) {
applyToLayer = null;
}
}
/**
* @return The types of mapping possible for the specified target (terrain
* or layer).
*/
public Set<Mapping> getPossibleMappings() {
if (applyToTerrain) {
return EnumSet.of(Mapping.ONE_TO_ONE);
} else if (applyToLayer.equals(Annotations.INSTANCE)) {
return EnumSet.of(Mapping.ONE_TO_ONE);
} else if (applyToLayer.equals(Biome.INSTANCE)) {
return EnumSet.of(Mapping.ONE_TO_ONE);
} else if (applyToLayer.getDataSize() == Layer.DataSize.BIT || applyToLayer.getDataSize() == Layer.DataSize.BIT_PER_CHUNK) {
switch (inputType) {
case ONE_BIT_GRAY_SCALE:
return EnumSet.of(Mapping.ONE_TO_ONE);
case EIGHT_BIT_GREY_SCALE:
case SIXTEEN_BIT_GREY_SCALE:
return EnumSet.of(Mapping.DITHERING, Mapping.THRESHOLD);
}
} else {
return EnumSet.of(Mapping.FULL_RANGE);
}
throw new IllegalStateException();
}
public Mapping getMapping() {
return mapping;
}
public void setMapping(Mapping mapping) {
if (! getPossibleMappings().contains(mapping)) {
throw new IllegalArgumentException();
}
this.mapping = mapping;
}
public int getScale() {
return scale;
}
public void setScale(int scale) {
this.scale = scale;
}
public int getxOffset() {
return xOffset;
}
public void setxOffset(int xOffset) {
this.xOffset = xOffset;
}
public int getyOffset() {
return yOffset;
}
public void setyOffset(int yOffset) {
this.yOffset = yOffset;
}
public int getThreshold() {
return threshold;
}
public void setThreshold(int threshold) {
if (threshold < 0) {
throw new IllegalArgumentException();
}
this.threshold = threshold;
}
public boolean isRemoveExistingLayer() {
return removeExistingLayer;
}
public void setRemoveExistingLayer(boolean removeExistingLayer) {
this.removeExistingLayer = removeExistingLayer;
}
public int getImageHighValue() {
return imageHighValue;
}
public int getImageLowValue() {
return imageLowValue;
}
private static int findNearestAnnotationValue(int colour) {
final int red = (colour & 0xff0000) >> 16;
final int green = (colour & 0xff00) >> 8;
final int blue = colour & 0xff;
float minDistance = Float.MAX_VALUE;
int minDistanceIndex = -1;
for (int i = 0; i < ANNOTATIONS_PALETTE.length; i++) {
final float distance = MathUtils.getDistance(red - ANNOTATIONS_PALETTE[i][0], green - ANNOTATIONS_PALETTE[i][1], blue - ANNOTATIONS_PALETTE[i][2]);
if (distance < minDistance) {
minDistance = distance;
minDistanceIndex = i;
}
}
return minDistanceIndex + 1;
}
private final Dimension dimension;
private final List<Layer> allLayers;
private final InputType inputType;
private final int imageLowValue, imageHighValue;
private final File imageFile;
private BufferedImage image;
private boolean applyToTerrain, removeExistingLayer;
private Layer applyToLayer;
private Mapping mapping;
private int scale, xOffset, yOffset, threshold = -1;
public enum InputType {UNSUPPORTED, ONE_BIT_GRAY_SCALE, EIGHT_BIT_GREY_SCALE, SIXTEEN_BIT_GREY_SCALE, COLOUR}
public enum Mapping {ONE_TO_ONE, DITHERING, THRESHOLD, FULL_RANGE}
private static int[][] ANNOTATIONS_PALETTE = {
{0xdd, 0xdd, 0xdd},
{0xdb, 0x7d, 0x3e},
{0xb3, 0x50, 0xbc},
{0x6a, 0x8a, 0xc9},
{0xb1, 0xa6, 0x27},
{0x41, 0xae, 0x38},
{0xd0, 0x84, 0x99},
{0x9a, 0xa1, 0xa1},
{0x2e, 0x6e, 0x89},
{0x7e, 0x3d, 0xb5},
{0x2e, 0x38, 0x8d},
{0x4f, 0x32, 0x1f},
{0x35, 0x46, 0x1b},
{0x96, 0x34, 0x30},
{0x19, 0x16, 0x16}
};
/**
* A table which maps colours to annotation layer values. The colours have
* their last four bits stripped to keep the table small.
*/
private static final int[] COLOUR_ANNOTATION_MAPPING = new int[4096];
static {
for (int i = 0; i < 4096; i++) {
COLOUR_ANNOTATION_MAPPING[i] = findNearestAnnotationValue(((i & 0xf00) << 12) | ((i & 0xf0) << 8) | ((i & 0xf) << 4));
}
}
} | InventivetalentDev/WorldPainter | WorldPainter/WPGUI/src/main/java/org/pepsoft/worldpainter/importing/MaskImporter.java | 7,370 | /**
*
* @author pepijn
*/ | block_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.pepsoft.worldpainter.importing;
import org.pepsoft.util.MathUtils;
import org.pepsoft.util.ProgressReceiver;
import org.pepsoft.worldpainter.Dimension;
import org.pepsoft.worldpainter.Terrain;
import org.pepsoft.worldpainter.Tile;
import org.pepsoft.worldpainter.biomeschemes.Minecraft1_13Biomes;
import org.pepsoft.worldpainter.history.HistoryEntry;
import org.pepsoft.worldpainter.layers.Annotations;
import org.pepsoft.worldpainter.layers.Biome;
import org.pepsoft.worldpainter.layers.Layer;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
import static org.pepsoft.worldpainter.Constants.TILE_SIZE;
import static org.pepsoft.worldpainter.Constants.TILE_SIZE_BITS;
import static org.pepsoft.worldpainter.importing.MaskImporter.InputType.SIXTEEN_BIT_GREY_SCALE;
/**
*
* @author pepijn
<SUF>*/
public class MaskImporter {
public MaskImporter(Dimension dimension, File imageFile, List<Layer> allLayers) throws IOException {
this(dimension, imageFile, ImageIO.read(imageFile), allLayers);
}
public MaskImporter(Dimension dimension, File imageFile, BufferedImage image, List<Layer> allLayers) {
this.dimension = dimension;
this.imageFile = imageFile;
this.image = image;
this.allLayers = allLayers;
int sampleSize = image.getSampleModel().getSampleSize(0);
if (sampleSize == 1) {
inputType = InputType.ONE_BIT_GRAY_SCALE;
} else if (image.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_GRAY) {
if (sampleSize == 8) {
inputType = InputType.EIGHT_BIT_GREY_SCALE;
} else if (sampleSize == 16) {
inputType = InputType.SIXTEEN_BIT_GREY_SCALE;
} else {
inputType = InputType.UNSUPPORTED;
}
} else {
inputType = InputType.COLOUR;
}
switch (inputType) {
case ONE_BIT_GRAY_SCALE:
imageLowValue = 0;
imageHighValue = 1;
break;
case EIGHT_BIT_GREY_SCALE:
case SIXTEEN_BIT_GREY_SCALE:
final int width = image.getWidth(), height = image.getHeight();
final Raster raster = image.getRaster();
int imageLowValue = Integer.MAX_VALUE, imageHighValue = Integer.MIN_VALUE;
outer: for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int value = raster.getSample(x, y, 0);
if (value < imageLowValue) {
imageLowValue = value;
}
if (value > imageHighValue) {
imageHighValue = value;
}
if ((imageLowValue == 0) && ((inputType == SIXTEEN_BIT_GREY_SCALE) ? (imageHighValue == 65535) : (imageHighValue == 255))) {
// Lowest and highest possible values found; no
// point in looking any further!
break outer;
}
}
}
this.imageLowValue = imageLowValue;
this.imageHighValue = imageHighValue;
break;
default:
this.imageLowValue = -1;
this.imageHighValue = -1;
break;
}
}
public void doImport(ProgressReceiver progressReceiver) throws ProgressReceiver.OperationCancelled {
if ((! applyToTerrain) && (applyToLayer == null)) {
throw new IllegalStateException("Target not set");
}
if (mapping == null) {
throw new IllegalStateException("Mapping not set");
}
if ((mapping == Mapping.THRESHOLD) && (threshold == -1)) {
throw new IllegalStateException("Threshold not set");
}
final int maxValue;
switch (inputType) {
case ONE_BIT_GRAY_SCALE:
maxValue = 1;
break;
case EIGHT_BIT_GREY_SCALE:
maxValue = 255;
break;
case SIXTEEN_BIT_GREY_SCALE:
maxValue = 65535;
break;
default:
maxValue = 0;
break;
}
final Random random = new Random(dimension.getSeed() + xOffset * 31 + yOffset);
// Scale the mask, if necessary
final BufferedImage scaledImage;
if (scale == 100) {
// No scaling necessary
scaledImage = image;
} else {
final int newWidth = image.getWidth() * scale / 100, newHeight = image.getHeight() * scale / 100;
if (image.getColorModel() instanceof IndexColorModel) {
scaledImage = new BufferedImage(newWidth, newHeight, image.getType(), (IndexColorModel) image.getColorModel());
} else {
scaledImage = new BufferedImage(newWidth, newHeight, image.getType());
}
Graphics2D g2 = scaledImage.createGraphics();
try {
if (mapping == Mapping.FULL_RANGE) {
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
}
g2.drawImage(image, 0, 0, newWidth, newHeight, null);
} finally {
g2.dispose();
}
}
image = null; // The original image is no longer necessary, so allow it to be garbage collected to make more space available for the import
// Create the appropriate mapping logic
abstract class Applicator {
void setTile(Tile tile) {
this.tile = tile;
}
abstract void apply(int x, int y, int value);
Tile tile;
}
final Applicator applicator;
final String aspect;
switch (inputType) {
case ONE_BIT_GRAY_SCALE:
if (removeExistingLayer) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
tile.setBitLayerValue(applyToLayer, x, y, value != 0);
}
};
} else {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if (value != 0) {
tile.setBitLayerValue(applyToLayer, x, y, true);
}
}
};
}
aspect = "layer " + applyToLayer.getName();
break;
case EIGHT_BIT_GREY_SCALE:
case SIXTEEN_BIT_GREY_SCALE:
switch (mapping) {
case ONE_TO_ONE:
if (applyToTerrain) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
tile.setTerrain(x, y, Terrain.VALUES[value]);
}
};
aspect = "terrain";
} else {
final int defaultValue = applyToLayer.getDefaultValue();
if (removeExistingLayer) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if ((value != defaultValue)
|| (tile.getLayerValue(applyToLayer, x, y) != defaultValue)) {
tile.setLayerValue(applyToLayer, x, y, value);
}
}
};
} else {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if ((value != defaultValue) && (value > tile.getLayerValue(applyToLayer, x, y))) {
tile.setLayerValue(applyToLayer, x, y, value);
}
}
};
}
aspect = "layer " + applyToLayer.getName();
}
break;
case DITHERING:
if (removeExistingLayer) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
boolean layerValue = (value > 0) && (random.nextInt(limit) <= value);
if (layerValue || (tile.getBitLayerValue(applyToLayer, x, y))) {
tile.setBitLayerValue(applyToLayer, x, y, layerValue);
}
}
private final int limit = maxValue + 1;
};
} else {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if ((value > 0) && (random.nextInt(limit) <= value)) {
tile.setBitLayerValue(applyToLayer, x, y, true);
}
}
private final int limit = maxValue + 1;
};
}
aspect = "layer " + applyToLayer.getName();
break;
case THRESHOLD:
if (removeExistingLayer) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
boolean layerValue = value >= threshold;
if (layerValue || tile.getBitLayerValue(applyToLayer, x, y)) {
tile.setBitLayerValue(applyToLayer, x, y, layerValue);
}
}
};
} else {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if (value >= threshold) {
tile.setBitLayerValue(applyToLayer, x, y, true);
}
}
};
}
aspect = "layer " + applyToLayer.getName();
break;
case FULL_RANGE:
final int layerLimit;
if (applyToLayer.getDataSize() == Layer.DataSize.NIBBLE) {
layerLimit = 16;
} else if (applyToLayer.getDataSize() == Layer.DataSize.BYTE) {
layerLimit = 256;
} else {
throw new IllegalArgumentException();
}
final int defaultValue = applyToLayer.getDefaultValue();
if (removeExistingLayer) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
int layerValue = value * layerLimit / limit;
if ((layerValue != defaultValue) || (tile.getLayerValue(applyToLayer, x, y) != defaultValue)) {
tile.setLayerValue(applyToLayer, x, y, layerValue);
}
}
private final int limit = maxValue + 1;
};
} else {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
int layerValue = value * layerLimit / limit;
if ((layerValue != defaultValue) && (layerValue > tile.getLayerValue(applyToLayer, x, y))) {
tile.setLayerValue(applyToLayer, x, y, layerValue);
}
}
private final int limit = maxValue + 1;
};
}
aspect = "layer " + applyToLayer.getName();
break;
default:
throw new IllegalArgumentException("Don't know how to apply this combo");
}
break;
case COLOUR:
if (removeExistingLayer) {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if (((value >> 24) & 0xff) > 0x7f) {
tile.setLayerValue(Annotations.INSTANCE, x, y, COLOUR_ANNOTATION_MAPPING[((value >> 12) & 0xf00) | ((value >> 8) & 0xf0) | ((value >> 4) & 0xf)]);
} else if (tile.getLayerValue(Annotations.INSTANCE, x, y) != 0) {
tile.setLayerValue(Annotations.INSTANCE, x, y, 0);
}
}
};
} else {
applicator = new Applicator() {
@Override
void apply(int x, int y, int value) {
if (((value >> 24) & 0xff) > 0x7f) {
tile.setLayerValue(Annotations.INSTANCE, x, y, COLOUR_ANNOTATION_MAPPING[((value >> 12) & 0xf00) | ((value >> 8) & 0xf0) | ((value >> 4) & 0xf)]);
}
}
};
}
aspect = "annotations";
break;
default:
throw new IllegalArgumentException("Don't know how to apply this combo");
}
if (dimension.getWorld() != null) {
dimension.getWorld().addHistoryEntry(HistoryEntry.WORLD_MASK_IMPORTED_TO_DIMENSION, dimension.getName(), imageFile, aspect);
}
// Apply the mask tile by tile
final int width = scaledImage.getWidth(), height = scaledImage.getHeight();
final int tileX1 = xOffset >> TILE_SIZE_BITS, tileX2 = (xOffset + width - 1) >> TILE_SIZE_BITS;
final int tileY1 = yOffset >> TILE_SIZE_BITS, tileY2 = (yOffset + height- 1) >> TILE_SIZE_BITS;
final int noOfTiles = (tileX2 - tileX1 + 1) * (tileY2 - tileY1 + 1);
int tileCount = 0;
for (int tileX = tileX1; tileX <= tileX2; tileX++) {
for (int tileY = tileY1; tileY <= tileY2; tileY++) {
final Tile tile = dimension.getTile(tileX, tileY);
if (tile == null) {
tileCount++;
if (progressReceiver != null) {
progressReceiver.setProgress((float) tileCount / noOfTiles);
}
continue;
}
tile.inhibitEvents();
try {
final int tileOffsetX = (tileX << TILE_SIZE_BITS) - xOffset, tileOffsetY = (tileY << TILE_SIZE_BITS) - yOffset;
final Raster raster = scaledImage.getRaster();
applicator.setTile(tile);
if (inputType == InputType.COLOUR) {
for (int xInTile = 0; xInTile < TILE_SIZE; xInTile++) {
for (int yInTile = 0; yInTile < TILE_SIZE; yInTile++) {
final int imageX = tileOffsetX + xInTile, imageY = tileOffsetY + yInTile;
if ((imageX >= 0) && (imageX < width) && (imageY >= 0) && (imageY < height)) {
applicator.apply(xInTile, yInTile, scaledImage.getRGB(imageX, imageY));
}
}
}
} else {
for (int xInTile = 0; xInTile < TILE_SIZE; xInTile++) {
for (int yInTile = 0; yInTile < TILE_SIZE; yInTile++) {
final int imageX = tileOffsetX + xInTile, imageY = tileOffsetY + yInTile;
if ((imageX >= 0) && (imageX < width) && (imageY >= 0) && (imageY < height)) {
applicator.apply(xInTile, yInTile, raster.getSample(imageX, imageY, 0));
}
}
}
}
} finally {
tile.releaseEvents();
}
tileCount++;
if (progressReceiver != null) {
progressReceiver.setProgress((float) tileCount / noOfTiles);
}
}
}
}
public InputType getInputType() {
return inputType;
}
public boolean isSupported() {
return inputType != InputType.UNSUPPORTED;
}
/**
* @return Whether this image type can be mapped to the terrain.
*/
public boolean isTerrainPossible() {
// Only gray scale images with at least 8 bits can be mapped to the
// terrain. Possible in the future we will support mapping colours to
// the terrain, but not yet.
return (inputType == InputType.EIGHT_BIT_GREY_SCALE || inputType == InputType.SIXTEEN_BIT_GREY_SCALE)
&& (imageHighValue < Terrain.VALUES.length);
}
// TODO: dithered en threshold ook ondersteunen voor terrain en continue layers - mappen op één waarde
// of beter nog: generieke mapping mode bouwen
/**
* @return The list of layers to which this image type can be mapped. May be
* empty.
*/
public List<Layer> getPossibleLayers() {
List<Layer> possibleLayers = new ArrayList<>(allLayers.size());
for (Layer layer: allLayers) {
if (layer.equals(Annotations.INSTANCE)) {
// Annotations are a special case; since they are coloured we
// support importing a colour image as annotations
if (((inputType == InputType.EIGHT_BIT_GREY_SCALE || inputType == InputType.SIXTEEN_BIT_GREY_SCALE) && (imageHighValue < 16)) || inputType == InputType.COLOUR) {
possibleLayers.add(layer);
}
} else if (layer.equals(Biome.INSTANCE)) {
// Biomes are a discrete layer which can only be mapped one on one
if ((inputType == InputType.EIGHT_BIT_GREY_SCALE || inputType == InputType.SIXTEEN_BIT_GREY_SCALE) && (imageHighValue <= Minecraft1_13Biomes.HIGHEST_BIOME_ID )) {
possibleLayers.add(layer);
}
} else if (layer.getDataSize() == Layer.DataSize.BIT || layer.getDataSize() == Layer.DataSize.BIT_PER_CHUNK) {
// 8 or 16 bit masks can be applied by either dithering or applying a threshold
if (inputType == InputType.ONE_BIT_GRAY_SCALE || inputType == InputType.EIGHT_BIT_GREY_SCALE || inputType == InputType.SIXTEEN_BIT_GREY_SCALE) {
possibleLayers.add(layer);
}
} else {
// Continuous layers need a gray scale mask
if (inputType == InputType.EIGHT_BIT_GREY_SCALE || inputType == InputType.SIXTEEN_BIT_GREY_SCALE) {
possibleLayers.add(layer);
}
}
}
return possibleLayers;
}
public Layer getApplyToLayer() {
return applyToLayer;
}
public void setApplyToLayer(Layer applyToLayer) {
if ((applyToLayer != null) && (! getPossibleLayers().contains(applyToLayer))) {
throw new IllegalArgumentException("This image type cannot be applied to the specified layer");
}
this.applyToLayer = applyToLayer;
if (applyToLayer != null) {
applyToTerrain = false;
}
}
public boolean isApplyToTerrain() {
return applyToTerrain;
}
public void setApplyToTerrain(boolean applyToTerrain) {
if (applyToTerrain && (! isTerrainPossible())) {
throw new IllegalArgumentException("This image type cannot be applied to the terrain");
}
this.applyToTerrain = applyToTerrain;
if (applyToTerrain) {
applyToLayer = null;
}
}
/**
* @return The types of mapping possible for the specified target (terrain
* or layer).
*/
public Set<Mapping> getPossibleMappings() {
if (applyToTerrain) {
return EnumSet.of(Mapping.ONE_TO_ONE);
} else if (applyToLayer.equals(Annotations.INSTANCE)) {
return EnumSet.of(Mapping.ONE_TO_ONE);
} else if (applyToLayer.equals(Biome.INSTANCE)) {
return EnumSet.of(Mapping.ONE_TO_ONE);
} else if (applyToLayer.getDataSize() == Layer.DataSize.BIT || applyToLayer.getDataSize() == Layer.DataSize.BIT_PER_CHUNK) {
switch (inputType) {
case ONE_BIT_GRAY_SCALE:
return EnumSet.of(Mapping.ONE_TO_ONE);
case EIGHT_BIT_GREY_SCALE:
case SIXTEEN_BIT_GREY_SCALE:
return EnumSet.of(Mapping.DITHERING, Mapping.THRESHOLD);
}
} else {
return EnumSet.of(Mapping.FULL_RANGE);
}
throw new IllegalStateException();
}
public Mapping getMapping() {
return mapping;
}
public void setMapping(Mapping mapping) {
if (! getPossibleMappings().contains(mapping)) {
throw new IllegalArgumentException();
}
this.mapping = mapping;
}
public int getScale() {
return scale;
}
public void setScale(int scale) {
this.scale = scale;
}
public int getxOffset() {
return xOffset;
}
public void setxOffset(int xOffset) {
this.xOffset = xOffset;
}
public int getyOffset() {
return yOffset;
}
public void setyOffset(int yOffset) {
this.yOffset = yOffset;
}
public int getThreshold() {
return threshold;
}
public void setThreshold(int threshold) {
if (threshold < 0) {
throw new IllegalArgumentException();
}
this.threshold = threshold;
}
public boolean isRemoveExistingLayer() {
return removeExistingLayer;
}
public void setRemoveExistingLayer(boolean removeExistingLayer) {
this.removeExistingLayer = removeExistingLayer;
}
public int getImageHighValue() {
return imageHighValue;
}
public int getImageLowValue() {
return imageLowValue;
}
private static int findNearestAnnotationValue(int colour) {
final int red = (colour & 0xff0000) >> 16;
final int green = (colour & 0xff00) >> 8;
final int blue = colour & 0xff;
float minDistance = Float.MAX_VALUE;
int minDistanceIndex = -1;
for (int i = 0; i < ANNOTATIONS_PALETTE.length; i++) {
final float distance = MathUtils.getDistance(red - ANNOTATIONS_PALETTE[i][0], green - ANNOTATIONS_PALETTE[i][1], blue - ANNOTATIONS_PALETTE[i][2]);
if (distance < minDistance) {
minDistance = distance;
minDistanceIndex = i;
}
}
return minDistanceIndex + 1;
}
private final Dimension dimension;
private final List<Layer> allLayers;
private final InputType inputType;
private final int imageLowValue, imageHighValue;
private final File imageFile;
private BufferedImage image;
private boolean applyToTerrain, removeExistingLayer;
private Layer applyToLayer;
private Mapping mapping;
private int scale, xOffset, yOffset, threshold = -1;
public enum InputType {UNSUPPORTED, ONE_BIT_GRAY_SCALE, EIGHT_BIT_GREY_SCALE, SIXTEEN_BIT_GREY_SCALE, COLOUR}
public enum Mapping {ONE_TO_ONE, DITHERING, THRESHOLD, FULL_RANGE}
private static int[][] ANNOTATIONS_PALETTE = {
{0xdd, 0xdd, 0xdd},
{0xdb, 0x7d, 0x3e},
{0xb3, 0x50, 0xbc},
{0x6a, 0x8a, 0xc9},
{0xb1, 0xa6, 0x27},
{0x41, 0xae, 0x38},
{0xd0, 0x84, 0x99},
{0x9a, 0xa1, 0xa1},
{0x2e, 0x6e, 0x89},
{0x7e, 0x3d, 0xb5},
{0x2e, 0x38, 0x8d},
{0x4f, 0x32, 0x1f},
{0x35, 0x46, 0x1b},
{0x96, 0x34, 0x30},
{0x19, 0x16, 0x16}
};
/**
* A table which maps colours to annotation layer values. The colours have
* their last four bits stripped to keep the table small.
*/
private static final int[] COLOUR_ANNOTATION_MAPPING = new int[4096];
static {
for (int i = 0; i < 4096; i++) {
COLOUR_ANNOTATION_MAPPING[i] = findNearestAnnotationValue(((i & 0xf00) << 12) | ((i & 0xf0) << 8) | ((i & 0xf) << 4));
}
}
} |
10296_1 | /*
* Copyright (c) 2020
* 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 com.toonapps.toon.entity;
import com.google.gson.annotations.SerializedName;
@SuppressWarnings({"unused", "HardCodedStringLiteral"})
/*
x.1 = gas
x.2 (imported analog elec measured)
x.3(PV measured zon op toon)
x.4(P1 imported elec) NT (Normal Tarif)
x.5(P1 exported elec) NT (Normal Tarif)
x.6(P1 imported elec) LT (lower Tarif)
x.7(P1 exported elec) LT (lower Tarif)
x.8 city heat
x.9 water meter
als je P1 hebt aangesloten is x.2 altijd NaN
owh en powerUsage is dus, indien zon op toon is geconfigureed, gecalculeerd
en dus niet wat de P1 zegt wat geimporteerd is
powerUsage = (P1 powerUsage) + (PV kWh meter power generated) - (P1 powerProduction)
en normaal gesproken is altijd een van beide (P1 powerusage of P1 powerproduction) 0 en de andere een waarde (je importeerd of produceerd volgens de P1 meter, nooit tegelijk)
Ook bij 3 fase is de totaal altijd een van de twee 0. Er zijn een tijdje foute slimme meters geweest die dat fout deden bij 3 fase.
De afspraak is namelijk dat de slimme meter intern de fases moet optellen en productie en verbruik tegen elkaar moet afwegen en dat pas rapporteren.
als je dus op fase 1 3000 watt produceerd en op fase 2 1000 watt verbruikt dan is je netto levering 2000 watt en netto import 0 watt (ook al importeer je 1000 watt)
*/
public class DeviceInfo {
@SerializedName("dev_settings_device")
private DeviceSettings devSettings;
@SerializedName(value="dev_2", alternate={"dev_3", "dev_4", "dev_5", "dev_6", "dev_7", "dev_8", "dev_9", "dev_10", "dev_11", "dev_12", "dev_13", "dev_14", "dev_15", "dev_16", "dev_17", "dev_19", "dev_20"})
private Device device;
@SerializedName(value="dev_2.1", alternate={"dev_3.1", "dev_4.1", "dev_5.1", "dev_6.1", "dev_7.1", "dev_8.1", "dev_9.1", "dev_10.1", "dev_11.1", "dev_12.1", "dev_13.1", "dev_14.1", "dev_15.1", "dev_16.1", "dev_17.1", "dev_19.1", "dev_20.1"})
private GasDevice gasDevice;
@SerializedName(value="dev_2.2", alternate={"dev_3.2", "dev_4.2", "dev_5.2", "dev_6.2", "dev_7.2", "dev_8.2", "dev_9.2", "dev_10.2", "dev_11.2", "dev_12.2", "dev_13.2", "dev_14.2", "dev_15.2", "dev_16.2", "dev_17.2", "dev_19.2", "dev_20.2"})
private PowerDevice powerDevice1;
@SerializedName(value="dev_2.3", alternate={"dev_3.3", "dev_4.3", "dev_5.3", "dev_6.3", "dev_7.3", "dev_8.3", "dev_9.3", "dev_10.3", "dev_11.3", "dev_12.3", "dev_13.3", "dev_14.3", "dev_15.3", "dev_16.3", "dev_17.3", "dev_19.3", "dev_20.3"})
private PowerDevice powerDevice2;
@SerializedName(value="dev_2.4", alternate={"dev_3.4", "dev_4.4", "dev_5.4", "dev_6.4", "dev_7.4", "dev_8.4", "dev_9.4", "dev_10.4", "dev_11.4", "dev_12.4", "dev_13.4", "dev_14.4", "dev_15.4", "dev_16.4", "dev_17.4", "dev_19.4", "dev_20.4"})
private PowerDevice powerDevice3;
@SerializedName(value="dev_2.5", alternate={"dev_3.5", "dev_4.5", "dev_5.5", "dev_6.5", "dev_7.5", "dev_8.5", "dev_9.5", "dev_10.5", "dev_11.5", "dev_12.5", "dev_13.5", "dev_14.5", "dev_15.5", "dev_16.5", "dev_17.5", "dev_19.5", "dev_20.5"})
private PowerDevice powerDevice4;
@SerializedName(value="dev_2.6", alternate={"dev_3.6", "dev_4.6", "dev_5.6", "dev_6.6", "dev_7.6", "dev_8.6", "dev_9.6", "dev_10.6", "dev_11.6", "dev_12.6", "dev_13.6", "dev_14.6", "dev_15.6", "dev_16.6", "dev_17.6", "dev_19.6", "dev_20.6"})
private PowerDevice powerDevice5;
@SerializedName(value="dev_2.7", alternate={"dev_3.7", "dev_4.7", "dev_5.7", "dev_6.7", "dev_7.7", "dev_8.7", "dev_9.7", "dev_10.7", "dev_11.7", "dev_12.7", "dev_13.7", "dev_14.7", "dev_15.7", "dev_16.7", "dev_17.7", "dev_19.7", "dev_20.7"})
private PowerDevice powerDevice6;
@SerializedName(value="dev_2.8", alternate={"dev_3.8", "dev_4.8", "dev_5.8", "dev_6.8", "dev_7.8", "dev_8.8", "dev_9.8", "dev_10.8", "dev_11.8", "dev_12.8", "dev_13.8", "dev_14.8", "dev_15.8", "dev_16.8", "dev_17.8", "dev_19.8", "dev_20.8"})
private HeatDevice heatDevice;
public double getGasUsed(){
return gasDevice.CurrentGasFlow;
}
public double getGasUsedQuantity(){
return gasDevice.CurrentGasQuantity / 1000;
}
public double getElecUsageFlow(){
return powerDevice1.CurrentElectricityFlow;
}
public double getElecUsageQuantity(){
return powerDevice1.CurrentElectricityQuantity;
}
public double getElecUsageFlowLow(){
return powerDevice4.CurrentElectricityFlow;
}
public double getElecUsageFlowLowQuantity() {
return powerDevice4.CurrentElectricityQuantity / 1000;
}
public double getElecUsageFlowHigh(){
return powerDevice2.CurrentElectricityFlow;
}
public double getElecUsageFlowHighQuantity(){
return powerDevice2.CurrentElectricityQuantity / 1000;
}
public double getElecProdFlowLow(){
return powerDevice5.CurrentElectricityFlow;
}
public double getElecProdFlowLowQuantity(){
return powerDevice5.CurrentElectricityQuantity / 1000;
}
public double getElecProdFlowHigh(){
return powerDevice3.CurrentElectricityFlow;
}
public double getElecProdFlowHighQuantity(){
return powerDevice3.CurrentElectricityQuantity / 1000;
}
public class DeviceSettings {
protected String uuid;
protected String name;
protected String internalAddress;
protected String type;
protected int supportsCrc;
private String[] nodeFlags;
protected String location;
private String DeviceName;
}
private class Device extends DeviceSettings {
private String ccList;
private String supportedCC;
private int IsConnected;
private int HealthValue;
private String CurrentSensorStatus;
}
private class GasDevice extends DeviceSettings {
private double CurrentGasFlow;
private double CurrentGasQuantity;
}
private class PowerDevice extends DeviceSettings {
private double CurrentElectricityFlow;
private double CurrentElectricityQuantity;
}
private class HeatDevice extends DeviceSettings {
private double CurrentHeatQuantity;
}
} | Inversion-NL/Toon-Android | app/src/main/java/com/toonapps/toon/entity/DeviceInfo.java | 2,533 | /*
x.1 = gas
x.2 (imported analog elec measured)
x.3(PV measured zon op toon)
x.4(P1 imported elec) NT (Normal Tarif)
x.5(P1 exported elec) NT (Normal Tarif)
x.6(P1 imported elec) LT (lower Tarif)
x.7(P1 exported elec) LT (lower Tarif)
x.8 city heat
x.9 water meter
als je P1 hebt aangesloten is x.2 altijd NaN
owh en powerUsage is dus, indien zon op toon is geconfigureed, gecalculeerd
en dus niet wat de P1 zegt wat geimporteerd is
powerUsage = (P1 powerUsage) + (PV kWh meter power generated) - (P1 powerProduction)
en normaal gesproken is altijd een van beide (P1 powerusage of P1 powerproduction) 0 en de andere een waarde (je importeerd of produceerd volgens de P1 meter, nooit tegelijk)
Ook bij 3 fase is de totaal altijd een van de twee 0. Er zijn een tijdje foute slimme meters geweest die dat fout deden bij 3 fase.
De afspraak is namelijk dat de slimme meter intern de fases moet optellen en productie en verbruik tegen elkaar moet afwegen en dat pas rapporteren.
als je dus op fase 1 3000 watt produceerd en op fase 2 1000 watt verbruikt dan is je netto levering 2000 watt en netto import 0 watt (ook al importeer je 1000 watt)
*/ | block_comment | nl | /*
* Copyright (c) 2020
* 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 com.toonapps.toon.entity;
import com.google.gson.annotations.SerializedName;
@SuppressWarnings({"unused", "HardCodedStringLiteral"})
/*
x.1 = gas<SUF>*/
public class DeviceInfo {
@SerializedName("dev_settings_device")
private DeviceSettings devSettings;
@SerializedName(value="dev_2", alternate={"dev_3", "dev_4", "dev_5", "dev_6", "dev_7", "dev_8", "dev_9", "dev_10", "dev_11", "dev_12", "dev_13", "dev_14", "dev_15", "dev_16", "dev_17", "dev_19", "dev_20"})
private Device device;
@SerializedName(value="dev_2.1", alternate={"dev_3.1", "dev_4.1", "dev_5.1", "dev_6.1", "dev_7.1", "dev_8.1", "dev_9.1", "dev_10.1", "dev_11.1", "dev_12.1", "dev_13.1", "dev_14.1", "dev_15.1", "dev_16.1", "dev_17.1", "dev_19.1", "dev_20.1"})
private GasDevice gasDevice;
@SerializedName(value="dev_2.2", alternate={"dev_3.2", "dev_4.2", "dev_5.2", "dev_6.2", "dev_7.2", "dev_8.2", "dev_9.2", "dev_10.2", "dev_11.2", "dev_12.2", "dev_13.2", "dev_14.2", "dev_15.2", "dev_16.2", "dev_17.2", "dev_19.2", "dev_20.2"})
private PowerDevice powerDevice1;
@SerializedName(value="dev_2.3", alternate={"dev_3.3", "dev_4.3", "dev_5.3", "dev_6.3", "dev_7.3", "dev_8.3", "dev_9.3", "dev_10.3", "dev_11.3", "dev_12.3", "dev_13.3", "dev_14.3", "dev_15.3", "dev_16.3", "dev_17.3", "dev_19.3", "dev_20.3"})
private PowerDevice powerDevice2;
@SerializedName(value="dev_2.4", alternate={"dev_3.4", "dev_4.4", "dev_5.4", "dev_6.4", "dev_7.4", "dev_8.4", "dev_9.4", "dev_10.4", "dev_11.4", "dev_12.4", "dev_13.4", "dev_14.4", "dev_15.4", "dev_16.4", "dev_17.4", "dev_19.4", "dev_20.4"})
private PowerDevice powerDevice3;
@SerializedName(value="dev_2.5", alternate={"dev_3.5", "dev_4.5", "dev_5.5", "dev_6.5", "dev_7.5", "dev_8.5", "dev_9.5", "dev_10.5", "dev_11.5", "dev_12.5", "dev_13.5", "dev_14.5", "dev_15.5", "dev_16.5", "dev_17.5", "dev_19.5", "dev_20.5"})
private PowerDevice powerDevice4;
@SerializedName(value="dev_2.6", alternate={"dev_3.6", "dev_4.6", "dev_5.6", "dev_6.6", "dev_7.6", "dev_8.6", "dev_9.6", "dev_10.6", "dev_11.6", "dev_12.6", "dev_13.6", "dev_14.6", "dev_15.6", "dev_16.6", "dev_17.6", "dev_19.6", "dev_20.6"})
private PowerDevice powerDevice5;
@SerializedName(value="dev_2.7", alternate={"dev_3.7", "dev_4.7", "dev_5.7", "dev_6.7", "dev_7.7", "dev_8.7", "dev_9.7", "dev_10.7", "dev_11.7", "dev_12.7", "dev_13.7", "dev_14.7", "dev_15.7", "dev_16.7", "dev_17.7", "dev_19.7", "dev_20.7"})
private PowerDevice powerDevice6;
@SerializedName(value="dev_2.8", alternate={"dev_3.8", "dev_4.8", "dev_5.8", "dev_6.8", "dev_7.8", "dev_8.8", "dev_9.8", "dev_10.8", "dev_11.8", "dev_12.8", "dev_13.8", "dev_14.8", "dev_15.8", "dev_16.8", "dev_17.8", "dev_19.8", "dev_20.8"})
private HeatDevice heatDevice;
public double getGasUsed(){
return gasDevice.CurrentGasFlow;
}
public double getGasUsedQuantity(){
return gasDevice.CurrentGasQuantity / 1000;
}
public double getElecUsageFlow(){
return powerDevice1.CurrentElectricityFlow;
}
public double getElecUsageQuantity(){
return powerDevice1.CurrentElectricityQuantity;
}
public double getElecUsageFlowLow(){
return powerDevice4.CurrentElectricityFlow;
}
public double getElecUsageFlowLowQuantity() {
return powerDevice4.CurrentElectricityQuantity / 1000;
}
public double getElecUsageFlowHigh(){
return powerDevice2.CurrentElectricityFlow;
}
public double getElecUsageFlowHighQuantity(){
return powerDevice2.CurrentElectricityQuantity / 1000;
}
public double getElecProdFlowLow(){
return powerDevice5.CurrentElectricityFlow;
}
public double getElecProdFlowLowQuantity(){
return powerDevice5.CurrentElectricityQuantity / 1000;
}
public double getElecProdFlowHigh(){
return powerDevice3.CurrentElectricityFlow;
}
public double getElecProdFlowHighQuantity(){
return powerDevice3.CurrentElectricityQuantity / 1000;
}
public class DeviceSettings {
protected String uuid;
protected String name;
protected String internalAddress;
protected String type;
protected int supportsCrc;
private String[] nodeFlags;
protected String location;
private String DeviceName;
}
private class Device extends DeviceSettings {
private String ccList;
private String supportedCC;
private int IsConnected;
private int HealthValue;
private String CurrentSensorStatus;
}
private class GasDevice extends DeviceSettings {
private double CurrentGasFlow;
private double CurrentGasQuantity;
}
private class PowerDevice extends DeviceSettings {
private double CurrentElectricityFlow;
private double CurrentElectricityQuantity;
}
private class HeatDevice extends DeviceSettings {
private double CurrentHeatQuantity;
}
} |
84615_38 | package eu.vicci.process.gesture;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Semaphore;
import org.eclipse.draw2d.FigureCanvas;
import org.eclipse.graphiti.ui.editor.DiagramEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.GestureEvent;
import org.eclipse.swt.events.GestureListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.TouchEvent;
import org.eclipse.swt.events.TouchListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Touch;
import eu.vicci.process.gesture.recognizer.ndollar.Multistroke;
public class Editor extends DiagramEditor implements MouseMoveListener, MouseListener, GestureListener, TouchListener,
PaintListener {
static {
DebugStream.activate();
}
/**
* Instanz eines Editor mit Gestenerkennung
*
* @author daniel
* @param mouseDown
* Gedrueckte Maustaste zur Steuerung des Timers
* @param loadSample
* Ob die Samples eingelesen werden
* @param staticRecognizer
* $N-Recognizer
* @param strokes
* Liste der Strokes
* @param currentMouseStroke
* Aktuell ausgefuehrter Mausstroke //Vorlaeufig wird zw. Touch
* u. Mouse unterschieden
* @param smplesDir
* Pfad zum Ordern mit den Pattern fuer den Recognizer // Muss
* angepasst werden//
* @param matchingScore
* Uebereinstimmung die eine Eingabe mit dem Pattern haben muss
* @param currentTouchStroke
* Aktuell ausgefuehrter Touchstroke //Vorlaeufig wird zw. Touch
* u. Mouse unterschieden
* @param timerOffset
* Timernachlauf bis Recognition ausgeloest wird
* @param timerTime
* Aufruf des TimerTask in ms
* @param timer
* Timer
* @param timertask
* Timertask
* @param coverage
* Prozentualer Anteil den ein Stroke innerhalb der durch
* strokeTolerance gesetzten Box um einen Stroke liegen muss
* @param strokeTolerance
*/
// Gedrueckte Maustaste zur Steuerung
private boolean mouseDown = false;
private boolean mouse = false;
// MouseEvent zur steuerung, Maus und Touch sind momentan nicht gleichzeitig
// moeglich
private boolean touchDown = false;
private boolean touch = false;
private boolean gesture = false;
// Var fuer den Recognizer
private PreProcessor preProcessor = new PreProcessor();
// Vektorarray mit Punkten aus points. Die Punkte werden fuer jeden Stroke
// in einen separaten Vektor geschrieben
private List<Stroke> strokes = new ArrayList<Stroke>();
private GestureRecognizer recognizer = new GestureRecognizer();
// Touch Variablen
// fuer die Verarbeitung der einzelnen Touchevents
private Stroke currentStroke = new Stroke();
private Map<Long, Stroke> currentTouchStrokes = new HashMap<Long, Stroke>();
private List<BasicGesture> findBasicGestures = new ArrayList<BasicGesture>();
// Mouse Variablen
// Die Verarbeitung der Events und insbeondere das Stroke aktualisieren
// funktioniert sehr unterschiedlich, daher nicht der gleiche Stroke wie bei
// Touch
private Stroke currentMouseStroke;
// Noetig um das updaten der MausStrokes zu kontrollieren
private boolean newStroke;
// Var fuer den Timer
// fuer den Timernachlauf d * timerOffset = Zeit nach der letzten
// Interaktion
private int timerOffset;
// Aufruf des Timers in ms
private static final int timerTime = 55;
// Timer zur Steuerung des Recognizers
private Timer timer;
public static TimerTask timertask;
// Zeit bis eine Geste als fertig betrachtet wird
private static final int finishOffset = 7;
private List<GestureResultListener> gestureResultListeners = new LinkedList<GestureResultListener>();
private static Semaphore recDelSemaphore = new Semaphore(1, true); // Semaphore
// verhindert,
// dass
// keine
// Strokes
// geloescht
// werden
// waehred
// Recognition
public Editor() {
super();
// Schonmal die Samples in den Recognizer einlesen, da das u.U. Zeit
// dauert
GestureRecognizer.readSamples();
}
@Override
protected void createGraphicalViewer(Composite parent) {
super.createGraphicalViewer(parent);
getGraphicalViewer().getControl().addGestureListener(this);
getGraphicalViewer().getControl().setTouchEnabled(true);
getGraphicalViewer().getControl().addTouchListener(this);
getGraphicalViewer().getControl().addMouseListener(this);
getGraphicalViewer().getControl().addMouseMoveListener(this);
getGraphicalViewer().getControl().addPaintListener(this);
}
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// Touch Events
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
/**
* Gesture Event Gesture Event erkennt die Standardgesten Liefert das Dell
* Touchdisplay nicht Surface lifert GestureEvent
*/
@Override
public void gesture(GestureEvent event) {
gesture = true;
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>GESTE<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
if (!touchDown && !mouseDown) {
if (event.detail == 2) // Geste beginnt
System.out.println("Gesture Start " + event.detail);
if (event.detail == 4)// Geste endet
System.out.println("Gesture End " + event.detail);
}
}
/**
* TouchEvent verarbeitung
*
* @param touches
* [] Alle Tocuhes
* @param currentTouchStroke
* aktueller zu verarbeitender Stroke
* @param currentTouchStrokes
* alle TouchStrokes // Das muss noch mit den Mousstrokes in
* Uebereinstimmung gebracht werden
* @param mouseDown
* keine andere Eingabe // wie gedrueckte Maustaste
* @param gesture
* // wenn Geste augefuehrt wird, keine andere Eingabe
* @param timerOffset
* Zuruecksetzen solange ein Stroke ausgefuehrt wird
*
*/
public void touch(TouchEvent event) {
// Das kommt noch vom Pixelsence bleibt auch erstmal, da es zunaechst
// auch keine parallele Mauseingabe geben soll
if (!mouse && !gesture) {
touch = true;
/*
* Jedes Touchevent bekommt einen Eintrag in touches[] und es wird
* immer durch die Schleife aktualisiert so lange das Event
* ausgeloest wird abgerufen wird es durch die ID timerOffset wird
* solange immer wieder auf 0 gesetzt
*/
Touch touches[] = event.touches;
for (int i = 0; i < touches.length; i++) {
Touch currentTouch = touches[i];
FigureCanvas canvas = (FigureCanvas) getGraphicalControl();
org.eclipse.swt.graphics.Point canvasOrigin = canvas.toDisplay(0, 0);
// Rectangle rect = currentTouch.source.getBounds();
// Touch beginnt, Stroke anlegen Timer wird gestartet
if (currentTouch.state == 1) {
this.currentStroke = new Stroke();
currentStroke.addPoint(new Point(currentTouch.x - canvasOrigin.x, currentTouch.y - canvasOrigin.y));
currentTouchStrokes.put(currentTouch.id, currentStroke);
strokes.add(currentStroke);
timerStart(timerTime);
touchDown = true;
timerOffset = 0;
}
// Touch wird ausgefuehrt
else if (currentTouch.state == 2) {
currentStroke = currentTouchStrokes.get(currentTouch.id);
if (currentStroke != null) {
int temp = strokes.indexOf(currentStroke);
currentStroke.addPoint(new Point(currentTouch.x - canvasOrigin.x, currentTouch.y
- canvasOrigin.y));
strokes.remove(temp);
strokes.add(currentStroke);
touchDown = true;
}
Point min = currentStroke.getMinPoint();
Point max = currentStroke.getMaxPoint();
// System.out.println("min: " + min.X + ", " + min.Y +
// "; max: "
// + max.X + ", " + max.Y);
canvas.redraw((int) min.X, (int) min.Y, (int) (max.X - min.X), (int) (max.Y - min.Y), true);
canvas.update();
}
// Touch endet, dann die Strokeliste abschliessen
else if (currentTouch.state == 4) {
currentStroke = currentTouchStrokes.get(currentTouch.id);
if (currentStroke != null) {
int temp = strokes.indexOf(currentStroke);
currentStroke.addPoint(new Point(currentTouch.x - canvasOrigin.x, currentTouch.y
- canvasOrigin.y));
strokes.remove(temp);
strokes.add(currentStroke);
currentStroke = null;
touchDown = false;
timerOffset = 0;
}
}
}
}
}
/**
* Mouse Down Event Wenn MouseDown wird der Timer gestartet und der erste
* Punkt in currentMouseStroke geschrieben
*
* @param mouseDown
* @param timerOffset
* Wird solange MouseDown immer wieder zurueckgesetzt
* @param currentMouseStroke
* Aktuelle Stroke mit Punkten
*/
@Override
public void mouseDown(MouseEvent event) {
// Erstmal nur eine Eingabemodalitaet
// Damit wird erstmal abgefangen, dass das Surface events etwas
// beliebig auswirft
if (!touch && !gesture) {
// Punkte werden nur gespeichert wenn linke Maustaste gedrueckt wird
if (event.button == 1 && ((event.stateMask & SWT.MODIFIER_MASK) != 0)) {
timerStart(timerTime);
mouseDown = true;
// Timernachlauf wird dann immer wieder zurueckgesetzt
timerOffset = 0;
this.currentMouseStroke = new Stroke();
currentMouseStroke.addPoint(new Point(event.x, event.y));
}
}
}
/**
* MouseUp Event Wenn MausUp dann wird der Aktuelle Stroke nach Strokes
* geschrieben
*
* @param mouseDown
* false
* @param strokes
* Strokes
* @param currentMouseStroke
* @param timerOffset
* wird letztes mal auf 0 gesetzt
*/
@Override
public void mouseUp(MouseEvent event) {
// Erstmal nur eine Eingabemodalitaet
if (!touch && !gesture) {
// dieses Konstrukt ist noetig, damit das Wechselspiel mit dem Timer
// funktioniert
mouseDown = false;
if (currentMouseStroke == null)
return;
if (strokes.isEmpty() || newStroke) {
newStroke = true;
strokes.add(currentMouseStroke);
currentMouseStroke.clearStroke();
currentMouseStroke = null;
FigureCanvas canvas = (FigureCanvas) getGraphicalControl();
canvas.redraw();
canvas.update();
} else {
// letzten Stroke holen und Punkte anhaengen
int indexOfLastStroke = strokes.size() - 1;
strokes.get(indexOfLastStroke).addNewPartOfStroke(currentMouseStroke);
newStroke = true;
currentMouseStroke.clearStroke();
currentMouseStroke = null;
FigureCanvas canvas = (FigureCanvas) getGraphicalControl();
canvas.redraw();
canvas.update();
}
timerOffset = 0;
}
}
/**
* MouseMove Event Solange die Maus bewegt wird und die Maustaste gedrueckt
* ist werden die Punktkoordinaten gesammelt
*
* @param mouseDown
* @param currentMouseStroke
* aktelle Punkte des Strokes
*/
@Override
public void mouseMove(MouseEvent event) {
if (!touch && !gesture) {
// mouseDown ist noetig, da waehrend MouseMove event.button keine
// Info liefert ob button 1 gedrueckt ist
if (mouseDown) {
currentMouseStroke.addPoint(new Point(event.x, event.y));
Point min = currentMouseStroke.getMinPoint();
Point max = currentMouseStroke.getMaxPoint();
// System.out.println("min: " + min.X + ", " + min.Y + "; max: "
// + max.X + ", " + max.Y);
FigureCanvas canvas = (FigureCanvas) getGraphicalControl();
if (canvas != null) {
canvas.redraw((int) min.X, (int) min.Y, (int) (max.X - min.X), (int) (max.Y - min.Y), true);
canvas.update();
}
}
}
}
@Override
public void mouseDoubleClick(MouseEvent event) {
}
/**
* Loescht Strokes aus ArrayList strokes Die Strokes der erkannten Gesten
* werden geloescht
*
* @param basicGesture
*/
private void deleteStrokes(BasicGesture basicGesture) {
Set<Stroke> delStrokes = new HashSet<Stroke>();
delStrokes.addAll(basicGesture.getStrokes());
Iterator<Stroke> iterator = delStrokes.iterator();
while (iterator.hasNext()) {
Stroke stroke = (Stroke) iterator.next();
if (strokes.contains(stroke)) {
strokes.remove(stroke);
findBasicGestures.remove(basicGesture);
}
}
}
/**
* Timer um Intervalweise die Eingabe zu pruefen Startet den Timertask im
* Intervall
*
* @param intervall
* Intervall in ms
* @param timer
* @param timertask
* @see timerAction()
*/
private void timerStart(long intervall)// Intervall in ms
{
if (timer == null) {
timer = new Timer();
timertask = new TimerTask() {
public void run() {
// verarbeitung der Eingaben
inputProcessing();
}
};
timer.schedule(timertask, 0, intervall);
}
}
/**
* Stoppt den Timer Verarbeiten moeglicher noch nicht verarbeiter Eingaben,
* und alles zuruecksetzen
*
* @param timer
* @param strokes
* @param findBasicGestures
* BasicGesture
*/
public void inputStopp() {
if (timer != null) {
// Alle Gesten die noch in strokes enthalten sein koennten
// abarbeiten
if (strokes.size() > 0) {
List<BasicGesture> finishedGestures = preProcessor.process(strokes);
for (int i = 0; i < finishedGestures.size(); i++) {
BasicGesture finishedGesture = finishedGestures.get(i);
// unterscheiden zwischen kontinuierlicher Geste und
// statischer
// if (finishedGesture.isContinous()) {
// Result result =
// recognizer.continousRecognize(finishedGesture);
// doSomethingOther(result);
// }
// statisch
// else
// {
Result result = recognizer.staticRecognize(finishedGesture);
deleteStrokes(finishedGesture);
doSomething(result);
// }
}
}
preProcessor.clear();
recognizer.setProcessingStep(0);
strokes.clear();
timertask.cancel();
timer.cancel();
timertask = null;
timer = null;
touch = false;
mouse = false;
gesture = false;
if (currentStroke != null)
currentStroke.clearStroke();
currentTouchStrokes.clear();
}
}
/**
* Aktionen waerend der Timer laeuft Recognition waehrend Gesten ausgefuehrt
* werden
*
* @param timerOffset
* Timernachlauf
* @param loadSmples
* Eingelesene Samples
* @param mouseDown
*/
public void inputProcessing() {
timerOffset++;
recognizer.setProcessingStep((recognizer.getProcessingStep()) + 1);
/**
* Wenn die Maustaste gedrueckt ist und der Timernachlauf > finishOffset
* wird geprueft ob Geste fertig ist
*/
if ((touchDown == true || mouseDown == true) && timerOffset >= finishOffset) {
// System.out.println("> RECOGNIZE UND FUCHTELN <");
/*
* Nur fuer Mauseingabe Um die Aenderung zu pruefen muss der
* aktuelle Stroke bei der kontinuierlichen Erkennung mitgeprueft
* werden Damit es nicht immer ein neues Objekt ist wegen
* PointsAtTime muss das so umstaendlich sein, d.h der Inhalt muss
* geaendert werden damit die Referenz gleich bleibt
*/
timerOffset = 0;
if (strokes.isEmpty() || newStroke) {
newStroke = false;
if (mouseDown) {
strokes.add(currentMouseStroke);
}
} else {
// letzten Stroke holen und Punkte anhaengen
int indexOfLastStroke = strokes.size() - 1;
if (mouseDown)
strokes.get(indexOfLastStroke).addNewPartOfStroke(currentMouseStroke);
}
try {
recDelSemaphore.acquire();
try {
preProcessor.setTimerOffset(timerOffset);
preProcessor.setFinishOffset(finishOffset);
BasicGesture basicGesture = preProcessor.preProcess(strokes);
// System.out.println("Rec unf fuchteln " +
// basicGesture.size()+" finished "
// +basicGesture.getFinished());
// unterscheiden zwischen statischer Geste und
if (basicGesture.getFinished() && !(basicGesture.isContinous())) {
Result result = recognizer.staticRecognize(basicGesture);
deleteStrokes(result.getGesture());
doSomething(result);
}
// kontinuierliche Geste
// wir nicht mehr ben�tigt
// if ((!(basicGesture.getFinished()) && touchDown) ||
// basicGesture.isContinous()) {
// Result result =
// recognizer.continousRecognize(basicGesture);
// doSomethingOther(result);
// }
} finally {
recDelSemaphore.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
// Thread.currentThread().interrupt();
// break;
}
}
// wenn keine Eingaben mehr kommen stoppen
else if ((touchDown == false || mouseDown == false) && timerOffset >= finishOffset) {
inputStopp();
}
}
/**
* Beispiel fuer die Ergebnisverarbeitung fuer die statischen Ergebnisse
*
* @param result
*/
// Mach was mit dem statischen Ergebnis
private void doSomething(Result result) {
// Schaerfe des Recognizers, die Uebereinstimmung mit dem Pattern in %
double matchingScore = 0.8;
// Sonderfall Tap abfragen
// wird nicht mehr gebraucht
// if (result.getName().contains("tap")) {
// System.out.println(result.getName());
// System.out.println("x: " + result.getFirstPoint().X + " y: " +
// result.getFirstPoint().Y);
// }
// Ansonsten das Recognizerergebnis verarbeiten
// else {
if (result.getRecognitionResult().getScore() == -1) {
// nicht erkannte Gesten werden geloescht
System.out.println(">>> Keine Geste erkannt <<<");
}
if (result.getRecognitionResult().getScore() > matchingScore) {
System.out.println();
System.out.println("Name: " + result.getName());
System.out.println(" Score: " + result.getScore());
System.out.println(" Distance: " + result.getDistance() + " Angle: " + result.getAngle());
System.out.println(" First Point: x " + result.getFirstPoint().X + ", y " + result.getFirstPoint().Y
+ " LastPoint x: " + result.getLastPoint().X + " y: " + result.getLastPoint().Y + " Centre x: "
+ +result.getCentreBox().X + " y: " + result.getCentreBox().Y);
System.out.println();
for (GestureResultListener listener : gestureResultListeners) {
listener.gestureDetected(result);
}
/*
* String[] resultNames =
* result.getResultNamesInOrderOfRecognition(); for (int i = 0; i <
* resultNames.length; i++) { System.out.println("Result Order "
* +i+" Name " +resultNames[i]); }
*/
} else {
System.out.println("<< zu geringer MatchingScore >>");
}
}
// }
/**
* Beispiel fuer die Ergebnisverarbeitung fuer die kontinuierlichen
* Ergebnisse
*
* @param result
*/
// Wird nicht mehr gebraucht
// private void doSomethingOther(Result result) {
// if (!(result.getName() == null)) {
// if (result.getName().contains("drag")) {
// System.out.println(" name: " + result.getName());
// for (int i = 0; i < result.getGesture().getStroke(1).getPoints().size();
// i++)
// System.out.print("-");
//
// System.out.println("");
// }
// }
// }
public void addGestureResultListener(GestureResultListener g) {
gestureResultListeners.add(g);
}
public void removeGestureResultListener(GestureResultListener g) {
gestureResultListeners.remove(g);
}
@Override
public void paintControl(PaintEvent e) {
if (currentMouseStroke != null)
for (Point p : currentMouseStroke.getPoints())
e.gc.fillOval((int) p.X, (int) p.Y, 4, 4);
if (currentStroke != null)
for (Point p : currentStroke.getPoints())
e.gc.fillOval((int) p.X, (int) p.Y, 4, 4);
}
public void addXMLGesture(String xmlGesture) {
if (xmlGesture != null) {
GestureRecognizer.addGesture(xmlGesture);
//System.out.println(xmlGesture);
}
}
public Hashtable<String, Multistroke> getGestures() {
return recognizer.getGestures();
}
}
| IoTUDresden/proteus | bundles/editor/eu.vicci.process.gesture/src/main/java/eu/vicci/process/gesture/Editor.java | 6,866 | // mouseDown ist noetig, da waehrend MouseMove event.button keine | line_comment | nl | package eu.vicci.process.gesture;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Semaphore;
import org.eclipse.draw2d.FigureCanvas;
import org.eclipse.graphiti.ui.editor.DiagramEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.GestureEvent;
import org.eclipse.swt.events.GestureListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.TouchEvent;
import org.eclipse.swt.events.TouchListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Touch;
import eu.vicci.process.gesture.recognizer.ndollar.Multistroke;
public class Editor extends DiagramEditor implements MouseMoveListener, MouseListener, GestureListener, TouchListener,
PaintListener {
static {
DebugStream.activate();
}
/**
* Instanz eines Editor mit Gestenerkennung
*
* @author daniel
* @param mouseDown
* Gedrueckte Maustaste zur Steuerung des Timers
* @param loadSample
* Ob die Samples eingelesen werden
* @param staticRecognizer
* $N-Recognizer
* @param strokes
* Liste der Strokes
* @param currentMouseStroke
* Aktuell ausgefuehrter Mausstroke //Vorlaeufig wird zw. Touch
* u. Mouse unterschieden
* @param smplesDir
* Pfad zum Ordern mit den Pattern fuer den Recognizer // Muss
* angepasst werden//
* @param matchingScore
* Uebereinstimmung die eine Eingabe mit dem Pattern haben muss
* @param currentTouchStroke
* Aktuell ausgefuehrter Touchstroke //Vorlaeufig wird zw. Touch
* u. Mouse unterschieden
* @param timerOffset
* Timernachlauf bis Recognition ausgeloest wird
* @param timerTime
* Aufruf des TimerTask in ms
* @param timer
* Timer
* @param timertask
* Timertask
* @param coverage
* Prozentualer Anteil den ein Stroke innerhalb der durch
* strokeTolerance gesetzten Box um einen Stroke liegen muss
* @param strokeTolerance
*/
// Gedrueckte Maustaste zur Steuerung
private boolean mouseDown = false;
private boolean mouse = false;
// MouseEvent zur steuerung, Maus und Touch sind momentan nicht gleichzeitig
// moeglich
private boolean touchDown = false;
private boolean touch = false;
private boolean gesture = false;
// Var fuer den Recognizer
private PreProcessor preProcessor = new PreProcessor();
// Vektorarray mit Punkten aus points. Die Punkte werden fuer jeden Stroke
// in einen separaten Vektor geschrieben
private List<Stroke> strokes = new ArrayList<Stroke>();
private GestureRecognizer recognizer = new GestureRecognizer();
// Touch Variablen
// fuer die Verarbeitung der einzelnen Touchevents
private Stroke currentStroke = new Stroke();
private Map<Long, Stroke> currentTouchStrokes = new HashMap<Long, Stroke>();
private List<BasicGesture> findBasicGestures = new ArrayList<BasicGesture>();
// Mouse Variablen
// Die Verarbeitung der Events und insbeondere das Stroke aktualisieren
// funktioniert sehr unterschiedlich, daher nicht der gleiche Stroke wie bei
// Touch
private Stroke currentMouseStroke;
// Noetig um das updaten der MausStrokes zu kontrollieren
private boolean newStroke;
// Var fuer den Timer
// fuer den Timernachlauf d * timerOffset = Zeit nach der letzten
// Interaktion
private int timerOffset;
// Aufruf des Timers in ms
private static final int timerTime = 55;
// Timer zur Steuerung des Recognizers
private Timer timer;
public static TimerTask timertask;
// Zeit bis eine Geste als fertig betrachtet wird
private static final int finishOffset = 7;
private List<GestureResultListener> gestureResultListeners = new LinkedList<GestureResultListener>();
private static Semaphore recDelSemaphore = new Semaphore(1, true); // Semaphore
// verhindert,
// dass
// keine
// Strokes
// geloescht
// werden
// waehred
// Recognition
public Editor() {
super();
// Schonmal die Samples in den Recognizer einlesen, da das u.U. Zeit
// dauert
GestureRecognizer.readSamples();
}
@Override
protected void createGraphicalViewer(Composite parent) {
super.createGraphicalViewer(parent);
getGraphicalViewer().getControl().addGestureListener(this);
getGraphicalViewer().getControl().setTouchEnabled(true);
getGraphicalViewer().getControl().addTouchListener(this);
getGraphicalViewer().getControl().addMouseListener(this);
getGraphicalViewer().getControl().addMouseMoveListener(this);
getGraphicalViewer().getControl().addPaintListener(this);
}
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// Touch Events
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
/**
* Gesture Event Gesture Event erkennt die Standardgesten Liefert das Dell
* Touchdisplay nicht Surface lifert GestureEvent
*/
@Override
public void gesture(GestureEvent event) {
gesture = true;
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>GESTE<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
if (!touchDown && !mouseDown) {
if (event.detail == 2) // Geste beginnt
System.out.println("Gesture Start " + event.detail);
if (event.detail == 4)// Geste endet
System.out.println("Gesture End " + event.detail);
}
}
/**
* TouchEvent verarbeitung
*
* @param touches
* [] Alle Tocuhes
* @param currentTouchStroke
* aktueller zu verarbeitender Stroke
* @param currentTouchStrokes
* alle TouchStrokes // Das muss noch mit den Mousstrokes in
* Uebereinstimmung gebracht werden
* @param mouseDown
* keine andere Eingabe // wie gedrueckte Maustaste
* @param gesture
* // wenn Geste augefuehrt wird, keine andere Eingabe
* @param timerOffset
* Zuruecksetzen solange ein Stroke ausgefuehrt wird
*
*/
public void touch(TouchEvent event) {
// Das kommt noch vom Pixelsence bleibt auch erstmal, da es zunaechst
// auch keine parallele Mauseingabe geben soll
if (!mouse && !gesture) {
touch = true;
/*
* Jedes Touchevent bekommt einen Eintrag in touches[] und es wird
* immer durch die Schleife aktualisiert so lange das Event
* ausgeloest wird abgerufen wird es durch die ID timerOffset wird
* solange immer wieder auf 0 gesetzt
*/
Touch touches[] = event.touches;
for (int i = 0; i < touches.length; i++) {
Touch currentTouch = touches[i];
FigureCanvas canvas = (FigureCanvas) getGraphicalControl();
org.eclipse.swt.graphics.Point canvasOrigin = canvas.toDisplay(0, 0);
// Rectangle rect = currentTouch.source.getBounds();
// Touch beginnt, Stroke anlegen Timer wird gestartet
if (currentTouch.state == 1) {
this.currentStroke = new Stroke();
currentStroke.addPoint(new Point(currentTouch.x - canvasOrigin.x, currentTouch.y - canvasOrigin.y));
currentTouchStrokes.put(currentTouch.id, currentStroke);
strokes.add(currentStroke);
timerStart(timerTime);
touchDown = true;
timerOffset = 0;
}
// Touch wird ausgefuehrt
else if (currentTouch.state == 2) {
currentStroke = currentTouchStrokes.get(currentTouch.id);
if (currentStroke != null) {
int temp = strokes.indexOf(currentStroke);
currentStroke.addPoint(new Point(currentTouch.x - canvasOrigin.x, currentTouch.y
- canvasOrigin.y));
strokes.remove(temp);
strokes.add(currentStroke);
touchDown = true;
}
Point min = currentStroke.getMinPoint();
Point max = currentStroke.getMaxPoint();
// System.out.println("min: " + min.X + ", " + min.Y +
// "; max: "
// + max.X + ", " + max.Y);
canvas.redraw((int) min.X, (int) min.Y, (int) (max.X - min.X), (int) (max.Y - min.Y), true);
canvas.update();
}
// Touch endet, dann die Strokeliste abschliessen
else if (currentTouch.state == 4) {
currentStroke = currentTouchStrokes.get(currentTouch.id);
if (currentStroke != null) {
int temp = strokes.indexOf(currentStroke);
currentStroke.addPoint(new Point(currentTouch.x - canvasOrigin.x, currentTouch.y
- canvasOrigin.y));
strokes.remove(temp);
strokes.add(currentStroke);
currentStroke = null;
touchDown = false;
timerOffset = 0;
}
}
}
}
}
/**
* Mouse Down Event Wenn MouseDown wird der Timer gestartet und der erste
* Punkt in currentMouseStroke geschrieben
*
* @param mouseDown
* @param timerOffset
* Wird solange MouseDown immer wieder zurueckgesetzt
* @param currentMouseStroke
* Aktuelle Stroke mit Punkten
*/
@Override
public void mouseDown(MouseEvent event) {
// Erstmal nur eine Eingabemodalitaet
// Damit wird erstmal abgefangen, dass das Surface events etwas
// beliebig auswirft
if (!touch && !gesture) {
// Punkte werden nur gespeichert wenn linke Maustaste gedrueckt wird
if (event.button == 1 && ((event.stateMask & SWT.MODIFIER_MASK) != 0)) {
timerStart(timerTime);
mouseDown = true;
// Timernachlauf wird dann immer wieder zurueckgesetzt
timerOffset = 0;
this.currentMouseStroke = new Stroke();
currentMouseStroke.addPoint(new Point(event.x, event.y));
}
}
}
/**
* MouseUp Event Wenn MausUp dann wird der Aktuelle Stroke nach Strokes
* geschrieben
*
* @param mouseDown
* false
* @param strokes
* Strokes
* @param currentMouseStroke
* @param timerOffset
* wird letztes mal auf 0 gesetzt
*/
@Override
public void mouseUp(MouseEvent event) {
// Erstmal nur eine Eingabemodalitaet
if (!touch && !gesture) {
// dieses Konstrukt ist noetig, damit das Wechselspiel mit dem Timer
// funktioniert
mouseDown = false;
if (currentMouseStroke == null)
return;
if (strokes.isEmpty() || newStroke) {
newStroke = true;
strokes.add(currentMouseStroke);
currentMouseStroke.clearStroke();
currentMouseStroke = null;
FigureCanvas canvas = (FigureCanvas) getGraphicalControl();
canvas.redraw();
canvas.update();
} else {
// letzten Stroke holen und Punkte anhaengen
int indexOfLastStroke = strokes.size() - 1;
strokes.get(indexOfLastStroke).addNewPartOfStroke(currentMouseStroke);
newStroke = true;
currentMouseStroke.clearStroke();
currentMouseStroke = null;
FigureCanvas canvas = (FigureCanvas) getGraphicalControl();
canvas.redraw();
canvas.update();
}
timerOffset = 0;
}
}
/**
* MouseMove Event Solange die Maus bewegt wird und die Maustaste gedrueckt
* ist werden die Punktkoordinaten gesammelt
*
* @param mouseDown
* @param currentMouseStroke
* aktelle Punkte des Strokes
*/
@Override
public void mouseMove(MouseEvent event) {
if (!touch && !gesture) {
// mouseDown ist<SUF>
// Info liefert ob button 1 gedrueckt ist
if (mouseDown) {
currentMouseStroke.addPoint(new Point(event.x, event.y));
Point min = currentMouseStroke.getMinPoint();
Point max = currentMouseStroke.getMaxPoint();
// System.out.println("min: " + min.X + ", " + min.Y + "; max: "
// + max.X + ", " + max.Y);
FigureCanvas canvas = (FigureCanvas) getGraphicalControl();
if (canvas != null) {
canvas.redraw((int) min.X, (int) min.Y, (int) (max.X - min.X), (int) (max.Y - min.Y), true);
canvas.update();
}
}
}
}
@Override
public void mouseDoubleClick(MouseEvent event) {
}
/**
* Loescht Strokes aus ArrayList strokes Die Strokes der erkannten Gesten
* werden geloescht
*
* @param basicGesture
*/
private void deleteStrokes(BasicGesture basicGesture) {
Set<Stroke> delStrokes = new HashSet<Stroke>();
delStrokes.addAll(basicGesture.getStrokes());
Iterator<Stroke> iterator = delStrokes.iterator();
while (iterator.hasNext()) {
Stroke stroke = (Stroke) iterator.next();
if (strokes.contains(stroke)) {
strokes.remove(stroke);
findBasicGestures.remove(basicGesture);
}
}
}
/**
* Timer um Intervalweise die Eingabe zu pruefen Startet den Timertask im
* Intervall
*
* @param intervall
* Intervall in ms
* @param timer
* @param timertask
* @see timerAction()
*/
private void timerStart(long intervall)// Intervall in ms
{
if (timer == null) {
timer = new Timer();
timertask = new TimerTask() {
public void run() {
// verarbeitung der Eingaben
inputProcessing();
}
};
timer.schedule(timertask, 0, intervall);
}
}
/**
* Stoppt den Timer Verarbeiten moeglicher noch nicht verarbeiter Eingaben,
* und alles zuruecksetzen
*
* @param timer
* @param strokes
* @param findBasicGestures
* BasicGesture
*/
public void inputStopp() {
if (timer != null) {
// Alle Gesten die noch in strokes enthalten sein koennten
// abarbeiten
if (strokes.size() > 0) {
List<BasicGesture> finishedGestures = preProcessor.process(strokes);
for (int i = 0; i < finishedGestures.size(); i++) {
BasicGesture finishedGesture = finishedGestures.get(i);
// unterscheiden zwischen kontinuierlicher Geste und
// statischer
// if (finishedGesture.isContinous()) {
// Result result =
// recognizer.continousRecognize(finishedGesture);
// doSomethingOther(result);
// }
// statisch
// else
// {
Result result = recognizer.staticRecognize(finishedGesture);
deleteStrokes(finishedGesture);
doSomething(result);
// }
}
}
preProcessor.clear();
recognizer.setProcessingStep(0);
strokes.clear();
timertask.cancel();
timer.cancel();
timertask = null;
timer = null;
touch = false;
mouse = false;
gesture = false;
if (currentStroke != null)
currentStroke.clearStroke();
currentTouchStrokes.clear();
}
}
/**
* Aktionen waerend der Timer laeuft Recognition waehrend Gesten ausgefuehrt
* werden
*
* @param timerOffset
* Timernachlauf
* @param loadSmples
* Eingelesene Samples
* @param mouseDown
*/
public void inputProcessing() {
timerOffset++;
recognizer.setProcessingStep((recognizer.getProcessingStep()) + 1);
/**
* Wenn die Maustaste gedrueckt ist und der Timernachlauf > finishOffset
* wird geprueft ob Geste fertig ist
*/
if ((touchDown == true || mouseDown == true) && timerOffset >= finishOffset) {
// System.out.println("> RECOGNIZE UND FUCHTELN <");
/*
* Nur fuer Mauseingabe Um die Aenderung zu pruefen muss der
* aktuelle Stroke bei der kontinuierlichen Erkennung mitgeprueft
* werden Damit es nicht immer ein neues Objekt ist wegen
* PointsAtTime muss das so umstaendlich sein, d.h der Inhalt muss
* geaendert werden damit die Referenz gleich bleibt
*/
timerOffset = 0;
if (strokes.isEmpty() || newStroke) {
newStroke = false;
if (mouseDown) {
strokes.add(currentMouseStroke);
}
} else {
// letzten Stroke holen und Punkte anhaengen
int indexOfLastStroke = strokes.size() - 1;
if (mouseDown)
strokes.get(indexOfLastStroke).addNewPartOfStroke(currentMouseStroke);
}
try {
recDelSemaphore.acquire();
try {
preProcessor.setTimerOffset(timerOffset);
preProcessor.setFinishOffset(finishOffset);
BasicGesture basicGesture = preProcessor.preProcess(strokes);
// System.out.println("Rec unf fuchteln " +
// basicGesture.size()+" finished "
// +basicGesture.getFinished());
// unterscheiden zwischen statischer Geste und
if (basicGesture.getFinished() && !(basicGesture.isContinous())) {
Result result = recognizer.staticRecognize(basicGesture);
deleteStrokes(result.getGesture());
doSomething(result);
}
// kontinuierliche Geste
// wir nicht mehr ben�tigt
// if ((!(basicGesture.getFinished()) && touchDown) ||
// basicGesture.isContinous()) {
// Result result =
// recognizer.continousRecognize(basicGesture);
// doSomethingOther(result);
// }
} finally {
recDelSemaphore.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
// Thread.currentThread().interrupt();
// break;
}
}
// wenn keine Eingaben mehr kommen stoppen
else if ((touchDown == false || mouseDown == false) && timerOffset >= finishOffset) {
inputStopp();
}
}
/**
* Beispiel fuer die Ergebnisverarbeitung fuer die statischen Ergebnisse
*
* @param result
*/
// Mach was mit dem statischen Ergebnis
private void doSomething(Result result) {
// Schaerfe des Recognizers, die Uebereinstimmung mit dem Pattern in %
double matchingScore = 0.8;
// Sonderfall Tap abfragen
// wird nicht mehr gebraucht
// if (result.getName().contains("tap")) {
// System.out.println(result.getName());
// System.out.println("x: " + result.getFirstPoint().X + " y: " +
// result.getFirstPoint().Y);
// }
// Ansonsten das Recognizerergebnis verarbeiten
// else {
if (result.getRecognitionResult().getScore() == -1) {
// nicht erkannte Gesten werden geloescht
System.out.println(">>> Keine Geste erkannt <<<");
}
if (result.getRecognitionResult().getScore() > matchingScore) {
System.out.println();
System.out.println("Name: " + result.getName());
System.out.println(" Score: " + result.getScore());
System.out.println(" Distance: " + result.getDistance() + " Angle: " + result.getAngle());
System.out.println(" First Point: x " + result.getFirstPoint().X + ", y " + result.getFirstPoint().Y
+ " LastPoint x: " + result.getLastPoint().X + " y: " + result.getLastPoint().Y + " Centre x: "
+ +result.getCentreBox().X + " y: " + result.getCentreBox().Y);
System.out.println();
for (GestureResultListener listener : gestureResultListeners) {
listener.gestureDetected(result);
}
/*
* String[] resultNames =
* result.getResultNamesInOrderOfRecognition(); for (int i = 0; i <
* resultNames.length; i++) { System.out.println("Result Order "
* +i+" Name " +resultNames[i]); }
*/
} else {
System.out.println("<< zu geringer MatchingScore >>");
}
}
// }
/**
* Beispiel fuer die Ergebnisverarbeitung fuer die kontinuierlichen
* Ergebnisse
*
* @param result
*/
// Wird nicht mehr gebraucht
// private void doSomethingOther(Result result) {
// if (!(result.getName() == null)) {
// if (result.getName().contains("drag")) {
// System.out.println(" name: " + result.getName());
// for (int i = 0; i < result.getGesture().getStroke(1).getPoints().size();
// i++)
// System.out.print("-");
//
// System.out.println("");
// }
// }
// }
public void addGestureResultListener(GestureResultListener g) {
gestureResultListeners.add(g);
}
public void removeGestureResultListener(GestureResultListener g) {
gestureResultListeners.remove(g);
}
@Override
public void paintControl(PaintEvent e) {
if (currentMouseStroke != null)
for (Point p : currentMouseStroke.getPoints())
e.gc.fillOval((int) p.X, (int) p.Y, 4, 4);
if (currentStroke != null)
for (Point p : currentStroke.getPoints())
e.gc.fillOval((int) p.X, (int) p.Y, 4, 4);
}
public void addXMLGesture(String xmlGesture) {
if (xmlGesture != null) {
GestureRecognizer.addGesture(xmlGesture);
//System.out.println(xmlGesture);
}
}
public Hashtable<String, Multistroke> getGestures() {
return recognizer.getGestures();
}
}
|
45078_16 | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import jd.PluginWrapper;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.download.DownloadInterface;
import org.jdownloader.downloader.hds.HDSDownloader;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*
* vrt.be network
* new content handling --> data-video-src
*/
@HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "deredactie.be", "sporza.be" }, urls = { "http://(www\\.)?deredactiedecrypted\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "http://(www\\.)?sporzadecrypted\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|sporza)([^/]+)?/(mediatheek|videozone).+)" }, flags = { 0, 0 })
public class DeredactieBe extends PluginForHost {
public DeredactieBe(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://deredactie.be/";
}
@Override
public void correctDownloadLink(DownloadLink link) {
link.setUrlDownload(link.getDownloadURL().replace("decrypted.be/", ".be/"));
// not sure what this does! -raz
link.setUrlDownload(link.getDownloadURL().replaceAll("/cm/vrtnieuws/mediatheek/[^/]+/[^/]+/[^/]+/([0-9\\.]+)(.+)?", "/permalink/$1"));
link.setUrlDownload(link.getDownloadURL().replaceAll("/cm/vrtnieuws([^/]+)?/mediatheek(\\w+)?/([0-9\\.]+)(.+)?", "/permalink/$3"));
}
@Override
public AvailableStatus requestFileInformation(DownloadLink downloadLink) throws Exception {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(downloadLink.getDownloadURL());
// Link offline
if (br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
HashMap<String, String> mediaValue = new HashMap<String, String>();
for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) {
mediaValue.put(s[0], s[1]);
}
// Nothing to download
if (mediaValue == null || mediaValue.size() == 0) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
finalurl = mediaValue.get("src");
final String filename = mediaValue.get("title");
if (finalurl == null || filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
if (finalurl.contains("youtube")) {
}
String ext = finalurl.substring(finalurl.lastIndexOf("."));
if (ext == null || ext.length() > 5) {
ext = ".mp4";
}
downloadLink.setFinalFileName(Encoding.htmlDecode(filename.trim()).replaceAll("\"", "").replace("/", "-") + ext);
if (finalurl.contains("vod.stream.vrt.be")) {
// <div class="video"
// data-video-id="2138237_1155250086"
// data-video-type="video"
// data-video-src="http://vod.stream.vrt.be/deredactie/_definst_/2014/11/1210141103430708821_Polopoly_16x9_DV25_NGeo.mp4"
// data-video-title="Reyers Laat - 3/11/14"
// data-video-iphone-server="http://vod.stream.vrt.be/deredactie/_definst_"
// data-video-iphone-path="mp4:2014/11/1210141103430708821_Polopoly_16x9_DV25_NGeo.mp4/playlist.m3u8"
// data-video-rtmp-server=""
// data-video-rtmp-path=""
// data-video-sitestat-program="reyers_laat_-_31114_id_1-2138237"
// data-video-sitestat-playlist=""
// data-video-sitestat-site="deredactie-be"
// data-video-sitestat-pubdate="1415048604184"
// data-video-sitestat-cliptype="FULL_EPISODE"
// data-video-sitestat-duration="2564"
// data-video-autoplay="true"
// data-video-whatsonid=""
// data-video-geoblocking="false"
// data-video-prerolls-enabled="false"
// data-video-preroll-category="senieuws"
// data-video-duration="2564000">
try {
// Request
// URL:http://vod.stream.vrt.be/deredactie/_definst_/mp4:2014/11/1210141103430708821_Polopoly_16x9_DV25_NGeo.mp4/manifest.f4m
ajaxGetPage(finalurl + "/manifest.f4m");
final DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final XPath xPath = XPathFactory.newInstance().newXPath();
Document d = parser.parse(new ByteArrayInputStream(ajax.toString().getBytes("UTF-8")));
NodeList mediaUrls = (NodeList) xPath.evaluate("/manifest/media", d, XPathConstants.NODESET);
Node media;
for (int j = 0; j < mediaUrls.getLength(); j++) {
media = mediaUrls.item(j);
// System.out.println(new String(Base64.decode(xPath.evaluate("/manifest/media[" + (j + 1) + "]/metadata", d).trim())));
String temp = getAttByNamedItem(media, "url");
if (temp != null) {
finalurl = finalurl + "/" + temp;
break;
}
}
ptcrl = protocol.HDS;
return AvailableStatus.TRUE;
} catch (Throwable t) {
t.printStackTrace();
}
}
Browser br2 = br.cloneBrowser();
// In case the link redirects to the finallink
br2.setFollowRedirects(true);
URLConnectionAdapter con = null;
try {
con = br2.openGetConnection(finalurl);
if (!con.getContentType().contains("html")) {
downloadLink.setDownloadSize(con.getLongContentLength());
ptcrl = protocol.HTTP;
} else {
br2.followConnection();
finalurl = mediaValue.get("rtmp-server");
finalurl = finalurl != null && mediaValue.get("rtmp-path") != null ? finalurl + "@" + mediaValue.get("rtmp-path") : null;
if (finalurl == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
ptcrl = protocol.RTMP;
}
return AvailableStatus.TRUE;
} finally {
try {
con.disconnect();
} catch (Throwable e) {
}
}
}
private Browser ajax = null;
private String finalurl = null;
private static enum protocol {
HTTP,
RTMP,
HDS;
}
private protocol ptcrl = null;
private void ajaxGetPage(final String url) throws Exception {
ajax = br.cloneBrowser();
ajax.getHeaders().put("Accept", "*/*");
ajax.getPage(url);
}
/**
* lets try and prevent possible NPE from killing the progress.
*
* @author raztoki
* @param n
* @param item
* @return
*/
private String getAttByNamedItem(final Node n, final String item) {
final String t = n.getAttributes().getNamedItem(item).getTextContent();
return (t != null ? t.trim() : null);
}
@Override
public void handleFree(DownloadLink downloadLink) throws Exception {
requestFileInformation(downloadLink);
if (protocol.HDS.equals(ptcrl)) {
dl = new HDSDownloader(downloadLink, br, finalurl);
dl.startDownload();
return;
} else if (protocol.RTMP.equals(ptcrl)) {
dl = new RTMPDownload(this, downloadLink, finalurl);
setupRTMPConnection(dl);
((RTMPDownload) dl).startDownload();
} else {
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, finalurl, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
}
}
private void setupRTMPConnection(final DownloadInterface dl) {
final jd.network.rtmp.url.RtmpUrlConnection rtmp = ((RTMPDownload) dl).getRtmpConnection();
rtmp.setPlayPath(finalurl.split("@")[1]);
rtmp.setUrl(finalurl.split("@")[0]);
rtmp.setSwfVfy("http://www.deredactie.be/html/flash/common/player.5.10.swf");
rtmp.setResume(true);
rtmp.setRealTime();
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void reset() {
}
@Override
public void resetPluginGlobals() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
}
} | Irbidan/jdownloader | src/jd/plugins/hoster/DeredactieBe.java | 3,246 | // data-video-title="Reyers Laat - 3/11/14"
| line_comment | nl | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import jd.PluginWrapper;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.download.DownloadInterface;
import org.jdownloader.downloader.hds.HDSDownloader;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*
* vrt.be network
* new content handling --> data-video-src
*/
@HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "deredactie.be", "sporza.be" }, urls = { "http://(www\\.)?deredactiedecrypted\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "http://(www\\.)?sporzadecrypted\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|sporza)([^/]+)?/(mediatheek|videozone).+)" }, flags = { 0, 0 })
public class DeredactieBe extends PluginForHost {
public DeredactieBe(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://deredactie.be/";
}
@Override
public void correctDownloadLink(DownloadLink link) {
link.setUrlDownload(link.getDownloadURL().replace("decrypted.be/", ".be/"));
// not sure what this does! -raz
link.setUrlDownload(link.getDownloadURL().replaceAll("/cm/vrtnieuws/mediatheek/[^/]+/[^/]+/[^/]+/([0-9\\.]+)(.+)?", "/permalink/$1"));
link.setUrlDownload(link.getDownloadURL().replaceAll("/cm/vrtnieuws([^/]+)?/mediatheek(\\w+)?/([0-9\\.]+)(.+)?", "/permalink/$3"));
}
@Override
public AvailableStatus requestFileInformation(DownloadLink downloadLink) throws Exception {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(downloadLink.getDownloadURL());
// Link offline
if (br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
HashMap<String, String> mediaValue = new HashMap<String, String>();
for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) {
mediaValue.put(s[0], s[1]);
}
// Nothing to download
if (mediaValue == null || mediaValue.size() == 0) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
finalurl = mediaValue.get("src");
final String filename = mediaValue.get("title");
if (finalurl == null || filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
if (finalurl.contains("youtube")) {
}
String ext = finalurl.substring(finalurl.lastIndexOf("."));
if (ext == null || ext.length() > 5) {
ext = ".mp4";
}
downloadLink.setFinalFileName(Encoding.htmlDecode(filename.trim()).replaceAll("\"", "").replace("/", "-") + ext);
if (finalurl.contains("vod.stream.vrt.be")) {
// <div class="video"
// data-video-id="2138237_1155250086"
// data-video-type="video"
// data-video-src="http://vod.stream.vrt.be/deredactie/_definst_/2014/11/1210141103430708821_Polopoly_16x9_DV25_NGeo.mp4"
// data-video-title="Reyers Laat<SUF>
// data-video-iphone-server="http://vod.stream.vrt.be/deredactie/_definst_"
// data-video-iphone-path="mp4:2014/11/1210141103430708821_Polopoly_16x9_DV25_NGeo.mp4/playlist.m3u8"
// data-video-rtmp-server=""
// data-video-rtmp-path=""
// data-video-sitestat-program="reyers_laat_-_31114_id_1-2138237"
// data-video-sitestat-playlist=""
// data-video-sitestat-site="deredactie-be"
// data-video-sitestat-pubdate="1415048604184"
// data-video-sitestat-cliptype="FULL_EPISODE"
// data-video-sitestat-duration="2564"
// data-video-autoplay="true"
// data-video-whatsonid=""
// data-video-geoblocking="false"
// data-video-prerolls-enabled="false"
// data-video-preroll-category="senieuws"
// data-video-duration="2564000">
try {
// Request
// URL:http://vod.stream.vrt.be/deredactie/_definst_/mp4:2014/11/1210141103430708821_Polopoly_16x9_DV25_NGeo.mp4/manifest.f4m
ajaxGetPage(finalurl + "/manifest.f4m");
final DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final XPath xPath = XPathFactory.newInstance().newXPath();
Document d = parser.parse(new ByteArrayInputStream(ajax.toString().getBytes("UTF-8")));
NodeList mediaUrls = (NodeList) xPath.evaluate("/manifest/media", d, XPathConstants.NODESET);
Node media;
for (int j = 0; j < mediaUrls.getLength(); j++) {
media = mediaUrls.item(j);
// System.out.println(new String(Base64.decode(xPath.evaluate("/manifest/media[" + (j + 1) + "]/metadata", d).trim())));
String temp = getAttByNamedItem(media, "url");
if (temp != null) {
finalurl = finalurl + "/" + temp;
break;
}
}
ptcrl = protocol.HDS;
return AvailableStatus.TRUE;
} catch (Throwable t) {
t.printStackTrace();
}
}
Browser br2 = br.cloneBrowser();
// In case the link redirects to the finallink
br2.setFollowRedirects(true);
URLConnectionAdapter con = null;
try {
con = br2.openGetConnection(finalurl);
if (!con.getContentType().contains("html")) {
downloadLink.setDownloadSize(con.getLongContentLength());
ptcrl = protocol.HTTP;
} else {
br2.followConnection();
finalurl = mediaValue.get("rtmp-server");
finalurl = finalurl != null && mediaValue.get("rtmp-path") != null ? finalurl + "@" + mediaValue.get("rtmp-path") : null;
if (finalurl == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
ptcrl = protocol.RTMP;
}
return AvailableStatus.TRUE;
} finally {
try {
con.disconnect();
} catch (Throwable e) {
}
}
}
private Browser ajax = null;
private String finalurl = null;
private static enum protocol {
HTTP,
RTMP,
HDS;
}
private protocol ptcrl = null;
private void ajaxGetPage(final String url) throws Exception {
ajax = br.cloneBrowser();
ajax.getHeaders().put("Accept", "*/*");
ajax.getPage(url);
}
/**
* lets try and prevent possible NPE from killing the progress.
*
* @author raztoki
* @param n
* @param item
* @return
*/
private String getAttByNamedItem(final Node n, final String item) {
final String t = n.getAttributes().getNamedItem(item).getTextContent();
return (t != null ? t.trim() : null);
}
@Override
public void handleFree(DownloadLink downloadLink) throws Exception {
requestFileInformation(downloadLink);
if (protocol.HDS.equals(ptcrl)) {
dl = new HDSDownloader(downloadLink, br, finalurl);
dl.startDownload();
return;
} else if (protocol.RTMP.equals(ptcrl)) {
dl = new RTMPDownload(this, downloadLink, finalurl);
setupRTMPConnection(dl);
((RTMPDownload) dl).startDownload();
} else {
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, finalurl, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
}
}
private void setupRTMPConnection(final DownloadInterface dl) {
final jd.network.rtmp.url.RtmpUrlConnection rtmp = ((RTMPDownload) dl).getRtmpConnection();
rtmp.setPlayPath(finalurl.split("@")[1]);
rtmp.setUrl(finalurl.split("@")[0]);
rtmp.setSwfVfy("http://www.deredactie.be/html/flash/common/player.5.10.swf");
rtmp.setResume(true);
rtmp.setRealTime();
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void reset() {
}
@Override
public void resetPluginGlobals() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
}
} |
10957_1 | package nl.novi.kapsalon.controllers;
import nl.novi.kapsalon.dtos.AuthDto;
import nl.novi.kapsalon.services.JwtService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AuthController {
private final AuthenticationManager authManager;
private final JwtService jwtService;
public AuthController(AuthenticationManager man, JwtService service) {
this.authManager = man;
this.jwtService = service;
}
@PostMapping("/auth")
public ResponseEntity<Object> signIn(@RequestBody AuthDto authDto) {
UsernamePasswordAuthenticationToken up =
new UsernamePasswordAuthenticationToken(authDto.username, authDto.password);
try {
Authentication auth = authManager.authenticate(up);
UserDetails ud = (UserDetails) auth.getPrincipal();
// Hier wordt de token gegenereerd op het moment dat iemand inlogt
String token = jwtService.generateToken(ud);
return ResponseEntity.ok()
// Token wordt teruggegeven. Stateless, dus bij elk request wordt de token meegestuurd en gecheckt
.header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
.body("Token generated");
}
catch (AuthenticationException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.UNAUTHORIZED);
}
}
}
| Irene-Jurna/novi-backend-eindopdracht | src/main/java/nl/novi/kapsalon/controllers/AuthController.java | 522 | // Token wordt teruggegeven. Stateless, dus bij elk request wordt de token meegestuurd en gecheckt | line_comment | nl | package nl.novi.kapsalon.controllers;
import nl.novi.kapsalon.dtos.AuthDto;
import nl.novi.kapsalon.services.JwtService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AuthController {
private final AuthenticationManager authManager;
private final JwtService jwtService;
public AuthController(AuthenticationManager man, JwtService service) {
this.authManager = man;
this.jwtService = service;
}
@PostMapping("/auth")
public ResponseEntity<Object> signIn(@RequestBody AuthDto authDto) {
UsernamePasswordAuthenticationToken up =
new UsernamePasswordAuthenticationToken(authDto.username, authDto.password);
try {
Authentication auth = authManager.authenticate(up);
UserDetails ud = (UserDetails) auth.getPrincipal();
// Hier wordt de token gegenereerd op het moment dat iemand inlogt
String token = jwtService.generateToken(ud);
return ResponseEntity.ok()
// Token wordt<SUF>
.header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
.body("Token generated");
}
catch (AuthenticationException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.UNAUTHORIZED);
}
}
}
|
145596_6 | /**
*
*/
package releve;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.util.Hashtable;
import java.util.List;
import org.apache.log4j.Logger;
import database.Unite_releves;
import utils.ComposantAlisma;
import utils.ComposantMeso;
/**
* @author quinton
*
* Second onglet
*/
public class Releve_tab2 extends ComposantAlisma {
int nbUR = 2;
boolean releve2Visible = true;
Object obj;
Unite_releves ur;
General[] general = new General[2];
Facies[] facies = new Facies[2];
Profondeur[] profondeur = new Profondeur[2];
Eclairement[] eclairement = new Eclairement[2];
Substrat[] substrat = new Substrat[2];
Vitesse[] vitesse = new Vitesse[2];
Dimension dimLabel = new Dimension(320, 20), dimDefault = new Dimension(120, 20);
int[] idUR = { -1, -1 };
static Logger logger = Logger.getLogger(Releve_tab2.class);
public Releve_tab2(int pnbUR, Unite_releves fur) {
super();
obj = this;
nbUR = pnbUR;
ur = fur;
/*
* Initialisations
*/
/*
* Boite d'affichage de l'UR
*/
ComposantAlisma urBox = new ComposantAlisma();
urBox.addLabel("libelleVide", 0, 0, dimLabel);
urBox.addLabel("ur1", 1, 0, dimDefault, GridBagConstraints.CENTER);
if (nbUR == 2)
urBox.addLabel("ur2", 2, 0, dimDefault, GridBagConstraints.CENTER);
/*
* Boite General
*/
ComposantAlisma generalBox = new ComposantAlisma();
ComposantAlisma generalLabel = new ComposantAlisma();
generalBox.setTitle("caracGen");
generalLabel.addLabel("pc_rec", 0, 0, dimLabel);
generalLabel.addLabel("typeUR", 0, 1, dimLabel);
generalLabel.addLabel("longueurUR", 0, 2, dimLabel);
generalLabel.addLabel("largeurUR", 0, 3, dimLabel);
generalLabel.addLabel("faciesDominant", 0, 4, dimLabel);
gbc.gridx = 0;
gbc.gridy = 0;
generalBox.addComposant(generalLabel, 0, 0);
for (int i = 0; i < nbUR; i++) {
general[i] = new General();
/*
* Definition par defaut des valeurs de type d'ur
*/
general[i].setTypeURList(i, null);
generalBox.addComposant(general[i], i + 1, 0);
}
/*
* Forcage de la valeur de recouvrement de l'ur1 a 100 dans le cas d'un
* ur unique
*/
if (nbUR == 1)
general[0].setValue("pc_ur", "100");
/*
* Boite legende
*/
ComposantAlisma legende = new ComposantAlisma();
legende.addLabel("echelleMeso", 0, 0, null);
/*
* Boite Facies
*/
ComposantAlisma faciesBox = new ComposantAlisma();
ComposantAlisma faciesLabel = new ComposantAlisma();
faciesBox.setTitle("typeFacies");
faciesLabel.setDimensionDefault(dimLabel);
faciesLabel.addLabelList(new String[] { "ch_lentique", "pl_lentique","mouille","fosse_dissipation",
"ch_lotique","radier","cascade","pl_courant","rapide",
"autreType", "autreTypeClass" }, 0, 0);
gbc.gridx = 0;
faciesBox.addComposant(faciesLabel, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
for (int i = 0; i < nbUR; i++) {
facies[i] = new Facies();
faciesBox.addComposant(facies[i], i + 1, 0);
}
/*
* Boite profondeur
*/
ComposantAlisma profondeurBox = new ComposantAlisma(), profondeurLabel = new ComposantAlisma();
profondeurBox.setTitle("profon");
profondeurLabel.setDimensionDefault(dimLabel);
profondeurLabel.addLabelList(new String[] { "p1", "p2", "p3", "p4", "p5" }, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
profondeurBox.addComposant(profondeurLabel, gbc);
for (int i = 0; i < nbUR; i++) {
profondeur[i] = new Profondeur();
profondeurBox.addComposant(profondeur[i], i + 1, 0);
}
/*
* Boite vitesse
*/
ComposantAlisma vitesseBox = new ComposantAlisma(), vitesseLabel = new ComposantAlisma();
vitesseBox.setTitle("vitess");
vitesseLabel.setDimensionDefault(dimLabel);
vitesseLabel.addLabelList(new String[] { "v1", "v2", "v3", "v4", "v5" }, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
vitesseBox.addComposant(vitesseLabel, gbc);
for (int i = 0; i < nbUR; i++) {
vitesse[i] = new Vitesse();
vitesseBox.addComposant(vitesse[i], i + 1, 0);
}
/*
* Boite eclairement
*/
ComposantAlisma eclairementBox = new ComposantAlisma(), eclairementLabel = new ComposantAlisma();
eclairementBox.setTitle("eclair");
eclairementLabel.setDimensionDefault(dimLabel);
eclairementLabel.addLabelList(new String[] { "tresOmbr", "ombr", "peuOmbr", "eclaire", "tresEcl" }, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
eclairementBox.addComposant(eclairementLabel, gbc);
for (int i = 0; i < nbUR; i++) {
eclairement[i] = new Eclairement();
eclairementBox.addComposant(eclairement[i], i + 1, 0);
}
/*
* Boite substrat
*/
ComposantAlisma substratBox = new ComposantAlisma(), substratLabel = new ComposantAlisma();
substratBox.setTitle("typeSubs");
substratLabel.setDimensionDefault(dimLabel);
substratLabel.addLabelList(
new String[] { "vase", "cailloux", "sables", "terre", "blocs", "racines", "debris", "artif" }, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
substratBox.addComposant(substratLabel, gbc);
for (int i = 0; i < nbUR; i++) {
substrat[i] = new Substrat();
substratBox.addComposant(substrat[i], i + 1, 0);
}
/*
* Ajout de toutes les boites au tab
*/
this.addComposant(urBox);
this.addComposant(generalBox);
this.addComposant(legende);
this.addComposant(faciesBox);
this.addComposant(profondeurBox);
this.addComposant(vitesseBox);
this.addComposant(eclairementBox);
this.addComposant(substratBox);
}
public void setUniteReleve(Unite_releves iur) {
ur = iur;
}
public int validation() {
int retour = super.validation();
/*
* Verification que le total de la part de l'UR fait 100 %
*/
String part1, part2;
int level1 = 0, level2 = 0, level = 0;
part1 = general[0].getData("pc_ur");
if (part1.isEmpty())
level1 = 3;
if (1 == nbUR) {
try {
if (!part1.equals("100"))
level1 = 3;
} catch (NullPointerException e) {
level1 = 3;
}
} else {
part2 = general[1].getData("pc_ur");
if (part2.isEmpty()) {
level2 = 3;
} else {
if (level1 == 0) {
Double total = Double.parseDouble(part1) + Double.parseDouble(part2);
if (total != 100) {
level1 = 3;
level2 = 3;
}
}
}
general[1].setBordure("pc_ur", level2);
}
general[0].setBordure("pc_ur", level1);
if (level1 > level)
level = level1;
if (level2 > level)
level = level2;
if (level > retour)
retour = level;
return retour;
}
/**
* Remet a jour la combo en fonction du protocole
*
* @param protocole
*/
public void setTypeURList(String lProtocole) {
for (int i = 0; i < nbUR; i++) {
general[i].setTypeURList(i, lProtocole);
}
}
/**
* Classes d'affichage des composants
*/
/**
* Donnees generales
*
* @author quinton
*
*/
class General extends ComposantAlisma {
public General() {
setDimensionDefault(dimDefault);
addTextPourcentage("pc_ur", 0, 0, 1);
addCombo("type_ur", 0, 1, 1, false, new Dimension (200,20));
addTextNumeric("longueur_ur", 0, 2, 1);
addTextDecimal("largeur_ur", 0, 3, 1);
addCombo("facies", 0, 4, 1, false);
addComboItemList("facies", ur.params.get("facies").getArray(), false);
setFieldMandatory(new String[] { "type_ur", "pc_ur" });
setFieldNecessary(new String[] {});
setFieldRecommanded(new String[] { "longueur_ur", "largeur_ur", "facies" });
}
/**
* Positionne le contenu du combo typeUR en fonction du numero d'UR et
* du protocole
*
* @param num_ur
* @param protocole
*/
public void setTypeURList(int i, String protocole) {
logger.debug("setTypeURList : i = " + String.valueOf(i) + ", protocole = " + protocole);
int protocole_id;
try {
protocole_id = ur.params.get("protocole").getKeyFromValue(protocole);
} catch (NullPointerException e) {
protocole_id = 1;
}
logger.debug("protocole_id :" + String.valueOf(protocole_id));
int num_ur = i + 1;
logger.debug("num_ur : " + String.valueOf(num_ur));
String[] liste = ur.params.get("type_ur").getArray();
if (nbUR == 1) {
addComboItemList("type_ur", new String[] { liste[4], liste[3] }, true);
} else {
switch (protocole_id) {
case 1:
if (num_ur == 1) {
addComboItemList("type_ur", new String[] { liste[1] }, true);
} else
addComboItemList("type_ur", new String[] { liste[2] }, true);
break;
case 2:
if (num_ur == 1) {
addComboItemList("type_ur",
new String[] { liste[5], liste[7], liste[3] }, true);
} else
addComboItemList("type_ur", new String[] { liste[6], liste[8], liste[3] }, true);
break;
case 3:
if (num_ur == 1) {
addComboItemList("type_ur",
new String[] { liste[1], liste[5], liste[7], liste[3] }, true);
} else
addComboItemList("type_ur", new String[] { liste[2], liste[6], liste[8], liste[3] }, true);
break;
}
}
}
}
/**
* Saisie des facies
*
* @author quinton
*
*/
class Facies extends ComposantMeso {
public Facies() {
setDimensionDefault(dimDefault);
addComboMesoList(new String[] { "ch_lentique", "pl_lentique","mouille","fosse_dissipation",
"ch_lotique","radier","waterfall","pl_courant","rapide"
/*,"autreType"*/
});
/*
* Rajout du champ autreType
*/
addCombo("facies_autre_type", 0, 9, 1, false);
addComboItemList("facies_autre_type", ur.params.get("facies_autre_type").getArray(), false);
// addFieldRecommanded("autreType");
addComboMeso("autretypeclass", 0, 10, 1);
}
public int validation() {
int retour = super.validation();
// logger.debug("Facies - valeur retour : " + String.valueOf(retour));
// if (retour == 2)
// retour = 1;
/*
* Rajout du controle autre type : si libelle saisi, la classe doit
* etre renseignee
*/
String autreType = getData("facies_autre_type");
String autretypeclass = getData("autretypeclass");
// logger.debug("facies - autreType - empty ? " + String.valueOf(autreType.isEmpty()));
// logger.debug("facies - autretypeclass - empty ? " + String.valueOf(autretypeclass.isEmpty()));
if (!autreType.isEmpty()) {
if (autretypeclass.isEmpty()) {
setBordure("autretypeclass", 3);
retour = 3;
} else {
setBordure("autretypeclass", 0);
}
setBordure("facies_autre_type", 0);
} else {
if (!autretypeclass.isEmpty()) {
setBordure("facies_autre_type", 3);
retour = 3;
} else {
setBordure("facies_autre_type", 0);
}
setBordure("autretypeclass", 0);
}
// logger.debug("facies - valeur retour en fin de validation : " + String.valueOf(retour));
this.bordure.setBordure(pane, retour);
return retour;
}
}
class Profondeur extends ComposantMeso {
public Profondeur() {
setDimensionDefault(dimDefault);
addComboMesoList(new String[] { "p1", "p2", "p3", "p4", "p5" });
}
}
class Vitesse extends ComposantMeso {
public Vitesse() {
setDimensionDefault(dimDefault);
addComboMesoList(new String[] { "v1", "v2", "v3", "v4", "v5" });
}
}
class Eclairement extends ComposantMeso {
public Eclairement() {
setDimensionDefault(dimDefault);
addComboMesoList(new String[] { "tres_ombrage", "ombrage", "peu_ombrage", "eclaire", "tres_eclaire" });
}
}
class Substrat extends ComposantMeso {
public Substrat() {
setDimensionDefault(dimDefault);
addComboMesoList(new String[] { "vase_limons", "cailloux_pierres", "sable_graviers", "terre_marne_tourbe",
"blocs_dalles", "racines", "debris_org", "artificiel" });
}
}
/**
* Recupere le taux d'occupation de l'UR dans la station
*
* @param num_ur
* @return double
*/
public double getpcUR(int num_ur) {
double taux;
String sValue = general[num_ur - 1].getData("pc_ur");
if (sValue.isEmpty()) {
taux = 0.0;
} else {
taux = Double.parseDouble(sValue) / 100;
}
return taux;
}
/**
* Retourne les donnees de l'onglet pour l'ur consideree
*
* @param num_ur
* @return Hashtable<String, String>
*/
public Hashtable<String, String> getDataUR(int num_ur) {
int i = num_ur - 1;
Hashtable<String, String> data = eclairement[i].getData();
data = hashtableFusionner(data, facies[i].getData());
data = hashtableFusionner(data, general[i].getData());
data = hashtableFusionner(data, profondeur[i].getData());
data = hashtableFusionner(data, substrat[i].getData());
data = hashtableFusionner(data, vitesse[i].getData());
data.put("num_ur", Integer.toString(num_ur));
return data;
}
/**
* Mise a jour de l'ensemble des donnees de l'onglet
*
* @param List
* <Hashtable<String, String>> lData : liste des donnees
*/
public void setDataGlobal(List<Hashtable<String, String>> lData) {
int num_ur, i;
for (Hashtable<String, String> ligne : lData) {
num_ur = Integer.parseInt(ligne.get("num_ur"));
/*
* mise a jour de la valeur de la cle
*/
setIdUR(num_ur, Integer.parseInt(ligne.get("id_ur")));
i = num_ur - 1;
/*
* Mise a jour des donnees
*/
eclairement[i].setData(ligne);
facies[i].setData(ligne);
general[i].setData(ligne);
profondeur[i].setData(ligne);
substrat[i].setData(ligne);
vitesse[i].setData(ligne);
}
}
/**
* Positionne la valeur de la cle de l'UR
*
* @param num_ur
* @param id
*/
public void setIdUR(int num_ur, int id) {
idUR[num_ur - 1] = id;
}
/**
* Retourne la valeur de la cle de l'UR consideree
*
* @param num_ur
* @return
*/
public int getIdUR(int num_ur) {
return idUR[num_ur - 1];
}
}
| Irstea/alisma | src/releve/Releve_tab2.java | 5,487 | /*
* Boite legende
*/ | block_comment | nl | /**
*
*/
package releve;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.util.Hashtable;
import java.util.List;
import org.apache.log4j.Logger;
import database.Unite_releves;
import utils.ComposantAlisma;
import utils.ComposantMeso;
/**
* @author quinton
*
* Second onglet
*/
public class Releve_tab2 extends ComposantAlisma {
int nbUR = 2;
boolean releve2Visible = true;
Object obj;
Unite_releves ur;
General[] general = new General[2];
Facies[] facies = new Facies[2];
Profondeur[] profondeur = new Profondeur[2];
Eclairement[] eclairement = new Eclairement[2];
Substrat[] substrat = new Substrat[2];
Vitesse[] vitesse = new Vitesse[2];
Dimension dimLabel = new Dimension(320, 20), dimDefault = new Dimension(120, 20);
int[] idUR = { -1, -1 };
static Logger logger = Logger.getLogger(Releve_tab2.class);
public Releve_tab2(int pnbUR, Unite_releves fur) {
super();
obj = this;
nbUR = pnbUR;
ur = fur;
/*
* Initialisations
*/
/*
* Boite d'affichage de l'UR
*/
ComposantAlisma urBox = new ComposantAlisma();
urBox.addLabel("libelleVide", 0, 0, dimLabel);
urBox.addLabel("ur1", 1, 0, dimDefault, GridBagConstraints.CENTER);
if (nbUR == 2)
urBox.addLabel("ur2", 2, 0, dimDefault, GridBagConstraints.CENTER);
/*
* Boite General
*/
ComposantAlisma generalBox = new ComposantAlisma();
ComposantAlisma generalLabel = new ComposantAlisma();
generalBox.setTitle("caracGen");
generalLabel.addLabel("pc_rec", 0, 0, dimLabel);
generalLabel.addLabel("typeUR", 0, 1, dimLabel);
generalLabel.addLabel("longueurUR", 0, 2, dimLabel);
generalLabel.addLabel("largeurUR", 0, 3, dimLabel);
generalLabel.addLabel("faciesDominant", 0, 4, dimLabel);
gbc.gridx = 0;
gbc.gridy = 0;
generalBox.addComposant(generalLabel, 0, 0);
for (int i = 0; i < nbUR; i++) {
general[i] = new General();
/*
* Definition par defaut des valeurs de type d'ur
*/
general[i].setTypeURList(i, null);
generalBox.addComposant(general[i], i + 1, 0);
}
/*
* Forcage de la valeur de recouvrement de l'ur1 a 100 dans le cas d'un
* ur unique
*/
if (nbUR == 1)
general[0].setValue("pc_ur", "100");
/*
* Boite legende
<SUF>*/
ComposantAlisma legende = new ComposantAlisma();
legende.addLabel("echelleMeso", 0, 0, null);
/*
* Boite Facies
*/
ComposantAlisma faciesBox = new ComposantAlisma();
ComposantAlisma faciesLabel = new ComposantAlisma();
faciesBox.setTitle("typeFacies");
faciesLabel.setDimensionDefault(dimLabel);
faciesLabel.addLabelList(new String[] { "ch_lentique", "pl_lentique","mouille","fosse_dissipation",
"ch_lotique","radier","cascade","pl_courant","rapide",
"autreType", "autreTypeClass" }, 0, 0);
gbc.gridx = 0;
faciesBox.addComposant(faciesLabel, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
for (int i = 0; i < nbUR; i++) {
facies[i] = new Facies();
faciesBox.addComposant(facies[i], i + 1, 0);
}
/*
* Boite profondeur
*/
ComposantAlisma profondeurBox = new ComposantAlisma(), profondeurLabel = new ComposantAlisma();
profondeurBox.setTitle("profon");
profondeurLabel.setDimensionDefault(dimLabel);
profondeurLabel.addLabelList(new String[] { "p1", "p2", "p3", "p4", "p5" }, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
profondeurBox.addComposant(profondeurLabel, gbc);
for (int i = 0; i < nbUR; i++) {
profondeur[i] = new Profondeur();
profondeurBox.addComposant(profondeur[i], i + 1, 0);
}
/*
* Boite vitesse
*/
ComposantAlisma vitesseBox = new ComposantAlisma(), vitesseLabel = new ComposantAlisma();
vitesseBox.setTitle("vitess");
vitesseLabel.setDimensionDefault(dimLabel);
vitesseLabel.addLabelList(new String[] { "v1", "v2", "v3", "v4", "v5" }, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
vitesseBox.addComposant(vitesseLabel, gbc);
for (int i = 0; i < nbUR; i++) {
vitesse[i] = new Vitesse();
vitesseBox.addComposant(vitesse[i], i + 1, 0);
}
/*
* Boite eclairement
*/
ComposantAlisma eclairementBox = new ComposantAlisma(), eclairementLabel = new ComposantAlisma();
eclairementBox.setTitle("eclair");
eclairementLabel.setDimensionDefault(dimLabel);
eclairementLabel.addLabelList(new String[] { "tresOmbr", "ombr", "peuOmbr", "eclaire", "tresEcl" }, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
eclairementBox.addComposant(eclairementLabel, gbc);
for (int i = 0; i < nbUR; i++) {
eclairement[i] = new Eclairement();
eclairementBox.addComposant(eclairement[i], i + 1, 0);
}
/*
* Boite substrat
*/
ComposantAlisma substratBox = new ComposantAlisma(), substratLabel = new ComposantAlisma();
substratBox.setTitle("typeSubs");
substratLabel.setDimensionDefault(dimLabel);
substratLabel.addLabelList(
new String[] { "vase", "cailloux", "sables", "terre", "blocs", "racines", "debris", "artif" }, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
substratBox.addComposant(substratLabel, gbc);
for (int i = 0; i < nbUR; i++) {
substrat[i] = new Substrat();
substratBox.addComposant(substrat[i], i + 1, 0);
}
/*
* Ajout de toutes les boites au tab
*/
this.addComposant(urBox);
this.addComposant(generalBox);
this.addComposant(legende);
this.addComposant(faciesBox);
this.addComposant(profondeurBox);
this.addComposant(vitesseBox);
this.addComposant(eclairementBox);
this.addComposant(substratBox);
}
public void setUniteReleve(Unite_releves iur) {
ur = iur;
}
public int validation() {
int retour = super.validation();
/*
* Verification que le total de la part de l'UR fait 100 %
*/
String part1, part2;
int level1 = 0, level2 = 0, level = 0;
part1 = general[0].getData("pc_ur");
if (part1.isEmpty())
level1 = 3;
if (1 == nbUR) {
try {
if (!part1.equals("100"))
level1 = 3;
} catch (NullPointerException e) {
level1 = 3;
}
} else {
part2 = general[1].getData("pc_ur");
if (part2.isEmpty()) {
level2 = 3;
} else {
if (level1 == 0) {
Double total = Double.parseDouble(part1) + Double.parseDouble(part2);
if (total != 100) {
level1 = 3;
level2 = 3;
}
}
}
general[1].setBordure("pc_ur", level2);
}
general[0].setBordure("pc_ur", level1);
if (level1 > level)
level = level1;
if (level2 > level)
level = level2;
if (level > retour)
retour = level;
return retour;
}
/**
* Remet a jour la combo en fonction du protocole
*
* @param protocole
*/
public void setTypeURList(String lProtocole) {
for (int i = 0; i < nbUR; i++) {
general[i].setTypeURList(i, lProtocole);
}
}
/**
* Classes d'affichage des composants
*/
/**
* Donnees generales
*
* @author quinton
*
*/
class General extends ComposantAlisma {
public General() {
setDimensionDefault(dimDefault);
addTextPourcentage("pc_ur", 0, 0, 1);
addCombo("type_ur", 0, 1, 1, false, new Dimension (200,20));
addTextNumeric("longueur_ur", 0, 2, 1);
addTextDecimal("largeur_ur", 0, 3, 1);
addCombo("facies", 0, 4, 1, false);
addComboItemList("facies", ur.params.get("facies").getArray(), false);
setFieldMandatory(new String[] { "type_ur", "pc_ur" });
setFieldNecessary(new String[] {});
setFieldRecommanded(new String[] { "longueur_ur", "largeur_ur", "facies" });
}
/**
* Positionne le contenu du combo typeUR en fonction du numero d'UR et
* du protocole
*
* @param num_ur
* @param protocole
*/
public void setTypeURList(int i, String protocole) {
logger.debug("setTypeURList : i = " + String.valueOf(i) + ", protocole = " + protocole);
int protocole_id;
try {
protocole_id = ur.params.get("protocole").getKeyFromValue(protocole);
} catch (NullPointerException e) {
protocole_id = 1;
}
logger.debug("protocole_id :" + String.valueOf(protocole_id));
int num_ur = i + 1;
logger.debug("num_ur : " + String.valueOf(num_ur));
String[] liste = ur.params.get("type_ur").getArray();
if (nbUR == 1) {
addComboItemList("type_ur", new String[] { liste[4], liste[3] }, true);
} else {
switch (protocole_id) {
case 1:
if (num_ur == 1) {
addComboItemList("type_ur", new String[] { liste[1] }, true);
} else
addComboItemList("type_ur", new String[] { liste[2] }, true);
break;
case 2:
if (num_ur == 1) {
addComboItemList("type_ur",
new String[] { liste[5], liste[7], liste[3] }, true);
} else
addComboItemList("type_ur", new String[] { liste[6], liste[8], liste[3] }, true);
break;
case 3:
if (num_ur == 1) {
addComboItemList("type_ur",
new String[] { liste[1], liste[5], liste[7], liste[3] }, true);
} else
addComboItemList("type_ur", new String[] { liste[2], liste[6], liste[8], liste[3] }, true);
break;
}
}
}
}
/**
* Saisie des facies
*
* @author quinton
*
*/
class Facies extends ComposantMeso {
public Facies() {
setDimensionDefault(dimDefault);
addComboMesoList(new String[] { "ch_lentique", "pl_lentique","mouille","fosse_dissipation",
"ch_lotique","radier","waterfall","pl_courant","rapide"
/*,"autreType"*/
});
/*
* Rajout du champ autreType
*/
addCombo("facies_autre_type", 0, 9, 1, false);
addComboItemList("facies_autre_type", ur.params.get("facies_autre_type").getArray(), false);
// addFieldRecommanded("autreType");
addComboMeso("autretypeclass", 0, 10, 1);
}
public int validation() {
int retour = super.validation();
// logger.debug("Facies - valeur retour : " + String.valueOf(retour));
// if (retour == 2)
// retour = 1;
/*
* Rajout du controle autre type : si libelle saisi, la classe doit
* etre renseignee
*/
String autreType = getData("facies_autre_type");
String autretypeclass = getData("autretypeclass");
// logger.debug("facies - autreType - empty ? " + String.valueOf(autreType.isEmpty()));
// logger.debug("facies - autretypeclass - empty ? " + String.valueOf(autretypeclass.isEmpty()));
if (!autreType.isEmpty()) {
if (autretypeclass.isEmpty()) {
setBordure("autretypeclass", 3);
retour = 3;
} else {
setBordure("autretypeclass", 0);
}
setBordure("facies_autre_type", 0);
} else {
if (!autretypeclass.isEmpty()) {
setBordure("facies_autre_type", 3);
retour = 3;
} else {
setBordure("facies_autre_type", 0);
}
setBordure("autretypeclass", 0);
}
// logger.debug("facies - valeur retour en fin de validation : " + String.valueOf(retour));
this.bordure.setBordure(pane, retour);
return retour;
}
}
class Profondeur extends ComposantMeso {
public Profondeur() {
setDimensionDefault(dimDefault);
addComboMesoList(new String[] { "p1", "p2", "p3", "p4", "p5" });
}
}
class Vitesse extends ComposantMeso {
public Vitesse() {
setDimensionDefault(dimDefault);
addComboMesoList(new String[] { "v1", "v2", "v3", "v4", "v5" });
}
}
class Eclairement extends ComposantMeso {
public Eclairement() {
setDimensionDefault(dimDefault);
addComboMesoList(new String[] { "tres_ombrage", "ombrage", "peu_ombrage", "eclaire", "tres_eclaire" });
}
}
class Substrat extends ComposantMeso {
public Substrat() {
setDimensionDefault(dimDefault);
addComboMesoList(new String[] { "vase_limons", "cailloux_pierres", "sable_graviers", "terre_marne_tourbe",
"blocs_dalles", "racines", "debris_org", "artificiel" });
}
}
/**
* Recupere le taux d'occupation de l'UR dans la station
*
* @param num_ur
* @return double
*/
public double getpcUR(int num_ur) {
double taux;
String sValue = general[num_ur - 1].getData("pc_ur");
if (sValue.isEmpty()) {
taux = 0.0;
} else {
taux = Double.parseDouble(sValue) / 100;
}
return taux;
}
/**
* Retourne les donnees de l'onglet pour l'ur consideree
*
* @param num_ur
* @return Hashtable<String, String>
*/
public Hashtable<String, String> getDataUR(int num_ur) {
int i = num_ur - 1;
Hashtable<String, String> data = eclairement[i].getData();
data = hashtableFusionner(data, facies[i].getData());
data = hashtableFusionner(data, general[i].getData());
data = hashtableFusionner(data, profondeur[i].getData());
data = hashtableFusionner(data, substrat[i].getData());
data = hashtableFusionner(data, vitesse[i].getData());
data.put("num_ur", Integer.toString(num_ur));
return data;
}
/**
* Mise a jour de l'ensemble des donnees de l'onglet
*
* @param List
* <Hashtable<String, String>> lData : liste des donnees
*/
public void setDataGlobal(List<Hashtable<String, String>> lData) {
int num_ur, i;
for (Hashtable<String, String> ligne : lData) {
num_ur = Integer.parseInt(ligne.get("num_ur"));
/*
* mise a jour de la valeur de la cle
*/
setIdUR(num_ur, Integer.parseInt(ligne.get("id_ur")));
i = num_ur - 1;
/*
* Mise a jour des donnees
*/
eclairement[i].setData(ligne);
facies[i].setData(ligne);
general[i].setData(ligne);
profondeur[i].setData(ligne);
substrat[i].setData(ligne);
vitesse[i].setData(ligne);
}
}
/**
* Positionne la valeur de la cle de l'UR
*
* @param num_ur
* @param id
*/
public void setIdUR(int num_ur, int id) {
idUR[num_ur - 1] = id;
}
/**
* Retourne la valeur de la cle de l'UR consideree
*
* @param num_ur
* @return
*/
public int getIdUR(int num_ur) {
return idUR[num_ur - 1];
}
}
|
24453_2 | package edu.ap.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import edu.ap.spring.controller.RedisController;
import edu.ap.spring.redis.RedisService;
@SpringBootApplication
public class RedisApplication {
private String CHANNEL = "edu:ap:redis";
@Autowired
private RedisService service;
//Subscript op channel
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new ChannelTopic(CHANNEL));
return container;
}
//Deze luistert op channel en wanneer er een message komt stuur die deze onMessage functie van Controller
@Bean
MessageListenerAdapter listenerAdapter(RedisController controller) {
return new MessageListenerAdapter(controller, "onMessage");
}
//Deze gaat de database leeg maken en een message daarin toevoegen
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return (args) -> {
// empty db
this.service.flushDb();
// messaging
service.sendMessage(CHANNEL, "Hello from Spring Boot");
};
}
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
| IsmatFaizi/studeren-examen | Spring-Redis/src/main/java/edu/ap/spring/RedisApplication.java | 524 | //Deze gaat de database leeg maken en een message daarin toevoegen | line_comment | nl | package edu.ap.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import edu.ap.spring.controller.RedisController;
import edu.ap.spring.redis.RedisService;
@SpringBootApplication
public class RedisApplication {
private String CHANNEL = "edu:ap:redis";
@Autowired
private RedisService service;
//Subscript op channel
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new ChannelTopic(CHANNEL));
return container;
}
//Deze luistert op channel en wanneer er een message komt stuur die deze onMessage functie van Controller
@Bean
MessageListenerAdapter listenerAdapter(RedisController controller) {
return new MessageListenerAdapter(controller, "onMessage");
}
//Deze gaat<SUF>
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return (args) -> {
// empty db
this.service.flushDb();
// messaging
service.sendMessage(CHANNEL, "Hello from Spring Boot");
};
}
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
|
200299_32 | /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.novelanheatpump;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
/**
* Represents all valid commands which could be processed by this binding
*
* @author Jan-Philipp Bolle
* @since 1.0.0
*/
public enum HeatpumpCommandType {
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE {
{
command = "temperature_outside";
itemClass = NumberItem.class;
}
},
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE_AVG {
{
command = "temperature_outside_avg";
itemClass = NumberItem.class;
}
},
//in german Rücklauf
TYPE_TEMPERATURE_RETURN {
{
command = "temperature_return";
itemClass = NumberItem.class;
}
},
//in german Rücklauf Soll
TYPE_TEMPERATURE_REFERENCE_RETURN {
{
command = "temperature_reference_return";
itemClass = NumberItem.class;
}
},
//in german Vorlauf
TYPE_TEMPERATURE_SUPPLAY {
{
command = "temperature_supplay";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Soll
TYPE_TEMPERATURE_SERVICEWATER_REFERENCE {
{
command = "temperature_servicewater_reference";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Ist
TYPE_TEMPERATURE_SERVICEWATER {
{
command = "temperature_servicewater";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_STATE {
{
command = "state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_EXTENDED_STATE {
{
command = "extended_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SOLAR_COLLECTOR {
{
command = "temperature_solar_collector";
itemClass = NumberItem.class;
}
},
// in german Temperatur Heissgas
TYPE_TEMPERATURE_HOT_GAS {
{
command = "temperature_hot_gas";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Eingang
TYPE_TEMPERATURE_PROBE_IN {
{
command = "temperature_probe_in";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Ausgang
TYPE_TEMPERATURE_PROBE_OUT {
{
command = "temperature_probe_out";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK1 {
{
command = "temperature_mk1";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK1_REFERENCE {
{
command = "temperature_mk1_reference";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK2 {
{
command = "temperature_mk2";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK2_REFERENCE {
{
command = "temperature_mk2_reference";
itemClass = NumberItem.class;
}
},
// in german Temperatur externe Energiequelle
TYPE_TEMPERATURE_EXTERNAL_SOURCE {
{
command = "temperature_external_source";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter1
TYPE_HOURS_COMPRESSOR1 {
{
command = "hours_compressor1";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 1
TYPE_STARTS_COMPRESSOR1 {
{
command = "starts_compressor1";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter2
TYPE_HOURS_COMPRESSOR2 {
{
command = "hours_compressor2";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 2
TYPE_STARTS_COMPRESSOR2 {
{
command = "starts_compressor2";
itemClass = NumberItem.class;
}
},
// Temperatur_TRL_ext
TYPE_TEMPERATURE_OUT_EXTERNAL {
{
command = "temperature_out_external";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE1 {
{
command = "hours_zwe1";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE2 {
{
command = "hours_zwe2";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE3 {
{
command = "hours_zwe3";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Wärmepumpe
TYPE_HOURS_HETPUMP {
{
command = "hours_heatpump";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Heizung
TYPE_HOURS_HEATING {
{
command = "hours_heating";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_WARMWATER {
{
command = "hours_warmwater";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_COOLING {
{
command = "hours_cooling";
itemClass = StringItem.class;
}
},
// in german Waermemenge Heizung
TYPE_THERMALENERGY_HEATING {
{
command = "thermalenergy_heating";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Brauchwasser
TYPE_THERMALENERGY_WARMWATER {
{
command = "thermalenergy_warmwater";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Schwimmbad
TYPE_THERMALENERGY_POOL {
{
command = "thermalenergy_pool";
itemClass = NumberItem.class;
}
},
// in german Waermemenge gesamt seit Reset
TYPE_THERMALENERGY_TOTAL {
{
command = "thermalenergy_total";
itemClass = NumberItem.class;
}
},
// in german Massentrom
TYPE_MASSFLOW {
{
command = "massflow";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SOLAR_STORAGE {
{
command = "temperature_solar_storage";
itemClass = NumberItem.class;
}
},
//in german Heizung Betriebsart
TYPE_HEATING_OPERATION_MODE {
{
command = "heating_operation_mode";
itemClass = NumberItem.class;
}
},
//in german Heizung Temperatur (Parallelverschiebung)
TYPE_HEATING_TEMPERATURE {
{
command = "heating_temperature";
itemClass = NumberItem.class;
}
},
//in german Warmwasser Betriebsart
TYPE_WARMWATER_OPERATION_MODE {
{
command = "warmwater_operation_mode";
itemClass = NumberItem.class;
}
},
//in german Warmwasser Temperatur
TYPE_WARMWATER_TEMPERATURE {
{
command = "warmwater_temperature";
itemClass = NumberItem.class;
}
},
//in german Comfort Kühlung Betriebsart
TYPE_COOLING_OPERATION_MODE {
{
command = "cooling_operation_mode";
itemClass = NumberItem.class;
}
},
//in german Comfort Kühlung AT-Freigabe
TYPE_COOLING_RELEASE_TEMPERATURE {
{
command = "cooling_release_temperature";
itemClass = NumberItem.class;
}
},
//in german Solltemp MK1
TYPE_COOLING_INLET_TEMP {
{
command = "cooling_inlet_temperature";
itemClass = NumberItem.class;
}
},
//in german AT-Überschreitung
TYPE_COOLING_START_AFTER_HOURS {
{
command = "cooling_start_hours";
itemClass = NumberItem.class;
}
},
//in german AT-Unterschreitung
TYPE_COOLING_STOP_AFTER_HOURS {
{
command = "cooling_stop_hours";
itemClass = NumberItem.class;
}
};
/** Represents the heatpump command as it will be used in *.items configuration */
String command;
Class<? extends Item> itemClass;
public String getCommand() {
return command;
}
public Class<? extends Item> getItemClass() {
return itemClass;
}
/**
*
* @param bindingConfig command string e.g. state, temperature_solar_storage,..
* @param itemClass class to validate
* @return true if item class can bound to heatpumpCommand
*/
public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) {
boolean ret = false;
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(bindingConfig.getCommand())
&& c.getItemClass().equals(itemClass)) {
ret = true;
break;
}
}
return ret;
}
public static HeatpumpCommandType fromString(String heatpumpCommand) {
if ("".equals(heatpumpCommand)) {
return null;
}
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(heatpumpCommand)) {
return c;
}
}
throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '"
+ heatpumpCommand + "'");
}
} | Issendorff/openhab | bundles/binding/org.openhab.binding.novelanheatpump/src/main/java/org/openhab/binding/novelanheatpump/HeatpumpCommandType.java | 3,207 | // in german Massentrom | line_comment | nl | /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.novelanheatpump;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
/**
* Represents all valid commands which could be processed by this binding
*
* @author Jan-Philipp Bolle
* @since 1.0.0
*/
public enum HeatpumpCommandType {
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE {
{
command = "temperature_outside";
itemClass = NumberItem.class;
}
},
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE_AVG {
{
command = "temperature_outside_avg";
itemClass = NumberItem.class;
}
},
//in german Rücklauf
TYPE_TEMPERATURE_RETURN {
{
command = "temperature_return";
itemClass = NumberItem.class;
}
},
//in german Rücklauf Soll
TYPE_TEMPERATURE_REFERENCE_RETURN {
{
command = "temperature_reference_return";
itemClass = NumberItem.class;
}
},
//in german Vorlauf
TYPE_TEMPERATURE_SUPPLAY {
{
command = "temperature_supplay";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Soll
TYPE_TEMPERATURE_SERVICEWATER_REFERENCE {
{
command = "temperature_servicewater_reference";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Ist
TYPE_TEMPERATURE_SERVICEWATER {
{
command = "temperature_servicewater";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_STATE {
{
command = "state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_EXTENDED_STATE {
{
command = "extended_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SOLAR_COLLECTOR {
{
command = "temperature_solar_collector";
itemClass = NumberItem.class;
}
},
// in german Temperatur Heissgas
TYPE_TEMPERATURE_HOT_GAS {
{
command = "temperature_hot_gas";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Eingang
TYPE_TEMPERATURE_PROBE_IN {
{
command = "temperature_probe_in";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Ausgang
TYPE_TEMPERATURE_PROBE_OUT {
{
command = "temperature_probe_out";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK1 {
{
command = "temperature_mk1";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK1_REFERENCE {
{
command = "temperature_mk1_reference";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK2 {
{
command = "temperature_mk2";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK2_REFERENCE {
{
command = "temperature_mk2_reference";
itemClass = NumberItem.class;
}
},
// in german Temperatur externe Energiequelle
TYPE_TEMPERATURE_EXTERNAL_SOURCE {
{
command = "temperature_external_source";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter1
TYPE_HOURS_COMPRESSOR1 {
{
command = "hours_compressor1";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 1
TYPE_STARTS_COMPRESSOR1 {
{
command = "starts_compressor1";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter2
TYPE_HOURS_COMPRESSOR2 {
{
command = "hours_compressor2";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 2
TYPE_STARTS_COMPRESSOR2 {
{
command = "starts_compressor2";
itemClass = NumberItem.class;
}
},
// Temperatur_TRL_ext
TYPE_TEMPERATURE_OUT_EXTERNAL {
{
command = "temperature_out_external";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE1 {
{
command = "hours_zwe1";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE2 {
{
command = "hours_zwe2";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE3 {
{
command = "hours_zwe3";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Wärmepumpe
TYPE_HOURS_HETPUMP {
{
command = "hours_heatpump";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Heizung
TYPE_HOURS_HEATING {
{
command = "hours_heating";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_WARMWATER {
{
command = "hours_warmwater";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_COOLING {
{
command = "hours_cooling";
itemClass = StringItem.class;
}
},
// in german Waermemenge Heizung
TYPE_THERMALENERGY_HEATING {
{
command = "thermalenergy_heating";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Brauchwasser
TYPE_THERMALENERGY_WARMWATER {
{
command = "thermalenergy_warmwater";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Schwimmbad
TYPE_THERMALENERGY_POOL {
{
command = "thermalenergy_pool";
itemClass = NumberItem.class;
}
},
// in german Waermemenge gesamt seit Reset
TYPE_THERMALENERGY_TOTAL {
{
command = "thermalenergy_total";
itemClass = NumberItem.class;
}
},
// in german<SUF>
TYPE_MASSFLOW {
{
command = "massflow";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SOLAR_STORAGE {
{
command = "temperature_solar_storage";
itemClass = NumberItem.class;
}
},
//in german Heizung Betriebsart
TYPE_HEATING_OPERATION_MODE {
{
command = "heating_operation_mode";
itemClass = NumberItem.class;
}
},
//in german Heizung Temperatur (Parallelverschiebung)
TYPE_HEATING_TEMPERATURE {
{
command = "heating_temperature";
itemClass = NumberItem.class;
}
},
//in german Warmwasser Betriebsart
TYPE_WARMWATER_OPERATION_MODE {
{
command = "warmwater_operation_mode";
itemClass = NumberItem.class;
}
},
//in german Warmwasser Temperatur
TYPE_WARMWATER_TEMPERATURE {
{
command = "warmwater_temperature";
itemClass = NumberItem.class;
}
},
//in german Comfort Kühlung Betriebsart
TYPE_COOLING_OPERATION_MODE {
{
command = "cooling_operation_mode";
itemClass = NumberItem.class;
}
},
//in german Comfort Kühlung AT-Freigabe
TYPE_COOLING_RELEASE_TEMPERATURE {
{
command = "cooling_release_temperature";
itemClass = NumberItem.class;
}
},
//in german Solltemp MK1
TYPE_COOLING_INLET_TEMP {
{
command = "cooling_inlet_temperature";
itemClass = NumberItem.class;
}
},
//in german AT-Überschreitung
TYPE_COOLING_START_AFTER_HOURS {
{
command = "cooling_start_hours";
itemClass = NumberItem.class;
}
},
//in german AT-Unterschreitung
TYPE_COOLING_STOP_AFTER_HOURS {
{
command = "cooling_stop_hours";
itemClass = NumberItem.class;
}
};
/** Represents the heatpump command as it will be used in *.items configuration */
String command;
Class<? extends Item> itemClass;
public String getCommand() {
return command;
}
public Class<? extends Item> getItemClass() {
return itemClass;
}
/**
*
* @param bindingConfig command string e.g. state, temperature_solar_storage,..
* @param itemClass class to validate
* @return true if item class can bound to heatpumpCommand
*/
public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) {
boolean ret = false;
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(bindingConfig.getCommand())
&& c.getItemClass().equals(itemClass)) {
ret = true;
break;
}
}
return ret;
}
public static HeatpumpCommandType fromString(String heatpumpCommand) {
if ("".equals(heatpumpCommand)) {
return null;
}
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(heatpumpCommand)) {
return c;
}
}
throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '"
+ heatpumpCommand + "'");
}
} |
168582_2 | package me.calebjones.spacelaunchnow.common.ui.views.custom;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import android.zetterstrom.com.forecast.models.DataPoint;
import android.zetterstrom.com.forecast.models.Forecast;
import com.github.pwittchen.weathericonview.WeatherIconView;
import java.text.SimpleDateFormat;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.Group;
import butterknife.BindView;
import butterknife.ButterKnife;
import me.calebjones.spacelaunchnow.common.R;
import me.calebjones.spacelaunchnow.common.R2;
import me.calebjones.spacelaunchnow.common.utils.Utils;
public class WeatherCard extends CardView {
@BindView(R2.id.weather_title)
TextView weatherTitle;
@BindView(R2.id.weather_icon)
WeatherIconView weatherIcon;
@BindView(R2.id.weather_percip_chance_icon)
WeatherIconView weatherPrecipIcon;
@BindView(R2.id.weather_percip_chance)
TextView weatherPercipChance;
@BindView(R2.id.weather_wind_speed_icon)
WeatherIconView weatherSpeedIcon;
@BindView(R2.id.weather_wind_speed)
TextView weatherWindSpeed;
@BindView(R2.id.weather_current_temp)
TextView weatherCurrentTemp;
@BindView(R2.id.weather_feels_like)
TextView weatherFeelsLike;
@BindView(R2.id.weather_low_high)
TextView weatherLowHigh;
@BindView(R2.id.weather_summary_day)
TextView weatherSummaryDay;
@BindView(R2.id.weather_location)
TextView weatherLocation;
@BindView(R2.id.day_two_weather_icon)
WeatherIconView dayTwoWeatherIcon;
@BindView(R2.id.day_two_day)
TextView dayTwoDay;
@BindView(R2.id.day_two_low_high)
TextView dayTwoWeatherLowHigh;
@BindView(R2.id.day_two_precip_prob_icon)
WeatherIconView dayTwoWeatherPrecipIcon;
@BindView(R2.id.day_two_precip_prob)
TextView dayTwoWeatherPrecip;
@BindView(R2.id.day_two_weather_wind_speed_icon)
WeatherIconView dayTwoWeatherWindIcon;
@BindView(R2.id.day_two_weather_wind_speed)
TextView dayTwoWeatherWindSpeed;
@BindView(R2.id.day_three_weather_icon)
WeatherIconView dayThreeWeatherIcon;
@BindView(R2.id.day_three_day)
TextView dayThreeDay;
@BindView(R2.id.day_three_low_high)
TextView dayThreeWeatherLowHigh;
@BindView(R2.id.day_three_precip_prob_icon)
WeatherIconView dayThreeWeatherPrecipIcon;
@BindView(R2.id.day_three_precip_prob)
TextView dayThreeWeatherPrecip;
@BindView(R2.id.day_three_weather_wind_speed_icon)
WeatherIconView dayThreeWeatherWindIcon;
@BindView(R2.id.day_three_weather_wind_speed)
TextView dayThreeWeatherWindSpeed;
@BindView(R2.id.day_four_weather_icon)
WeatherIconView dayFourWeatherIcon;
@BindView(R2.id.day_four_day)
TextView dayFourDay;
@BindView(R2.id.day_four_low_high)
TextView dayFourWeatherLowHigh;
@BindView(R2.id.day_four_precip_prob_icon)
WeatherIconView dayFourWeatherPrecipIcon;
@BindView(R2.id.day_four_precip_prob)
TextView dayFourWeatherPrecip;
@BindView(R2.id.day_four_weather_wind_speed_icon)
WeatherIconView dayFourWeatherWindIcon;
@BindView(R2.id.day_four_weather_wind_speed)
TextView dayFourWeatherWindSpeed;
@BindView(R2.id.three_day_forecast)
Group threeDayForecast;
@BindView(R2.id.constraintLayout)
ConstraintLayout constraintLayout;
private SharedPreferences sharedPref;
private boolean nightMode = false;
private boolean current = true;
private Forecast forecast;
private String location;
public WeatherCard(Context context) {
super(context);
init(context);
}
public WeatherCard(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public WeatherCard(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
inflate(context, R.layout.custom_weather_card, this);
ButterKnife.bind(this);
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setNightMode(boolean nightMode) {
this.nightMode = nightMode;
}
;
public void setWeather(Forecast forecast, String location, boolean current, boolean nightMode) {
this.forecast = forecast;
this.current = current;
this.location = location;
this.nightMode = nightMode;
if (current) {
updateCurrentWeatherView(forecast, location);
} else {
updatePastWeatherView(forecast, location);
}
}
public void setTitle(String title) {
weatherTitle.setText(title);
}
private void updateCurrentWeatherView(Forecast forecast, String location) {
final String temp;
final String speed;
String precip;
String pressure;
String visibility;
if (sharedPref.getBoolean("weather_US_SI", true)) {
temp = "F";
speed = "Mph";
precip = "in.";
pressure = "mb";
visibility = "mile";
} else {
temp = "C";
speed = "m/s";
precip = "cm";
pressure = "hPa";
visibility = "km";
}
if (forecast.getCurrently() != null) {
if (forecast.getCurrently().getTemperature() != null) {
String currentTemp = String.valueOf(Math.round(forecast.getCurrently().getTemperature())) + (char) 0x00B0 + " " + temp;
weatherCurrentTemp.setText(currentTemp);
}
if (forecast.getCurrently().getApparentTemperature() != null) {
String feelsLikeTemp = "Feels like ";
feelsLikeTemp = feelsLikeTemp + String.valueOf(Math.round(forecast.getCurrently().getApparentTemperature())) + (char) 0x00B0;
weatherFeelsLike.setText(feelsLikeTemp);
}
if (forecast.getCurrently().getWindSpeed() != null) {
String windSpeed = String.valueOf(Math.round(forecast.getCurrently().getWindSpeed())) + " " + speed;
weatherWindSpeed.setText(windSpeed);
}
}
if (forecast.getDaily() != null && forecast.getDaily().getDataPoints() != null && forecast.getDaily().getDataPoints().size() > 0) {
String highTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(0).getTemperatureMax()));
String lowTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(0).getTemperatureMin()));
String lowHigh = lowTemp + (char) 0x00B0 + " " + temp + " | " + highTemp + (char) 0x00B0 + " " + temp;
weatherLowHigh.setText(lowHigh);
if (forecast.getDaily().getDataPoints().get(0).getPrecipProbability() != null) {
String precipProb = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(0).getPrecipProbability() * 100) + "%");
weatherPercipChance.setText(precipProb);
}
if (forecast.getDaily().getDataPoints().size() >= 3) {
DataPoint dayOne = forecast.getDaily().getDataPoints().get(1);
if (dayOne.getIcon() != null && dayOne.getIcon().getText() != null) {
//Day One!
setIconView(dayTwoWeatherIcon, dayOne.getIcon().getText());
}
String dayTwoLowHigh = "";
if (dayOne.getTemperatureMax() != null && dayOne.getTemperatureMin() != null) {
//Get Low - High temp
String dayTwoHighTemp = String.valueOf(Math.round(dayOne.getTemperatureMax()));
String dayTwoLowTemp = String.valueOf(Math.round(dayOne.getTemperatureMin()));
dayTwoLowHigh = dayTwoLowTemp + (char) 0x00B0 + " " + temp + " | " + dayTwoHighTemp + (char) 0x00B0 + " " + temp;
}
//Get rain prop
String dayTwoPrecipProb = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(1).getPrecipProbability() * 100) + "%");
//Get Wind speed
String dayTwoWindSpeed = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(1).getWindSpeed())) + " " + speed;
//Get day date
String dayTwoDate = new SimpleDateFormat("EE ").format(forecast.getDaily().getDataPoints().get(1).getTime());
dayTwoWeatherLowHigh.setText(dayTwoLowHigh);
dayTwoWeatherPrecip.setText(dayTwoPrecipProb);
dayTwoWeatherWindSpeed.setText(dayTwoWindSpeed);
dayTwoDay.setText(dayTwoDate);
//Day Two!
setIconView(dayThreeWeatherIcon, forecast.getDaily().getDataPoints().get(2).getIcon().getText());
//Get Low - High temp
String dayThreeHighTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(2).getTemperatureMax()));
String dayThreeLowTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(2).getTemperatureMin()));
String dayThreeLowHigh = dayThreeLowTemp + (char) 0x00B0 + " " + temp + " | " + dayThreeHighTemp + (char) 0x00B0 + " " + temp;
//Get rain prop
String dayThreePrecipProb = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(2).getPrecipProbability() * 100) + "%");
//Get Wind speed
String dayThreeWindSpeed = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(2).getWindSpeed())) + " " + speed;
//Get day date
String dayThreeDate = new SimpleDateFormat("EE").format(forecast.getDaily().getDataPoints().get(2).getTime());
dayThreeWeatherLowHigh.setText(dayThreeLowHigh);
dayThreeWeatherPrecip.setText(dayThreePrecipProb);
dayThreeWeatherWindSpeed.setText(dayThreeWindSpeed);
dayThreeDay.setText(dayThreeDate);
//Day Three!
setIconView(dayFourWeatherIcon, forecast.getDaily().getDataPoints().get(3).getIcon().getText());
//Get Low - High temp
String dayFourHighTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(3).getTemperatureMax()));
String dayFourLowTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(3).getTemperatureMin()));
String dayFourLowHigh = dayFourLowTemp + (char) 0x00B0 + " " + temp + " | " + dayFourHighTemp + (char) 0x00B0 + " " + temp;
String dayFourPrecipProb = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(3).getPrecipProbability() * 100) + "%");
//Get Wind speed
String dayFourWindSpeed = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(3).getWindSpeed())) + " " + speed;
//Get day date
String dayFourDate = new SimpleDateFormat("EE").format(forecast.getDaily().getDataPoints().get(3).getTime());
dayFourWeatherLowHigh.setText(dayFourLowHigh);
dayFourWeatherPrecip.setText(dayFourPrecipProb);
dayFourWeatherWindSpeed.setText(dayFourWindSpeed);
dayFourDay.setText(dayFourDate);
} else {
threeDayForecast.setVisibility(View.GONE);
}
}
if (forecast.getCurrently().getIcon() != null && forecast.getCurrently().getIcon().getText() != null) {
setIconView(weatherIcon, forecast.getCurrently().getIcon().getText());
}
if (forecast.getDaily() != null && forecast.getDaily().getSummary() != null) {
weatherSummaryDay.setText(forecast.getDaily().getSummary());
} else if (forecast.getCurrently() != null && forecast.getCurrently().getSummary() != null) {
weatherSummaryDay.setText(forecast.getCurrently().getSummary());
} else {
weatherSummaryDay.setVisibility(View.GONE);
}
weatherLocation.setText(location);
if (nightMode) {
dayTwoWeatherWindIcon.setIconColor(Color.WHITE);
dayTwoWeatherPrecipIcon.setIconColor(Color.WHITE);
dayThreeWeatherWindIcon.setIconColor(Color.WHITE);
dayThreeWeatherPrecipIcon.setIconColor(Color.WHITE);
dayFourWeatherWindIcon.setIconColor(Color.WHITE);
dayFourWeatherPrecipIcon.setIconColor(Color.WHITE);
weatherPrecipIcon.setIconColor(Color.WHITE);
weatherSpeedIcon.setIconColor(Color.WHITE);
}
}
private void updatePastWeatherView(Forecast forecast, String location) {
final String temp;
final String speed;
String precip;
String pressure;
String visibility;
if (sharedPref.getBoolean("weather_US_SI", true)) {
temp = "F";
speed = "Mph";
precip = "in.";
pressure = "mb";
visibility = "mile";
} else {
temp = "C";
speed = "m/s";
precip = "cm";
pressure = "hPa";
visibility = "km";
}
if (forecast.getCurrently() != null) {
if (forecast.getCurrently().getTemperature() != null) {
String currentTemp = String.valueOf(Math.round(forecast.getCurrently().getTemperature())) + (char) 0x00B0 + " " + temp;
weatherCurrentTemp.setText(currentTemp);
}
if (forecast.getCurrently().getApparentTemperature() != null) {
String feelsLikeTemp = "Feels like ";
feelsLikeTemp = feelsLikeTemp + String.valueOf(Math.round(forecast.getCurrently().getApparentTemperature())) + (char) 0x00B0;
weatherFeelsLike.setText(feelsLikeTemp);
}
if (forecast.getCurrently().getWindSpeed() != null) {
String windSpeed = String.valueOf(Math.round(forecast.getCurrently().getWindSpeed())) + " " + speed;
weatherWindSpeed.setText(windSpeed);
}
}
if (forecast.getDaily() != null && forecast.getDaily().getDataPoints() != null && forecast.getDaily().getDataPoints().size() > 0) {
String highTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(0).getTemperatureMax()));
String lowTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(0).getTemperatureMin()));
String lowHigh = lowTemp + (char) 0x00B0 + " " + temp + " | " + highTemp + (char) 0x00B0 + " " + temp;
weatherLowHigh.setText(lowHigh);
if (forecast.getDaily().getDataPoints().get(0).getPrecipProbability() != null) {
String precipProb = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(0).getPrecipProbability() * 100) + "%");
weatherPercipChance.setText(precipProb);
}
threeDayForecast.setVisibility(View.GONE);
}
if (forecast.getCurrently().getIcon() != null && forecast.getCurrently().getIcon().getText() != null) {
setIconView(weatherIcon, forecast.getCurrently().getIcon().getText());
}
if (forecast.getDaily() != null && forecast.getDaily().getDataPoints() != null && forecast.getDaily().getDataPoints().size() > 0 && forecast.getDaily().getDataPoints().get(0).getSummary() != null) {
weatherSummaryDay.setText(forecast.getDaily().getDataPoints().get(0).getSummary());
} else if (forecast.getCurrently() != null && forecast.getCurrently().getSummary() != null) {
weatherSummaryDay.setText(forecast.getCurrently().getSummary());
} else {
weatherSummaryDay.setVisibility(View.GONE);
}
weatherLocation.setText(location);
if (nightMode) {
dayTwoWeatherWindIcon.setIconColor(Color.WHITE);
dayTwoWeatherPrecipIcon.setIconColor(Color.WHITE);
dayThreeWeatherWindIcon.setIconColor(Color.WHITE);
dayThreeWeatherPrecipIcon.setIconColor(Color.WHITE);
dayFourWeatherWindIcon.setIconColor(Color.WHITE);
dayFourWeatherPrecipIcon.setIconColor(Color.WHITE);
weatherPrecipIcon.setIconColor(Color.WHITE);
weatherSpeedIcon.setIconColor(Color.WHITE);
}
}
private void setIconView(WeatherIconView view, String icon) {
if (icon.contains("partly-cloudy-day")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_partly_cloudy_day));
} else if (icon.contains("partly-cloudy-night")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_partly_cloudy_night));
} else if (icon.contains("clear-day")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_clear_day));
} else if (icon.contains("clear-night")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_clear_night));
} else if (icon.contains("rain")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_rain));
} else if (icon.contains("snow")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_snow));
} else if (icon.contains("sleet")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_sleet));
} else if (icon.contains("wind")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_wind));
} else if (icon.contains("fog")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_fog));
} else if (icon.contains("cloudy")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_cloudy));
} else if (icon.contains("hail")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_hail));
} else if (icon.contains("thunderstorm")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_thunderstorm));
} else if (icon.contains("tornado")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_tornado));
}
if (nightMode) {
view.setIconColor(Color.WHITE);
} else {
view.setIconColor(Color.BLACK);
}
}
}
| ItsCalebJones/SpaceLaunchNow-Android | common/src/main/java/me/calebjones/spacelaunchnow/common/ui/views/custom/WeatherCard.java | 5,863 | //Get Wind speed | line_comment | nl | package me.calebjones.spacelaunchnow.common.ui.views.custom;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import android.zetterstrom.com.forecast.models.DataPoint;
import android.zetterstrom.com.forecast.models.Forecast;
import com.github.pwittchen.weathericonview.WeatherIconView;
import java.text.SimpleDateFormat;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.Group;
import butterknife.BindView;
import butterknife.ButterKnife;
import me.calebjones.spacelaunchnow.common.R;
import me.calebjones.spacelaunchnow.common.R2;
import me.calebjones.spacelaunchnow.common.utils.Utils;
public class WeatherCard extends CardView {
@BindView(R2.id.weather_title)
TextView weatherTitle;
@BindView(R2.id.weather_icon)
WeatherIconView weatherIcon;
@BindView(R2.id.weather_percip_chance_icon)
WeatherIconView weatherPrecipIcon;
@BindView(R2.id.weather_percip_chance)
TextView weatherPercipChance;
@BindView(R2.id.weather_wind_speed_icon)
WeatherIconView weatherSpeedIcon;
@BindView(R2.id.weather_wind_speed)
TextView weatherWindSpeed;
@BindView(R2.id.weather_current_temp)
TextView weatherCurrentTemp;
@BindView(R2.id.weather_feels_like)
TextView weatherFeelsLike;
@BindView(R2.id.weather_low_high)
TextView weatherLowHigh;
@BindView(R2.id.weather_summary_day)
TextView weatherSummaryDay;
@BindView(R2.id.weather_location)
TextView weatherLocation;
@BindView(R2.id.day_two_weather_icon)
WeatherIconView dayTwoWeatherIcon;
@BindView(R2.id.day_two_day)
TextView dayTwoDay;
@BindView(R2.id.day_two_low_high)
TextView dayTwoWeatherLowHigh;
@BindView(R2.id.day_two_precip_prob_icon)
WeatherIconView dayTwoWeatherPrecipIcon;
@BindView(R2.id.day_two_precip_prob)
TextView dayTwoWeatherPrecip;
@BindView(R2.id.day_two_weather_wind_speed_icon)
WeatherIconView dayTwoWeatherWindIcon;
@BindView(R2.id.day_two_weather_wind_speed)
TextView dayTwoWeatherWindSpeed;
@BindView(R2.id.day_three_weather_icon)
WeatherIconView dayThreeWeatherIcon;
@BindView(R2.id.day_three_day)
TextView dayThreeDay;
@BindView(R2.id.day_three_low_high)
TextView dayThreeWeatherLowHigh;
@BindView(R2.id.day_three_precip_prob_icon)
WeatherIconView dayThreeWeatherPrecipIcon;
@BindView(R2.id.day_three_precip_prob)
TextView dayThreeWeatherPrecip;
@BindView(R2.id.day_three_weather_wind_speed_icon)
WeatherIconView dayThreeWeatherWindIcon;
@BindView(R2.id.day_three_weather_wind_speed)
TextView dayThreeWeatherWindSpeed;
@BindView(R2.id.day_four_weather_icon)
WeatherIconView dayFourWeatherIcon;
@BindView(R2.id.day_four_day)
TextView dayFourDay;
@BindView(R2.id.day_four_low_high)
TextView dayFourWeatherLowHigh;
@BindView(R2.id.day_four_precip_prob_icon)
WeatherIconView dayFourWeatherPrecipIcon;
@BindView(R2.id.day_four_precip_prob)
TextView dayFourWeatherPrecip;
@BindView(R2.id.day_four_weather_wind_speed_icon)
WeatherIconView dayFourWeatherWindIcon;
@BindView(R2.id.day_four_weather_wind_speed)
TextView dayFourWeatherWindSpeed;
@BindView(R2.id.three_day_forecast)
Group threeDayForecast;
@BindView(R2.id.constraintLayout)
ConstraintLayout constraintLayout;
private SharedPreferences sharedPref;
private boolean nightMode = false;
private boolean current = true;
private Forecast forecast;
private String location;
public WeatherCard(Context context) {
super(context);
init(context);
}
public WeatherCard(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public WeatherCard(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
inflate(context, R.layout.custom_weather_card, this);
ButterKnife.bind(this);
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setNightMode(boolean nightMode) {
this.nightMode = nightMode;
}
;
public void setWeather(Forecast forecast, String location, boolean current, boolean nightMode) {
this.forecast = forecast;
this.current = current;
this.location = location;
this.nightMode = nightMode;
if (current) {
updateCurrentWeatherView(forecast, location);
} else {
updatePastWeatherView(forecast, location);
}
}
public void setTitle(String title) {
weatherTitle.setText(title);
}
private void updateCurrentWeatherView(Forecast forecast, String location) {
final String temp;
final String speed;
String precip;
String pressure;
String visibility;
if (sharedPref.getBoolean("weather_US_SI", true)) {
temp = "F";
speed = "Mph";
precip = "in.";
pressure = "mb";
visibility = "mile";
} else {
temp = "C";
speed = "m/s";
precip = "cm";
pressure = "hPa";
visibility = "km";
}
if (forecast.getCurrently() != null) {
if (forecast.getCurrently().getTemperature() != null) {
String currentTemp = String.valueOf(Math.round(forecast.getCurrently().getTemperature())) + (char) 0x00B0 + " " + temp;
weatherCurrentTemp.setText(currentTemp);
}
if (forecast.getCurrently().getApparentTemperature() != null) {
String feelsLikeTemp = "Feels like ";
feelsLikeTemp = feelsLikeTemp + String.valueOf(Math.round(forecast.getCurrently().getApparentTemperature())) + (char) 0x00B0;
weatherFeelsLike.setText(feelsLikeTemp);
}
if (forecast.getCurrently().getWindSpeed() != null) {
String windSpeed = String.valueOf(Math.round(forecast.getCurrently().getWindSpeed())) + " " + speed;
weatherWindSpeed.setText(windSpeed);
}
}
if (forecast.getDaily() != null && forecast.getDaily().getDataPoints() != null && forecast.getDaily().getDataPoints().size() > 0) {
String highTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(0).getTemperatureMax()));
String lowTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(0).getTemperatureMin()));
String lowHigh = lowTemp + (char) 0x00B0 + " " + temp + " | " + highTemp + (char) 0x00B0 + " " + temp;
weatherLowHigh.setText(lowHigh);
if (forecast.getDaily().getDataPoints().get(0).getPrecipProbability() != null) {
String precipProb = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(0).getPrecipProbability() * 100) + "%");
weatherPercipChance.setText(precipProb);
}
if (forecast.getDaily().getDataPoints().size() >= 3) {
DataPoint dayOne = forecast.getDaily().getDataPoints().get(1);
if (dayOne.getIcon() != null && dayOne.getIcon().getText() != null) {
//Day One!
setIconView(dayTwoWeatherIcon, dayOne.getIcon().getText());
}
String dayTwoLowHigh = "";
if (dayOne.getTemperatureMax() != null && dayOne.getTemperatureMin() != null) {
//Get Low - High temp
String dayTwoHighTemp = String.valueOf(Math.round(dayOne.getTemperatureMax()));
String dayTwoLowTemp = String.valueOf(Math.round(dayOne.getTemperatureMin()));
dayTwoLowHigh = dayTwoLowTemp + (char) 0x00B0 + " " + temp + " | " + dayTwoHighTemp + (char) 0x00B0 + " " + temp;
}
//Get rain prop
String dayTwoPrecipProb = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(1).getPrecipProbability() * 100) + "%");
//Get Wind<SUF>
String dayTwoWindSpeed = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(1).getWindSpeed())) + " " + speed;
//Get day date
String dayTwoDate = new SimpleDateFormat("EE ").format(forecast.getDaily().getDataPoints().get(1).getTime());
dayTwoWeatherLowHigh.setText(dayTwoLowHigh);
dayTwoWeatherPrecip.setText(dayTwoPrecipProb);
dayTwoWeatherWindSpeed.setText(dayTwoWindSpeed);
dayTwoDay.setText(dayTwoDate);
//Day Two!
setIconView(dayThreeWeatherIcon, forecast.getDaily().getDataPoints().get(2).getIcon().getText());
//Get Low - High temp
String dayThreeHighTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(2).getTemperatureMax()));
String dayThreeLowTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(2).getTemperatureMin()));
String dayThreeLowHigh = dayThreeLowTemp + (char) 0x00B0 + " " + temp + " | " + dayThreeHighTemp + (char) 0x00B0 + " " + temp;
//Get rain prop
String dayThreePrecipProb = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(2).getPrecipProbability() * 100) + "%");
//Get Wind speed
String dayThreeWindSpeed = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(2).getWindSpeed())) + " " + speed;
//Get day date
String dayThreeDate = new SimpleDateFormat("EE").format(forecast.getDaily().getDataPoints().get(2).getTime());
dayThreeWeatherLowHigh.setText(dayThreeLowHigh);
dayThreeWeatherPrecip.setText(dayThreePrecipProb);
dayThreeWeatherWindSpeed.setText(dayThreeWindSpeed);
dayThreeDay.setText(dayThreeDate);
//Day Three!
setIconView(dayFourWeatherIcon, forecast.getDaily().getDataPoints().get(3).getIcon().getText());
//Get Low - High temp
String dayFourHighTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(3).getTemperatureMax()));
String dayFourLowTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(3).getTemperatureMin()));
String dayFourLowHigh = dayFourLowTemp + (char) 0x00B0 + " " + temp + " | " + dayFourHighTemp + (char) 0x00B0 + " " + temp;
String dayFourPrecipProb = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(3).getPrecipProbability() * 100) + "%");
//Get Wind speed
String dayFourWindSpeed = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(3).getWindSpeed())) + " " + speed;
//Get day date
String dayFourDate = new SimpleDateFormat("EE").format(forecast.getDaily().getDataPoints().get(3).getTime());
dayFourWeatherLowHigh.setText(dayFourLowHigh);
dayFourWeatherPrecip.setText(dayFourPrecipProb);
dayFourWeatherWindSpeed.setText(dayFourWindSpeed);
dayFourDay.setText(dayFourDate);
} else {
threeDayForecast.setVisibility(View.GONE);
}
}
if (forecast.getCurrently().getIcon() != null && forecast.getCurrently().getIcon().getText() != null) {
setIconView(weatherIcon, forecast.getCurrently().getIcon().getText());
}
if (forecast.getDaily() != null && forecast.getDaily().getSummary() != null) {
weatherSummaryDay.setText(forecast.getDaily().getSummary());
} else if (forecast.getCurrently() != null && forecast.getCurrently().getSummary() != null) {
weatherSummaryDay.setText(forecast.getCurrently().getSummary());
} else {
weatherSummaryDay.setVisibility(View.GONE);
}
weatherLocation.setText(location);
if (nightMode) {
dayTwoWeatherWindIcon.setIconColor(Color.WHITE);
dayTwoWeatherPrecipIcon.setIconColor(Color.WHITE);
dayThreeWeatherWindIcon.setIconColor(Color.WHITE);
dayThreeWeatherPrecipIcon.setIconColor(Color.WHITE);
dayFourWeatherWindIcon.setIconColor(Color.WHITE);
dayFourWeatherPrecipIcon.setIconColor(Color.WHITE);
weatherPrecipIcon.setIconColor(Color.WHITE);
weatherSpeedIcon.setIconColor(Color.WHITE);
}
}
private void updatePastWeatherView(Forecast forecast, String location) {
final String temp;
final String speed;
String precip;
String pressure;
String visibility;
if (sharedPref.getBoolean("weather_US_SI", true)) {
temp = "F";
speed = "Mph";
precip = "in.";
pressure = "mb";
visibility = "mile";
} else {
temp = "C";
speed = "m/s";
precip = "cm";
pressure = "hPa";
visibility = "km";
}
if (forecast.getCurrently() != null) {
if (forecast.getCurrently().getTemperature() != null) {
String currentTemp = String.valueOf(Math.round(forecast.getCurrently().getTemperature())) + (char) 0x00B0 + " " + temp;
weatherCurrentTemp.setText(currentTemp);
}
if (forecast.getCurrently().getApparentTemperature() != null) {
String feelsLikeTemp = "Feels like ";
feelsLikeTemp = feelsLikeTemp + String.valueOf(Math.round(forecast.getCurrently().getApparentTemperature())) + (char) 0x00B0;
weatherFeelsLike.setText(feelsLikeTemp);
}
if (forecast.getCurrently().getWindSpeed() != null) {
String windSpeed = String.valueOf(Math.round(forecast.getCurrently().getWindSpeed())) + " " + speed;
weatherWindSpeed.setText(windSpeed);
}
}
if (forecast.getDaily() != null && forecast.getDaily().getDataPoints() != null && forecast.getDaily().getDataPoints().size() > 0) {
String highTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(0).getTemperatureMax()));
String lowTemp = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(0).getTemperatureMin()));
String lowHigh = lowTemp + (char) 0x00B0 + " " + temp + " | " + highTemp + (char) 0x00B0 + " " + temp;
weatherLowHigh.setText(lowHigh);
if (forecast.getDaily().getDataPoints().get(0).getPrecipProbability() != null) {
String precipProb = String.valueOf(Math.round(forecast.getDaily().getDataPoints().get(0).getPrecipProbability() * 100) + "%");
weatherPercipChance.setText(precipProb);
}
threeDayForecast.setVisibility(View.GONE);
}
if (forecast.getCurrently().getIcon() != null && forecast.getCurrently().getIcon().getText() != null) {
setIconView(weatherIcon, forecast.getCurrently().getIcon().getText());
}
if (forecast.getDaily() != null && forecast.getDaily().getDataPoints() != null && forecast.getDaily().getDataPoints().size() > 0 && forecast.getDaily().getDataPoints().get(0).getSummary() != null) {
weatherSummaryDay.setText(forecast.getDaily().getDataPoints().get(0).getSummary());
} else if (forecast.getCurrently() != null && forecast.getCurrently().getSummary() != null) {
weatherSummaryDay.setText(forecast.getCurrently().getSummary());
} else {
weatherSummaryDay.setVisibility(View.GONE);
}
weatherLocation.setText(location);
if (nightMode) {
dayTwoWeatherWindIcon.setIconColor(Color.WHITE);
dayTwoWeatherPrecipIcon.setIconColor(Color.WHITE);
dayThreeWeatherWindIcon.setIconColor(Color.WHITE);
dayThreeWeatherPrecipIcon.setIconColor(Color.WHITE);
dayFourWeatherWindIcon.setIconColor(Color.WHITE);
dayFourWeatherPrecipIcon.setIconColor(Color.WHITE);
weatherPrecipIcon.setIconColor(Color.WHITE);
weatherSpeedIcon.setIconColor(Color.WHITE);
}
}
private void setIconView(WeatherIconView view, String icon) {
if (icon.contains("partly-cloudy-day")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_partly_cloudy_day));
} else if (icon.contains("partly-cloudy-night")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_partly_cloudy_night));
} else if (icon.contains("clear-day")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_clear_day));
} else if (icon.contains("clear-night")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_clear_night));
} else if (icon.contains("rain")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_rain));
} else if (icon.contains("snow")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_snow));
} else if (icon.contains("sleet")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_sleet));
} else if (icon.contains("wind")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_wind));
} else if (icon.contains("fog")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_fog));
} else if (icon.contains("cloudy")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_cloudy));
} else if (icon.contains("hail")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_hail));
} else if (icon.contains("thunderstorm")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_thunderstorm));
} else if (icon.contains("tornado")) {
view.setIconResource(getContext().getString(R.string.wi_forecast_io_tornado));
}
if (nightMode) {
view.setIconColor(Color.WHITE);
} else {
view.setIconColor(Color.BLACK);
}
}
}
|
104703_3 | /*
* Copyright (c) 2014 Ivo Woltring
*
* 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 nl.ivonet.core_java.design_patterns.behavioral.strategy;
import org.junit.Test;
/**
* Unit tests voor de Eend simulator.
* @author Ivo Woltring
*/
public class EendSimulatorTest {
@Test
public void testWildeEend() throws Exception {
final WildeEend wildeEend = new WildeEend();
wildeEend.toon();
wildeEend.doeKwaak();
wildeEend.doeVlieg();
}
@Test
public void testKuifEend() throws Exception {
final KuifEend kuifEend = new KuifEend();
kuifEend.toon();
kuifEend.doeKwaak();
kuifEend.doeVlieg();
kuifEend.raakGewond(); //gedrag verandert door omstandigheden
kuifEend.doeVlieg();
}
@Test
public void testLokEend() throws Exception {
final LokEend lokEend = new LokEend();
lokEend.toon();
lokEend.doeKwaak();
lokEend.doeVlieg();
lokEend.setVliegGedrag(new VliegMetStraalMotor()); // geef ander gedrag
lokEend.doeVlieg();
}
@Test
public void testBadEend() throws Exception {
final BadEend badEend = new BadEend();
badEend.toon();
badEend.doeKwaak();
badEend.doeVlieg();
}
}
| IvoNet/core-java | src/test/java/nl/ivonet/core_java/design_patterns/behavioral/strategy/EendSimulatorTest.java | 585 | // geef ander gedrag | line_comment | nl | /*
* Copyright (c) 2014 Ivo Woltring
*
* 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 nl.ivonet.core_java.design_patterns.behavioral.strategy;
import org.junit.Test;
/**
* Unit tests voor de Eend simulator.
* @author Ivo Woltring
*/
public class EendSimulatorTest {
@Test
public void testWildeEend() throws Exception {
final WildeEend wildeEend = new WildeEend();
wildeEend.toon();
wildeEend.doeKwaak();
wildeEend.doeVlieg();
}
@Test
public void testKuifEend() throws Exception {
final KuifEend kuifEend = new KuifEend();
kuifEend.toon();
kuifEend.doeKwaak();
kuifEend.doeVlieg();
kuifEend.raakGewond(); //gedrag verandert door omstandigheden
kuifEend.doeVlieg();
}
@Test
public void testLokEend() throws Exception {
final LokEend lokEend = new LokEend();
lokEend.toon();
lokEend.doeKwaak();
lokEend.doeVlieg();
lokEend.setVliegGedrag(new VliegMetStraalMotor()); // geef ander<SUF>
lokEend.doeVlieg();
}
@Test
public void testBadEend() throws Exception {
final BadEend badEend = new BadEend();
badEend.toon();
badEend.doeKwaak();
badEend.doeVlieg();
}
}
|
4362_3 | public class App {
public static void main(String[] args) {
//Flip comment op de volgende twee regels om de else tak in te gaan
final Object obj = "Het Werkt!!!";
// final Object obj = 42;
if(obj instanceof String s){
// s is direct te gebruiken als: s = (String) obj;
System.out.println(s + " <- heeft lengte :" + s.length());
} else{
// s is hier niet beschikbaar
System.out.println("Niet een string");
}
}
}
| IvoNet/javamagazine | poc/java14/src/main/java/App.java | 147 | // s is hier niet beschikbaar | line_comment | nl | public class App {
public static void main(String[] args) {
//Flip comment op de volgende twee regels om de else tak in te gaan
final Object obj = "Het Werkt!!!";
// final Object obj = 42;
if(obj instanceof String s){
// s is direct te gebruiken als: s = (String) obj;
System.out.println(s + " <- heeft lengte :" + s.length());
} else{
// s is<SUF>
System.out.println("Niet een string");
}
}
}
|
62669_28 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.*;
import javax.swing.JOptionPane;
/**
* Write a description of class KraanGrijper_tegenstander here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class KraanGrijper_tegenstander extends Vrachoverslaanobjecten
{
public double kraanSnelheid = 0.1;
public class coord
{
public coord (int px, int py)
{
x = px;
y = py;
}
public int x;
public int y;
}
public class planRegel
{
public coord origin;
public coord destination;
public int destinationTreinstel;
public boolean treinVol;
public int containerSize;
}
//maak een lijst van zetten
List<planRegel> movePlan = null;
int currentRegel = -1;
//krijg de locaties van de containers en vul de lijst van zetten
public void acceptContainerMap(String[][] containerMap)
{
planRegel regel = null;
boolean treinIsVol = false;
movePlan = new ArrayList<planRegel>();
// array met treinstel, x- en y-positie in het treinstel
boolean[][][] treincell = new boolean[2][2][4];
do{
//STAP 1: zoek naar grootste vrije ruimte op trein
regel = null;
treinIsVol = false;
int grootsteVrijeRuimte = 0;
coord GVRcoord = null;
int GVRtreinstel = 0;
do
{
for(int treinstel = 0; treinstel < 2; treinstel++)
{
for(int y = 0; y < 2; y++)
{
for(int x = 0; x < 4; x++)
{
if(getVrijeRuimte(treincell[treinstel][y], x) > grootsteVrijeRuimte)
{
grootsteVrijeRuimte = getVrijeRuimte(treincell[treinstel][y], x);
GVRcoord = new coord(x,y);
GVRtreinstel = treinstel;
}
}
}
}
if (grootsteVrijeRuimte==0)
{
// trein=vol
treinIsVol = true;
treincell = new boolean[2][2][4]; // maak een lege trein aan0
}
} while (grootsteVrijeRuimte==0) ;
//STAP 2: wat is de grootste contsainer op de boot, kleiner of gelijkaan de grootste vrije ruimte
regel = getVolgendeContainerOpBoot(containerMap, grootsteVrijeRuimte);
if (regel == null)
{
// Er is geen planregel: dus boot is leeg OF er zijn geen containers meer die passen op de trein
if (!IsBootLeeg(containerMap))
{
// er zijn nog containers, dus laat trein gaan
treinIsVol=true;
// Let op! dit moeten we bij de vorige planregel noteren!
movePlan.get(movePlan.size()-1).treinVol = true;
}
}
else
{ //Als er iets gevonden is, maak een planregel aan
// als trein nu vol is, dan moet de trein rijden bij de vorige container
if (treinIsVol)
{
movePlan.get(movePlan.size()-1).treinVol = true;
}
//hoera we hebben een container om te verplaatsen, party bij mij thuis
regel.destination = GVRcoord;
regel.destinationTreinstel = GVRtreinstel;
regel.treinVol = false;
movePlan.add(regel);
//afvinken plek op de trein
for(int x = regel.destination.x; x < regel.destination.x + regel.containerSize; x++)
{
treincell[regel.destinationTreinstel][regel.destination.y][x] = true;
}
}
} while (regel != null || treinIsVol);
//de tegenstander is klaar met het maken van het plan
}
private planRegel getVolgendeContainerOpBoot(String[][] containerMap, int grootsteVrijeRuimte)
{
if(grootsteVrijeRuimte > 3)
grootsteVrijeRuimte = 3;
for(int containerSize = grootsteVrijeRuimte; containerSize > 0; containerSize--)
{
String searchFor ="container" + Integer.toString(containerSize);
for(int y = 0; y < 3; y++)
{
for(int x = 0; x < 15; x++)
{
if(containerMap[x][y].contains(searchFor))
{
//vink conatainerplek op de boot af
containerMap[x][y] = "empty";
planRegel regel = new planRegel();
regel.origin = new coord(x,y);
regel.containerSize = containerSize;
return regel;
}
}
}
}
return null;
}
private boolean IsBootLeeg(String[][] containerMap)
{
for(int y = 0; y < 3; y++)
{
for(int x = 0; x < 15; x++)
{
if(containerMap[x][y].contains("container"))
{
return false;
}
}
}
return true;
}
private int getVrijeRuimte(boolean[] cell, int x)
{
int ruimte = 0;
for(int i = x; i < cell.length; i++)
{
if(cell[i])
{
return ruimte;
}
else
{
ruimte++;
}
}
return ruimte;
}
/**
* Act - Wat de grijper moet doen volgens het plan
*/
public enum Status {
INIT, MOVETO_ORIGIN_X, MOVETO_DESTINATION_X, MOVETO_ORIGIN_Y, MOVETO_DESTINATION_Y, WAITFORTRAIN, IDLE
}
Status tegenstanderStatus = Status.INIT;
int bestemmingX = 0;
int bestemmingY = 0;
double currentX = 0;
double currentY = 0;
Krat_vrachtoverslaan_tegenstander currentContainer =null;
public void act()
{
int grijperx = getX();
int grijpery = getY();
if(tegenstanderStatus == Status.INIT)
{
currentX=getX();
currentY=getY();
//bepaal volgende regel
tegenstanderStatus = Status.WAITFORTRAIN;
}
else if(tegenstanderStatus == Status.MOVETO_ORIGIN_X)
{
//check of de trein in het station staat
Trein_vrachtoverslaan_tegenstander trein = (Trein_vrachtoverslaan_tegenstander) getWorld().getObjects(Trein_vrachtoverslaan_tegenstander.class).get(0);
if(trein.isInStation())
{
if(getX() == bestemmingX)
{
tegenstanderStatus = Status.MOVETO_ORIGIN_Y;
}
else{
currentX = currentX + Math.signum(bestemmingX - currentX) * kraanSnelheid;
}
}
}
else if(tegenstanderStatus == Status.MOVETO_ORIGIN_Y)
{
if(getY() == bestemmingY)
{
tegenstanderStatus = Status.MOVETO_DESTINATION_X;
//moveto destination op trein
bestemmingX = movePlan.get(currentRegel).destination.x * 2 + 17 + movePlan.get(currentRegel).containerSize - 1 + movePlan.get(currentRegel).destinationTreinstel*11;
bestemmingY = movePlan.get(currentRegel).destination.y * 2 + 2;
// onthou de container die we gaan verplaatsen
Actor containerActor = getOneObjectAtOffset(0, 0, Krat_vrachtoverslaan_tegenstander.class);
currentContainer = (Krat_vrachtoverslaan_tegenstander) containerActor;
}
else{
currentY = currentY + Math.signum(bestemmingY - currentY) * kraanSnelheid;
}
}
else if(tegenstanderStatus == Status.MOVETO_DESTINATION_X)
{
if(getX() == bestemmingX)
{
tegenstanderStatus = Status.MOVETO_DESTINATION_Y;
}
else{
currentX = currentX + Math.signum(bestemmingX - currentX) * kraanSnelheid;
//zorg ervoor dat de container meebeweegt
currentContainer.setLocation((int)currentX, (int)currentY);
}
}
else if(tegenstanderStatus == Status.MOVETO_DESTINATION_Y)
{
if(getY() == bestemmingY)
{
tegenstanderStatus = Status.WAITFORTRAIN;
// als de trein vol is, laat hem dan vertrekken
if (movePlan.get(currentRegel).treinVol)
{
Trein_vrachtoverslaan_tegenstander trein = (Trein_vrachtoverslaan_tegenstander) getWorld().getObjects(Trein_vrachtoverslaan_tegenstander.class).get(0);
trein.gaRijden();
}
}
else{
currentY = currentY + Math.signum(bestemmingY - currentY) * kraanSnelheid;
//zorg ervoor dat de container meebeweegt
currentContainer.setLocation((int)currentX, (int)currentY);
}
}
else if(tegenstanderStatus == Status.WAITFORTRAIN)
{
Trein_vrachtoverslaan_tegenstander trein = (Trein_vrachtoverslaan_tegenstander) getWorld().getObjects(Trein_vrachtoverslaan_tegenstander.class).get(0);
if(!trein.isAanHetRijden())
{
// moveto origin op boot
currentRegel++;
if (currentRegel < movePlan.size())
{
bestemmingX = movePlan.get(currentRegel).origin.x * 2 + 10 + movePlan.get(currentRegel).containerSize - 1;
bestemmingY = 18 - (movePlan.get(currentRegel).origin.y * 2);
tegenstanderStatus = Status.MOVETO_ORIGIN_X;
}
else{
//TEGENSTANDER HEFT GEWONNEN
int reply = JOptionPane.showConfirmDialog(null, "Helaas, u heeft verloren. Wilt u nog een keer spelen?", "Verloren!", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION){
getWorld().removeObject(this);
Greenfoot.setWorld(new VrachtOverslaan());
return;
}
else if(reply == JOptionPane.NO_OPTION){
Greenfoot.setWorld(new Menu());
return;
}
}
}
}
else if(tegenstanderStatus == Status.IDLE)
{
//PLAYER HEEFT GEWONNEN
//speler wint als zijn laatste trein weg gaat dus dit kan weg
}
setLocation((int)currentX, (int)currentY);
// Move kraan tegenstander
KraanXding_tegenstander kraanXding = (KraanXding_tegenstander) getWorld().getObjects(KraanXding_tegenstander.class).get(0);
kraanXding.setLocation((int)currentX,kraanXding.getY());
}
public void setKraanSnelheid(double snelheid){
kraanSnelheid = snelheid;
}
}
| JARRS/game | Main/Port of Rotterdam/KraanGrijper_tegenstander.java | 3,624 | //speler wint als zijn laatste trein weg gaat dus dit kan weg | line_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.*;
import javax.swing.JOptionPane;
/**
* Write a description of class KraanGrijper_tegenstander here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class KraanGrijper_tegenstander extends Vrachoverslaanobjecten
{
public double kraanSnelheid = 0.1;
public class coord
{
public coord (int px, int py)
{
x = px;
y = py;
}
public int x;
public int y;
}
public class planRegel
{
public coord origin;
public coord destination;
public int destinationTreinstel;
public boolean treinVol;
public int containerSize;
}
//maak een lijst van zetten
List<planRegel> movePlan = null;
int currentRegel = -1;
//krijg de locaties van de containers en vul de lijst van zetten
public void acceptContainerMap(String[][] containerMap)
{
planRegel regel = null;
boolean treinIsVol = false;
movePlan = new ArrayList<planRegel>();
// array met treinstel, x- en y-positie in het treinstel
boolean[][][] treincell = new boolean[2][2][4];
do{
//STAP 1: zoek naar grootste vrije ruimte op trein
regel = null;
treinIsVol = false;
int grootsteVrijeRuimte = 0;
coord GVRcoord = null;
int GVRtreinstel = 0;
do
{
for(int treinstel = 0; treinstel < 2; treinstel++)
{
for(int y = 0; y < 2; y++)
{
for(int x = 0; x < 4; x++)
{
if(getVrijeRuimte(treincell[treinstel][y], x) > grootsteVrijeRuimte)
{
grootsteVrijeRuimte = getVrijeRuimte(treincell[treinstel][y], x);
GVRcoord = new coord(x,y);
GVRtreinstel = treinstel;
}
}
}
}
if (grootsteVrijeRuimte==0)
{
// trein=vol
treinIsVol = true;
treincell = new boolean[2][2][4]; // maak een lege trein aan0
}
} while (grootsteVrijeRuimte==0) ;
//STAP 2: wat is de grootste contsainer op de boot, kleiner of gelijkaan de grootste vrije ruimte
regel = getVolgendeContainerOpBoot(containerMap, grootsteVrijeRuimte);
if (regel == null)
{
// Er is geen planregel: dus boot is leeg OF er zijn geen containers meer die passen op de trein
if (!IsBootLeeg(containerMap))
{
// er zijn nog containers, dus laat trein gaan
treinIsVol=true;
// Let op! dit moeten we bij de vorige planregel noteren!
movePlan.get(movePlan.size()-1).treinVol = true;
}
}
else
{ //Als er iets gevonden is, maak een planregel aan
// als trein nu vol is, dan moet de trein rijden bij de vorige container
if (treinIsVol)
{
movePlan.get(movePlan.size()-1).treinVol = true;
}
//hoera we hebben een container om te verplaatsen, party bij mij thuis
regel.destination = GVRcoord;
regel.destinationTreinstel = GVRtreinstel;
regel.treinVol = false;
movePlan.add(regel);
//afvinken plek op de trein
for(int x = regel.destination.x; x < regel.destination.x + regel.containerSize; x++)
{
treincell[regel.destinationTreinstel][regel.destination.y][x] = true;
}
}
} while (regel != null || treinIsVol);
//de tegenstander is klaar met het maken van het plan
}
private planRegel getVolgendeContainerOpBoot(String[][] containerMap, int grootsteVrijeRuimte)
{
if(grootsteVrijeRuimte > 3)
grootsteVrijeRuimte = 3;
for(int containerSize = grootsteVrijeRuimte; containerSize > 0; containerSize--)
{
String searchFor ="container" + Integer.toString(containerSize);
for(int y = 0; y < 3; y++)
{
for(int x = 0; x < 15; x++)
{
if(containerMap[x][y].contains(searchFor))
{
//vink conatainerplek op de boot af
containerMap[x][y] = "empty";
planRegel regel = new planRegel();
regel.origin = new coord(x,y);
regel.containerSize = containerSize;
return regel;
}
}
}
}
return null;
}
private boolean IsBootLeeg(String[][] containerMap)
{
for(int y = 0; y < 3; y++)
{
for(int x = 0; x < 15; x++)
{
if(containerMap[x][y].contains("container"))
{
return false;
}
}
}
return true;
}
private int getVrijeRuimte(boolean[] cell, int x)
{
int ruimte = 0;
for(int i = x; i < cell.length; i++)
{
if(cell[i])
{
return ruimte;
}
else
{
ruimte++;
}
}
return ruimte;
}
/**
* Act - Wat de grijper moet doen volgens het plan
*/
public enum Status {
INIT, MOVETO_ORIGIN_X, MOVETO_DESTINATION_X, MOVETO_ORIGIN_Y, MOVETO_DESTINATION_Y, WAITFORTRAIN, IDLE
}
Status tegenstanderStatus = Status.INIT;
int bestemmingX = 0;
int bestemmingY = 0;
double currentX = 0;
double currentY = 0;
Krat_vrachtoverslaan_tegenstander currentContainer =null;
public void act()
{
int grijperx = getX();
int grijpery = getY();
if(tegenstanderStatus == Status.INIT)
{
currentX=getX();
currentY=getY();
//bepaal volgende regel
tegenstanderStatus = Status.WAITFORTRAIN;
}
else if(tegenstanderStatus == Status.MOVETO_ORIGIN_X)
{
//check of de trein in het station staat
Trein_vrachtoverslaan_tegenstander trein = (Trein_vrachtoverslaan_tegenstander) getWorld().getObjects(Trein_vrachtoverslaan_tegenstander.class).get(0);
if(trein.isInStation())
{
if(getX() == bestemmingX)
{
tegenstanderStatus = Status.MOVETO_ORIGIN_Y;
}
else{
currentX = currentX + Math.signum(bestemmingX - currentX) * kraanSnelheid;
}
}
}
else if(tegenstanderStatus == Status.MOVETO_ORIGIN_Y)
{
if(getY() == bestemmingY)
{
tegenstanderStatus = Status.MOVETO_DESTINATION_X;
//moveto destination op trein
bestemmingX = movePlan.get(currentRegel).destination.x * 2 + 17 + movePlan.get(currentRegel).containerSize - 1 + movePlan.get(currentRegel).destinationTreinstel*11;
bestemmingY = movePlan.get(currentRegel).destination.y * 2 + 2;
// onthou de container die we gaan verplaatsen
Actor containerActor = getOneObjectAtOffset(0, 0, Krat_vrachtoverslaan_tegenstander.class);
currentContainer = (Krat_vrachtoverslaan_tegenstander) containerActor;
}
else{
currentY = currentY + Math.signum(bestemmingY - currentY) * kraanSnelheid;
}
}
else if(tegenstanderStatus == Status.MOVETO_DESTINATION_X)
{
if(getX() == bestemmingX)
{
tegenstanderStatus = Status.MOVETO_DESTINATION_Y;
}
else{
currentX = currentX + Math.signum(bestemmingX - currentX) * kraanSnelheid;
//zorg ervoor dat de container meebeweegt
currentContainer.setLocation((int)currentX, (int)currentY);
}
}
else if(tegenstanderStatus == Status.MOVETO_DESTINATION_Y)
{
if(getY() == bestemmingY)
{
tegenstanderStatus = Status.WAITFORTRAIN;
// als de trein vol is, laat hem dan vertrekken
if (movePlan.get(currentRegel).treinVol)
{
Trein_vrachtoverslaan_tegenstander trein = (Trein_vrachtoverslaan_tegenstander) getWorld().getObjects(Trein_vrachtoverslaan_tegenstander.class).get(0);
trein.gaRijden();
}
}
else{
currentY = currentY + Math.signum(bestemmingY - currentY) * kraanSnelheid;
//zorg ervoor dat de container meebeweegt
currentContainer.setLocation((int)currentX, (int)currentY);
}
}
else if(tegenstanderStatus == Status.WAITFORTRAIN)
{
Trein_vrachtoverslaan_tegenstander trein = (Trein_vrachtoverslaan_tegenstander) getWorld().getObjects(Trein_vrachtoverslaan_tegenstander.class).get(0);
if(!trein.isAanHetRijden())
{
// moveto origin op boot
currentRegel++;
if (currentRegel < movePlan.size())
{
bestemmingX = movePlan.get(currentRegel).origin.x * 2 + 10 + movePlan.get(currentRegel).containerSize - 1;
bestemmingY = 18 - (movePlan.get(currentRegel).origin.y * 2);
tegenstanderStatus = Status.MOVETO_ORIGIN_X;
}
else{
//TEGENSTANDER HEFT GEWONNEN
int reply = JOptionPane.showConfirmDialog(null, "Helaas, u heeft verloren. Wilt u nog een keer spelen?", "Verloren!", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION){
getWorld().removeObject(this);
Greenfoot.setWorld(new VrachtOverslaan());
return;
}
else if(reply == JOptionPane.NO_OPTION){
Greenfoot.setWorld(new Menu());
return;
}
}
}
}
else if(tegenstanderStatus == Status.IDLE)
{
//PLAYER HEEFT GEWONNEN
//speler wint<SUF>
}
setLocation((int)currentX, (int)currentY);
// Move kraan tegenstander
KraanXding_tegenstander kraanXding = (KraanXding_tegenstander) getWorld().getObjects(KraanXding_tegenstander.class).get(0);
kraanXding.setLocation((int)currentX,kraanXding.getY());
}
public void setKraanSnelheid(double snelheid){
kraanSnelheid = snelheid;
}
}
|
169765_0 | package nl.hu.cisq1.lingo.trainer.domain;
import nl.hu.cisq1.lingo.trainer.domain.enumerations.Mark;
import nl.hu.cisq1.lingo.trainer.domain.enumerations.Round_States;
import nl.hu.cisq1.lingo.trainer.domain.exceptions.InvalidFeedbackException;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import static nl.hu.cisq1.lingo.trainer.domain.enumerations.Mark.ABSENT;
@Entity
public class Round {
public static final int max_attempts = 5;
@Id
@GeneratedValue
private Long id;
private String wordToGuess;
@Enumerated(EnumType.STRING)
private Round_States round_status = Round_States.PLAYING;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn
private final List<Feedback> feedbackHistory = new ArrayList<>();
public Round_States getRound_status() {
return round_status;
}
public void setRound_status(Round_States round_status) {
this.round_status = round_status;
}
public Round(String wordToGuess) {
this.wordToGuess = wordToGuess;
}
public Round() {
}
public String giveFirstHint(String wordToGuess) {
String firstHint = "";
if (wordToGuess.length() > 0) {
firstHint += wordToGuess.charAt(0);
for (int i = 1; i < wordToGuess.length(); i++) {
firstHint += ".";
}
}
return firstHint;
}
public void guess(String guess) {
if (guess.length() != this.wordToGuess.length()) {
throw new InvalidFeedbackException("Attempt is too long");
} else if(feedbackHistory.size() > 4) {
this.setRound_status(Round_States.ELIMINATED);
}
Feedback feedback = new Feedback(guess, this.generateMarks(guess));
feedbackHistory.add(feedback); // schrijf nog een test hiervoor + test dit
}
public List<Character> showFeedback(){
return feedbackHistory.get(feedbackHistory.size()-1).giveHint();
}
public List<Mark> generateMarks(String guess) {
List<Mark> marks = new ArrayList<>();
List<Character> presentList = new ArrayList<>();
int index = 0;
for (char character : wordToGuess.toCharArray()) {
if (guess.charAt(index) == character) {
marks.add(index, Mark.CORRECT);
index++;
continue;
} else if (!presentList.contains(guess.charAt(index))
&& wordToGuess.contains(Character.toString(guess.charAt(index)))) {
marks.add(index, Mark.PRESENT);
presentList.add(guess.charAt(index));
index++;
continue;
}
marks.add(index, ABSENT);
index++;
}
return marks;
}
public int calculateScore(){
return 5 * (5-feedbackHistory.size()) + 5;
}
}
| JBaltjes1997/HU_Lingo | cisq1-lingo-v2b-Lobohuargo822-main/src/main/java/nl/hu/cisq1/lingo/trainer/domain/Round.java | 906 | // schrijf nog een test hiervoor + test dit | line_comment | nl | package nl.hu.cisq1.lingo.trainer.domain;
import nl.hu.cisq1.lingo.trainer.domain.enumerations.Mark;
import nl.hu.cisq1.lingo.trainer.domain.enumerations.Round_States;
import nl.hu.cisq1.lingo.trainer.domain.exceptions.InvalidFeedbackException;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import static nl.hu.cisq1.lingo.trainer.domain.enumerations.Mark.ABSENT;
@Entity
public class Round {
public static final int max_attempts = 5;
@Id
@GeneratedValue
private Long id;
private String wordToGuess;
@Enumerated(EnumType.STRING)
private Round_States round_status = Round_States.PLAYING;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn
private final List<Feedback> feedbackHistory = new ArrayList<>();
public Round_States getRound_status() {
return round_status;
}
public void setRound_status(Round_States round_status) {
this.round_status = round_status;
}
public Round(String wordToGuess) {
this.wordToGuess = wordToGuess;
}
public Round() {
}
public String giveFirstHint(String wordToGuess) {
String firstHint = "";
if (wordToGuess.length() > 0) {
firstHint += wordToGuess.charAt(0);
for (int i = 1; i < wordToGuess.length(); i++) {
firstHint += ".";
}
}
return firstHint;
}
public void guess(String guess) {
if (guess.length() != this.wordToGuess.length()) {
throw new InvalidFeedbackException("Attempt is too long");
} else if(feedbackHistory.size() > 4) {
this.setRound_status(Round_States.ELIMINATED);
}
Feedback feedback = new Feedback(guess, this.generateMarks(guess));
feedbackHistory.add(feedback); // schrijf nog<SUF>
}
public List<Character> showFeedback(){
return feedbackHistory.get(feedbackHistory.size()-1).giveHint();
}
public List<Mark> generateMarks(String guess) {
List<Mark> marks = new ArrayList<>();
List<Character> presentList = new ArrayList<>();
int index = 0;
for (char character : wordToGuess.toCharArray()) {
if (guess.charAt(index) == character) {
marks.add(index, Mark.CORRECT);
index++;
continue;
} else if (!presentList.contains(guess.charAt(index))
&& wordToGuess.contains(Character.toString(guess.charAt(index)))) {
marks.add(index, Mark.PRESENT);
presentList.add(guess.charAt(index));
index++;
continue;
}
marks.add(index, ABSENT);
index++;
}
return marks;
}
public int calculateScore(){
return 5 * (5-feedbackHistory.size()) + 5;
}
}
|
23529_0 | package usb14.themeCourse.ee.application;
import java.util.SortedMap;
import java.util.TreeMap;
import usb14.themeCourse.ee.framework.Appliance;
import usb14.themeCourse.ee.framework.Controller;
import usb14.themeCourse.ee.framework.CostFunction;
public class Fridge extends Appliance{
public enum State {
ON, OFF
}
private State state;
private double temp;
private int time;
private int currentPrice;
private final int usage = 200;
private final int maxCost = CostFunction.MAX_COST;
// Constructor
public Fridge(String name) {
super(name);
this.state = State.OFF;
this.temp = 4;
this.time = 0;
SortedMap<Integer, Integer> function = new TreeMap<Integer, Integer>();
function.put(usage, 0);
super.setCostFunction(new CostFunction(function));
updateCostFunction();
}
// Queries
@Override
public int getCurrentUsage() {
return super.getCostFunction().getDemandByCost(currentPrice);
}
public State getState() {
return state;
}
public double getTemp(){
return temp;
}
// Commands
private void updateCostFunction(){
int cost;
if(time > 0 && time < 20)
cost = maxCost;
else
// Met deze functie zou de temperatuur tussen 3 en 7 graden moeten schommelen.
// Bij een prijs van 500 blijkt het tussen de 4 en 5 te blijven, dus er is wat
// marge om warmer of kouder te worden bij een hogere of lagere energieprijs.
cost = (int) Math.round(((temp-3.0)/4.0) * (float)maxCost);
if (cost < 0 ) cost = 0;
super.getCostFunction().updateCostForDemand(cost, usage);
}
@Override
public void updateState(){
int t = Controller.getInstance().getIntervalDuration();
// update temperature and time running
if(this.state == State.ON){
temp -= 0.05*t;
this.time += t;
} else {
temp += 0.025*t;
this.time = 0;
}
// update costfunction based on the new temperature and time running
this.updateCostFunction();
}
@Override
public void updatePrice(int price){
this.currentPrice = price;
// update state based on the current price
if(getCurrentUsage() == 0)
this.state = State.OFF;
else
this.state = State.ON;
setChanged();
notifyObservers();
}
}
| JElsinga/ThemeCourse | Framework/src/usb14/themeCourse/ee/application/Fridge.java | 774 | // Met deze functie zou de temperatuur tussen 3 en 7 graden moeten schommelen. | line_comment | nl | package usb14.themeCourse.ee.application;
import java.util.SortedMap;
import java.util.TreeMap;
import usb14.themeCourse.ee.framework.Appliance;
import usb14.themeCourse.ee.framework.Controller;
import usb14.themeCourse.ee.framework.CostFunction;
public class Fridge extends Appliance{
public enum State {
ON, OFF
}
private State state;
private double temp;
private int time;
private int currentPrice;
private final int usage = 200;
private final int maxCost = CostFunction.MAX_COST;
// Constructor
public Fridge(String name) {
super(name);
this.state = State.OFF;
this.temp = 4;
this.time = 0;
SortedMap<Integer, Integer> function = new TreeMap<Integer, Integer>();
function.put(usage, 0);
super.setCostFunction(new CostFunction(function));
updateCostFunction();
}
// Queries
@Override
public int getCurrentUsage() {
return super.getCostFunction().getDemandByCost(currentPrice);
}
public State getState() {
return state;
}
public double getTemp(){
return temp;
}
// Commands
private void updateCostFunction(){
int cost;
if(time > 0 && time < 20)
cost = maxCost;
else
// Met deze<SUF>
// Bij een prijs van 500 blijkt het tussen de 4 en 5 te blijven, dus er is wat
// marge om warmer of kouder te worden bij een hogere of lagere energieprijs.
cost = (int) Math.round(((temp-3.0)/4.0) * (float)maxCost);
if (cost < 0 ) cost = 0;
super.getCostFunction().updateCostForDemand(cost, usage);
}
@Override
public void updateState(){
int t = Controller.getInstance().getIntervalDuration();
// update temperature and time running
if(this.state == State.ON){
temp -= 0.05*t;
this.time += t;
} else {
temp += 0.025*t;
this.time = 0;
}
// update costfunction based on the new temperature and time running
this.updateCostFunction();
}
@Override
public void updatePrice(int price){
this.currentPrice = price;
// update state based on the current price
if(getCurrentUsage() == 0)
this.state = State.OFF;
else
this.state = State.ON;
setChanged();
notifyObservers();
}
}
|
7432_0 | public class Statements {
public static void main(String[] args) {
int startPositie = 1;
if (startPositie == 1) {
System.out.println("Jij start van pole-position.");
}
int cijfer = 2;
if (cijfer >= 8) {
System.out.println("je hebt een mooi cijfer");
} else if (cijfer >= 3) {
System.out.println("je komt in aanmerking voor een herkansing");
} else {
System.out.println("je bent gezakt voor deze leerlijn");
}
//Als je in Java twee variabelen van het datatype String met elkaar wilt vergelijken, doe je dat niet met de ==-operator, maar met de equals() of equalsIgnoreCase()-methode.
String voornaam = "Jef";
if (voornaam.equals("Jef")) {
System.out.println("jij hebt dit statement geschreven");
} else {
System.out.println("wie ben jij?");
}
int weekdag = 0; // verander deze waarde
String dag;
switch (weekdag) {
case 0:
dag = "zondag";
break;
case 1:
dag = "maandag";
break;
case 2:
dag = "dinsdag";
break;
case 3:
dag = "woensdag";
break;
case 4:
dag = "donderdag";
break;
case 5:
dag = "vrijdag";
break;
case 6:
dag = "zaterdag";
break;
default:
dag = "onbekend";
}
System.out.println("Het is: " + dag);
}
}
| JJ-Bas/herhaling-java | src/Statements.java | 486 | //Als je in Java twee variabelen van het datatype String met elkaar wilt vergelijken, doe je dat niet met de ==-operator, maar met de equals() of equalsIgnoreCase()-methode. | line_comment | nl | public class Statements {
public static void main(String[] args) {
int startPositie = 1;
if (startPositie == 1) {
System.out.println("Jij start van pole-position.");
}
int cijfer = 2;
if (cijfer >= 8) {
System.out.println("je hebt een mooi cijfer");
} else if (cijfer >= 3) {
System.out.println("je komt in aanmerking voor een herkansing");
} else {
System.out.println("je bent gezakt voor deze leerlijn");
}
//Als je<SUF>
String voornaam = "Jef";
if (voornaam.equals("Jef")) {
System.out.println("jij hebt dit statement geschreven");
} else {
System.out.println("wie ben jij?");
}
int weekdag = 0; // verander deze waarde
String dag;
switch (weekdag) {
case 0:
dag = "zondag";
break;
case 1:
dag = "maandag";
break;
case 2:
dag = "dinsdag";
break;
case 3:
dag = "woensdag";
break;
case 4:
dag = "donderdag";
break;
case 5:
dag = "vrijdag";
break;
case 6:
dag = "zaterdag";
break;
default:
dag = "onbekend";
}
System.out.println("Het is: " + dag);
}
}
|
180575_2 | package de.hs_el.streekmann.algodat.aufgabe1;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<E> implements List<E> {
//Variablen
public int currentCount = 0; //Var die die Anzahl der Listenaufrufe zählt
public int iteratorCount = 0; //Var die die Anzahl der Iterator List aufrufe Zählt
private class Node {
E element;
Node successor;
Node(E element) {
this.element = element;
this.successor = null; //erstellt nulltes Element (leeres Element)
}
}
Node firstNode;
Node lastNode;
Node emptyNode;
int numberOfElements;
public LinkedList() {
emptyNode = new Node (null);
firstNode = emptyNode;
lastNode = emptyNode;
numberOfElements = 0; //setzt die Anzahl der Elemente auf 0
}
//Methoden für die LinkedList
@Override
public boolean add(E element) {
Node addedNode = new Node(element);
lastNode.successor = addedNode;
lastNode = addedNode;
numberOfElements++;
return true;
}
@Override
public E get(int index) {
if (index < 0 || index >= numberOfElements) { //prüft ob der Index im Array liegt
throw new IndexOutOfBoundsException();
}
Node nodeAtCurrentIndex = firstNode.successor; //setzt die Var nodeAtCurrentIndex auf das erste Element das nicht das leere Element ist
currentCount = 0; //Var die die Anzahl der Listenaufrufe zählt
for (int currentIndex = 0; currentIndex < index; currentIndex++) { //geht durch die Liste bis zum gewünschten Index
nodeAtCurrentIndex = nodeAtCurrentIndex.successor; //setzt die Var nodeAtCurrentIndex auf das nächste Element
currentCount++; //zählt die Anzahl der Schleifendurchläufe (Aufgabe 3.1)
}
return nodeAtCurrentIndex.element;
}
//Aufgabe 3
@Override
public int getCurrentCount(int index){ //retunt die anzahl der Listenaufrufe
return currentCount;
}
@Override
public int getIteratorCount(){ //retunt die anzahl der Listenaufrufe im Iterator
return iteratorCount;
}
@Override
public int size() { //gibt die "länge" der Liste (Anzahl der Elemente zurück)
return numberOfElements;
}
@Override
public E remove(int index) { //entfernt ein Element an der Stelle index
if (index < 0 || index >= numberOfElements) { //prüft ob der Index im Array liegt
throw new IndexOutOfBoundsException();
}
// Allgemeiner Fall: Element in der Mitte oder am Ende entfernen
Node previousNode = firstNode; //setzt die Var previousNode auf das erste Element das nicht das leere Element ist
Node currentNode = previousNode.successor; //setzt die Var currentNode auf das zweite Element das nicht das leere Element ist
for (int currentIndex = 0; currentIndex < index; currentIndex++){ //geht durch die Liste bis zum gewünschten Index
previousNode = currentNode; //setzt die Var previousNode auf das Element das currentNode ist
currentNode = currentNode.successor; //setzt die Var currentNode auf den nachfolger der currentNode
}
if(index == numberOfElements -1) { //wenn der nachfolger des zu entfernenden Elements null ist...
lastNode = previousNode; //setzt die Var lastNode auf das vorherige Element
}
E removedElement = currentNode.element;
previousNode.successor = currentNode.successor; //setzt den nachfolger des vorherigen Elements auf den nachfolger des zu entfernenden Elements
numberOfElements--; //subtrahiert die Anzahl der Elemente um 1
return removedElement;
}
//notwendig?
private Node getNodeAtIndex(int index) { //gibt das Element an der Stelle index zurück
Node nodeAtCurrentIndex = firstNode;
for (int currentIndex = 0; currentIndex < index; currentIndex++) {
nodeAtCurrentIndex = nodeAtCurrentIndex.successor;
}
return nodeAtCurrentIndex;
}
@Override
public boolean remove(Object o) { //entfernt ein Element
Node previousNode = firstNode; //setzt die Var previousNode auf das erste Element das nicht das leere Element ist
Node currentNode = firstNode.successor; //setzt die Var currentNode auf das zweite Element das nicht das leere Element ist
while (currentNode != null) { //solange currentNode nicht null ist...
if (o == null ? currentNode.element == null : o.equals(currentNode.element)) { //prüft ob das Element null ist
// Spezialfall: Das erste Element(das nicht Empty/Null ist :D) der Liste wird entfernt!!!
if (previousNode != null) { //wenn previousNode nicht null ist...
previousNode.successor = currentNode.successor; //setzt den nachfolger des vorherigen Elements auf den nachfolger des zu entfernenden Elements
if(currentNode == lastNode) { //wenn der nachfolger des zu entfernenden Elements null ist...
lastNode = previousNode; //setzt die Var lastNode auf das vorherige Element
}
numberOfElements--;
return true; //Element gefunden und entfernt
}
}
previousNode = currentNode; //setzt previousNode auf das Element der currentNode
currentNode = currentNode.successor; //setzt currentNode auf den nachfolger der currentNode
}
return false; //Das gesuchte Element nicht gefunden und nicht entfernt
}
@Override
public int indexOf(Object o) {
int index = 0;
Node currentNode = firstNode;
while (currentNode != null) {
if (o == null ? currentNode.element == null : o.equals(currentNode.element)) {
// Das gesuchte Element wurde gefunden
return index -1;
}
currentNode = currentNode.successor;
index++;
}
return -1;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
Node nextNode = firstNode;
@Override
public boolean hasNext() {
return nextNode != null && nextNode.successor != null;
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
E element = nextNode.successor.element;
nextNode = nextNode.successor;
iteratorCount = 0;
iteratorCount++;
return element;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
} | JJOmin/AlgoDatTesting | src/main/java/de/hs_el/streekmann/algodat/aufgabe1/LinkedList.java | 1,785 | //erstellt nulltes Element (leeres Element) | line_comment | nl | package de.hs_el.streekmann.algodat.aufgabe1;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<E> implements List<E> {
//Variablen
public int currentCount = 0; //Var die die Anzahl der Listenaufrufe zählt
public int iteratorCount = 0; //Var die die Anzahl der Iterator List aufrufe Zählt
private class Node {
E element;
Node successor;
Node(E element) {
this.element = element;
this.successor = null; //erstellt nulltes<SUF>
}
}
Node firstNode;
Node lastNode;
Node emptyNode;
int numberOfElements;
public LinkedList() {
emptyNode = new Node (null);
firstNode = emptyNode;
lastNode = emptyNode;
numberOfElements = 0; //setzt die Anzahl der Elemente auf 0
}
//Methoden für die LinkedList
@Override
public boolean add(E element) {
Node addedNode = new Node(element);
lastNode.successor = addedNode;
lastNode = addedNode;
numberOfElements++;
return true;
}
@Override
public E get(int index) {
if (index < 0 || index >= numberOfElements) { //prüft ob der Index im Array liegt
throw new IndexOutOfBoundsException();
}
Node nodeAtCurrentIndex = firstNode.successor; //setzt die Var nodeAtCurrentIndex auf das erste Element das nicht das leere Element ist
currentCount = 0; //Var die die Anzahl der Listenaufrufe zählt
for (int currentIndex = 0; currentIndex < index; currentIndex++) { //geht durch die Liste bis zum gewünschten Index
nodeAtCurrentIndex = nodeAtCurrentIndex.successor; //setzt die Var nodeAtCurrentIndex auf das nächste Element
currentCount++; //zählt die Anzahl der Schleifendurchläufe (Aufgabe 3.1)
}
return nodeAtCurrentIndex.element;
}
//Aufgabe 3
@Override
public int getCurrentCount(int index){ //retunt die anzahl der Listenaufrufe
return currentCount;
}
@Override
public int getIteratorCount(){ //retunt die anzahl der Listenaufrufe im Iterator
return iteratorCount;
}
@Override
public int size() { //gibt die "länge" der Liste (Anzahl der Elemente zurück)
return numberOfElements;
}
@Override
public E remove(int index) { //entfernt ein Element an der Stelle index
if (index < 0 || index >= numberOfElements) { //prüft ob der Index im Array liegt
throw new IndexOutOfBoundsException();
}
// Allgemeiner Fall: Element in der Mitte oder am Ende entfernen
Node previousNode = firstNode; //setzt die Var previousNode auf das erste Element das nicht das leere Element ist
Node currentNode = previousNode.successor; //setzt die Var currentNode auf das zweite Element das nicht das leere Element ist
for (int currentIndex = 0; currentIndex < index; currentIndex++){ //geht durch die Liste bis zum gewünschten Index
previousNode = currentNode; //setzt die Var previousNode auf das Element das currentNode ist
currentNode = currentNode.successor; //setzt die Var currentNode auf den nachfolger der currentNode
}
if(index == numberOfElements -1) { //wenn der nachfolger des zu entfernenden Elements null ist...
lastNode = previousNode; //setzt die Var lastNode auf das vorherige Element
}
E removedElement = currentNode.element;
previousNode.successor = currentNode.successor; //setzt den nachfolger des vorherigen Elements auf den nachfolger des zu entfernenden Elements
numberOfElements--; //subtrahiert die Anzahl der Elemente um 1
return removedElement;
}
//notwendig?
private Node getNodeAtIndex(int index) { //gibt das Element an der Stelle index zurück
Node nodeAtCurrentIndex = firstNode;
for (int currentIndex = 0; currentIndex < index; currentIndex++) {
nodeAtCurrentIndex = nodeAtCurrentIndex.successor;
}
return nodeAtCurrentIndex;
}
@Override
public boolean remove(Object o) { //entfernt ein Element
Node previousNode = firstNode; //setzt die Var previousNode auf das erste Element das nicht das leere Element ist
Node currentNode = firstNode.successor; //setzt die Var currentNode auf das zweite Element das nicht das leere Element ist
while (currentNode != null) { //solange currentNode nicht null ist...
if (o == null ? currentNode.element == null : o.equals(currentNode.element)) { //prüft ob das Element null ist
// Spezialfall: Das erste Element(das nicht Empty/Null ist :D) der Liste wird entfernt!!!
if (previousNode != null) { //wenn previousNode nicht null ist...
previousNode.successor = currentNode.successor; //setzt den nachfolger des vorherigen Elements auf den nachfolger des zu entfernenden Elements
if(currentNode == lastNode) { //wenn der nachfolger des zu entfernenden Elements null ist...
lastNode = previousNode; //setzt die Var lastNode auf das vorherige Element
}
numberOfElements--;
return true; //Element gefunden und entfernt
}
}
previousNode = currentNode; //setzt previousNode auf das Element der currentNode
currentNode = currentNode.successor; //setzt currentNode auf den nachfolger der currentNode
}
return false; //Das gesuchte Element nicht gefunden und nicht entfernt
}
@Override
public int indexOf(Object o) {
int index = 0;
Node currentNode = firstNode;
while (currentNode != null) {
if (o == null ? currentNode.element == null : o.equals(currentNode.element)) {
// Das gesuchte Element wurde gefunden
return index -1;
}
currentNode = currentNode.successor;
index++;
}
return -1;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
Node nextNode = firstNode;
@Override
public boolean hasNext() {
return nextNode != null && nextNode.successor != null;
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
E element = nextNode.successor.element;
nextNode = nextNode.successor;
iteratorCount = 0;
iteratorCount++;
return element;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
} |
138877_27 | package edu.avans.hartigehap.service.testutil;
/**
* @author thom145
*/
public class MenuTestDrive {
// public static void main(String[] args) {
// MenuComponent allMenus = new PredefinedMenu("Alle menu's", "Alle menu's");
// MenuComponent hamburger = new PredefinedMenu("Hamburger menu", "Great hamburger for breakfast");
//
// MenuItem hamburgerItem = new Meal("Hamburger", "NietTeVinden.png", 3, "easy");
// MenuItem hamburgerBun = new Meal("HamburgerBuns", "Gevonden.png", 3, "hard");
// MenuItem lettuce = new Meal("Lettuce", "mooi.png", 3, "easy");
// MenuItem cheese = new Meal("Chees", "OokNietTeVinden.png", 1, "easy");
// MenuItem cheddarCheese = new Meal("Cheddar Cheese", "WatIsTest.wav", 1, "easy");
// MenuItem patty = new Meal("Patty", "Hoi.wav", 1, "easy");
// MenuItem bacon = new Meal("Bacon", "hmBacon.png", 1, "easy");
// MenuItem ketchup = new Meal("Ketchup", "Hoi.wav", 1, "hard");
// MenuItem americanCheese = new Meal("American Cheese", "WatIsTestTwee.wav", 1, "easy");
// MenuItem cokeItem = new Drink("Cola", "WaarIsDeze.jpg", 2, Drink.Size.LARGE);
// MenuItem francefrice = new Meal("France frice", "hoi.png", 1, "hard");
//
//
// cheese.add(cheddarCheese);
// cheese.add(cheddarCheese);
// cheese.add(americanCheese);
//
// hamburgerItem.add(hamburgerBun);
// hamburgerItem.add(patty);
// hamburgerItem.add(cheese);
// hamburgerItem.add(bacon);
// hamburgerItem.add(ketchup);
// hamburgerItem.add(lettuce);
// hamburger.add(cokeItem);
// hamburger.add(hamburgerItem);
// hamburger.add(francefrice);
//
// allMenus.add(hamburger);
//
// allMenus.print(1);
// }
// public static void main(String args[]) {
// MenuComponent pancakeHouseMenu =
// new MenuComposite("Pankoeken menu", "Breakfast");
// MenuComponent dinerMenu =
// new MenuComposite("Diner menu", "Lunch");
// MenuComponent cafeMenu =
// new MenuComposite("Cafe menu", "Dinner");
// MenuComponent dessertMenu =
// new MenuComposite("Toetjes menu", "Dessert of course!");
//
// MenuComponent allMenus = new MenuComposite("ALL MENUS", "All menus combined");
//
// allMenus.add(pancakeHouseMenu);
// allMenus.add(dinerMenu);
// allMenus.add(cafeMenu);
//
// pancakeHouseMenu.add(
// new Meal(
// "K&B's Pankoeken ontbijt",
// "Pannekoeken met ei en toast",
// 3, "easy"
// )
// );
//// pancakeHouseMenu.add(new MenuItemComposite(
//// "Normale panekoeken ontbijt",
//// "Panekoeken met gebakken ei en worst",
//// false,
//// 2.99));
//// pancakeHouseMenu.add(new MenuItemComposite(
//// "Blueberry Pancakes",
//// "Pancakes made with fresh blueberries, and blueberry syrup",
//// true,
//// 3.49));
//// pancakeHouseMenu.add(new MenuItemComposite(
//// "Waffles",
//// "Waffles, with your choice of blueberries or strawberries",
//// true,
//// 3.59));
////
//// dinerMenu.add(new MenuItemComposite(
//// "Vegetarian BLT",
//// "(Fakin') Bacon with lettuce & tomato on whole wheat",
//// true,
//// 2.99));
//// dinerMenu.add(new MenuItemComposite(
//// "BLT",
//// "Bacon with lettuce & tomato on whole wheat",
//// false,
//// 2.99));
//// dinerMenu.add(new MenuItemComposite(
//// "Soup of the day",
//// "A bowl of the soup of the day, with a side of potato salad",
//// false,
//// 3.29));
//// dinerMenu.add(new MenuItemComposite(
//// "Hotdog",
//// "A hot dog, with saurkraut, relish, onions, topped with cheese",
//// false,
//// 3.05));
//// dinerMenu.add(new MenuItemComposite(
//// "Steamed Veggies and Brown Rice",
//// "A medly of steamed vegetables over brown rice",
//// true,
//// 3.99));
////
//// dinerMenu.add(new MenuItemComposite(
//// "Pasta",
//// "Spaghetti with Marinara Sauce, and a slice of sourdough bread",
//// true,
//// 3.89));
////
//// dinerMenu.add(dessertMenu);
////
//// dessertMenu.add(new MenuItemComposite(
//// "Apple Pie",
//// "Apple pie with a flakey crust, topped with vanilla icecream",
//// true,
//// 1.59));
//// dessertMenu.add(new MenuItemComposite(
//// "Cheesecake",
//// "Creamy New York cheesecake, with a chocolate graham crust",
//// true,
//// 1.99));
//// dessertMenu.add(new MenuItemComposite(
//// "Sorbet",
//// "A scoop of raspberry and a scoop of lime",
//// true,
//// 1.89));
////
//// cafeMenu.add(new MenuItemComposite(
//// "Veggie Burger and Air Fries",
//// "Veggie burger on a whole wheat bun, lettuce, tomato, and fries",
//// true,
//// 3.99));
//// cafeMenu.add(new MenuItemComposite(
//// "Soup of the day",
//// "A cup of the soup of the day, with a side salad",
//// false,
//// 3.69));
//// cafeMenu.add(new MenuItemComposite(
//// "Burrito",
//// "A large burrito, with whole pinto beans, salsa, guacamole",
//// true,
//// 4.29));
//
//// dinerMenu.add(new MenuItemComposite("Paste", "Spaghettie with marina sacuse and ", true, 4.39));
//
// dinerMenu.add(dessertMenu);
//
//// dessertMenu.add(new MenuItemComposite("ApplePie", "Apple pie with a lil bit of stuff all over it", true, 1.59));
//
// Waitress waitress = new Waitress(allMenus);
//
// waitress.printMenu();
//
// }
}
| JKetelaar/hhspring | src/test/java/edu/avans/hartigehap/service/testutil/MenuTestDrive.java | 2,014 | //// "Normale panekoeken ontbijt", | line_comment | nl | package edu.avans.hartigehap.service.testutil;
/**
* @author thom145
*/
public class MenuTestDrive {
// public static void main(String[] args) {
// MenuComponent allMenus = new PredefinedMenu("Alle menu's", "Alle menu's");
// MenuComponent hamburger = new PredefinedMenu("Hamburger menu", "Great hamburger for breakfast");
//
// MenuItem hamburgerItem = new Meal("Hamburger", "NietTeVinden.png", 3, "easy");
// MenuItem hamburgerBun = new Meal("HamburgerBuns", "Gevonden.png", 3, "hard");
// MenuItem lettuce = new Meal("Lettuce", "mooi.png", 3, "easy");
// MenuItem cheese = new Meal("Chees", "OokNietTeVinden.png", 1, "easy");
// MenuItem cheddarCheese = new Meal("Cheddar Cheese", "WatIsTest.wav", 1, "easy");
// MenuItem patty = new Meal("Patty", "Hoi.wav", 1, "easy");
// MenuItem bacon = new Meal("Bacon", "hmBacon.png", 1, "easy");
// MenuItem ketchup = new Meal("Ketchup", "Hoi.wav", 1, "hard");
// MenuItem americanCheese = new Meal("American Cheese", "WatIsTestTwee.wav", 1, "easy");
// MenuItem cokeItem = new Drink("Cola", "WaarIsDeze.jpg", 2, Drink.Size.LARGE);
// MenuItem francefrice = new Meal("France frice", "hoi.png", 1, "hard");
//
//
// cheese.add(cheddarCheese);
// cheese.add(cheddarCheese);
// cheese.add(americanCheese);
//
// hamburgerItem.add(hamburgerBun);
// hamburgerItem.add(patty);
// hamburgerItem.add(cheese);
// hamburgerItem.add(bacon);
// hamburgerItem.add(ketchup);
// hamburgerItem.add(lettuce);
// hamburger.add(cokeItem);
// hamburger.add(hamburgerItem);
// hamburger.add(francefrice);
//
// allMenus.add(hamburger);
//
// allMenus.print(1);
// }
// public static void main(String args[]) {
// MenuComponent pancakeHouseMenu =
// new MenuComposite("Pankoeken menu", "Breakfast");
// MenuComponent dinerMenu =
// new MenuComposite("Diner menu", "Lunch");
// MenuComponent cafeMenu =
// new MenuComposite("Cafe menu", "Dinner");
// MenuComponent dessertMenu =
// new MenuComposite("Toetjes menu", "Dessert of course!");
//
// MenuComponent allMenus = new MenuComposite("ALL MENUS", "All menus combined");
//
// allMenus.add(pancakeHouseMenu);
// allMenus.add(dinerMenu);
// allMenus.add(cafeMenu);
//
// pancakeHouseMenu.add(
// new Meal(
// "K&B's Pankoeken ontbijt",
// "Pannekoeken met ei en toast",
// 3, "easy"
// )
// );
//// pancakeHouseMenu.add(new MenuItemComposite(
//// "Normale panekoeken<SUF>
//// "Panekoeken met gebakken ei en worst",
//// false,
//// 2.99));
//// pancakeHouseMenu.add(new MenuItemComposite(
//// "Blueberry Pancakes",
//// "Pancakes made with fresh blueberries, and blueberry syrup",
//// true,
//// 3.49));
//// pancakeHouseMenu.add(new MenuItemComposite(
//// "Waffles",
//// "Waffles, with your choice of blueberries or strawberries",
//// true,
//// 3.59));
////
//// dinerMenu.add(new MenuItemComposite(
//// "Vegetarian BLT",
//// "(Fakin') Bacon with lettuce & tomato on whole wheat",
//// true,
//// 2.99));
//// dinerMenu.add(new MenuItemComposite(
//// "BLT",
//// "Bacon with lettuce & tomato on whole wheat",
//// false,
//// 2.99));
//// dinerMenu.add(new MenuItemComposite(
//// "Soup of the day",
//// "A bowl of the soup of the day, with a side of potato salad",
//// false,
//// 3.29));
//// dinerMenu.add(new MenuItemComposite(
//// "Hotdog",
//// "A hot dog, with saurkraut, relish, onions, topped with cheese",
//// false,
//// 3.05));
//// dinerMenu.add(new MenuItemComposite(
//// "Steamed Veggies and Brown Rice",
//// "A medly of steamed vegetables over brown rice",
//// true,
//// 3.99));
////
//// dinerMenu.add(new MenuItemComposite(
//// "Pasta",
//// "Spaghetti with Marinara Sauce, and a slice of sourdough bread",
//// true,
//// 3.89));
////
//// dinerMenu.add(dessertMenu);
////
//// dessertMenu.add(new MenuItemComposite(
//// "Apple Pie",
//// "Apple pie with a flakey crust, topped with vanilla icecream",
//// true,
//// 1.59));
//// dessertMenu.add(new MenuItemComposite(
//// "Cheesecake",
//// "Creamy New York cheesecake, with a chocolate graham crust",
//// true,
//// 1.99));
//// dessertMenu.add(new MenuItemComposite(
//// "Sorbet",
//// "A scoop of raspberry and a scoop of lime",
//// true,
//// 1.89));
////
//// cafeMenu.add(new MenuItemComposite(
//// "Veggie Burger and Air Fries",
//// "Veggie burger on a whole wheat bun, lettuce, tomato, and fries",
//// true,
//// 3.99));
//// cafeMenu.add(new MenuItemComposite(
//// "Soup of the day",
//// "A cup of the soup of the day, with a side salad",
//// false,
//// 3.69));
//// cafeMenu.add(new MenuItemComposite(
//// "Burrito",
//// "A large burrito, with whole pinto beans, salsa, guacamole",
//// true,
//// 4.29));
//
//// dinerMenu.add(new MenuItemComposite("Paste", "Spaghettie with marina sacuse and ", true, 4.39));
//
// dinerMenu.add(dessertMenu);
//
//// dessertMenu.add(new MenuItemComposite("ApplePie", "Apple pie with a lil bit of stuff all over it", true, 1.59));
//
// Waitress waitress = new Waitress(allMenus);
//
// waitress.printMenu();
//
// }
}
|
14064_8 | package protocol;
public class Protocol {
/**
* @author Rosalyn.Sleurink
* @version 6
*/
/**
* Aanpassing versie 1 -> 2:
* Bij START worden de namen van de spelers niet meegegeven, dit is wel handig om te doen.
*
* Aanpassing versie 2 -> 3:
* - Version verdeeld in VERSION (String) en VERSIONNO (int)
* - Constantes BLACK en WHITE toegevoegd
*
* Aanpassing versie 3 -> 4:
* - Beide delimiters een String gemaakt en $ is //$ geworden.
*
* Aanpassing versie 4 -> 5:
* - Delimiter weer terugveranderd naar $.
* - Aan TURN zijn String FIRST en PASS toegevoegd
* - Tweede voorbeeld bij START is aangepast naar het format.
*
* Aanpassing versie 5 -> 6:
* - EXIT commando toegevoegd
* - Afspraak gemaakt dat bord grootte kan hebben van 5 t/m 19.
*/
/**
* OVERAL WAAR SPATIES STAAN KOMT DUS DELIMITER1 (in de voorbeelden en formats).
* OOK MOETEN ALLE COMMANDO'S EINDIGEN MET COMMAND_END.
*/
public static final int VERSION_NO = 6;
public static class Client {
/**
* Het eerste commando wat de client naar de server stuurt. Gaat om versie
* van het protocol. De volgorde van de extensions is als volgt:
* chat challenge leaderboard security 2+ simultaneous multiplemoves.<br>
* Format: NAME clientnaam VERSION versienummer EXTENSIONS boolean boolean boolean etc<br>
* Voorbeeld: NAME piet VERSION 2 EXTENSIONS 0 0 1 1 0 0 0
*/
public static final String NAME = "NAME";
public static final String VERSION = "VERSION";
public static final int VERSIONNO = VERSION_NO;
public static final String EXTENSIONS = "EXTENSIONS";
/**
* Om een move te communiceren. Bord begint linksboven met 0,0.<br>
* Format: MOVE rij_kolom of MOVE PASS<br>
* Voorbeeld: MOVE 1_3
*/
public static final String MOVE = "MOVE";
public static final String PASS = "PASS";
/**
* Als de server een START met aantal spelers heeft gestuurd mag je je voorkeur doorgeven
* voor kleur en grootte van het bord. Dit wordt gevraagd aan de speler die er als eerst
* was. Grootte van het bord mag van 5 t/m 19 zijn.<br>
* Format: SETTINGS kleur bordgrootte<br>
* Voorbeeld: SETTINGS BLACK 19
*/
public static final String SETTINGS = "SETTINGS";
/**
* Als je midden in een spel zit en wil stoppen. Je krijgt dan 0 punten.
* Wordt niet gestuurd als client abrupt.
* afgesloten wordt. Als je dit stuurt nadat je een REQUESTGAME hebt gedaan gebeurt er
* niks.<br>
* Format: QUIT<br>
* Voorbeeld: QUIT
*/
public static final String QUIT = "QUIT";
/**
* Kan gestuurd worden als je in een spel zit of in de lobby, betekent dat de Client
* helemaal weg gaat.<br>
* Format: EXIT<br>
* Voorbeeld: QUIT
*/
public static final String EXIT = "EXIT";
/**
* Sturen als je een spel wilt spelen. De eerste keer en als een spel afgelopen is opnieuw.
* Als je de Challenge extensie niet ondersteunt, stuur dan RANDOM in plaats van een naam.
* <br>
* Format: REQUESTGAME aantalspelers naamtegenspeler (RANDOM als je geen challenge doet)<br>
* Voorbeeld: REQUESTGAME 2 RANDOM of REQUESTGAME 2 piet
*/
public static final String REQUESTGAME = "REQUESTGAME";
public static final String RANDOM = "RANDOM";
// -------------- EXTENSIES ------------ //
/**
* Als je de uitdaging wil accepteren.<br>
* Format: ACCEPTGAME naamuitdager<br>
* Voorbeeld: ACCEPTGAME piet
*/
public static final String ACCEPTGAME = "ACCEPTGAME";
/**
* Als je de uitdaging niet accepteert.<br>
* Format: DECLINEGAME naamuitdager<br>
* Voorbeeld: DECLINEGAME piet
*/
public static final String DECLINEGAME = "DECLINEGAME";
/**
* Om op te vragen wie je allemaal kan uitdagen.<br>
* Format: LOBBY<br>
* Voorbeeld: LOBBY
*/
public static final String LOBBY = "LOBBY";
/**
* Om een chatbericht te sturen. Als je in een spel zit mogen alleen de spelers het zien.
* Als je in de lobby zit mag iedereen in de lobby het zien.<br>
* Format: CHAT bericht<br>
* Voorbeeld: CHAT hoi ik ben piet
*/
public static final String CHAT = "CHAT";
/**
* Om de leaderboard op te vragen. Overige queries moet je afspreken met anderen die ook
* leaderboard willen implementeren.<br>
* Format: LEADERBOARD<br>
* Voorbeeld: LEADERBOARD
*/
public static final String LEADERBOARD = "LEADERBOARD";
}
public static class Server {
/**
* Het eerste commando wat de server naar de client stuurt. Gaat om versie
* van het protocol. De volgorde van de extensions is als volgt:
* chat challenge leaderboard security 2+ simultaneous multiplemoves.<br>
* Format: NAME clientnaam VERSION versienummer EXTENSIONS boolean boolean boolean etc<br>
* Voorbeeld: NAME serverpiet VERSION 2 EXTENSIONS 0 0 1 1 0 0 0
*/
public static final String NAME = "NAME";
public static final String VERSION = "VERSION";
public static final int VERSIONNO = VERSION_NO;
public static final String EXTENSIONS = "EXTENSIONS";
/**
* Een spel starten. Dit stuur je naar de eerste speler. <br>
* Format: START aantalspelers (naar speler 1)<br>
* Format: START aantalspelers kleur bordgrootte speler1 speler2 (3, etc..)
* (naar alle spelers) Bordgrootte kan waarde hebben van 5 t/m 19.<br>
* Voorbeeld: START 2 of START 2 BLACK 19 jan piet
*/
public static final String START = "START";
/**
* Vertelt aan de spelers welke beurt er gedaan is. Speler1 is de speler die de beurt heeft
* gedaan, speler 2 de speler die nu aan de beurt is om een MOVE door te geven. Als dit de
* eerste beurt is zijn speler1 en speler2 allebei de speler die nu aan de beurt is, en dan
* stuur je FIRST i.p.v. de integers. Als de speler past geeft je PASS door ip.v. de
* integers.<br>
* Format: TURN speler1 rij_kolom speler2<br>
* Voorbeeld: TURN piet 1_3 jan of TURN piet FIRST piet
*/
public static final String TURN = "TURN";
public static final String FIRST = "FIRST";
public static final String PASS = "PASS";
/**
* Als het spel klaar is om welke reden dan ook. Reden kan zijn FINISHED (normaal einde),
* ABORTED (abrupt einde) of TIMEOUT (geen respons binnen redelijke tijd)<br>
* Format: ENDGAME reden winspeler score verliesspeler score<br>
* Voorbeeld: ENDGAME FINISHED piet 12 jan 10
*/
public static final String ENDGAME = "ENDGAME";
public static final String FINISHED = "FINISHED";
public static final String ABORTED = "ABORTED";
public static final String TIMEOUT = "TIMEOUT";
/**
* Errortypes die we gedefinieerd hebben: UNKNOWNCOMMAND, INVALIDMOVE, NAMETAKEN,
* INCOMPATIBLEPROTOCOL, OTHER.<br>
* Format: ERROR type bericht<br>
* Voorbeeld: ERROR NAMETAKEN de naam piet is al bezet
*/
public static final String ERROR = "ERROR";
public static final String UNKNOWN = "UNKNOWNCOMMAND";
public static final String INVALID = "INVALIDMOVE";
public static final String NAMETAKEN = "NAMETAKEN";
public static final String INCOMPATIBLEPROTOCOL = "INCOMPATIBLEPROTOCOL";
public static final String OTHER = "OTHER";
// -------------- EXTENSIES ------------ //
/**
* Stuurt aan één client wie hem heeft uitgedaagd.<br>
* Format: REQUESTGAME uitdager<br>
* Voorbeeld: REQUESTGAME piet
*/
public static final String REQUESTGAME = "REQUESTGAME";
/**
* Stuurt aan de uitdager dat de uitdaging is geweigerd en door wie.<br>
* Format: DECLINED uitgedaagde<br>
* Voorbeeld: DECLINED piet
*/
public static final String DECLINED = "DECLINED";
/**
* Reactie op LOBBY van de client. Stuurt alle spelers die uitgedaagd kunnen worden
* (in de lobby zitten).<br>
* Format: LOBBY naam1_naam2_naam3<br>
* Voorbeeld: LOBBY piet jan koos
*/
public static final String LOBBY = "LOBBY";
/**
* Stuurt chatbericht naar relevante clients (in spel of in lobby).<br>
* Format: CHAT naam bericht<br>
* Voorbeeld: CHAT piet hallo ik ben piet (Met correcte delimiter ziet dat er dus uit als:
* CHAT$piet$hallo ik ben piet)
*/
public static final String CHAT = "CHAT";
/**
* Reactie op LEADERBOARD van client. Stuurt de beste 10 scores naar één client.
* Overige queries moet je afspreken met anderen die ook
* leaderboard willen implementeren.<br>
* Format: LEADERBOARD naam1 score1 naam2 score2 naam3 score3 enz<br>
* Voorbeeld: LEADERBOARD piet 1834897 jan 2 koos 1
*/
public static final String LEADERBOARD = "LEADERBOARD";
}
public static class General {
/**
* ENCODING kun je ergens bij je printstream/bufferedreader/writer instellen (zie API).
*/
public static final String ENCODING = "UTF-8";
public static final int TIMEOUTSECONDS = 90;
public static final short DEFAULT_PORT = 5647;
public static final String DELIMITER1 = "$";
public static final String DELIMITER2 = "_";
public static final String COMMAND_END = "\n";
public static final String BLACK = "BLACK";
public static final String WHITE = "WHITE";
}
}
| JKleinRot/NedapUniversity_FinalAssignment | src/protocol/Protocol.java | 3,062 | /**
* Sturen als je een spel wilt spelen. De eerste keer en als een spel afgelopen is opnieuw.
* Als je de Challenge extensie niet ondersteunt, stuur dan RANDOM in plaats van een naam.
* <br>
* Format: REQUESTGAME aantalspelers naamtegenspeler (RANDOM als je geen challenge doet)<br>
* Voorbeeld: REQUESTGAME 2 RANDOM of REQUESTGAME 2 piet
*/ | block_comment | nl | package protocol;
public class Protocol {
/**
* @author Rosalyn.Sleurink
* @version 6
*/
/**
* Aanpassing versie 1 -> 2:
* Bij START worden de namen van de spelers niet meegegeven, dit is wel handig om te doen.
*
* Aanpassing versie 2 -> 3:
* - Version verdeeld in VERSION (String) en VERSIONNO (int)
* - Constantes BLACK en WHITE toegevoegd
*
* Aanpassing versie 3 -> 4:
* - Beide delimiters een String gemaakt en $ is //$ geworden.
*
* Aanpassing versie 4 -> 5:
* - Delimiter weer terugveranderd naar $.
* - Aan TURN zijn String FIRST en PASS toegevoegd
* - Tweede voorbeeld bij START is aangepast naar het format.
*
* Aanpassing versie 5 -> 6:
* - EXIT commando toegevoegd
* - Afspraak gemaakt dat bord grootte kan hebben van 5 t/m 19.
*/
/**
* OVERAL WAAR SPATIES STAAN KOMT DUS DELIMITER1 (in de voorbeelden en formats).
* OOK MOETEN ALLE COMMANDO'S EINDIGEN MET COMMAND_END.
*/
public static final int VERSION_NO = 6;
public static class Client {
/**
* Het eerste commando wat de client naar de server stuurt. Gaat om versie
* van het protocol. De volgorde van de extensions is als volgt:
* chat challenge leaderboard security 2+ simultaneous multiplemoves.<br>
* Format: NAME clientnaam VERSION versienummer EXTENSIONS boolean boolean boolean etc<br>
* Voorbeeld: NAME piet VERSION 2 EXTENSIONS 0 0 1 1 0 0 0
*/
public static final String NAME = "NAME";
public static final String VERSION = "VERSION";
public static final int VERSIONNO = VERSION_NO;
public static final String EXTENSIONS = "EXTENSIONS";
/**
* Om een move te communiceren. Bord begint linksboven met 0,0.<br>
* Format: MOVE rij_kolom of MOVE PASS<br>
* Voorbeeld: MOVE 1_3
*/
public static final String MOVE = "MOVE";
public static final String PASS = "PASS";
/**
* Als de server een START met aantal spelers heeft gestuurd mag je je voorkeur doorgeven
* voor kleur en grootte van het bord. Dit wordt gevraagd aan de speler die er als eerst
* was. Grootte van het bord mag van 5 t/m 19 zijn.<br>
* Format: SETTINGS kleur bordgrootte<br>
* Voorbeeld: SETTINGS BLACK 19
*/
public static final String SETTINGS = "SETTINGS";
/**
* Als je midden in een spel zit en wil stoppen. Je krijgt dan 0 punten.
* Wordt niet gestuurd als client abrupt.
* afgesloten wordt. Als je dit stuurt nadat je een REQUESTGAME hebt gedaan gebeurt er
* niks.<br>
* Format: QUIT<br>
* Voorbeeld: QUIT
*/
public static final String QUIT = "QUIT";
/**
* Kan gestuurd worden als je in een spel zit of in de lobby, betekent dat de Client
* helemaal weg gaat.<br>
* Format: EXIT<br>
* Voorbeeld: QUIT
*/
public static final String EXIT = "EXIT";
/**
* Sturen als je<SUF>*/
public static final String REQUESTGAME = "REQUESTGAME";
public static final String RANDOM = "RANDOM";
// -------------- EXTENSIES ------------ //
/**
* Als je de uitdaging wil accepteren.<br>
* Format: ACCEPTGAME naamuitdager<br>
* Voorbeeld: ACCEPTGAME piet
*/
public static final String ACCEPTGAME = "ACCEPTGAME";
/**
* Als je de uitdaging niet accepteert.<br>
* Format: DECLINEGAME naamuitdager<br>
* Voorbeeld: DECLINEGAME piet
*/
public static final String DECLINEGAME = "DECLINEGAME";
/**
* Om op te vragen wie je allemaal kan uitdagen.<br>
* Format: LOBBY<br>
* Voorbeeld: LOBBY
*/
public static final String LOBBY = "LOBBY";
/**
* Om een chatbericht te sturen. Als je in een spel zit mogen alleen de spelers het zien.
* Als je in de lobby zit mag iedereen in de lobby het zien.<br>
* Format: CHAT bericht<br>
* Voorbeeld: CHAT hoi ik ben piet
*/
public static final String CHAT = "CHAT";
/**
* Om de leaderboard op te vragen. Overige queries moet je afspreken met anderen die ook
* leaderboard willen implementeren.<br>
* Format: LEADERBOARD<br>
* Voorbeeld: LEADERBOARD
*/
public static final String LEADERBOARD = "LEADERBOARD";
}
public static class Server {
/**
* Het eerste commando wat de server naar de client stuurt. Gaat om versie
* van het protocol. De volgorde van de extensions is als volgt:
* chat challenge leaderboard security 2+ simultaneous multiplemoves.<br>
* Format: NAME clientnaam VERSION versienummer EXTENSIONS boolean boolean boolean etc<br>
* Voorbeeld: NAME serverpiet VERSION 2 EXTENSIONS 0 0 1 1 0 0 0
*/
public static final String NAME = "NAME";
public static final String VERSION = "VERSION";
public static final int VERSIONNO = VERSION_NO;
public static final String EXTENSIONS = "EXTENSIONS";
/**
* Een spel starten. Dit stuur je naar de eerste speler. <br>
* Format: START aantalspelers (naar speler 1)<br>
* Format: START aantalspelers kleur bordgrootte speler1 speler2 (3, etc..)
* (naar alle spelers) Bordgrootte kan waarde hebben van 5 t/m 19.<br>
* Voorbeeld: START 2 of START 2 BLACK 19 jan piet
*/
public static final String START = "START";
/**
* Vertelt aan de spelers welke beurt er gedaan is. Speler1 is de speler die de beurt heeft
* gedaan, speler 2 de speler die nu aan de beurt is om een MOVE door te geven. Als dit de
* eerste beurt is zijn speler1 en speler2 allebei de speler die nu aan de beurt is, en dan
* stuur je FIRST i.p.v. de integers. Als de speler past geeft je PASS door ip.v. de
* integers.<br>
* Format: TURN speler1 rij_kolom speler2<br>
* Voorbeeld: TURN piet 1_3 jan of TURN piet FIRST piet
*/
public static final String TURN = "TURN";
public static final String FIRST = "FIRST";
public static final String PASS = "PASS";
/**
* Als het spel klaar is om welke reden dan ook. Reden kan zijn FINISHED (normaal einde),
* ABORTED (abrupt einde) of TIMEOUT (geen respons binnen redelijke tijd)<br>
* Format: ENDGAME reden winspeler score verliesspeler score<br>
* Voorbeeld: ENDGAME FINISHED piet 12 jan 10
*/
public static final String ENDGAME = "ENDGAME";
public static final String FINISHED = "FINISHED";
public static final String ABORTED = "ABORTED";
public static final String TIMEOUT = "TIMEOUT";
/**
* Errortypes die we gedefinieerd hebben: UNKNOWNCOMMAND, INVALIDMOVE, NAMETAKEN,
* INCOMPATIBLEPROTOCOL, OTHER.<br>
* Format: ERROR type bericht<br>
* Voorbeeld: ERROR NAMETAKEN de naam piet is al bezet
*/
public static final String ERROR = "ERROR";
public static final String UNKNOWN = "UNKNOWNCOMMAND";
public static final String INVALID = "INVALIDMOVE";
public static final String NAMETAKEN = "NAMETAKEN";
public static final String INCOMPATIBLEPROTOCOL = "INCOMPATIBLEPROTOCOL";
public static final String OTHER = "OTHER";
// -------------- EXTENSIES ------------ //
/**
* Stuurt aan één client wie hem heeft uitgedaagd.<br>
* Format: REQUESTGAME uitdager<br>
* Voorbeeld: REQUESTGAME piet
*/
public static final String REQUESTGAME = "REQUESTGAME";
/**
* Stuurt aan de uitdager dat de uitdaging is geweigerd en door wie.<br>
* Format: DECLINED uitgedaagde<br>
* Voorbeeld: DECLINED piet
*/
public static final String DECLINED = "DECLINED";
/**
* Reactie op LOBBY van de client. Stuurt alle spelers die uitgedaagd kunnen worden
* (in de lobby zitten).<br>
* Format: LOBBY naam1_naam2_naam3<br>
* Voorbeeld: LOBBY piet jan koos
*/
public static final String LOBBY = "LOBBY";
/**
* Stuurt chatbericht naar relevante clients (in spel of in lobby).<br>
* Format: CHAT naam bericht<br>
* Voorbeeld: CHAT piet hallo ik ben piet (Met correcte delimiter ziet dat er dus uit als:
* CHAT$piet$hallo ik ben piet)
*/
public static final String CHAT = "CHAT";
/**
* Reactie op LEADERBOARD van client. Stuurt de beste 10 scores naar één client.
* Overige queries moet je afspreken met anderen die ook
* leaderboard willen implementeren.<br>
* Format: LEADERBOARD naam1 score1 naam2 score2 naam3 score3 enz<br>
* Voorbeeld: LEADERBOARD piet 1834897 jan 2 koos 1
*/
public static final String LEADERBOARD = "LEADERBOARD";
}
public static class General {
/**
* ENCODING kun je ergens bij je printstream/bufferedreader/writer instellen (zie API).
*/
public static final String ENCODING = "UTF-8";
public static final int TIMEOUTSECONDS = 90;
public static final short DEFAULT_PORT = 5647;
public static final String DELIMITER1 = "$";
public static final String DELIMITER2 = "_";
public static final String COMMAND_END = "\n";
public static final String BLACK = "BLACK";
public static final String WHITE = "WHITE";
}
}
|
16645_5 | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.commander;
import com.intellij.diff.actions.CompareFilesAction;
import com.intellij.ide.CopyPasteDelegator;
import com.intellij.ide.PsiCopyPasteManager;
import com.intellij.ide.TwoPaneIdeView;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.AbstractProjectTreeStructure;
import com.intellij.ide.projectView.impl.ProjectAbstractTreeStructureBase;
import com.intellij.ide.ui.customization.CustomActionsSchema;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.ide.util.treeView.AlphaComparator;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.components.StoragePathMacros;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.wm.*;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.AutoScrollToSourceHandler;
import com.intellij.ui.PopupHandler;
import com.intellij.util.ObjectUtils;
import com.intellij.util.SmartList;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.List;
import static com.intellij.ide.commander.CommanderPanel.getNodeElement;
import static com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy.getPreferredFocusedComponent;
/**
* @author Eugene Belyaev
*/
@State(name = "Commander", storages = @Storage(StoragePathMacros.WORKSPACE_FILE))
public class Commander extends JPanel implements PersistentStateComponent<Element>, DataProvider, TwoPaneIdeView, Disposable {
private final Project project;
private CommanderPanel myLeftPanel;
private CommanderPanel myRightPanel;
private final Splitter mySplitter;
private final ListSelectionListener mySelectionListener;
private final ListDataListener myListDataListener;
public boolean MOVE_FOCUS = true; // internal option: move focus to editor when class/file/...etc. is created
private Element myElement;
private final FocusWatcher myFocusWatcher;
private final CommanderHistory myHistory;
private boolean myAutoScrollMode;
@NonNls private static final String ACTION_BACKCOMMAND = "backCommand";
@NonNls private static final String ACTION_FORWARDCOMMAND = "forwardCommand";
@NonNls private static final String ELEMENT_LEFTPANEL = "leftPanel";
@NonNls private static final String ATTRIBUTE_MOVE_FOCUS = "MOVE_FOCUS";
@NonNls private static final String ELEMENT_OPTION = "OPTION";
@NonNls private static final String ATTRIBUTE_PROPORTION = "proportion";
@NonNls private static final String ELEMENT_SPLITTER = "splitter";
@NonNls private static final String ELEMENT_RIGHTPANEL = "rightPanel";
@NonNls private static final String ATTRIBUTE_URL = "url";
@NonNls private static final String ATTRIBUTE_CLASS = "class";
public Commander(Project project) {
super(new BorderLayout());
this.project = project;
final AbstractAction backAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
myHistory.back();
}
};
final AbstractAction fwdAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
myHistory.forward();
}
};
KeymapManager keymapManager = KeymapManager.getInstance();
final ActionMap actionMap = getActionMap();
actionMap.put(ACTION_BACKCOMMAND, backAction);
actionMap.put(ACTION_FORWARDCOMMAND, fwdAction);
for (KeyStroke stroke : getKeyStrokes(IdeActions.ACTION_GOTO_BACK, keymapManager)) {
//getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "backCommand");
//getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(stroke, "backCommand");
registerKeyboardAction(backAction, ACTION_BACKCOMMAND, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
registerKeyboardAction(backAction, ACTION_BACKCOMMAND, stroke, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
for (KeyStroke stroke : getKeyStrokes(IdeActions.ACTION_GOTO_FORWARD, keymapManager)) {
//getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "forwardCommand");
//getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(stroke, "forwardCommand");
registerKeyboardAction(fwdAction, ACTION_FORWARDCOMMAND, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
registerKeyboardAction(fwdAction, ACTION_FORWARDCOMMAND, stroke, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
myHistory = new CommanderHistory(this);
mySelectionListener = new ListSelectionListener() {
@Override
public void valueChanged(final ListSelectionEvent e) {
updateToolWindowTitle();
}
};
myListDataListener = new ListDataListener() {
@Override
public void intervalAdded(final ListDataEvent e) {
updateToolWindowTitle();
}
@Override
public void intervalRemoved(final ListDataEvent e) {
updateToolWindowTitle();
}
@Override
public void contentsChanged(final ListDataEvent e) {
updateToolWindowTitle();
}
};
myFocusWatcher = new FocusWatcher();
myLeftPanel = createPanel();
myLeftPanel.addHistoryListener(new CommanderHistoryListener() {
@Override
public void historyChanged(final PsiElement selectedElement, final boolean elementExpanded) {
getCommandHistory().saveState(selectedElement, elementExpanded, true);
}
});
myRightPanel = createPanel();
myRightPanel.addHistoryListener(new CommanderHistoryListener() {
@Override
public void historyChanged(final PsiElement selectedElement, final boolean elementExpanded) {
getCommandHistory().saveState(selectedElement, elementExpanded, false);
}
});
mySplitter = new Splitter();
mySplitter.setFirstComponent(myLeftPanel);
mySplitter.setSecondComponent(myRightPanel);
add(mySplitter, BorderLayout.CENTER);
final AutoScrollToSourceHandler handler = new AutoScrollToSourceHandler() {
@Override
protected boolean isAutoScrollMode() {
return myAutoScrollMode;
}
@Override
protected void setAutoScrollMode(boolean state) {
myAutoScrollMode = state;
}
};
handler.install(myLeftPanel.getList());
handler.install(myRightPanel.getList());
final boolean shouldAddToolbar = !ApplicationManager.getApplication().isUnitTestMode();
if (shouldAddToolbar) {
final DefaultActionGroup toolbarActions = createToolbarActions();
toolbarActions.add(handler.createToggleAction());
final ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.COMMANDER_TOOLBAR, toolbarActions, true);
add(toolbar.getComponent(), BorderLayout.NORTH);
}
myFocusWatcher.install(this);
}
public static Commander getInstance(final Project project) {
return project.getService(Commander.class);
}
public CommanderHistory getCommandHistory() {
return myHistory;
}
private void processConfigurationElement() {
if (myElement == null) return;
Element element = myElement.getChild(ELEMENT_LEFTPANEL);
if (element != null) {
final PsiElement parentElement = readParentElement(element);
if (parentElement != null) {
myLeftPanel.getBuilder().enterElement(parentElement, PsiUtilCore.getVirtualFile(parentElement));
}
}
element = myElement.getChild(ELEMENT_RIGHTPANEL);
if (element != null) {
final PsiElement parentElement = readParentElement(element);
if (parentElement != null) {
myRightPanel.getBuilder().enterElement(parentElement, PsiUtilCore.getVirtualFile(parentElement));
}
}
element = myElement.getChild(ELEMENT_SPLITTER);
if (element != null) {
final String attribute = element.getAttributeValue(ATTRIBUTE_PROPORTION);
if (attribute != null) {
try {
final float proportion = Float.valueOf(attribute).floatValue();
if (proportion >= 0 && proportion <= 1) {
mySplitter.setProportion(proportion);
}
}
catch (NumberFormatException ignored) {
}
}
}
element = myElement.getChild(ELEMENT_OPTION);
if (element != null) {
//noinspection HardCodedStringLiteral
MOVE_FOCUS = !"false".equals(element.getAttributeValue(ATTRIBUTE_MOVE_FOCUS));
}
myLeftPanel.setActive(false);
myRightPanel.setActive(false);
myLeftPanel.setMoveFocus(MOVE_FOCUS);
myRightPanel.setMoveFocus(MOVE_FOCUS);
myElement = null;
}
private static KeyStroke[] getKeyStrokes(String actionId, KeymapManager keymapManager) {
List<KeyStroke> strokes = new SmartList<>();
for (Shortcut shortcut : keymapManager.getActiveKeymap().getShortcuts(actionId)) {
if (shortcut instanceof KeyboardShortcut) {
strokes.add(((KeyboardShortcut)shortcut).getFirstKeyStroke());
}
}
return strokes.toArray(new KeyStroke[0]);
}
private DefaultActionGroup createToolbarActions() {
final ActionManager actionManager = ActionManager.getInstance();
final DefaultActionGroup group = new DefaultActionGroup();
final AnAction backAction = new AnAction() {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
myHistory.back();
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabled(myHistory.canGoBack());
}
@Override
public @NotNull ActionUpdateThread getActionUpdateThread() {
return ActionUpdateThread.EDT;
}
};
ActionUtil.copyFrom(backAction, IdeActions.ACTION_GOTO_BACK);
group.add(backAction);
final AnAction forwardAction = new AnAction() {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
myHistory.forward();
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabled(myHistory.canGoForward());
}
@Override
public @NotNull ActionUpdateThread getActionUpdateThread() {
return ActionUpdateThread.EDT;
}
};
ActionUtil.copyFrom(forwardAction, IdeActions.ACTION_GOTO_FORWARD);
group.add(forwardAction);
group.add(actionManager.getAction("CommanderSwapPanels"));
group.add(actionManager.getAction("CommanderSyncViews"));
return group;
}
private CommanderPanel createPanel() {
final CommanderPanel panel = new CommanderPluginPanel(project, true, false);
panel.getList().addKeyListener(new PsiCopyPasteManager.EscapeHandler());
final ProjectAbstractTreeStructureBase treeStructure = createProjectTreeStructure();
panel.setBuilder(new ProjectListBuilder(project, panel, treeStructure, AlphaComparator.INSTANCE, true));
panel.setProjectTreeStructure(treeStructure);
final FocusAdapter focusListener = new FocusAdapter() {
@Override
public void focusGained(final FocusEvent e) {
updateToolWindowTitle(panel);
}
};
final JList list = panel.getList();
list.addFocusListener(focusListener);
list.getSelectionModel().addListSelectionListener(mySelectionListener);
list.getModel().addListDataListener(myListDataListener);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
list.removeFocusListener(focusListener);
list.getSelectionModel().removeListSelectionListener(mySelectionListener);
list.getModel().removeListDataListener(myListDataListener);
}
});
return panel;
}
protected AbstractProjectTreeStructure createProjectTreeStructure() {
return new AbstractProjectTreeStructure(project) {
@Override
public boolean isShowMembers() {
return true;
}
@Override
public boolean isShowModules() {
return false;
}
};
}
/**
* invoked in AWT thread
*/
private void updateToolWindowTitle() {
final CommanderPanel panel = getActivePanel();
updateToolWindowTitle(panel);
}
protected void updateToolWindowTitle(CommanderPanel activePanel) {
ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.COMMANDER);
if (toolWindow != null) {
AbstractTreeNode<?> node = activePanel.getSelectedNode();
if (node instanceof ProjectViewNode) {
toolWindow.setTitle(ObjectUtils.notNull(((ProjectViewNode<?>)node).getTitle(), ""));
}
}
}
public boolean isLeftPanelActive() {
return isPanelActive(myLeftPanel);
}
boolean isPanelActive(final CommanderPanel panel) {
return panel.getList() == myFocusWatcher.getFocusedComponent();
}
public void selectElementInLeftPanel(final Object element, VirtualFile virtualFile) {
myLeftPanel.getBuilder().selectElement(element, virtualFile);
if (!isPanelActive(myLeftPanel)) {
switchActivePanel();
}
}
public void selectElementInRightPanel(final Object element, VirtualFile virtualFile) {
myRightPanel.getBuilder().selectElement(element, virtualFile);
if (!isPanelActive(myRightPanel)) {
switchActivePanel();
}
}
public void switchActivePanel() {
final CommanderPanel activePanel = getActivePanel();
final CommanderPanel inactivePanel = getInactivePanel();
inactivePanel.setActive(true);
activePanel.setActive(false);
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(getPreferredFocusedComponent(inactivePanel), true));
}
public void enterElementInActivePanel(final PsiElement element) {
final CommanderPanel activePanel = isLeftPanelActive() ? myLeftPanel : myRightPanel;
activePanel.getBuilder().enterElement(element, PsiUtilCore.getVirtualFile(element));
}
public void swapPanels() {
mySplitter.swapComponents();
final CommanderPanel tmpPanel = myLeftPanel;
myLeftPanel = myRightPanel;
myRightPanel = tmpPanel;
}
public void syncViews() {
final CommanderPanel activePanel;
final CommanderPanel passivePanel;
if (isLeftPanelActive()) {
activePanel = myLeftPanel;
passivePanel = myRightPanel;
} else {
activePanel = myRightPanel;
passivePanel = myLeftPanel;
}
ProjectViewNode element = (ProjectViewNode)activePanel.getBuilder().getParentNode();
passivePanel.getBuilder().enterElement(element);
}
public CommanderPanel getActivePanel() {
return isLeftPanelActive() ? myLeftPanel : myRightPanel;
}
public CommanderPanel getInactivePanel() {
return !isLeftPanelActive() ? myLeftPanel : myRightPanel;
}
@Override
public Object getData(@NotNull final String dataId) {
if (PlatformCoreDataKeys.HELP_ID.is(dataId)) {
return "viewingStructure.commander";
}
else if (CommonDataKeys.PROJECT.is(dataId)) {
return project;
}
else if (PlatformCoreDataKeys.BGT_DATA_PROVIDER.is(dataId)) {
AbstractTreeNode<?> parent1 = getActivePanel().getBuilder().getParentNode();
AbstractTreeNode<?> selection1 = getActivePanel().getSelectedNode();
AbstractTreeNode<?> parent2 = getInactivePanel().getBuilder().getParentNode();
AbstractTreeNode<?> selection2 = getInactivePanel().getSelectedNode();
Couple<AbstractTreeNode<?>> activeSelection = Couple.of(parent1, selection1);
Couple<AbstractTreeNode<?>> inactiveSelection = Couple.of(parent2, selection2);
DataProvider panelProvider = (DataProvider)getActivePanel().getDataImpl(dataId);
return CompositeDataProvider.compose(slowId -> getSlowData(slowId, activeSelection, inactiveSelection), panelProvider);
}
else {
return getActivePanel().getDataImpl(dataId);
}
}
private static @Nullable Object getSlowData(@NotNull String dataId,
@NotNull Couple<AbstractTreeNode<?>> active,
@NotNull Couple<AbstractTreeNode<?>> inactive) {
if (LangDataKeys.TARGET_PSI_ELEMENT.is(dataId)) {
return getNodeElement(inactive.first);
}
else if (CompareFilesAction.DIFF_REQUEST.is(dataId)) {
PsiElement primary = getNodeElement(active.second);
PsiElement secondary = getNodeElement(inactive.second);
if (primary != null && secondary != null &&
primary.isValid() && secondary.isValid() &&
!PsiTreeUtil.isAncestor(primary, secondary, false) &&
!PsiTreeUtil.isAncestor(secondary, primary, false)) {
return PsiDiffContentFactory.comparePsiElements(primary, secondary);
}
}
return null;
}
@Override
public Element getState() {
Element element = new Element("commander");
if (myLeftPanel == null || myRightPanel == null) {
return element;
}
PsiDocumentManager.getInstance(project).commitAllDocuments();
Element e = new Element(ELEMENT_LEFTPANEL);
element.addContent(e);
writePanel(myLeftPanel, e);
e = new Element(ELEMENT_RIGHTPANEL);
element.addContent(e);
writePanel(myRightPanel, e);
e = new Element(ELEMENT_SPLITTER);
element.addContent(e);
e.setAttribute(ATTRIBUTE_PROPORTION, Float.toString(mySplitter.getProportion()));
if (!MOVE_FOCUS) {
e = new Element(ELEMENT_OPTION);
element.addContent(e);
e.setAttribute(ATTRIBUTE_MOVE_FOCUS, "false");
}
return element;
}
private static void writePanel(final CommanderPanel panel, final Element element) {
/*TODO[anton,vova]: it's a patch!!!*/
final AbstractListBuilder builder = panel.getBuilder();
if (builder == null) return;
final AbstractTreeNode parentNode = builder.getParentNode();
final Object parentElement = parentNode != null? parentNode.getValue() : null;
if (parentElement instanceof PsiDirectory directory) {
element.setAttribute(ATTRIBUTE_URL, directory.getVirtualFile().getUrl());
}
else if (parentElement instanceof PsiClass) {
for (PsiElement e = (PsiElement) parentElement; e != null && e.isValid(); e = e.getParent()) {
if (e instanceof PsiClass) {
final String qualifiedName = ((PsiClass) e).getQualifiedName();
if (qualifiedName != null) {
element.setAttribute(ATTRIBUTE_CLASS, qualifiedName);
break;
}
}
}
}
}
@Override
public void loadState(@NotNull Element state) {
myElement = state;
processConfigurationElement();
myElement = null;
}
private PsiElement readParentElement(final Element element) {
if (element.getAttributeValue(ATTRIBUTE_URL) != null) {
final String url = element.getAttributeValue(ATTRIBUTE_URL);
final VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url);
return file != null ? PsiManager.getInstance(project).findDirectory(file) : null;
}
if (element.getAttributeValue(ATTRIBUTE_CLASS) != null) {
final String className = element.getAttributeValue(ATTRIBUTE_CLASS);
return className != null ? JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.allScope(project)) : null;
}
return null;
}
@Override
public void dispose() {
if (myLeftPanel == null) {
// not opened project (default?)
return;
}
myLeftPanel.dispose();
myRightPanel.dispose();
myHistory.clearHistory();
}
public CommanderPanel getRightPanel() {
return myRightPanel;
}
public CommanderPanel getLeftPanel() {
return myLeftPanel;
}
@Override
public void selectElement(PsiElement element, boolean selectInActivePanel) {
CommanderPanel panel = selectInActivePanel ? getActivePanel() : getInactivePanel();
panel.getBuilder().selectElement(element, PsiUtilCore.getVirtualFile(element));
}
private static class CommanderPluginPanel extends CommanderPanel {
@NotNull
private final CopyPasteDelegator myCopyPasteDelegator;
CommanderPluginPanel(Project project, boolean enablePopupMenu, boolean enableSearchHighlighting) {
super(project, enableSearchHighlighting);
myCopyPasteDelegator = new CopyPasteDelegator(project, myList);
myList.addMouseListener(new PopupHandler() {
@Override
public void invokePopup(final Component comp, final int x, final int y) {
CommanderPluginPanel.this.invokePopup(comp, x, y);
}
});
}
private void invokePopup(final Component c, final int x, final int y) {
if (myBuilder == null) return;
if (myList.getSelectedIndices().length <= 1) {
final int popupIndex = myList.locationToIndex(new Point(x, y));
if (popupIndex >= 0) {
myList.setSelectedIndex(popupIndex);
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(myList, true));
}
}
final ActionGroup group = (ActionGroup)CustomActionsSchema.getInstance().getCorrectedAction(IdeActions.GROUP_COMMANDER_POPUP);
final ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.COMMANDER_POPUP, group);
popupMenu.getComponent().show(c, x, y);
}
@Override
public Object getDataImpl(String dataId) {
if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) {
return myCopyPasteDelegator.getCopyProvider();
}
if (PlatformDataKeys.CUT_PROVIDER.is(dataId)) {
return myCopyPasteDelegator.getCutProvider();
}
if (PlatformDataKeys.PASTE_PROVIDER.is(dataId)) {
return myCopyPasteDelegator.getPasteProvider();
}
return super.getDataImpl(dataId);
}
}
} | JLLeitschuh/intellij-community | plugins/commander/src/com/intellij/ide/commander/Commander.java | 6,743 | // not opened project (default?) | line_comment | nl | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.commander;
import com.intellij.diff.actions.CompareFilesAction;
import com.intellij.ide.CopyPasteDelegator;
import com.intellij.ide.PsiCopyPasteManager;
import com.intellij.ide.TwoPaneIdeView;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.AbstractProjectTreeStructure;
import com.intellij.ide.projectView.impl.ProjectAbstractTreeStructureBase;
import com.intellij.ide.ui.customization.CustomActionsSchema;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.ide.util.treeView.AlphaComparator;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.components.StoragePathMacros;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.wm.*;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.AutoScrollToSourceHandler;
import com.intellij.ui.PopupHandler;
import com.intellij.util.ObjectUtils;
import com.intellij.util.SmartList;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.List;
import static com.intellij.ide.commander.CommanderPanel.getNodeElement;
import static com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy.getPreferredFocusedComponent;
/**
* @author Eugene Belyaev
*/
@State(name = "Commander", storages = @Storage(StoragePathMacros.WORKSPACE_FILE))
public class Commander extends JPanel implements PersistentStateComponent<Element>, DataProvider, TwoPaneIdeView, Disposable {
private final Project project;
private CommanderPanel myLeftPanel;
private CommanderPanel myRightPanel;
private final Splitter mySplitter;
private final ListSelectionListener mySelectionListener;
private final ListDataListener myListDataListener;
public boolean MOVE_FOCUS = true; // internal option: move focus to editor when class/file/...etc. is created
private Element myElement;
private final FocusWatcher myFocusWatcher;
private final CommanderHistory myHistory;
private boolean myAutoScrollMode;
@NonNls private static final String ACTION_BACKCOMMAND = "backCommand";
@NonNls private static final String ACTION_FORWARDCOMMAND = "forwardCommand";
@NonNls private static final String ELEMENT_LEFTPANEL = "leftPanel";
@NonNls private static final String ATTRIBUTE_MOVE_FOCUS = "MOVE_FOCUS";
@NonNls private static final String ELEMENT_OPTION = "OPTION";
@NonNls private static final String ATTRIBUTE_PROPORTION = "proportion";
@NonNls private static final String ELEMENT_SPLITTER = "splitter";
@NonNls private static final String ELEMENT_RIGHTPANEL = "rightPanel";
@NonNls private static final String ATTRIBUTE_URL = "url";
@NonNls private static final String ATTRIBUTE_CLASS = "class";
public Commander(Project project) {
super(new BorderLayout());
this.project = project;
final AbstractAction backAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
myHistory.back();
}
};
final AbstractAction fwdAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
myHistory.forward();
}
};
KeymapManager keymapManager = KeymapManager.getInstance();
final ActionMap actionMap = getActionMap();
actionMap.put(ACTION_BACKCOMMAND, backAction);
actionMap.put(ACTION_FORWARDCOMMAND, fwdAction);
for (KeyStroke stroke : getKeyStrokes(IdeActions.ACTION_GOTO_BACK, keymapManager)) {
//getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "backCommand");
//getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(stroke, "backCommand");
registerKeyboardAction(backAction, ACTION_BACKCOMMAND, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
registerKeyboardAction(backAction, ACTION_BACKCOMMAND, stroke, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
for (KeyStroke stroke : getKeyStrokes(IdeActions.ACTION_GOTO_FORWARD, keymapManager)) {
//getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "forwardCommand");
//getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(stroke, "forwardCommand");
registerKeyboardAction(fwdAction, ACTION_FORWARDCOMMAND, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
registerKeyboardAction(fwdAction, ACTION_FORWARDCOMMAND, stroke, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
myHistory = new CommanderHistory(this);
mySelectionListener = new ListSelectionListener() {
@Override
public void valueChanged(final ListSelectionEvent e) {
updateToolWindowTitle();
}
};
myListDataListener = new ListDataListener() {
@Override
public void intervalAdded(final ListDataEvent e) {
updateToolWindowTitle();
}
@Override
public void intervalRemoved(final ListDataEvent e) {
updateToolWindowTitle();
}
@Override
public void contentsChanged(final ListDataEvent e) {
updateToolWindowTitle();
}
};
myFocusWatcher = new FocusWatcher();
myLeftPanel = createPanel();
myLeftPanel.addHistoryListener(new CommanderHistoryListener() {
@Override
public void historyChanged(final PsiElement selectedElement, final boolean elementExpanded) {
getCommandHistory().saveState(selectedElement, elementExpanded, true);
}
});
myRightPanel = createPanel();
myRightPanel.addHistoryListener(new CommanderHistoryListener() {
@Override
public void historyChanged(final PsiElement selectedElement, final boolean elementExpanded) {
getCommandHistory().saveState(selectedElement, elementExpanded, false);
}
});
mySplitter = new Splitter();
mySplitter.setFirstComponent(myLeftPanel);
mySplitter.setSecondComponent(myRightPanel);
add(mySplitter, BorderLayout.CENTER);
final AutoScrollToSourceHandler handler = new AutoScrollToSourceHandler() {
@Override
protected boolean isAutoScrollMode() {
return myAutoScrollMode;
}
@Override
protected void setAutoScrollMode(boolean state) {
myAutoScrollMode = state;
}
};
handler.install(myLeftPanel.getList());
handler.install(myRightPanel.getList());
final boolean shouldAddToolbar = !ApplicationManager.getApplication().isUnitTestMode();
if (shouldAddToolbar) {
final DefaultActionGroup toolbarActions = createToolbarActions();
toolbarActions.add(handler.createToggleAction());
final ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.COMMANDER_TOOLBAR, toolbarActions, true);
add(toolbar.getComponent(), BorderLayout.NORTH);
}
myFocusWatcher.install(this);
}
public static Commander getInstance(final Project project) {
return project.getService(Commander.class);
}
public CommanderHistory getCommandHistory() {
return myHistory;
}
private void processConfigurationElement() {
if (myElement == null) return;
Element element = myElement.getChild(ELEMENT_LEFTPANEL);
if (element != null) {
final PsiElement parentElement = readParentElement(element);
if (parentElement != null) {
myLeftPanel.getBuilder().enterElement(parentElement, PsiUtilCore.getVirtualFile(parentElement));
}
}
element = myElement.getChild(ELEMENT_RIGHTPANEL);
if (element != null) {
final PsiElement parentElement = readParentElement(element);
if (parentElement != null) {
myRightPanel.getBuilder().enterElement(parentElement, PsiUtilCore.getVirtualFile(parentElement));
}
}
element = myElement.getChild(ELEMENT_SPLITTER);
if (element != null) {
final String attribute = element.getAttributeValue(ATTRIBUTE_PROPORTION);
if (attribute != null) {
try {
final float proportion = Float.valueOf(attribute).floatValue();
if (proportion >= 0 && proportion <= 1) {
mySplitter.setProportion(proportion);
}
}
catch (NumberFormatException ignored) {
}
}
}
element = myElement.getChild(ELEMENT_OPTION);
if (element != null) {
//noinspection HardCodedStringLiteral
MOVE_FOCUS = !"false".equals(element.getAttributeValue(ATTRIBUTE_MOVE_FOCUS));
}
myLeftPanel.setActive(false);
myRightPanel.setActive(false);
myLeftPanel.setMoveFocus(MOVE_FOCUS);
myRightPanel.setMoveFocus(MOVE_FOCUS);
myElement = null;
}
private static KeyStroke[] getKeyStrokes(String actionId, KeymapManager keymapManager) {
List<KeyStroke> strokes = new SmartList<>();
for (Shortcut shortcut : keymapManager.getActiveKeymap().getShortcuts(actionId)) {
if (shortcut instanceof KeyboardShortcut) {
strokes.add(((KeyboardShortcut)shortcut).getFirstKeyStroke());
}
}
return strokes.toArray(new KeyStroke[0]);
}
private DefaultActionGroup createToolbarActions() {
final ActionManager actionManager = ActionManager.getInstance();
final DefaultActionGroup group = new DefaultActionGroup();
final AnAction backAction = new AnAction() {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
myHistory.back();
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabled(myHistory.canGoBack());
}
@Override
public @NotNull ActionUpdateThread getActionUpdateThread() {
return ActionUpdateThread.EDT;
}
};
ActionUtil.copyFrom(backAction, IdeActions.ACTION_GOTO_BACK);
group.add(backAction);
final AnAction forwardAction = new AnAction() {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
myHistory.forward();
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabled(myHistory.canGoForward());
}
@Override
public @NotNull ActionUpdateThread getActionUpdateThread() {
return ActionUpdateThread.EDT;
}
};
ActionUtil.copyFrom(forwardAction, IdeActions.ACTION_GOTO_FORWARD);
group.add(forwardAction);
group.add(actionManager.getAction("CommanderSwapPanels"));
group.add(actionManager.getAction("CommanderSyncViews"));
return group;
}
private CommanderPanel createPanel() {
final CommanderPanel panel = new CommanderPluginPanel(project, true, false);
panel.getList().addKeyListener(new PsiCopyPasteManager.EscapeHandler());
final ProjectAbstractTreeStructureBase treeStructure = createProjectTreeStructure();
panel.setBuilder(new ProjectListBuilder(project, panel, treeStructure, AlphaComparator.INSTANCE, true));
panel.setProjectTreeStructure(treeStructure);
final FocusAdapter focusListener = new FocusAdapter() {
@Override
public void focusGained(final FocusEvent e) {
updateToolWindowTitle(panel);
}
};
final JList list = panel.getList();
list.addFocusListener(focusListener);
list.getSelectionModel().addListSelectionListener(mySelectionListener);
list.getModel().addListDataListener(myListDataListener);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
list.removeFocusListener(focusListener);
list.getSelectionModel().removeListSelectionListener(mySelectionListener);
list.getModel().removeListDataListener(myListDataListener);
}
});
return panel;
}
protected AbstractProjectTreeStructure createProjectTreeStructure() {
return new AbstractProjectTreeStructure(project) {
@Override
public boolean isShowMembers() {
return true;
}
@Override
public boolean isShowModules() {
return false;
}
};
}
/**
* invoked in AWT thread
*/
private void updateToolWindowTitle() {
final CommanderPanel panel = getActivePanel();
updateToolWindowTitle(panel);
}
protected void updateToolWindowTitle(CommanderPanel activePanel) {
ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.COMMANDER);
if (toolWindow != null) {
AbstractTreeNode<?> node = activePanel.getSelectedNode();
if (node instanceof ProjectViewNode) {
toolWindow.setTitle(ObjectUtils.notNull(((ProjectViewNode<?>)node).getTitle(), ""));
}
}
}
public boolean isLeftPanelActive() {
return isPanelActive(myLeftPanel);
}
boolean isPanelActive(final CommanderPanel panel) {
return panel.getList() == myFocusWatcher.getFocusedComponent();
}
public void selectElementInLeftPanel(final Object element, VirtualFile virtualFile) {
myLeftPanel.getBuilder().selectElement(element, virtualFile);
if (!isPanelActive(myLeftPanel)) {
switchActivePanel();
}
}
public void selectElementInRightPanel(final Object element, VirtualFile virtualFile) {
myRightPanel.getBuilder().selectElement(element, virtualFile);
if (!isPanelActive(myRightPanel)) {
switchActivePanel();
}
}
public void switchActivePanel() {
final CommanderPanel activePanel = getActivePanel();
final CommanderPanel inactivePanel = getInactivePanel();
inactivePanel.setActive(true);
activePanel.setActive(false);
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(getPreferredFocusedComponent(inactivePanel), true));
}
public void enterElementInActivePanel(final PsiElement element) {
final CommanderPanel activePanel = isLeftPanelActive() ? myLeftPanel : myRightPanel;
activePanel.getBuilder().enterElement(element, PsiUtilCore.getVirtualFile(element));
}
public void swapPanels() {
mySplitter.swapComponents();
final CommanderPanel tmpPanel = myLeftPanel;
myLeftPanel = myRightPanel;
myRightPanel = tmpPanel;
}
public void syncViews() {
final CommanderPanel activePanel;
final CommanderPanel passivePanel;
if (isLeftPanelActive()) {
activePanel = myLeftPanel;
passivePanel = myRightPanel;
} else {
activePanel = myRightPanel;
passivePanel = myLeftPanel;
}
ProjectViewNode element = (ProjectViewNode)activePanel.getBuilder().getParentNode();
passivePanel.getBuilder().enterElement(element);
}
public CommanderPanel getActivePanel() {
return isLeftPanelActive() ? myLeftPanel : myRightPanel;
}
public CommanderPanel getInactivePanel() {
return !isLeftPanelActive() ? myLeftPanel : myRightPanel;
}
@Override
public Object getData(@NotNull final String dataId) {
if (PlatformCoreDataKeys.HELP_ID.is(dataId)) {
return "viewingStructure.commander";
}
else if (CommonDataKeys.PROJECT.is(dataId)) {
return project;
}
else if (PlatformCoreDataKeys.BGT_DATA_PROVIDER.is(dataId)) {
AbstractTreeNode<?> parent1 = getActivePanel().getBuilder().getParentNode();
AbstractTreeNode<?> selection1 = getActivePanel().getSelectedNode();
AbstractTreeNode<?> parent2 = getInactivePanel().getBuilder().getParentNode();
AbstractTreeNode<?> selection2 = getInactivePanel().getSelectedNode();
Couple<AbstractTreeNode<?>> activeSelection = Couple.of(parent1, selection1);
Couple<AbstractTreeNode<?>> inactiveSelection = Couple.of(parent2, selection2);
DataProvider panelProvider = (DataProvider)getActivePanel().getDataImpl(dataId);
return CompositeDataProvider.compose(slowId -> getSlowData(slowId, activeSelection, inactiveSelection), panelProvider);
}
else {
return getActivePanel().getDataImpl(dataId);
}
}
private static @Nullable Object getSlowData(@NotNull String dataId,
@NotNull Couple<AbstractTreeNode<?>> active,
@NotNull Couple<AbstractTreeNode<?>> inactive) {
if (LangDataKeys.TARGET_PSI_ELEMENT.is(dataId)) {
return getNodeElement(inactive.first);
}
else if (CompareFilesAction.DIFF_REQUEST.is(dataId)) {
PsiElement primary = getNodeElement(active.second);
PsiElement secondary = getNodeElement(inactive.second);
if (primary != null && secondary != null &&
primary.isValid() && secondary.isValid() &&
!PsiTreeUtil.isAncestor(primary, secondary, false) &&
!PsiTreeUtil.isAncestor(secondary, primary, false)) {
return PsiDiffContentFactory.comparePsiElements(primary, secondary);
}
}
return null;
}
@Override
public Element getState() {
Element element = new Element("commander");
if (myLeftPanel == null || myRightPanel == null) {
return element;
}
PsiDocumentManager.getInstance(project).commitAllDocuments();
Element e = new Element(ELEMENT_LEFTPANEL);
element.addContent(e);
writePanel(myLeftPanel, e);
e = new Element(ELEMENT_RIGHTPANEL);
element.addContent(e);
writePanel(myRightPanel, e);
e = new Element(ELEMENT_SPLITTER);
element.addContent(e);
e.setAttribute(ATTRIBUTE_PROPORTION, Float.toString(mySplitter.getProportion()));
if (!MOVE_FOCUS) {
e = new Element(ELEMENT_OPTION);
element.addContent(e);
e.setAttribute(ATTRIBUTE_MOVE_FOCUS, "false");
}
return element;
}
private static void writePanel(final CommanderPanel panel, final Element element) {
/*TODO[anton,vova]: it's a patch!!!*/
final AbstractListBuilder builder = panel.getBuilder();
if (builder == null) return;
final AbstractTreeNode parentNode = builder.getParentNode();
final Object parentElement = parentNode != null? parentNode.getValue() : null;
if (parentElement instanceof PsiDirectory directory) {
element.setAttribute(ATTRIBUTE_URL, directory.getVirtualFile().getUrl());
}
else if (parentElement instanceof PsiClass) {
for (PsiElement e = (PsiElement) parentElement; e != null && e.isValid(); e = e.getParent()) {
if (e instanceof PsiClass) {
final String qualifiedName = ((PsiClass) e).getQualifiedName();
if (qualifiedName != null) {
element.setAttribute(ATTRIBUTE_CLASS, qualifiedName);
break;
}
}
}
}
}
@Override
public void loadState(@NotNull Element state) {
myElement = state;
processConfigurationElement();
myElement = null;
}
private PsiElement readParentElement(final Element element) {
if (element.getAttributeValue(ATTRIBUTE_URL) != null) {
final String url = element.getAttributeValue(ATTRIBUTE_URL);
final VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url);
return file != null ? PsiManager.getInstance(project).findDirectory(file) : null;
}
if (element.getAttributeValue(ATTRIBUTE_CLASS) != null) {
final String className = element.getAttributeValue(ATTRIBUTE_CLASS);
return className != null ? JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.allScope(project)) : null;
}
return null;
}
@Override
public void dispose() {
if (myLeftPanel == null) {
// not opened<SUF>
return;
}
myLeftPanel.dispose();
myRightPanel.dispose();
myHistory.clearHistory();
}
public CommanderPanel getRightPanel() {
return myRightPanel;
}
public CommanderPanel getLeftPanel() {
return myLeftPanel;
}
@Override
public void selectElement(PsiElement element, boolean selectInActivePanel) {
CommanderPanel panel = selectInActivePanel ? getActivePanel() : getInactivePanel();
panel.getBuilder().selectElement(element, PsiUtilCore.getVirtualFile(element));
}
private static class CommanderPluginPanel extends CommanderPanel {
@NotNull
private final CopyPasteDelegator myCopyPasteDelegator;
CommanderPluginPanel(Project project, boolean enablePopupMenu, boolean enableSearchHighlighting) {
super(project, enableSearchHighlighting);
myCopyPasteDelegator = new CopyPasteDelegator(project, myList);
myList.addMouseListener(new PopupHandler() {
@Override
public void invokePopup(final Component comp, final int x, final int y) {
CommanderPluginPanel.this.invokePopup(comp, x, y);
}
});
}
private void invokePopup(final Component c, final int x, final int y) {
if (myBuilder == null) return;
if (myList.getSelectedIndices().length <= 1) {
final int popupIndex = myList.locationToIndex(new Point(x, y));
if (popupIndex >= 0) {
myList.setSelectedIndex(popupIndex);
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(myList, true));
}
}
final ActionGroup group = (ActionGroup)CustomActionsSchema.getInstance().getCorrectedAction(IdeActions.GROUP_COMMANDER_POPUP);
final ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.COMMANDER_POPUP, group);
popupMenu.getComponent().show(c, x, y);
}
@Override
public Object getDataImpl(String dataId) {
if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) {
return myCopyPasteDelegator.getCopyProvider();
}
if (PlatformDataKeys.CUT_PROVIDER.is(dataId)) {
return myCopyPasteDelegator.getCutProvider();
}
if (PlatformDataKeys.PASTE_PROVIDER.is(dataId)) {
return myCopyPasteDelegator.getPasteProvider();
}
return super.getDataImpl(dataId);
}
}
} |
10233_19 | // Mx1Message.java
package jmri.jmrix.zimo;
import java.io.Serializable;
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
* @version $Revision$
*
* Adapted by Sip Bosch for use with zimo MX-1
*
*/
public class Mx1Message extends jmri.jmrix.NetMessage implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6404655263624067289L;
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.
*/
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
*/
public int getModule() {
int mod = getElement(1) & 0x0F;
if ((mod & MX1) == MX1) {
return MX1;
}
if ((mod & MX8) == MX8) {
return MX8;
}
if ((mod & MX9) == 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;
/*public int messageUser(){
return getElement(1)&0x0F;
}*/
final static boolean CS = true;
final static boolean PC = false;
/**
* Indicates the source of the message.
*/
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 whether the message has a valid parity in fact check for CR or LF
* as end of message
*/
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
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 " + (getElement(0) & 0xff));
if (getLongMessage()) {
txt.append(" (L)");
} else {
txt.append(" (S)");
}
int offset = 0;
if (getMessageType() == PRIMARY) {
txt.append(" Prim");
} else if (getMessageType() == ACKREP1) {
txt.append(" Ack/Reply 1");
} else if (getMessageType() == REPLY2) {
txt.append(" Reply 2");
} else if (getMessageType() == ACK2) {
txt.append(" Ack 2");
} else {
txt.append(" Unknown msg");
}
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: " + 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: " + 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: " + Integer.toString(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: " + (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;
}
/**
* @param locoAddress : address of the loco, if left blank then programming
* track is used
* @param cv : CV that is to be either read in or written
* @param value : Value to be written to the CV, if set to -1, then a
* read is done
* @param dcc : Is the decoder Protocol DCC, true = DCC, false =
* Motorola
*/
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;
}
/**
*
* @param locoAddress Address of the loco that we are issuing the command
* too.
* @param speed Speed Step in the actual Speed Step System
* @param dcc Is this a packet for a DCC or Motorola device
* @param cData1
* @param cData2 - Functions Output 0-7
* @param cData3 - Functions Output 9-12
* @return Mx1Message
*/
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
static Logger log = LoggerFactory.getLogger(Mx1Message.class.getName());
}
/* @(#)Mx1Message.java */
| JMRI/jmri-test | java/src/jmri/jmrix/zimo/Mx1Message.java | 6,244 | //int type = getElement(2); | line_comment | nl | // Mx1Message.java
package jmri.jmrix.zimo;
import java.io.Serializable;
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
* @version $Revision$
*
* Adapted by Sip Bosch for use with zimo MX-1
*
*/
public class Mx1Message extends jmri.jmrix.NetMessage implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6404655263624067289L;
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.
*/
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
*/
public int getModule() {
int mod = getElement(1) & 0x0F;
if ((mod & MX1) == MX1) {
return MX1;
}
if ((mod & MX8) == MX8) {
return MX8;
}
if ((mod & MX9) == 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;
/*public int messageUser(){
return getElement(1)&0x0F;
}*/
final static boolean CS = true;
final static boolean PC = false;
/**
* Indicates the source of the message.
*/
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 whether the message has a valid parity in fact check for CR or LF
* as end of message
*/
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
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 " + (getElement(0) & 0xff));
if (getLongMessage()) {
txt.append(" (L)");
} else {
txt.append(" (S)");
}
int offset = 0;
if (getMessageType() == PRIMARY) {
txt.append(" Prim");
} else if (getMessageType() == ACKREP1) {
txt.append(" Ack/Reply 1");
} else if (getMessageType() == REPLY2) {
txt.append(" Reply 2");
} else if (getMessageType() == ACK2) {
txt.append(" Ack 2");
} else {
txt.append(" Unknown msg");
}
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: " + 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: " + 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: " + Integer.toString(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: " + (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<SUF>
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;
}
/**
* @param locoAddress : address of the loco, if left blank then programming
* track is used
* @param cv : CV that is to be either read in or written
* @param value : Value to be written to the CV, if set to -1, then a
* read is done
* @param dcc : Is the decoder Protocol DCC, true = DCC, false =
* Motorola
*/
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;
}
/**
*
* @param locoAddress Address of the loco that we are issuing the command
* too.
* @param speed Speed Step in the actual Speed Step System
* @param dcc Is this a packet for a DCC or Motorola device
* @param cData1
* @param cData2 - Functions Output 0-7
* @param cData3 - Functions Output 9-12
* @return Mx1Message
*/
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
static Logger log = LoggerFactory.getLogger(Mx1Message.class.getName());
}
/* @(#)Mx1Message.java */
|
15766_1 | package domain;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.Period;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Transient;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import repository.VerblijfplaatsRepository;
@Entity
@NamedQueries({
@NamedQuery(name = "Dier.findByName", query = "SELECT d FROM Dier d WHERE d.naam LIKE CONCAT(:diernaam,'%')"),
@NamedQuery(name = "Dier.findByRas", query = "SELECT d FROM Dier d WHERE d.ras LIKE CONCAT(:ras,'%')"),
@NamedQuery(name = "Dier.getAllSorted", query = "SELECT d FROM Dier d ORDER BY d.ras, d.geboorteDatum") })
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode(exclude = "id")
@ToString(exclude = "id")
public class Dier implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Setter
@Getter
private String naam;
// private ImageIcon foto;
@Setter
@Getter
private String ras;
@Setter
@Getter
private String geslacht;
@Setter
@Getter
private LocalDate geboorteDatum;
@Setter
@Getter
private double medischeKosten;
@Setter
@Getter
private boolean kanMetJongeKinderen;
@Setter
@Getter
private String identificationCode;
@Setter
@Getter
private boolean kanMetOudereKinderen;
@Setter
@Getter
private boolean kanMetKatten;
@Setter
@Getter
private boolean kanMetHonden;
@Setter
@Getter
private boolean geschiktAlsBinnenkat;
@Setter
@Getter
private boolean reedsGereserveerd;
public Dier(String naam, String ras, String identificationCode, String geslacht, LocalDate geboorteDatum,
double medischeKosten, boolean kanMetJongeKinderen, boolean kanMetOudereKinderen, boolean kanMetKatten,
boolean kanMetHonden, boolean geschiktAlsBinnenkat, boolean reedsGereserveerd) {
super();
this.identificationCode = identificationCode;
this.naam = naam;
this.ras = ras;
this.geslacht = geslacht;
this.geboorteDatum = geboorteDatum;
this.medischeKosten = medischeKosten;
this.kanMetJongeKinderen = kanMetJongeKinderen;
this.kanMetOudereKinderen = kanMetOudereKinderen;
this.kanMetKatten = kanMetKatten;
this.kanMetHonden = kanMetHonden;
this.geschiktAlsBinnenkat = geschiktAlsBinnenkat;
this.reedsGereserveerd = reedsGereserveerd;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setRas(String ras) {
this.ras = ras;
}
public void setGeslacht(String geslacht) { // Todo, enum maken of controle op invoer(enkel man, vrouw)
this.geslacht = geslacht;
}
public void setMedischeKosten(double medischeKosten) {
this.medischeKosten = medischeKosten;
}
public void setKanMetJongeKinderen(boolean kanMetJongeKinderen) {
this.kanMetJongeKinderen = kanMetJongeKinderen;
}
public void setKanMetOudereKinderen(boolean kanMetOudereKinderen) {
this.kanMetOudereKinderen = kanMetOudereKinderen;
}
public void setKanMetKatten(boolean kanMetKatten) {
this.kanMetKatten = kanMetKatten;
}
public void setKanMetHonden(boolean kanMetHonden) {
this.kanMetHonden = kanMetHonden;
}
public void setGeschiktAlsBinnenkat(boolean geschiktAlsBinnenkat) {
this.geschiktAlsBinnenkat = geschiktAlsBinnenkat;
}
public void setReedsGereserveerd(boolean reedsGereserveerd) {
this.reedsGereserveerd = reedsGereserveerd;
}
public void setGeboorteDatum(LocalDate geboorteDatum) {
this.geboorteDatum = geboorteDatum;
}
public int getLeeftijd() {
LocalDate date2 = LocalDate.now();
Period period = geboorteDatum.until(date2);
return period.getYears();
}
public String getNaam() {
return naam;
}
public String getRas() {
return ras;
}
public String getGeslacht() {
return geslacht;
}
public double getMedischeKosten() {
return medischeKosten;
}
public boolean isKanMetJongeKinderen() {
return kanMetJongeKinderen;
}
public boolean isKanMetOudereKinderen() {
return kanMetOudereKinderen;
}
public boolean isKanMetKatten() {
return kanMetKatten;
}
public boolean isKanMetHonden() {
return kanMetHonden;
}
public boolean isGeschiktAlsBinnenkat() {
return geschiktAlsBinnenkat;
}
public boolean isReedsGereserveerd() {
return reedsGereserveerd;
}
}
| JMonkeyFan/Opdracht_EWDJ_2022-2023_Thomas_Lelong-1_AsielBeheer | src/main/java/domain/Dier.java | 1,690 | // Todo, enum maken of controle op invoer(enkel man, vrouw) | line_comment | nl | package domain;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.Period;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Transient;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import repository.VerblijfplaatsRepository;
@Entity
@NamedQueries({
@NamedQuery(name = "Dier.findByName", query = "SELECT d FROM Dier d WHERE d.naam LIKE CONCAT(:diernaam,'%')"),
@NamedQuery(name = "Dier.findByRas", query = "SELECT d FROM Dier d WHERE d.ras LIKE CONCAT(:ras,'%')"),
@NamedQuery(name = "Dier.getAllSorted", query = "SELECT d FROM Dier d ORDER BY d.ras, d.geboorteDatum") })
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode(exclude = "id")
@ToString(exclude = "id")
public class Dier implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Setter
@Getter
private String naam;
// private ImageIcon foto;
@Setter
@Getter
private String ras;
@Setter
@Getter
private String geslacht;
@Setter
@Getter
private LocalDate geboorteDatum;
@Setter
@Getter
private double medischeKosten;
@Setter
@Getter
private boolean kanMetJongeKinderen;
@Setter
@Getter
private String identificationCode;
@Setter
@Getter
private boolean kanMetOudereKinderen;
@Setter
@Getter
private boolean kanMetKatten;
@Setter
@Getter
private boolean kanMetHonden;
@Setter
@Getter
private boolean geschiktAlsBinnenkat;
@Setter
@Getter
private boolean reedsGereserveerd;
public Dier(String naam, String ras, String identificationCode, String geslacht, LocalDate geboorteDatum,
double medischeKosten, boolean kanMetJongeKinderen, boolean kanMetOudereKinderen, boolean kanMetKatten,
boolean kanMetHonden, boolean geschiktAlsBinnenkat, boolean reedsGereserveerd) {
super();
this.identificationCode = identificationCode;
this.naam = naam;
this.ras = ras;
this.geslacht = geslacht;
this.geboorteDatum = geboorteDatum;
this.medischeKosten = medischeKosten;
this.kanMetJongeKinderen = kanMetJongeKinderen;
this.kanMetOudereKinderen = kanMetOudereKinderen;
this.kanMetKatten = kanMetKatten;
this.kanMetHonden = kanMetHonden;
this.geschiktAlsBinnenkat = geschiktAlsBinnenkat;
this.reedsGereserveerd = reedsGereserveerd;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setRas(String ras) {
this.ras = ras;
}
public void setGeslacht(String geslacht) { // Todo, enum<SUF>
this.geslacht = geslacht;
}
public void setMedischeKosten(double medischeKosten) {
this.medischeKosten = medischeKosten;
}
public void setKanMetJongeKinderen(boolean kanMetJongeKinderen) {
this.kanMetJongeKinderen = kanMetJongeKinderen;
}
public void setKanMetOudereKinderen(boolean kanMetOudereKinderen) {
this.kanMetOudereKinderen = kanMetOudereKinderen;
}
public void setKanMetKatten(boolean kanMetKatten) {
this.kanMetKatten = kanMetKatten;
}
public void setKanMetHonden(boolean kanMetHonden) {
this.kanMetHonden = kanMetHonden;
}
public void setGeschiktAlsBinnenkat(boolean geschiktAlsBinnenkat) {
this.geschiktAlsBinnenkat = geschiktAlsBinnenkat;
}
public void setReedsGereserveerd(boolean reedsGereserveerd) {
this.reedsGereserveerd = reedsGereserveerd;
}
public void setGeboorteDatum(LocalDate geboorteDatum) {
this.geboorteDatum = geboorteDatum;
}
public int getLeeftijd() {
LocalDate date2 = LocalDate.now();
Period period = geboorteDatum.until(date2);
return period.getYears();
}
public String getNaam() {
return naam;
}
public String getRas() {
return ras;
}
public String getGeslacht() {
return geslacht;
}
public double getMedischeKosten() {
return medischeKosten;
}
public boolean isKanMetJongeKinderen() {
return kanMetJongeKinderen;
}
public boolean isKanMetOudereKinderen() {
return kanMetOudereKinderen;
}
public boolean isKanMetKatten() {
return kanMetKatten;
}
public boolean isKanMetHonden() {
return kanMetHonden;
}
public boolean isGeschiktAlsBinnenkat() {
return geschiktAlsBinnenkat;
}
public boolean isReedsGereserveerd() {
return reedsGereserveerd;
}
}
|
195938_5 | package com.hr.hrmap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import org.jgrapht.Graphs;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import static java.lang.Math.*;
public class PlattegrondView extends View implements OnTouchListener {
private static final String TAG = "DrawView";
List<Point> points = new ArrayList<Point>();
Paint paint = new Paint();
List<Locatie> locaties = new ArrayList<>();
UndirectedGraph<Locatie, DefaultEdge> g = new SimpleGraph<Locatie, DefaultEdge>(DefaultEdge.class);
Canvas canvas;
public int currentVerdieping = 1;
List<Locatie> path = new ArrayList<>();
public PlattegrondView(Context context, AttributeSet attrs) {
super(context, attrs);
this.init(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
//this.setBackgroundResource(R.drawable.h2);
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
/* Load the correct list of locaties */
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PlattegrondView, 0, 0);
String verdieping = a.getString(R.styleable.PlattegrondView_verdieping);
MainActivity activity = (MainActivity) getContext();
this.locaties = activity.plattegrond.getLocatiesVanVerdieping(Integer.parseInt(verdieping));
if (activity.plattegrond.getPath() != null && activity.plattegrond.getPath().isEmpty() == false) {
this.path = activity.plattegrond.getPath();
}
}
private void init(Context context) {
}
public PlattegrondView(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
}
@Override
public void onDraw(Canvas canvas) {
this.canvas = canvas;
paint.setColor(Color.BLACK);
paint.setStrokeWidth(5);
for (Locatie locatie : locaties) {
if(locatie.naam.contains("lift")){
locatie.visible = true;
}
locatie.draw(canvas);
}
if (this.path.isEmpty() == false) {
Locatie prev = null;
//draw the path
for (Locatie locatie : path
) {
if(containsLocatie(locatie) == false)
{
continue;
}
if(locatie.naam.contains("lift")){
locatie.visible = true;
}
if (prev == null) {
prev = locatie;
if(prev.naam.contains("lift")){
prev.visible = true;
}
continue;
}
if(prev.naam.contains("lift")){
prev.visible = true;
}
drawPath(prev, locatie);
prev = locatie;
}
}
}
public boolean containsLocatie(Locatie locatie) {
return this.locaties.contains(locatie);
}
public void drawPath(Locatie l1, Locatie l2) {
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setColor(Color.BLUE);
Path path = new Path();
path.moveTo(l1.x, l1.y);
path.lineTo(l2.x, l2.y);
path.close();
canvas.drawPath(path, paint);
}
public void drawAllEdges() {
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setColor(Color.BLUE);
for (Locatie locatie : locaties) {
for (Locatie locatie1 : locaties) {
if (locatie == locatie1) {
continue;
}
DefaultEdge edge = g.getEdge(locatie, locatie1);
if (edge != null) {
Path path = new Path();
path.moveTo(locatie.x, locatie.y);
path.lineTo(locatie1.x, locatie1.y);
path.close();
canvas.drawPath(path, paint);
}
}
}
}
private void drawLocatie(Canvas canvas, Locatie locatie) {
canvas.drawCircle(locatie.x, locatie.y, 10, locatie.paint);
canvas.drawText(locatie.naam, locatie.x - 50, locatie.y - 20, locatie.paint);
}
private static Path makeArrow(float length, float height) {
Path p = new Path();
p.moveTo(-2.0f, 0.0f);
p.lineTo(length, height / 2.0f);
p.lineTo(-2.0f, height);
p.lineTo(-2.0f, 0.0f);
p.close();
return p;
}
public boolean onTouch(View view, MotionEvent event) {
return true;
// if(event.getAction() != MotionEvent.ACTION_DOWN)
// return super.onTouchEvent(event);
// Point point = new Point();
// point.x = event.getX();
// point.y = event.getY();
// points.add(point);
// invalidate();
// Log.d(TAG, "point: " + point);
//
// return true;
}
class Point {
float x, y;
@Override
public String toString() {
return x + ", " + y;
}
}
} | JStorne/HR-MAP | android/HRMap/app/src/main/java/com/hr/hrmap/PlattegrondView.java | 1,801 | // point.y = event.getY(); | line_comment | nl | package com.hr.hrmap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import org.jgrapht.Graphs;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import static java.lang.Math.*;
public class PlattegrondView extends View implements OnTouchListener {
private static final String TAG = "DrawView";
List<Point> points = new ArrayList<Point>();
Paint paint = new Paint();
List<Locatie> locaties = new ArrayList<>();
UndirectedGraph<Locatie, DefaultEdge> g = new SimpleGraph<Locatie, DefaultEdge>(DefaultEdge.class);
Canvas canvas;
public int currentVerdieping = 1;
List<Locatie> path = new ArrayList<>();
public PlattegrondView(Context context, AttributeSet attrs) {
super(context, attrs);
this.init(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
//this.setBackgroundResource(R.drawable.h2);
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
/* Load the correct list of locaties */
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PlattegrondView, 0, 0);
String verdieping = a.getString(R.styleable.PlattegrondView_verdieping);
MainActivity activity = (MainActivity) getContext();
this.locaties = activity.plattegrond.getLocatiesVanVerdieping(Integer.parseInt(verdieping));
if (activity.plattegrond.getPath() != null && activity.plattegrond.getPath().isEmpty() == false) {
this.path = activity.plattegrond.getPath();
}
}
private void init(Context context) {
}
public PlattegrondView(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
}
@Override
public void onDraw(Canvas canvas) {
this.canvas = canvas;
paint.setColor(Color.BLACK);
paint.setStrokeWidth(5);
for (Locatie locatie : locaties) {
if(locatie.naam.contains("lift")){
locatie.visible = true;
}
locatie.draw(canvas);
}
if (this.path.isEmpty() == false) {
Locatie prev = null;
//draw the path
for (Locatie locatie : path
) {
if(containsLocatie(locatie) == false)
{
continue;
}
if(locatie.naam.contains("lift")){
locatie.visible = true;
}
if (prev == null) {
prev = locatie;
if(prev.naam.contains("lift")){
prev.visible = true;
}
continue;
}
if(prev.naam.contains("lift")){
prev.visible = true;
}
drawPath(prev, locatie);
prev = locatie;
}
}
}
public boolean containsLocatie(Locatie locatie) {
return this.locaties.contains(locatie);
}
public void drawPath(Locatie l1, Locatie l2) {
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setColor(Color.BLUE);
Path path = new Path();
path.moveTo(l1.x, l1.y);
path.lineTo(l2.x, l2.y);
path.close();
canvas.drawPath(path, paint);
}
public void drawAllEdges() {
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setColor(Color.BLUE);
for (Locatie locatie : locaties) {
for (Locatie locatie1 : locaties) {
if (locatie == locatie1) {
continue;
}
DefaultEdge edge = g.getEdge(locatie, locatie1);
if (edge != null) {
Path path = new Path();
path.moveTo(locatie.x, locatie.y);
path.lineTo(locatie1.x, locatie1.y);
path.close();
canvas.drawPath(path, paint);
}
}
}
}
private void drawLocatie(Canvas canvas, Locatie locatie) {
canvas.drawCircle(locatie.x, locatie.y, 10, locatie.paint);
canvas.drawText(locatie.naam, locatie.x - 50, locatie.y - 20, locatie.paint);
}
private static Path makeArrow(float length, float height) {
Path p = new Path();
p.moveTo(-2.0f, 0.0f);
p.lineTo(length, height / 2.0f);
p.lineTo(-2.0f, height);
p.lineTo(-2.0f, 0.0f);
p.close();
return p;
}
public boolean onTouch(View view, MotionEvent event) {
return true;
// if(event.getAction() != MotionEvent.ACTION_DOWN)
// return super.onTouchEvent(event);
// Point point = new Point();
// point.x = event.getX();
// point.y =<SUF>
// points.add(point);
// invalidate();
// Log.d(TAG, "point: " + point);
//
// return true;
}
class Point {
float x, y;
@Override
public String toString() {
return x + ", " + y;
}
}
} |
207160_1 | package com.jadonvb;
import org.knowm.xchart.*;
import org.knowm.xchart.style.Styler;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Voer een geheel getal in: ");
int startingNumber = scanner.nextInt();
List<Integer> xData = new ArrayList<>();
List<Integer> yData = new ArrayList<>();
int n = startingNumber;
int step = 0;
while (n != 1) {
xData.add(step);
yData.add(n);
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
step++;
}
xData.add(step);
yData.add(1);
// Tooltip-tekst genereren voor hele getallen
List<String> toolTips = new ArrayList<>();
for (int i = 0; i < xData.size(); i++) {
if (xData.get(i) % 1 == 0) {
toolTips.add("Step: " + xData.get(i) + ", Number: " + yData.get(i));
} else {
toolTips.add(""); // Geen tooltip voor niet-gehele getallen
}
}
// Grafiek maken
XYChart chart = new XYChartBuilder().width(800).height(600).title("Collatz Conjecture").xAxisTitle("Tijd").yAxisTitle("Getal").build();
// Data toevoegen
XYSeries series = chart.addSeries("Collatz", xData, yData);
// Tooltips instellen met aangepaste tooltip generator
chart.getStyler().setToolTipType(Styler.ToolTipType.yLabels);
chart.getStyler().setCursorEnabled(true);
chart.getStyler().setToolTipsEnabled(true);
chart.getStyler().setToolTipFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12));
chart.getStyler().setToolTipBackgroundColor(java.awt.Color.WHITE);
chart.getStyler().setToolTipBorderColor(java.awt.Color.BLACK);
// Laten zien
new SwingWrapper<>(chart).displayChart();
}
} | Ja90n/CollatzDisplayer | src/main/java/com/jadonvb/Main.java | 658 | // Geen tooltip voor niet-gehele getallen | line_comment | nl | package com.jadonvb;
import org.knowm.xchart.*;
import org.knowm.xchart.style.Styler;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Voer een geheel getal in: ");
int startingNumber = scanner.nextInt();
List<Integer> xData = new ArrayList<>();
List<Integer> yData = new ArrayList<>();
int n = startingNumber;
int step = 0;
while (n != 1) {
xData.add(step);
yData.add(n);
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
step++;
}
xData.add(step);
yData.add(1);
// Tooltip-tekst genereren voor hele getallen
List<String> toolTips = new ArrayList<>();
for (int i = 0; i < xData.size(); i++) {
if (xData.get(i) % 1 == 0) {
toolTips.add("Step: " + xData.get(i) + ", Number: " + yData.get(i));
} else {
toolTips.add(""); // Geen tooltip<SUF>
}
}
// Grafiek maken
XYChart chart = new XYChartBuilder().width(800).height(600).title("Collatz Conjecture").xAxisTitle("Tijd").yAxisTitle("Getal").build();
// Data toevoegen
XYSeries series = chart.addSeries("Collatz", xData, yData);
// Tooltips instellen met aangepaste tooltip generator
chart.getStyler().setToolTipType(Styler.ToolTipType.yLabels);
chart.getStyler().setCursorEnabled(true);
chart.getStyler().setToolTipsEnabled(true);
chart.getStyler().setToolTipFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12));
chart.getStyler().setToolTipBackgroundColor(java.awt.Color.WHITE);
chart.getStyler().setToolTipBorderColor(java.awt.Color.BLACK);
// Laten zien
new SwingWrapper<>(chart).displayChart();
}
} |
40916_10 | package org.jabref.logic.importer.fileformat;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.jabref.logic.importer.ParseException;
import org.jabref.logic.importer.Parser;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UnknownField;
import org.jabref.model.entry.types.EntryType;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.model.strings.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class PicaXmlParser implements Parser {
private static final Logger LOGGER = LoggerFactory.getLogger(PicaXmlParser.class);
private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
@Override
public List<BibEntry> parseEntries(InputStream inputStream) throws ParseException {
try {
DocumentBuilder dbuild = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
Document content = dbuild.parse(inputStream);
return this.parseEntries(content);
} catch (ParserConfigurationException | SAXException | IOException exception) {
throw new ParseException(exception);
}
}
private List<BibEntry> parseEntries(Document content) {
List<BibEntry> result = new ArrayList<>();
// used for creating test cases
// XMLUtil.printDocument(content);
Element root = (Element) content.getElementsByTagName("zs:searchRetrieveResponse").item(0);
Element srwrecords = getChild("zs:records", root);
if (srwrecords == null) {
// no records found -> return empty list
return result;
}
List<Element> records = getChildren("zs:record", srwrecords);
for (Element gvkRecord : records) {
Element e = getChild("zs:recordData", gvkRecord);
if (e != null) {
e = getChild("record", e);
if (e != null) {
BibEntry bibEntry = parseEntry(e);
// TODO: Add filtering on years (based on org.jabref.logic.importer.fetcher.transformers.YearRangeByFilteringQueryTransformer.getStartYear)
result.add(bibEntry);
}
}
}
return result;
}
private BibEntry parseEntry(Element e) {
String author = null;
String editor = null;
String title = null;
String publisher = null;
String year = null;
String address = null;
String series = null;
String edition = null;
String isbn = null;
String issn = null;
String number = null;
String pagetotal = null;
String volume = null;
String pages = null;
String journal = null;
String ppn = null;
String booktitle = null;
String url = null;
String note = null;
String source = "";
String bibliographicGenre = "";
String subtitle = "";
EntryType entryType = StandardEntryType.Book; // Default
List<Element> datafields = getChildren("datafield", e);
for (Element datafield : datafields) {
String tag = datafield.getAttribute("tag");
LOGGER.debug("tag: " + tag);
// genre/type of the entry https://swbtools.bsz-bw.de/cgi-bin/k10plushelp.pl?cmd=kat&val=0500&katalog=Standard
if ("002@".equals(tag)) {
bibliographicGenre = getSubfield("0", datafield);
if (bibliographicGenre == null) {
bibliographicGenre = "";
}
}
// ppn
if ("003@".equals(tag)) {
ppn = getSubfield("0", datafield);
}
// author
if ("028A".equals(tag)) {
String vorname = getSubfield("d", datafield);
String nachname = getSubfield("a", datafield);
if (author == null) {
author = "";
} else {
author = author.concat(" and ");
}
author = author.concat(vorname + " " + nachname);
}
// author (weiterer)
if ("028B".equals(tag)) {
String vorname = getSubfield("d", datafield);
String nachname = getSubfield("a", datafield);
if (author == null) {
author = "";
} else {
author = author.concat(" and ");
}
author = author.concat(vorname + " " + nachname);
}
// editor
if ("028C".equals(tag)) {
String vorname = getSubfield("d", datafield);
String nachname = getSubfield("a", datafield);
if (editor == null) {
editor = "";
} else {
editor = editor.concat(" and ");
}
editor = editor.concat(vorname + " " + nachname);
}
// title and subtitle
if ("021A".equals(tag)) {
title = getSubfield("a", datafield);
subtitle = getSubfield("d", datafield);
}
// publisher and address
if ("033A".equals(tag)) {
publisher = getSubfield("n", datafield);
address = getSubfield("p", datafield);
}
// year
if ("011@".equals(tag)) {
year = getSubfield("a", datafield);
}
// year, volume, number, pages (year bei Zeitschriften (evtl. redundant mit 011@))
if ("031A".equals(tag)) {
year = getSubfield("j", datafield);
volume = getSubfield("e", datafield);
number = getSubfield("a", datafield);
pages = getSubfield("h", datafield);
}
// 036D seems to contain more information than the other fields
// overwrite information using that field
// 036D also contains information normally found in 036E
if ("036D".equals(tag)) {
// 021 might have been present
if (title != null) {
// convert old title (contained in "a" of 021A) to volume
if (title.startsWith("@")) {
// "@" indicates a number
title = title.substring(1);
}
number = title;
}
// title and subtitle
title = getSubfield("a", datafield);
subtitle = getSubfield("d", datafield);
volume = getSubfield("l", datafield);
}
// series and number
if ("036E".equals(tag)) {
series = getSubfield("a", datafield);
number = getSubfield("l", datafield);
String kor = getSubfield("b", datafield);
if (kor != null) {
series = series + " / " + kor;
}
}
// note
if ("037A".equals(tag)) {
note = getSubfield("a", datafield);
}
// edition
if ("032@".equals(tag)) {
edition = getSubfield("a", datafield);
}
// isbn
if ("004A".equals(tag)) {
final String isbn10 = getSubfield("0", datafield);
final String isbn13 = getSubfield("A", datafield);
if (isbn10 != null) {
isbn = isbn10;
}
if (isbn13 != null) {
isbn = isbn13;
}
}
// Hochschulschriftenvermerk
// Bei einer Verlagsdissertation ist der Ort schon eingetragen
if ("037C".equals(tag)) {
if (address == null) {
address = getSubfield("b", datafield);
if (address != null) {
address = removeSortCharacters(address);
}
}
String st = getSubfield("a", datafield);
if ((st != null) && st.contains("Diss")) {
entryType = StandardEntryType.PhdThesis;
}
}
// journal oder booktitle
/* Problematiken hier: Sowohl für Artikel in
* Zeitschriften als für Beiträge in Büchern
* wird 027D verwendet. Der Titel muß je nach
* Fall booktitle oder journal zugeordnet
* werden. Auch bei Zeitschriften werden hier
* ggf. Verlag und Ort angegeben (sind dann
* eigentlich überflüssig), während bei
* Buchbeiträgen Verlag und Ort wichtig sind
* (sonst in Kategorie 033A).
*/
if ("027D".equals(tag)) {
journal = getSubfield("a", datafield);
booktitle = getSubfield("a", datafield);
address = getSubfield("p", datafield);
publisher = getSubfield("n", datafield);
}
// pagetotal
if ("034D".equals(tag)) {
pagetotal = getSubfield("a", datafield);
if (pagetotal != null) {
// S, S. etc. entfernen
pagetotal = pagetotal.replaceAll(" S\\.?$", "");
}
}
// Behandlung von Konferenzen
if ("030F".equals(tag)) {
address = getSubfield("k", datafield);
if (!"proceedings".equals(entryType.getName())) {
subtitle = getSubfield("a", datafield);
}
entryType = StandardEntryType.Proceedings;
}
// Wenn eine Verlagsdiss vorliegt
if (entryType.equals(StandardEntryType.PhdThesis) && (isbn != null)) {
entryType = StandardEntryType.Book;
}
// Hilfskategorien zur Entscheidung @article
// oder @incollection; hier könnte man auch die
// ISBN herausparsen als Erleichterung für das
// Auffinden der Quelle, die über die
// SRU-Schnittstelle gelieferten Daten zur
// Quelle unvollständig sind (z.B. nicht Serie
// und Nummer angegeben werden)
if ("039B".equals(tag)) {
source = getSubfield("8", datafield);
}
if ("046R".equals(tag) && ((source == null) || source.isEmpty())) {
source = getSubfield("a", datafield);
}
// URLs behandeln
if ("009P".equals(tag) && ("03".equals(datafield.getAttribute("occurrence"))
|| "05".equals(datafield.getAttribute("occurrence"))) && (url == null)) {
url = getSubfield("a", datafield);
}
}
if (source == null) {
source = "";
}
if (author != null) {
author = removeSortCharacters(author);
}
if (editor != null) {
editor = removeSortCharacters(editor);
}
if (title != null) {
title = removeSortCharacters(title);
}
if (subtitle != null) {
subtitle = removeSortCharacters(subtitle);
}
if (bibliographicGenre.startsWith("As")) {
entryType = BibEntry.DEFAULT_TYPE;
if (source.contains("ISBN")) {
entryType = StandardEntryType.InCollection;
}
if (source.contains("ZDB-ID")) {
entryType = StandardEntryType.Article;
}
} else if (bibliographicGenre.isEmpty()) {
entryType = BibEntry.DEFAULT_TYPE;
} else if (bibliographicGenre.startsWith("O")) {
// Oa is standalone so we assume we have a book
if (bibliographicGenre.startsWith("Oa") && isbn != null) {
entryType = StandardEntryType.Book;
}
// 0b is journal
if (bibliographicGenre.startsWith("Ob")) {
entryType = StandardEntryType.Article;
}
}
/*
* Wahrscheinlichkeit, dass ZDB-ID
* vorhanden ist, ist größer als ISBN bei
* Buchbeiträgen. Daher bei As?-Sätzen am besten immer
* dann @incollection annehmen, wenn weder ISBN noch
* ZDB-ID vorhanden sind.
*/
BibEntry result = new BibEntry(entryType);
// Zuordnung der Felder in Abhängigkeit vom Dokumenttyp
if (author != null) {
result.setField(StandardField.AUTHOR, author);
}
if (editor != null) {
result.setField(StandardField.EDITOR, editor);
}
if (title != null) {
result.setField(StandardField.TITLE, title);
}
if (!StringUtil.isNullOrEmpty(subtitle)) {
// ensure that first letter is an upper case letter
// there could be the edge case that the string is only one character long, therefore, this special treatment
// this is Apache commons lang StringUtils.capitalize (https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#capitalize%28java.lang.String%29), but we don't want to add an additional dependency ('org.apache.commons:commons-lang3:3.4')
StringBuilder newSubtitle = new StringBuilder(
Character.toString(Character.toUpperCase(subtitle.charAt(0))));
if (subtitle.length() > 1) {
newSubtitle.append(subtitle.substring(1));
}
result.setField(StandardField.SUBTITLE, newSubtitle.toString());
}
if (publisher != null) {
result.setField(StandardField.PUBLISHER, publisher);
}
if (year != null) {
result.setField(StandardField.YEAR, year);
}
if (address != null) {
result.setField(StandardField.ADDRESS, address);
}
if (series != null) {
result.setField(StandardField.SERIES, series);
}
if (edition != null) {
result.setField(StandardField.EDITION, edition);
}
if (isbn != null) {
result.setField(StandardField.ISBN, isbn);
}
if (issn != null) {
result.setField(StandardField.ISSN, issn);
}
if (number != null) {
result.setField(StandardField.NUMBER, number);
}
if (pagetotal != null) {
result.setField(StandardField.PAGETOTAL, pagetotal);
}
if (pages != null) {
result.setField(StandardField.PAGES, pages);
}
if (volume != null) {
result.setField(StandardField.VOLUME, volume);
}
if (journal != null) {
result.setField(StandardField.JOURNAL, journal);
}
if (ppn != null) {
result.setField(new UnknownField("ppn_GVK"), ppn);
}
if (url != null) {
result.setField(StandardField.URL, url);
}
if (note != null) {
result.setField(StandardField.NOTE, note);
}
if ("article".equals(entryType.getName()) && (journal != null)) {
result.setField(StandardField.JOURNAL, journal);
} else if ("incollection".equals(entryType.getName()) && (booktitle != null)) {
result.setField(StandardField.BOOKTITLE, booktitle);
}
return result;
}
private String getSubfield(String a, Element datafield) {
List<Element> subfields = getChildren("subfield", datafield);
for (Element subfield : subfields) {
if (subfield.getAttribute("code").equalsIgnoreCase(a)) {
return subfield.getTextContent();
}
}
return null;
}
private Element getChild(String name, Element e) {
if (e == null) {
return null;
}
NodeList children = e.getChildNodes();
int j = children.getLength();
for (int i = 0; i < j; i++) {
Node test = children.item(i);
if (test.getNodeType() == Node.ELEMENT_NODE) {
Element entry = (Element) test;
if (entry.getTagName().equals(name)) {
return entry;
}
}
}
return null;
}
private List<Element> getChildren(String name, Element e) {
List<Element> result = new ArrayList<>();
NodeList children = e.getChildNodes();
int j = children.getLength();
for (int i = 0; i < j; i++) {
Node test = children.item(i);
if (test.getNodeType() == Node.ELEMENT_NODE) {
Element entry = (Element) test;
if (entry.getTagName().equals(name)) {
result.add(entry);
}
}
}
return result;
}
private String removeSortCharacters(String input) {
return input.replaceAll("\\@", "");
}
}
| JabRef/jabref | src/main/java/org/jabref/logic/importer/fileformat/PicaXmlParser.java | 4,799 | // 021 might have been present | line_comment | nl | package org.jabref.logic.importer.fileformat;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.jabref.logic.importer.ParseException;
import org.jabref.logic.importer.Parser;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UnknownField;
import org.jabref.model.entry.types.EntryType;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.model.strings.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class PicaXmlParser implements Parser {
private static final Logger LOGGER = LoggerFactory.getLogger(PicaXmlParser.class);
private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
@Override
public List<BibEntry> parseEntries(InputStream inputStream) throws ParseException {
try {
DocumentBuilder dbuild = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
Document content = dbuild.parse(inputStream);
return this.parseEntries(content);
} catch (ParserConfigurationException | SAXException | IOException exception) {
throw new ParseException(exception);
}
}
private List<BibEntry> parseEntries(Document content) {
List<BibEntry> result = new ArrayList<>();
// used for creating test cases
// XMLUtil.printDocument(content);
Element root = (Element) content.getElementsByTagName("zs:searchRetrieveResponse").item(0);
Element srwrecords = getChild("zs:records", root);
if (srwrecords == null) {
// no records found -> return empty list
return result;
}
List<Element> records = getChildren("zs:record", srwrecords);
for (Element gvkRecord : records) {
Element e = getChild("zs:recordData", gvkRecord);
if (e != null) {
e = getChild("record", e);
if (e != null) {
BibEntry bibEntry = parseEntry(e);
// TODO: Add filtering on years (based on org.jabref.logic.importer.fetcher.transformers.YearRangeByFilteringQueryTransformer.getStartYear)
result.add(bibEntry);
}
}
}
return result;
}
private BibEntry parseEntry(Element e) {
String author = null;
String editor = null;
String title = null;
String publisher = null;
String year = null;
String address = null;
String series = null;
String edition = null;
String isbn = null;
String issn = null;
String number = null;
String pagetotal = null;
String volume = null;
String pages = null;
String journal = null;
String ppn = null;
String booktitle = null;
String url = null;
String note = null;
String source = "";
String bibliographicGenre = "";
String subtitle = "";
EntryType entryType = StandardEntryType.Book; // Default
List<Element> datafields = getChildren("datafield", e);
for (Element datafield : datafields) {
String tag = datafield.getAttribute("tag");
LOGGER.debug("tag: " + tag);
// genre/type of the entry https://swbtools.bsz-bw.de/cgi-bin/k10plushelp.pl?cmd=kat&val=0500&katalog=Standard
if ("002@".equals(tag)) {
bibliographicGenre = getSubfield("0", datafield);
if (bibliographicGenre == null) {
bibliographicGenre = "";
}
}
// ppn
if ("003@".equals(tag)) {
ppn = getSubfield("0", datafield);
}
// author
if ("028A".equals(tag)) {
String vorname = getSubfield("d", datafield);
String nachname = getSubfield("a", datafield);
if (author == null) {
author = "";
} else {
author = author.concat(" and ");
}
author = author.concat(vorname + " " + nachname);
}
// author (weiterer)
if ("028B".equals(tag)) {
String vorname = getSubfield("d", datafield);
String nachname = getSubfield("a", datafield);
if (author == null) {
author = "";
} else {
author = author.concat(" and ");
}
author = author.concat(vorname + " " + nachname);
}
// editor
if ("028C".equals(tag)) {
String vorname = getSubfield("d", datafield);
String nachname = getSubfield("a", datafield);
if (editor == null) {
editor = "";
} else {
editor = editor.concat(" and ");
}
editor = editor.concat(vorname + " " + nachname);
}
// title and subtitle
if ("021A".equals(tag)) {
title = getSubfield("a", datafield);
subtitle = getSubfield("d", datafield);
}
// publisher and address
if ("033A".equals(tag)) {
publisher = getSubfield("n", datafield);
address = getSubfield("p", datafield);
}
// year
if ("011@".equals(tag)) {
year = getSubfield("a", datafield);
}
// year, volume, number, pages (year bei Zeitschriften (evtl. redundant mit 011@))
if ("031A".equals(tag)) {
year = getSubfield("j", datafield);
volume = getSubfield("e", datafield);
number = getSubfield("a", datafield);
pages = getSubfield("h", datafield);
}
// 036D seems to contain more information than the other fields
// overwrite information using that field
// 036D also contains information normally found in 036E
if ("036D".equals(tag)) {
// 021 might<SUF>
if (title != null) {
// convert old title (contained in "a" of 021A) to volume
if (title.startsWith("@")) {
// "@" indicates a number
title = title.substring(1);
}
number = title;
}
// title and subtitle
title = getSubfield("a", datafield);
subtitle = getSubfield("d", datafield);
volume = getSubfield("l", datafield);
}
// series and number
if ("036E".equals(tag)) {
series = getSubfield("a", datafield);
number = getSubfield("l", datafield);
String kor = getSubfield("b", datafield);
if (kor != null) {
series = series + " / " + kor;
}
}
// note
if ("037A".equals(tag)) {
note = getSubfield("a", datafield);
}
// edition
if ("032@".equals(tag)) {
edition = getSubfield("a", datafield);
}
// isbn
if ("004A".equals(tag)) {
final String isbn10 = getSubfield("0", datafield);
final String isbn13 = getSubfield("A", datafield);
if (isbn10 != null) {
isbn = isbn10;
}
if (isbn13 != null) {
isbn = isbn13;
}
}
// Hochschulschriftenvermerk
// Bei einer Verlagsdissertation ist der Ort schon eingetragen
if ("037C".equals(tag)) {
if (address == null) {
address = getSubfield("b", datafield);
if (address != null) {
address = removeSortCharacters(address);
}
}
String st = getSubfield("a", datafield);
if ((st != null) && st.contains("Diss")) {
entryType = StandardEntryType.PhdThesis;
}
}
// journal oder booktitle
/* Problematiken hier: Sowohl für Artikel in
* Zeitschriften als für Beiträge in Büchern
* wird 027D verwendet. Der Titel muß je nach
* Fall booktitle oder journal zugeordnet
* werden. Auch bei Zeitschriften werden hier
* ggf. Verlag und Ort angegeben (sind dann
* eigentlich überflüssig), während bei
* Buchbeiträgen Verlag und Ort wichtig sind
* (sonst in Kategorie 033A).
*/
if ("027D".equals(tag)) {
journal = getSubfield("a", datafield);
booktitle = getSubfield("a", datafield);
address = getSubfield("p", datafield);
publisher = getSubfield("n", datafield);
}
// pagetotal
if ("034D".equals(tag)) {
pagetotal = getSubfield("a", datafield);
if (pagetotal != null) {
// S, S. etc. entfernen
pagetotal = pagetotal.replaceAll(" S\\.?$", "");
}
}
// Behandlung von Konferenzen
if ("030F".equals(tag)) {
address = getSubfield("k", datafield);
if (!"proceedings".equals(entryType.getName())) {
subtitle = getSubfield("a", datafield);
}
entryType = StandardEntryType.Proceedings;
}
// Wenn eine Verlagsdiss vorliegt
if (entryType.equals(StandardEntryType.PhdThesis) && (isbn != null)) {
entryType = StandardEntryType.Book;
}
// Hilfskategorien zur Entscheidung @article
// oder @incollection; hier könnte man auch die
// ISBN herausparsen als Erleichterung für das
// Auffinden der Quelle, die über die
// SRU-Schnittstelle gelieferten Daten zur
// Quelle unvollständig sind (z.B. nicht Serie
// und Nummer angegeben werden)
if ("039B".equals(tag)) {
source = getSubfield("8", datafield);
}
if ("046R".equals(tag) && ((source == null) || source.isEmpty())) {
source = getSubfield("a", datafield);
}
// URLs behandeln
if ("009P".equals(tag) && ("03".equals(datafield.getAttribute("occurrence"))
|| "05".equals(datafield.getAttribute("occurrence"))) && (url == null)) {
url = getSubfield("a", datafield);
}
}
if (source == null) {
source = "";
}
if (author != null) {
author = removeSortCharacters(author);
}
if (editor != null) {
editor = removeSortCharacters(editor);
}
if (title != null) {
title = removeSortCharacters(title);
}
if (subtitle != null) {
subtitle = removeSortCharacters(subtitle);
}
if (bibliographicGenre.startsWith("As")) {
entryType = BibEntry.DEFAULT_TYPE;
if (source.contains("ISBN")) {
entryType = StandardEntryType.InCollection;
}
if (source.contains("ZDB-ID")) {
entryType = StandardEntryType.Article;
}
} else if (bibliographicGenre.isEmpty()) {
entryType = BibEntry.DEFAULT_TYPE;
} else if (bibliographicGenre.startsWith("O")) {
// Oa is standalone so we assume we have a book
if (bibliographicGenre.startsWith("Oa") && isbn != null) {
entryType = StandardEntryType.Book;
}
// 0b is journal
if (bibliographicGenre.startsWith("Ob")) {
entryType = StandardEntryType.Article;
}
}
/*
* Wahrscheinlichkeit, dass ZDB-ID
* vorhanden ist, ist größer als ISBN bei
* Buchbeiträgen. Daher bei As?-Sätzen am besten immer
* dann @incollection annehmen, wenn weder ISBN noch
* ZDB-ID vorhanden sind.
*/
BibEntry result = new BibEntry(entryType);
// Zuordnung der Felder in Abhängigkeit vom Dokumenttyp
if (author != null) {
result.setField(StandardField.AUTHOR, author);
}
if (editor != null) {
result.setField(StandardField.EDITOR, editor);
}
if (title != null) {
result.setField(StandardField.TITLE, title);
}
if (!StringUtil.isNullOrEmpty(subtitle)) {
// ensure that first letter is an upper case letter
// there could be the edge case that the string is only one character long, therefore, this special treatment
// this is Apache commons lang StringUtils.capitalize (https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#capitalize%28java.lang.String%29), but we don't want to add an additional dependency ('org.apache.commons:commons-lang3:3.4')
StringBuilder newSubtitle = new StringBuilder(
Character.toString(Character.toUpperCase(subtitle.charAt(0))));
if (subtitle.length() > 1) {
newSubtitle.append(subtitle.substring(1));
}
result.setField(StandardField.SUBTITLE, newSubtitle.toString());
}
if (publisher != null) {
result.setField(StandardField.PUBLISHER, publisher);
}
if (year != null) {
result.setField(StandardField.YEAR, year);
}
if (address != null) {
result.setField(StandardField.ADDRESS, address);
}
if (series != null) {
result.setField(StandardField.SERIES, series);
}
if (edition != null) {
result.setField(StandardField.EDITION, edition);
}
if (isbn != null) {
result.setField(StandardField.ISBN, isbn);
}
if (issn != null) {
result.setField(StandardField.ISSN, issn);
}
if (number != null) {
result.setField(StandardField.NUMBER, number);
}
if (pagetotal != null) {
result.setField(StandardField.PAGETOTAL, pagetotal);
}
if (pages != null) {
result.setField(StandardField.PAGES, pages);
}
if (volume != null) {
result.setField(StandardField.VOLUME, volume);
}
if (journal != null) {
result.setField(StandardField.JOURNAL, journal);
}
if (ppn != null) {
result.setField(new UnknownField("ppn_GVK"), ppn);
}
if (url != null) {
result.setField(StandardField.URL, url);
}
if (note != null) {
result.setField(StandardField.NOTE, note);
}
if ("article".equals(entryType.getName()) && (journal != null)) {
result.setField(StandardField.JOURNAL, journal);
} else if ("incollection".equals(entryType.getName()) && (booktitle != null)) {
result.setField(StandardField.BOOKTITLE, booktitle);
}
return result;
}
private String getSubfield(String a, Element datafield) {
List<Element> subfields = getChildren("subfield", datafield);
for (Element subfield : subfields) {
if (subfield.getAttribute("code").equalsIgnoreCase(a)) {
return subfield.getTextContent();
}
}
return null;
}
private Element getChild(String name, Element e) {
if (e == null) {
return null;
}
NodeList children = e.getChildNodes();
int j = children.getLength();
for (int i = 0; i < j; i++) {
Node test = children.item(i);
if (test.getNodeType() == Node.ELEMENT_NODE) {
Element entry = (Element) test;
if (entry.getTagName().equals(name)) {
return entry;
}
}
}
return null;
}
private List<Element> getChildren(String name, Element e) {
List<Element> result = new ArrayList<>();
NodeList children = e.getChildNodes();
int j = children.getLength();
for (int i = 0; i < j; i++) {
Node test = children.item(i);
if (test.getNodeType() == Node.ELEMENT_NODE) {
Element entry = (Element) test;
if (entry.getTagName().equals(name)) {
result.add(entry);
}
}
}
return result;
}
private String removeSortCharacters(String input) {
return input.replaceAll("\\@", "");
}
}
|
66559_1 | package com.example.jacco.tictactoe;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
// variables
Game game;
int row;
int column;
String[] names = {"t1","t2","t3","t4","t5","t6","t7","t8","t9"};
int[] buttons = {R.id.t1, R.id.t2, R.id.t3, R.id.t4, R.id.t5, R.id.t6, R.id.t7,
R.id.t8, R.id.t9};
int[][] coordinates = {{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}};
boolean AIOn;
int randTile;
// saving state buttons
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
game =(Game) savedInstanceState.getSerializable("Game");
for (int i=0; i<names.length; i++){
// kan niet meer winnen na draaaien en X begint altijd na draaien
Tile tile = game.drawTile(i/3, i%3);
Button button = findViewById(buttons[i]);
if (tile == Tile.CROSS) {
button.setText("X");
} else if (tile == Tile.CIRCLE) {
button.setText("O");
}
}
} else {
game = new Game();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("Game",game);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Game game =(Game) savedInstanceState.getSerializable("Game");
for (int i=0; i<names.length; i++){
// kan niet meer winnen na draaaien en X begint altijd na draaien
Tile tile = game.drawTile(i/3, i%3);
Button button = findViewById(buttons[i]);
if (tile == Tile.CROSS) {
button.setText("X");
} else if (tile == Tile.CIRCLE) {
button.setText("O");
}
}
}
public void tileClicked(View view) {
// find clicked button
int id = view.getId();
int length = buttons.length;
for (int i=0; i<length; i++) {
if (id == buttons[i]) {
row = coordinates[i][0];
column = coordinates[i][1];
}
}
// find out what to draw
Tile tile = game.draw(row, column);
// print on board
Button button = (Button) view;
switch(tile) {
case CROSS:
button.setText("X");
break;
case CIRCLE:
button.setText("O");
break;
case INVALID:
// popup message from:
// https://developer.android.com/guide/topics/ui/notifiers/toasts.html#Positioning
Context context = getApplicationContext();
CharSequence text = "Invalid move!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
break;
// check if AI has to play
// if (AIOn && game.process() != GameState.PLAYER_ONE) {
// // check if there's a good play
//
// if (game.prevent()<9) {
// randTile = game.prevent();
// } else {
// // find a random blank tile and find out what to draw
// Tile tileTest;
// do {
// Random rand = new Random();
// randTile = rand.nextInt(9);
// tileTest = game.test(coordinates[randTile][0], coordinates[randTile][1]);
// }
// while (tileTest == Tile.INVALID || row == coordinates[randTile][0] || column == coordinates[randTile][1]);
// }
//
// game.draw(coordinates[randTile][0],coordinates[randTile][1]);
//
// // print on board
//
// Button button2 = findViewById(buttons[randTile]);
// button2.setText("O");
// }
}
// find out who won and print message
if (game.process() == GameState.DRAW) {
Context context = getApplicationContext();
CharSequence text = "It's a draw! Press new game";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else if (game.process() == GameState.PLAYER_ONE) {
Context context = getApplicationContext();
CharSequence text = "Player one wins! Press new game";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else if (game.process() == GameState.PLAYER_TWO) {
Context context = getApplicationContext();
CharSequence text = "Player two wins! Press new game";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
public void resetClicked(View view) {
// clear all buttons and start new game
for (int i : buttons) {
Button button = findViewById(i);
button.setText("");
}
game = new Game();
}
public void switchCheck(View view) {
Switch aSwitch = findViewById(R.id.switch1);
if (aSwitch.isChecked()) {
AIOn = true;
// clear all buttons and start new game
for (int i : buttons) {
Button button = findViewById(i);
button.setText("");
}
game = new Game();
} else {
AIOn = false;
}
}
}
| JaccovanWijk/TicTacToe | app/src/main/java/com/example/jacco/tictactoe/MainActivity.java | 1,795 | // kan niet meer winnen na draaaien en X begint altijd na draaien | line_comment | nl | package com.example.jacco.tictactoe;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
// variables
Game game;
int row;
int column;
String[] names = {"t1","t2","t3","t4","t5","t6","t7","t8","t9"};
int[] buttons = {R.id.t1, R.id.t2, R.id.t3, R.id.t4, R.id.t5, R.id.t6, R.id.t7,
R.id.t8, R.id.t9};
int[][] coordinates = {{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}};
boolean AIOn;
int randTile;
// saving state buttons
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
game =(Game) savedInstanceState.getSerializable("Game");
for (int i=0; i<names.length; i++){
// kan niet<SUF>
Tile tile = game.drawTile(i/3, i%3);
Button button = findViewById(buttons[i]);
if (tile == Tile.CROSS) {
button.setText("X");
} else if (tile == Tile.CIRCLE) {
button.setText("O");
}
}
} else {
game = new Game();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("Game",game);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Game game =(Game) savedInstanceState.getSerializable("Game");
for (int i=0; i<names.length; i++){
// kan niet meer winnen na draaaien en X begint altijd na draaien
Tile tile = game.drawTile(i/3, i%3);
Button button = findViewById(buttons[i]);
if (tile == Tile.CROSS) {
button.setText("X");
} else if (tile == Tile.CIRCLE) {
button.setText("O");
}
}
}
public void tileClicked(View view) {
// find clicked button
int id = view.getId();
int length = buttons.length;
for (int i=0; i<length; i++) {
if (id == buttons[i]) {
row = coordinates[i][0];
column = coordinates[i][1];
}
}
// find out what to draw
Tile tile = game.draw(row, column);
// print on board
Button button = (Button) view;
switch(tile) {
case CROSS:
button.setText("X");
break;
case CIRCLE:
button.setText("O");
break;
case INVALID:
// popup message from:
// https://developer.android.com/guide/topics/ui/notifiers/toasts.html#Positioning
Context context = getApplicationContext();
CharSequence text = "Invalid move!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
break;
// check if AI has to play
// if (AIOn && game.process() != GameState.PLAYER_ONE) {
// // check if there's a good play
//
// if (game.prevent()<9) {
// randTile = game.prevent();
// } else {
// // find a random blank tile and find out what to draw
// Tile tileTest;
// do {
// Random rand = new Random();
// randTile = rand.nextInt(9);
// tileTest = game.test(coordinates[randTile][0], coordinates[randTile][1]);
// }
// while (tileTest == Tile.INVALID || row == coordinates[randTile][0] || column == coordinates[randTile][1]);
// }
//
// game.draw(coordinates[randTile][0],coordinates[randTile][1]);
//
// // print on board
//
// Button button2 = findViewById(buttons[randTile]);
// button2.setText("O");
// }
}
// find out who won and print message
if (game.process() == GameState.DRAW) {
Context context = getApplicationContext();
CharSequence text = "It's a draw! Press new game";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else if (game.process() == GameState.PLAYER_ONE) {
Context context = getApplicationContext();
CharSequence text = "Player one wins! Press new game";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else if (game.process() == GameState.PLAYER_TWO) {
Context context = getApplicationContext();
CharSequence text = "Player two wins! Press new game";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
public void resetClicked(View view) {
// clear all buttons and start new game
for (int i : buttons) {
Button button = findViewById(i);
button.setText("");
}
game = new Game();
}
public void switchCheck(View view) {
Switch aSwitch = findViewById(R.id.switch1);
if (aSwitch.isChecked()) {
AIOn = true;
// clear all buttons and start new game
for (int i : buttons) {
Button button = findViewById(i);
button.setText("");
}
game = new Game();
} else {
AIOn = false;
}
}
}
|
140583_50 | /*
* Copyright (C) 2015 Jack Jiang(cngeeker.com) The BeautyEye Project.
* All rights reserved.
* Project URL:https://github.com/JackJiang2011/beautyeye
* Version 3.6
*
* Jack Jiang PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
* BEInternalFrameTitlePane.java at 2015-2-1 20:25:36, original version by Jack Jiang.
* You can contact author with [email protected].
*/
package org.jb2011.lnf.beautyeye.ch10_internalframe;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.Icon;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import javax.swing.plaf.metal.MetalLookAndFeel;
import org.jb2011.lnf.beautyeye.ch1_titlepane.BETitlePane;
import org.jb2011.lnf.beautyeye.utils.MySwingUtilities2;
import org.jb2011.lnf.beautyeye.winlnfutils.WinUtils;
/**
* 内部窗体的标题栏UI实现.
*
* @author Jack Jiang
*/
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 一些说明 Start
//BeautyEye外观实现中取消了isPalette的所有特殊处理,isPalette及相关属性在
//该外观中将失去意义,请注意!
//虽然beautyEye是参考自MetalLookAndFeel,但因beautyEye使用了Insets很大的立体边框,
//则如果还要像MetalLookAndFeel实现Palette类型的JInternalFrame则效果会很难看,干脆就就像
//WindowsLookAndFeel一样,不去理会什么Palette,在当前的L&F下没有任何减分。
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 一些说明 END
public class BEInternalFrameTitlePane extends BasicInternalFrameTitlePane
{
// protected boolean isPalette = false;
// protected Icon paletteCloseIcon;
// protected int paletteTitleHeight;
/** The Constant handyEmptyBorder. */
private static final Border handyEmptyBorder = new EmptyBorder(0, 0, 0, 0);
/**
* Key used to lookup Color from UIManager. If this is null,
* <code>getWindowTitleBackground</code> is used.
*/
private String selectedBackgroundKey;
/**
* Key used to lookup Color from UIManager. If this is null,
* <code>getWindowTitleForeground</code> is used.
*/
private String selectedForegroundKey;
/**
* Key used to lookup shadow color from UIManager. If this is null,
* <code>getPrimaryControlDarkShadow</code> is used.
*/
private String selectedShadowKey;
/**
* Boolean indicating the state of the <code>JInternalFrame</code>s
* closable property at <code>updateUI</code> time.
*/
private boolean wasClosable;
/** The buttons width. */
int buttonsWidth = 0;
/**
* Instantiates a new bE internal frame title pane.
*
* @param f the f
*/
public BEInternalFrameTitlePane(JInternalFrame f)
{
super(f);
}
/* (non-Javadoc)
* @see javax.swing.JComponent#addNotify()
*/
public void addNotify()
{
super.addNotify();
// This is done here instead of in installDefaults as I was worried
// that the BasicInternalFrameUI might not be fully initialized, and
// that if this resets the closable state the BasicInternalFrameUI
// Listeners that get notified might be in an odd/uninitialized state.
updateOptionPaneState();
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#installDefaults()
*/
protected void installDefaults()
{
super.installDefaults();
setFont(UIManager.getFont("InternalFrame.titleFont"));
// paletteTitleHeight = UIManager
// .getInt("InternalFrame.paletteTitleHeight");
// paletteCloseIcon = UIManager.getIcon("InternalFrame.paletteCloseIcon");
wasClosable = frame.isClosable();
selectedForegroundKey = selectedBackgroundKey = null;
if (true)
{
setOpaque(false);
}
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#uninstallDefaults()
*/
protected void uninstallDefaults()
{
super.uninstallDefaults();
if (wasClosable != frame.isClosable())
{
frame.setClosable(wasClosable);
}
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#createButtons()
*/
protected void createButtons()
{
super.createButtons();
Boolean paintActive = frame.isSelected() ? Boolean.TRUE : Boolean.FALSE;
iconButton.putClientProperty("paintActive", paintActive);
iconButton.setBorder(handyEmptyBorder);
maxButton.putClientProperty("paintActive", paintActive);
maxButton.setBorder(handyEmptyBorder);
closeButton.putClientProperty("paintActive", paintActive);
closeButton.setBorder(handyEmptyBorder);
// The palette close icon isn't opaque while the regular close icon is.
// This makes sure palette close buttons have the right background.
closeButton.setBackground(MetalLookAndFeel.getPrimaryControlShadow());
if (true)
{
iconButton.setContentAreaFilled(false);
maxButton.setContentAreaFilled(false);
closeButton.setContentAreaFilled(false);
}
}
/**
* Override the parent's method to do nothing. Metal frames do not
* have system menus.
*/
protected void assembleSystemMenu()
{
}
/**
* Override the parent's method to do nothing. Metal frames do not
* have system menus.
*
* @param systemMenu the system menu
*/
protected void addSystemMenuItems(JMenu systemMenu)
{
}
/**
* Override the parent's method to do nothing. Metal frames do not
* have system menus.
*/
protected void showSystemMenu()
{
}
/**
* Override the parent's method avoid creating a menu bar. Metal frames
* do not have system menus.
*/
protected void addSubComponents()
{
add(iconButton);
add(maxButton);
add(closeButton);
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#createPropertyChangeListener()
*/
protected PropertyChangeListener createPropertyChangeListener()
{
return new MetalPropertyChangeHandler();
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#createLayout()
*/
protected LayoutManager createLayout()
{
return new XMetalTitlePaneLayout();
}
/**
* The Class MetalPropertyChangeHandler.
*/
class MetalPropertyChangeHandler extends
BasicInternalFrameTitlePane.PropertyChangeHandler
{
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.PropertyChangeHandler#propertyChange(java.beans.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent evt)
{
String prop = (String) evt.getPropertyName();
if (prop.equals(JInternalFrame.IS_SELECTED_PROPERTY))
{
Boolean b = (Boolean) evt.getNewValue();
iconButton.putClientProperty("paintActive", b);
closeButton.putClientProperty("paintActive", b);
maxButton.putClientProperty("paintActive", b);
}
else if ("JInternalFrame.messageType".equals(prop))
{
updateOptionPaneState();
frame.repaint();
}
super.propertyChange(evt);
}
}
/**
* The Class XZCMetalTitlePaneLayout.
*/
class XMetalTitlePaneLayout extends TitlePaneLayout
{
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#addLayoutComponent(java.lang.String, java.awt.Component)
*/
public void addLayoutComponent(String name, Component c)
{
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#removeLayoutComponent(java.awt.Component)
*/
public void removeLayoutComponent(Component c)
{
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#preferredLayoutSize(java.awt.Container)
*/
public Dimension preferredLayoutSize(Container c)
{
return minimumLayoutSize(c);
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#minimumLayoutSize(java.awt.Container)
*/
public Dimension minimumLayoutSize(Container c)
{
// Compute width.
int width = 30;
if (frame.isClosable())
{
width += 21;
}
if (frame.isMaximizable())
{
width += 16 + (frame.isClosable() ? 10 : 4);
}
if (frame.isIconifiable())
{
width += 16 + (frame.isMaximizable() ? 2
: (frame.isClosable() ? 10 : 4));
}
FontMetrics fm = frame.getFontMetrics(getFont());
String frameTitle = frame.getTitle();
int title_w = frameTitle != null ? MySwingUtilities2.stringWidth(
frame, fm, frameTitle) : 0;
int title_length = frameTitle != null ? frameTitle.length() : 0;
if (title_length > 2)
{
int subtitle_w = MySwingUtilities2.stringWidth(frame, fm, frame
.getTitle().substring(0, 2)
+ "...");
width += (title_w < subtitle_w) ? title_w : subtitle_w;
}
else
{
width += title_w;
}
// Compute height.
int height = 0;
// if (isPalette)
// {
// height = paletteTitleHeight;
// }
// else
{
int fontHeight = fm.getHeight();
fontHeight += 4;//默认是 +=7
Icon icon = frame.getFrameIcon();
int iconHeight = 0;
if (icon != null)
{
// SystemMenuBar forces the icon to be 16x16 or less.
iconHeight = Math.min(icon.getIconHeight(), 16);
}
iconHeight += 5;
height = Math.max(fontHeight, iconHeight) + 5;//默认是 +0,modified by jb2011 2012-06-18
}
return new Dimension(width, height);
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#layoutContainer(java.awt.Container)
*/
public void layoutContainer(Container c)
{
boolean leftToRight = WinUtils.isLeftToRight(frame);
int w = getWidth();
int x = leftToRight ? w : 0;
int y = 5;//默认是0,modified by jb2011
int spacing;
// assumes all buttons have the same dimensions
// these dimensions include the borders
int buttonHeight = closeButton.getIcon().getIconHeight();
int buttonWidth = closeButton.getIcon().getIconWidth();
if (frame.isClosable())
{
// if (isPalette)
// {
// spacing = 3;
// x += leftToRight ? -spacing - (buttonWidth + 2) : spacing;
// closeButton.setBounds(x, y, buttonWidth + 2,
// getHeight() - 4);
// if (!leftToRight)
// x += (buttonWidth + 2);
// }
// else
{
spacing = 4;
x += leftToRight ? -spacing - buttonWidth : spacing;
closeButton.setBounds(x, y, buttonWidth, buttonHeight);
if (!leftToRight)
x += buttonWidth;
}
}
if (frame.isMaximizable())// && !isPalette)
{
spacing = frame.isClosable() ? 2 : 4; //10 : 40
x += leftToRight ? -spacing - buttonWidth : spacing;
maxButton.setBounds(x, y, buttonWidth, buttonHeight);
if (!leftToRight)
x += buttonWidth;
}
if (frame.isIconifiable())// && !isPalette)
{
spacing = frame.isMaximizable() ? 2 : (frame.isClosable() ? 10
: 4);
x += leftToRight ? -spacing - buttonWidth : spacing;
iconButton.setBounds(x, y, buttonWidth, buttonHeight);
if (!leftToRight)
x += buttonWidth;
}
buttonsWidth = leftToRight ? w - x : x;
}
}
// public void paintPalette(Graphics g)
// {
// boolean leftToRight = WinUtils.isLeftToRight(frame);
//
// int width = getWidth();
// int height = getHeight();
//
// Color background = MetalLookAndFeel.getPrimaryControlShadow();
// Color darkShadow = MetalLookAndFeel.getPrimaryControlDarkShadow();
//
// NLTitlePane.paintTitlePane(g, 0, 0, width , height, false
// , background, darkShadow);
// }
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#paintComponent(java.awt.Graphics)
*/
public void paintComponent(Graphics g)
{
// if (isPalette)
// {
// paintPalette(g);
// return;
// }
boolean leftToRight = WinUtils.isLeftToRight(frame);
boolean isSelected = frame.isSelected();//! 选中与否的判断方式,参见border部分的注释
int width = getWidth();
int height = getHeight();
Color background = null;
Color foreground = null;
Color shadow = null;
if (isSelected)
{
// if (!true)
// {
// closeButton.setContentAreaFilled(true);
// maxButton.setContentAreaFilled(true);
// iconButton.setContentAreaFilled(true);
// }
if (selectedBackgroundKey != null)
{
background = UIManager.getColor(selectedBackgroundKey);
}
if (background == null)
{
background = UIManager.getColor("activeCaption");
}
if (selectedForegroundKey != null)
{
foreground = UIManager.getColor(selectedForegroundKey);
}
if (selectedShadowKey != null)
{
shadow = UIManager.getColor(selectedShadowKey);
}
if (shadow == null)
{
shadow = UIManager.getColor("activeCaptionBorder");
}
if (foreground == null)
{
foreground = UIManager.getColor("activeCaptionText");
}
}
else
{
if (!true)
{
closeButton.setContentAreaFilled(false);
maxButton.setContentAreaFilled(false);
iconButton.setContentAreaFilled(false);
}
background = UIManager.getColor("inactiveCaption");
foreground = UIManager.getColor("inactiveCaptionText");
shadow = UIManager.getColor("inactiveCaptionBorder");
}
//---------------------------------------------------绘制标题栏背景
// Color topDarkShadow2 = LNFUtils.getColor(
// background, -40, -40, -40)
// ,topHightLight2 = LNFUtils.getColor(background,
// 60, 60, 60)
// ,topDarkHightLight2 = LNFUtils.getColor(background,
// 20, 20, 20);
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 绘制标题栏背景START */
/*
* ** bug修正 by js,2009-09-30(这因是JDK1.5的Swing底层BUG)
*
* BUG描述:当操作系统的主题切换时,JInternalFrame有时相同的方法this.getBounds()获得的结果是不一样的
* ,这种差异主要在于有时this.getBounds()获得的结果并未包括它的border,主要表现就是结果
* 的(x,y)的坐标是未包含border的坐标,因而这种情况下它的(x=0,y=0),而正确应该
* (x=border.insets.left,y=border.insets.top),如果无视此bug,则titlePane
* 在填充时会变的丑陋。
*
* 解决方法:当确知这个bug发生后,只能以人工方式弥补这种异相,如 强制修正其(x,y)的坐标,并相应地调整
* titlePane的填充区域。
*/
// Border b=frame.getBorder();
// Insets is=b.getBorderInsets(frame);
// Rectangle bounds = this.getBounds();
// int paintTitlePaneX = bounds.x,paintTitlePaneY = bounds.y;
//// boolean isBUG = false;
////// System.out.println("JInternalFrame的UI是否处于正常isBUG="+isBUG);
//// if(isBUG=(is.left!=bounds.x))//当is.left!=bounds.x即可认定已经产生了BUG
//// paintTitlePaneX = is.left;
//// if(isBUG=(is.top!=bounds.y))//当is.left!=bounds.x同样可认定已经产生了BUG
//// paintTitlePaneY = is.top;
//// if(isBUG)//有BUG时的填充
//// {
//// //----------------------------- 以下代码是为了弥补因BUG而产生的填充异常
//// //*以下(1),(2),(3)部分代码是用于弥补BUG下的border外观被titlePane覆盖的错误
//// //*请参见JInternalFrameDialogBorder的边框填充代码(尽量在此处模拟出边框的TOP部分效果)>
//// //水平第一条线(1)
//// g.setColor(topDarkShadow2);
//// g.drawLine(0, 0, width, 0);
//// g.drawLine(0, 1, 0, height);//左坚线
//// g.drawLine(width, 1, width, height);//右坚线
//// //水平第二条线(2)
//// g.setColor(topHightLight2);
//// g.drawLine(1, 1, width-NLMetalBorders.InternalFrameDialogBorder.insets.left, 1);
//// //水平第三条线(3)
//// g.setColor(topDarkHightLight2);
//// g.drawLine(2, 2, width-NLMetalBorders.InternalFrameDialogBorder.insets.left, 2);
////
//// NLTitlePane.paintTitlePane(g//左右空起的部分由Border绘制
//// , paintTitlePaneX//ZCMetalBorders.InternalFrameDialogBorder.insets.left
//// , paintTitlePaneY//ZCMetalBorders.InternalFrameDialogBorder.insets.left
//// , width-is.left*2 //注意此处也因BUG而作了填充区域的调整
//// , height, isSelected
//// , background, shadow);
//// //----------------------------- END
//// }
//// //正常无BUG时的填充
//// else
{
Insets frameInsets = frame.getInsets();
//** Swing BUG:按理说,此处是不需要传入frameInstes的,因父类BasicInternalFrameTitlePane的布局
//是存在BUG(布计算时没有把BorderInstes算入到x、y的偏移中,导致UI中paint时只能自行
//进行增益,否则填充的图璩形肯定就因没有算上borderInstes而错位,详见父类中的
//BasicInternalFrameTitlePane中内部类Handler的layoutContainer方法里
//getNorthPane().setBounds(..)这一段
// NLTitlePane.paintTitlePane(g
// , frameInsets.left//0
// , frameInsets.top//0
// , width-frameInsets.left-frameInsets.right//-0
// , height, isSelected
//// , background, shadow
// );
paintTitlePaneImpl(frameInsets, g, width,height, isSelected);
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 绘制标题栏背景END */
//----------------------------------------------------绘制标题及图标
int titleLength = 0;
int xOffset = leftToRight ? 5 : width - 5;
String frameTitle = frame.getTitle();
Icon icon = frame.getFrameIcon();
if (icon != null)
{
if (!leftToRight)
xOffset -= icon.getIconWidth();
int iconY = ((height / 2) - (icon.getIconHeight() / 2));
icon.paintIcon(frame, g, xOffset +2, iconY+1);//默认是xOffset +0, iconY+0
xOffset += leftToRight ? icon.getIconWidth() + 5 : -5;
}
if (frameTitle != null)
{
Font f = getFont();
g.setFont(f);
FontMetrics fm = MySwingUtilities2.getFontMetrics(frame, g, f);
int fHeight = fm.getHeight();
int yOffset = ((height - fm.getHeight()) / 2) + fm.getAscent();
Rectangle rect = new Rectangle(0, 0, 0, 0);
if (frame.isIconifiable())
{
rect = iconButton.getBounds();
}
else if (frame.isMaximizable())
{
rect = maxButton.getBounds();
}
else if (frame.isClosable())
{
rect = closeButton.getBounds();
}
int titleW;
if (leftToRight)
{
if (rect.x == 0)
{
rect.x = frame.getWidth() - frame.getInsets().right - 2;
}
titleW = rect.x - xOffset - 4;
frameTitle = getTitle(frameTitle, fm, titleW);
}
else
{
titleW = xOffset - rect.x - rect.width - 4;
frameTitle = getTitle(frameTitle, fm, titleW);
xOffset -= MySwingUtilities2.stringWidth(frame, fm, frameTitle);
}
titleLength = MySwingUtilities2.stringWidth(frame, fm, frameTitle);
// g.setColor(Color.DARK_GRAY);//
// NLUtils.drawString(frame, g, frameTitle, xOffset+1, yOffset+1);
g.setColor(foreground);
// if(NLLookAndFeel.windowTitleAntialising)
// NLLookAndFeel.setAntiAliasing((Graphics2D) g,true);
MySwingUtilities2.drawString(frame, g, frameTitle, xOffset, yOffset);
// if(NLLookAndFeel.windowTitleAntialising)
// NLLookAndFeel.setAntiAliasing((Graphics2D) g,false);
xOffset += leftToRight ? titleLength + 5 : -5;
}
}
/**
* Paint title pane impl.
*
* @param frameInsets the frame insets
* @param g the g
* @param width the width
* @param height the height
* @param isSelected the is selected
*/
protected void paintTitlePaneImpl(Insets frameInsets,Graphics g
, int width,int height, boolean isSelected)
{
BETitlePane.paintTitlePane(g
, frameInsets.left//0
, frameInsets.top//0
, width-frameInsets.left-frameInsets.right//-0
, height, isSelected
// , background, shadow
);
}
// public void setPalette(boolean b)
// {
// isPalette = b;
//
// if (isPalette)
// {
// closeButton.setIcon(paletteCloseIcon);
// if (frame.isMaximizable())
// remove(maxButton);
// if (frame.isIconifiable())
// remove(iconButton);
// }
// else
// {
// closeButton.setIcon(closeIcon);
// if (frame.isMaximizable())
// add(maxButton);
// if (frame.isIconifiable())
// add(iconButton);
// }
// revalidate();
// repaint();
// }
/**
* Updates any state dependant upon the JInternalFrame being shown in
* a <code>JOptionPane</code>.
*/
private void updateOptionPaneState()
{
int type = -2;
boolean closable = wasClosable;
Object obj = frame.getClientProperty("JInternalFrame.messageType");
if (obj == null)
{
// Don't change the closable state unless in an JOptionPane.
return;
}
if (obj instanceof Integer)
{
type = ((Integer) obj).intValue();
}
switch (type)
{
case JOptionPane.ERROR_MESSAGE:
selectedBackgroundKey = "OptionPane.errorDialog.titlePane.background";
selectedForegroundKey = "OptionPane.errorDialog.titlePane.foreground";
selectedShadowKey = "OptionPane.errorDialog.titlePane.shadow";
closable = false;
break;
case JOptionPane.QUESTION_MESSAGE:
selectedBackgroundKey = "OptionPane.questionDialog.titlePane.background";
selectedForegroundKey = "OptionPane.questionDialog.titlePane.foreground";
selectedShadowKey = "OptionPane.questionDialog.titlePane.shadow";
closable = false;
break;
case JOptionPane.WARNING_MESSAGE:
selectedBackgroundKey = "OptionPane.warningDialog.titlePane.background";
selectedForegroundKey = "OptionPane.warningDialog.titlePane.foreground";
selectedShadowKey = "OptionPane.warningDialog.titlePane.shadow";
closable = false;
break;
case JOptionPane.INFORMATION_MESSAGE:
case JOptionPane.PLAIN_MESSAGE:
selectedBackgroundKey = selectedForegroundKey = selectedShadowKey = null;
closable = false;
break;
default:
selectedBackgroundKey = selectedForegroundKey = selectedShadowKey = null;
break;
}
if (closable != frame.isClosable())
{
frame.setClosable(closable);
}
}
//改变父类的方法的可见性为public,方便外界调用,仅此而已,
//modified by jb2011
//@see com.sun.java.swing.plaf.windows.uninstallListeners()
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#uninstallListeners()
*/
public void uninstallListeners() {
// Get around protected method in superclass
super.uninstallListeners();
}
}
| JackJiang2011/beautyeye | src_all/beautyeye_v3.7_utf8/src/org/jb2011/lnf/beautyeye/ch10_internalframe/BEInternalFrameTitlePane.java | 7,920 | // getHeight() - 4);
| line_comment | nl | /*
* Copyright (C) 2015 Jack Jiang(cngeeker.com) The BeautyEye Project.
* All rights reserved.
* Project URL:https://github.com/JackJiang2011/beautyeye
* Version 3.6
*
* Jack Jiang PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
* BEInternalFrameTitlePane.java at 2015-2-1 20:25:36, original version by Jack Jiang.
* You can contact author with [email protected].
*/
package org.jb2011.lnf.beautyeye.ch10_internalframe;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.Icon;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import javax.swing.plaf.metal.MetalLookAndFeel;
import org.jb2011.lnf.beautyeye.ch1_titlepane.BETitlePane;
import org.jb2011.lnf.beautyeye.utils.MySwingUtilities2;
import org.jb2011.lnf.beautyeye.winlnfutils.WinUtils;
/**
* 内部窗体的标题栏UI实现.
*
* @author Jack Jiang
*/
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 一些说明 Start
//BeautyEye外观实现中取消了isPalette的所有特殊处理,isPalette及相关属性在
//该外观中将失去意义,请注意!
//虽然beautyEye是参考自MetalLookAndFeel,但因beautyEye使用了Insets很大的立体边框,
//则如果还要像MetalLookAndFeel实现Palette类型的JInternalFrame则效果会很难看,干脆就就像
//WindowsLookAndFeel一样,不去理会什么Palette,在当前的L&F下没有任何减分。
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 一些说明 END
public class BEInternalFrameTitlePane extends BasicInternalFrameTitlePane
{
// protected boolean isPalette = false;
// protected Icon paletteCloseIcon;
// protected int paletteTitleHeight;
/** The Constant handyEmptyBorder. */
private static final Border handyEmptyBorder = new EmptyBorder(0, 0, 0, 0);
/**
* Key used to lookup Color from UIManager. If this is null,
* <code>getWindowTitleBackground</code> is used.
*/
private String selectedBackgroundKey;
/**
* Key used to lookup Color from UIManager. If this is null,
* <code>getWindowTitleForeground</code> is used.
*/
private String selectedForegroundKey;
/**
* Key used to lookup shadow color from UIManager. If this is null,
* <code>getPrimaryControlDarkShadow</code> is used.
*/
private String selectedShadowKey;
/**
* Boolean indicating the state of the <code>JInternalFrame</code>s
* closable property at <code>updateUI</code> time.
*/
private boolean wasClosable;
/** The buttons width. */
int buttonsWidth = 0;
/**
* Instantiates a new bE internal frame title pane.
*
* @param f the f
*/
public BEInternalFrameTitlePane(JInternalFrame f)
{
super(f);
}
/* (non-Javadoc)
* @see javax.swing.JComponent#addNotify()
*/
public void addNotify()
{
super.addNotify();
// This is done here instead of in installDefaults as I was worried
// that the BasicInternalFrameUI might not be fully initialized, and
// that if this resets the closable state the BasicInternalFrameUI
// Listeners that get notified might be in an odd/uninitialized state.
updateOptionPaneState();
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#installDefaults()
*/
protected void installDefaults()
{
super.installDefaults();
setFont(UIManager.getFont("InternalFrame.titleFont"));
// paletteTitleHeight = UIManager
// .getInt("InternalFrame.paletteTitleHeight");
// paletteCloseIcon = UIManager.getIcon("InternalFrame.paletteCloseIcon");
wasClosable = frame.isClosable();
selectedForegroundKey = selectedBackgroundKey = null;
if (true)
{
setOpaque(false);
}
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#uninstallDefaults()
*/
protected void uninstallDefaults()
{
super.uninstallDefaults();
if (wasClosable != frame.isClosable())
{
frame.setClosable(wasClosable);
}
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#createButtons()
*/
protected void createButtons()
{
super.createButtons();
Boolean paintActive = frame.isSelected() ? Boolean.TRUE : Boolean.FALSE;
iconButton.putClientProperty("paintActive", paintActive);
iconButton.setBorder(handyEmptyBorder);
maxButton.putClientProperty("paintActive", paintActive);
maxButton.setBorder(handyEmptyBorder);
closeButton.putClientProperty("paintActive", paintActive);
closeButton.setBorder(handyEmptyBorder);
// The palette close icon isn't opaque while the regular close icon is.
// This makes sure palette close buttons have the right background.
closeButton.setBackground(MetalLookAndFeel.getPrimaryControlShadow());
if (true)
{
iconButton.setContentAreaFilled(false);
maxButton.setContentAreaFilled(false);
closeButton.setContentAreaFilled(false);
}
}
/**
* Override the parent's method to do nothing. Metal frames do not
* have system menus.
*/
protected void assembleSystemMenu()
{
}
/**
* Override the parent's method to do nothing. Metal frames do not
* have system menus.
*
* @param systemMenu the system menu
*/
protected void addSystemMenuItems(JMenu systemMenu)
{
}
/**
* Override the parent's method to do nothing. Metal frames do not
* have system menus.
*/
protected void showSystemMenu()
{
}
/**
* Override the parent's method avoid creating a menu bar. Metal frames
* do not have system menus.
*/
protected void addSubComponents()
{
add(iconButton);
add(maxButton);
add(closeButton);
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#createPropertyChangeListener()
*/
protected PropertyChangeListener createPropertyChangeListener()
{
return new MetalPropertyChangeHandler();
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#createLayout()
*/
protected LayoutManager createLayout()
{
return new XMetalTitlePaneLayout();
}
/**
* The Class MetalPropertyChangeHandler.
*/
class MetalPropertyChangeHandler extends
BasicInternalFrameTitlePane.PropertyChangeHandler
{
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.PropertyChangeHandler#propertyChange(java.beans.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent evt)
{
String prop = (String) evt.getPropertyName();
if (prop.equals(JInternalFrame.IS_SELECTED_PROPERTY))
{
Boolean b = (Boolean) evt.getNewValue();
iconButton.putClientProperty("paintActive", b);
closeButton.putClientProperty("paintActive", b);
maxButton.putClientProperty("paintActive", b);
}
else if ("JInternalFrame.messageType".equals(prop))
{
updateOptionPaneState();
frame.repaint();
}
super.propertyChange(evt);
}
}
/**
* The Class XZCMetalTitlePaneLayout.
*/
class XMetalTitlePaneLayout extends TitlePaneLayout
{
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#addLayoutComponent(java.lang.String, java.awt.Component)
*/
public void addLayoutComponent(String name, Component c)
{
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#removeLayoutComponent(java.awt.Component)
*/
public void removeLayoutComponent(Component c)
{
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#preferredLayoutSize(java.awt.Container)
*/
public Dimension preferredLayoutSize(Container c)
{
return minimumLayoutSize(c);
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#minimumLayoutSize(java.awt.Container)
*/
public Dimension minimumLayoutSize(Container c)
{
// Compute width.
int width = 30;
if (frame.isClosable())
{
width += 21;
}
if (frame.isMaximizable())
{
width += 16 + (frame.isClosable() ? 10 : 4);
}
if (frame.isIconifiable())
{
width += 16 + (frame.isMaximizable() ? 2
: (frame.isClosable() ? 10 : 4));
}
FontMetrics fm = frame.getFontMetrics(getFont());
String frameTitle = frame.getTitle();
int title_w = frameTitle != null ? MySwingUtilities2.stringWidth(
frame, fm, frameTitle) : 0;
int title_length = frameTitle != null ? frameTitle.length() : 0;
if (title_length > 2)
{
int subtitle_w = MySwingUtilities2.stringWidth(frame, fm, frame
.getTitle().substring(0, 2)
+ "...");
width += (title_w < subtitle_w) ? title_w : subtitle_w;
}
else
{
width += title_w;
}
// Compute height.
int height = 0;
// if (isPalette)
// {
// height = paletteTitleHeight;
// }
// else
{
int fontHeight = fm.getHeight();
fontHeight += 4;//默认是 +=7
Icon icon = frame.getFrameIcon();
int iconHeight = 0;
if (icon != null)
{
// SystemMenuBar forces the icon to be 16x16 or less.
iconHeight = Math.min(icon.getIconHeight(), 16);
}
iconHeight += 5;
height = Math.max(fontHeight, iconHeight) + 5;//默认是 +0,modified by jb2011 2012-06-18
}
return new Dimension(width, height);
}
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#layoutContainer(java.awt.Container)
*/
public void layoutContainer(Container c)
{
boolean leftToRight = WinUtils.isLeftToRight(frame);
int w = getWidth();
int x = leftToRight ? w : 0;
int y = 5;//默认是0,modified by jb2011
int spacing;
// assumes all buttons have the same dimensions
// these dimensions include the borders
int buttonHeight = closeButton.getIcon().getIconHeight();
int buttonWidth = closeButton.getIcon().getIconWidth();
if (frame.isClosable())
{
// if (isPalette)
// {
// spacing = 3;
// x += leftToRight ? -spacing - (buttonWidth + 2) : spacing;
// closeButton.setBounds(x, y, buttonWidth + 2,
// getHeight() -<SUF>
// if (!leftToRight)
// x += (buttonWidth + 2);
// }
// else
{
spacing = 4;
x += leftToRight ? -spacing - buttonWidth : spacing;
closeButton.setBounds(x, y, buttonWidth, buttonHeight);
if (!leftToRight)
x += buttonWidth;
}
}
if (frame.isMaximizable())// && !isPalette)
{
spacing = frame.isClosable() ? 2 : 4; //10 : 40
x += leftToRight ? -spacing - buttonWidth : spacing;
maxButton.setBounds(x, y, buttonWidth, buttonHeight);
if (!leftToRight)
x += buttonWidth;
}
if (frame.isIconifiable())// && !isPalette)
{
spacing = frame.isMaximizable() ? 2 : (frame.isClosable() ? 10
: 4);
x += leftToRight ? -spacing - buttonWidth : spacing;
iconButton.setBounds(x, y, buttonWidth, buttonHeight);
if (!leftToRight)
x += buttonWidth;
}
buttonsWidth = leftToRight ? w - x : x;
}
}
// public void paintPalette(Graphics g)
// {
// boolean leftToRight = WinUtils.isLeftToRight(frame);
//
// int width = getWidth();
// int height = getHeight();
//
// Color background = MetalLookAndFeel.getPrimaryControlShadow();
// Color darkShadow = MetalLookAndFeel.getPrimaryControlDarkShadow();
//
// NLTitlePane.paintTitlePane(g, 0, 0, width , height, false
// , background, darkShadow);
// }
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#paintComponent(java.awt.Graphics)
*/
public void paintComponent(Graphics g)
{
// if (isPalette)
// {
// paintPalette(g);
// return;
// }
boolean leftToRight = WinUtils.isLeftToRight(frame);
boolean isSelected = frame.isSelected();//! 选中与否的判断方式,参见border部分的注释
int width = getWidth();
int height = getHeight();
Color background = null;
Color foreground = null;
Color shadow = null;
if (isSelected)
{
// if (!true)
// {
// closeButton.setContentAreaFilled(true);
// maxButton.setContentAreaFilled(true);
// iconButton.setContentAreaFilled(true);
// }
if (selectedBackgroundKey != null)
{
background = UIManager.getColor(selectedBackgroundKey);
}
if (background == null)
{
background = UIManager.getColor("activeCaption");
}
if (selectedForegroundKey != null)
{
foreground = UIManager.getColor(selectedForegroundKey);
}
if (selectedShadowKey != null)
{
shadow = UIManager.getColor(selectedShadowKey);
}
if (shadow == null)
{
shadow = UIManager.getColor("activeCaptionBorder");
}
if (foreground == null)
{
foreground = UIManager.getColor("activeCaptionText");
}
}
else
{
if (!true)
{
closeButton.setContentAreaFilled(false);
maxButton.setContentAreaFilled(false);
iconButton.setContentAreaFilled(false);
}
background = UIManager.getColor("inactiveCaption");
foreground = UIManager.getColor("inactiveCaptionText");
shadow = UIManager.getColor("inactiveCaptionBorder");
}
//---------------------------------------------------绘制标题栏背景
// Color topDarkShadow2 = LNFUtils.getColor(
// background, -40, -40, -40)
// ,topHightLight2 = LNFUtils.getColor(background,
// 60, 60, 60)
// ,topDarkHightLight2 = LNFUtils.getColor(background,
// 20, 20, 20);
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 绘制标题栏背景START */
/*
* ** bug修正 by js,2009-09-30(这因是JDK1.5的Swing底层BUG)
*
* BUG描述:当操作系统的主题切换时,JInternalFrame有时相同的方法this.getBounds()获得的结果是不一样的
* ,这种差异主要在于有时this.getBounds()获得的结果并未包括它的border,主要表现就是结果
* 的(x,y)的坐标是未包含border的坐标,因而这种情况下它的(x=0,y=0),而正确应该
* (x=border.insets.left,y=border.insets.top),如果无视此bug,则titlePane
* 在填充时会变的丑陋。
*
* 解决方法:当确知这个bug发生后,只能以人工方式弥补这种异相,如 强制修正其(x,y)的坐标,并相应地调整
* titlePane的填充区域。
*/
// Border b=frame.getBorder();
// Insets is=b.getBorderInsets(frame);
// Rectangle bounds = this.getBounds();
// int paintTitlePaneX = bounds.x,paintTitlePaneY = bounds.y;
//// boolean isBUG = false;
////// System.out.println("JInternalFrame的UI是否处于正常isBUG="+isBUG);
//// if(isBUG=(is.left!=bounds.x))//当is.left!=bounds.x即可认定已经产生了BUG
//// paintTitlePaneX = is.left;
//// if(isBUG=(is.top!=bounds.y))//当is.left!=bounds.x同样可认定已经产生了BUG
//// paintTitlePaneY = is.top;
//// if(isBUG)//有BUG时的填充
//// {
//// //----------------------------- 以下代码是为了弥补因BUG而产生的填充异常
//// //*以下(1),(2),(3)部分代码是用于弥补BUG下的border外观被titlePane覆盖的错误
//// //*请参见JInternalFrameDialogBorder的边框填充代码(尽量在此处模拟出边框的TOP部分效果)>
//// //水平第一条线(1)
//// g.setColor(topDarkShadow2);
//// g.drawLine(0, 0, width, 0);
//// g.drawLine(0, 1, 0, height);//左坚线
//// g.drawLine(width, 1, width, height);//右坚线
//// //水平第二条线(2)
//// g.setColor(topHightLight2);
//// g.drawLine(1, 1, width-NLMetalBorders.InternalFrameDialogBorder.insets.left, 1);
//// //水平第三条线(3)
//// g.setColor(topDarkHightLight2);
//// g.drawLine(2, 2, width-NLMetalBorders.InternalFrameDialogBorder.insets.left, 2);
////
//// NLTitlePane.paintTitlePane(g//左右空起的部分由Border绘制
//// , paintTitlePaneX//ZCMetalBorders.InternalFrameDialogBorder.insets.left
//// , paintTitlePaneY//ZCMetalBorders.InternalFrameDialogBorder.insets.left
//// , width-is.left*2 //注意此处也因BUG而作了填充区域的调整
//// , height, isSelected
//// , background, shadow);
//// //----------------------------- END
//// }
//// //正常无BUG时的填充
//// else
{
Insets frameInsets = frame.getInsets();
//** Swing BUG:按理说,此处是不需要传入frameInstes的,因父类BasicInternalFrameTitlePane的布局
//是存在BUG(布计算时没有把BorderInstes算入到x、y的偏移中,导致UI中paint时只能自行
//进行增益,否则填充的图璩形肯定就因没有算上borderInstes而错位,详见父类中的
//BasicInternalFrameTitlePane中内部类Handler的layoutContainer方法里
//getNorthPane().setBounds(..)这一段
// NLTitlePane.paintTitlePane(g
// , frameInsets.left//0
// , frameInsets.top//0
// , width-frameInsets.left-frameInsets.right//-0
// , height, isSelected
//// , background, shadow
// );
paintTitlePaneImpl(frameInsets, g, width,height, isSelected);
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 绘制标题栏背景END */
//----------------------------------------------------绘制标题及图标
int titleLength = 0;
int xOffset = leftToRight ? 5 : width - 5;
String frameTitle = frame.getTitle();
Icon icon = frame.getFrameIcon();
if (icon != null)
{
if (!leftToRight)
xOffset -= icon.getIconWidth();
int iconY = ((height / 2) - (icon.getIconHeight() / 2));
icon.paintIcon(frame, g, xOffset +2, iconY+1);//默认是xOffset +0, iconY+0
xOffset += leftToRight ? icon.getIconWidth() + 5 : -5;
}
if (frameTitle != null)
{
Font f = getFont();
g.setFont(f);
FontMetrics fm = MySwingUtilities2.getFontMetrics(frame, g, f);
int fHeight = fm.getHeight();
int yOffset = ((height - fm.getHeight()) / 2) + fm.getAscent();
Rectangle rect = new Rectangle(0, 0, 0, 0);
if (frame.isIconifiable())
{
rect = iconButton.getBounds();
}
else if (frame.isMaximizable())
{
rect = maxButton.getBounds();
}
else if (frame.isClosable())
{
rect = closeButton.getBounds();
}
int titleW;
if (leftToRight)
{
if (rect.x == 0)
{
rect.x = frame.getWidth() - frame.getInsets().right - 2;
}
titleW = rect.x - xOffset - 4;
frameTitle = getTitle(frameTitle, fm, titleW);
}
else
{
titleW = xOffset - rect.x - rect.width - 4;
frameTitle = getTitle(frameTitle, fm, titleW);
xOffset -= MySwingUtilities2.stringWidth(frame, fm, frameTitle);
}
titleLength = MySwingUtilities2.stringWidth(frame, fm, frameTitle);
// g.setColor(Color.DARK_GRAY);//
// NLUtils.drawString(frame, g, frameTitle, xOffset+1, yOffset+1);
g.setColor(foreground);
// if(NLLookAndFeel.windowTitleAntialising)
// NLLookAndFeel.setAntiAliasing((Graphics2D) g,true);
MySwingUtilities2.drawString(frame, g, frameTitle, xOffset, yOffset);
// if(NLLookAndFeel.windowTitleAntialising)
// NLLookAndFeel.setAntiAliasing((Graphics2D) g,false);
xOffset += leftToRight ? titleLength + 5 : -5;
}
}
/**
* Paint title pane impl.
*
* @param frameInsets the frame insets
* @param g the g
* @param width the width
* @param height the height
* @param isSelected the is selected
*/
protected void paintTitlePaneImpl(Insets frameInsets,Graphics g
, int width,int height, boolean isSelected)
{
BETitlePane.paintTitlePane(g
, frameInsets.left//0
, frameInsets.top//0
, width-frameInsets.left-frameInsets.right//-0
, height, isSelected
// , background, shadow
);
}
// public void setPalette(boolean b)
// {
// isPalette = b;
//
// if (isPalette)
// {
// closeButton.setIcon(paletteCloseIcon);
// if (frame.isMaximizable())
// remove(maxButton);
// if (frame.isIconifiable())
// remove(iconButton);
// }
// else
// {
// closeButton.setIcon(closeIcon);
// if (frame.isMaximizable())
// add(maxButton);
// if (frame.isIconifiable())
// add(iconButton);
// }
// revalidate();
// repaint();
// }
/**
* Updates any state dependant upon the JInternalFrame being shown in
* a <code>JOptionPane</code>.
*/
private void updateOptionPaneState()
{
int type = -2;
boolean closable = wasClosable;
Object obj = frame.getClientProperty("JInternalFrame.messageType");
if (obj == null)
{
// Don't change the closable state unless in an JOptionPane.
return;
}
if (obj instanceof Integer)
{
type = ((Integer) obj).intValue();
}
switch (type)
{
case JOptionPane.ERROR_MESSAGE:
selectedBackgroundKey = "OptionPane.errorDialog.titlePane.background";
selectedForegroundKey = "OptionPane.errorDialog.titlePane.foreground";
selectedShadowKey = "OptionPane.errorDialog.titlePane.shadow";
closable = false;
break;
case JOptionPane.QUESTION_MESSAGE:
selectedBackgroundKey = "OptionPane.questionDialog.titlePane.background";
selectedForegroundKey = "OptionPane.questionDialog.titlePane.foreground";
selectedShadowKey = "OptionPane.questionDialog.titlePane.shadow";
closable = false;
break;
case JOptionPane.WARNING_MESSAGE:
selectedBackgroundKey = "OptionPane.warningDialog.titlePane.background";
selectedForegroundKey = "OptionPane.warningDialog.titlePane.foreground";
selectedShadowKey = "OptionPane.warningDialog.titlePane.shadow";
closable = false;
break;
case JOptionPane.INFORMATION_MESSAGE:
case JOptionPane.PLAIN_MESSAGE:
selectedBackgroundKey = selectedForegroundKey = selectedShadowKey = null;
closable = false;
break;
default:
selectedBackgroundKey = selectedForegroundKey = selectedShadowKey = null;
break;
}
if (closable != frame.isClosable())
{
frame.setClosable(closable);
}
}
//改变父类的方法的可见性为public,方便外界调用,仅此而已,
//modified by jb2011
//@see com.sun.java.swing.plaf.windows.uninstallListeners()
/* (non-Javadoc)
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#uninstallListeners()
*/
public void uninstallListeners() {
// Get around protected method in superclass
super.uninstallListeners();
}
}
|
175575_7 | import java.util.Scanner;
public class Exercise19 {
public static void main(String[] args) {
// INTERLEAVE
Scanner console = new Scanner(System.in);
System.out.print("First string: ");
String first = console.nextLine();
System.out.print("Second string: ");
String second = console.nextLine();
// 1. Write a loop to interleave two strings to form a new string.
// To interleave, during each loop take one character from the first string and add it to the result
// and take one character from the second string and add it to the result.
// If there are no more characters available, don't add characters.
// 2. Print the result.
int max = Math.max(first.length(),second.length());
String mix = "";
for (int i = 0; i < max; i++) {
if (i < Math.min(first.length(), second.length())) {
mix += (Character.toString(first.charAt(i)) + Character.toString(second.charAt(i)));
continue;
}
if (first.length() == max){
mix += (Character.toString((first.charAt(i))));
}
if (second.length() == max){
mix += (Character.toString((second.charAt(i))));
}
}
System.out.println(mix);
// Examples
// "abc", "123" -> "a1b2c3"
// "cat", "dog" -> "cdaotg"
// "wonder", "o" -> "woonder"
// "B", "igstar" -> "Bigstar"
// "", "huh?" -> "huh?"
// "wha?", "" -> "wha?"
}
}
| JacobBMitchell/java-exercises-JacobMitchell | week-01/exercises/repetition-exercises/src/Exercise19.java | 479 | // "wonder", "o" -> "woonder"
| line_comment | nl | import java.util.Scanner;
public class Exercise19 {
public static void main(String[] args) {
// INTERLEAVE
Scanner console = new Scanner(System.in);
System.out.print("First string: ");
String first = console.nextLine();
System.out.print("Second string: ");
String second = console.nextLine();
// 1. Write a loop to interleave two strings to form a new string.
// To interleave, during each loop take one character from the first string and add it to the result
// and take one character from the second string and add it to the result.
// If there are no more characters available, don't add characters.
// 2. Print the result.
int max = Math.max(first.length(),second.length());
String mix = "";
for (int i = 0; i < max; i++) {
if (i < Math.min(first.length(), second.length())) {
mix += (Character.toString(first.charAt(i)) + Character.toString(second.charAt(i)));
continue;
}
if (first.length() == max){
mix += (Character.toString((first.charAt(i))));
}
if (second.length() == max){
mix += (Character.toString((second.charAt(i))));
}
}
System.out.println(mix);
// Examples
// "abc", "123" -> "a1b2c3"
// "cat", "dog" -> "cdaotg"
// "wonder", "o"<SUF>
// "B", "igstar" -> "Bigstar"
// "", "huh?" -> "huh?"
// "wha?", "" -> "wha?"
}
}
|
208918_0 | package Data;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class Agenda {
private final ArrayList<Artist> artistList;
private final ArrayList<Podium> podiumList;
private final ArrayList<Performance> performanceList;
private final File artistFile;
private final File podiumFile;
private final File performanceFile;
public Agenda() {
this.artistList = new ArrayList<>();
this.podiumList = new ArrayList<>();
this.performanceList = new ArrayList<>();
this.artistFile = new File("Files/Artist.txt");
this.podiumFile = new File("Files/Podium.txt");
this.performanceFile = new File("Files/Performance.txt");
}
public void save() {
String fileName = this.artistFile.getPath();
try (PrintWriter print = new PrintWriter(fileName)) {
for (Artist artist : this.artistList) {
print.print(artist.getName());
print.print("_");
print.println(artist.getGenre());
}
} catch (Exception e) {
e.printStackTrace();
}
fileName = podiumFile.getPath();
try (PrintWriter print = new PrintWriter(fileName)) {
for (Podium podium : podiumList) {
print.println(podium.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
fileName = performanceFile.getPath();
try (PrintWriter print = new PrintWriter(fileName)) {
for (Performance performance : performanceList) {
print.print(performance.getPodium().getName());
print.print("_");
print.print(performance.getStartTimeGui());
print.print("_");
print.print(performance.getEndTimeGui());
print.print("_");
for (Artist artist : performance.getArtists()) {
print.print(artist.getName());
print.print("/");
}
print.print("_");
print.println(performance.getPopularity());
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
public void load() {
artistList.clear();
String name;
String genre;
String[] input;
try (Scanner scanner = new Scanner(this.artistFile)) {
while (scanner.hasNext()) {
input = scanner.nextLine().split("_");
name = input[0];
genre = input[1];
this.artistList.add(new Artist(name, genre));
}
} catch (Exception exception) {
exception.printStackTrace();
}
this.podiumList.clear();
try (Scanner scanner = new Scanner(this.podiumFile)) {
while (scanner.hasNext()) {
this.podiumList.add(new Podium(scanner.nextLine()));
}
} catch (Exception exception) {
exception.printStackTrace();
}
this.performanceList.clear();
Podium podiumInput = new Podium("Undefined");
String startTijd;
String endTijd;
int populariteit;
String[] artists;
ArrayList<Artist> list = new ArrayList<>();
try (Scanner scanner1 = new Scanner(this.performanceFile)) {
while (scanner1.hasNext()) {
input = scanner1.nextLine().split("_");
for (Podium podium : this.podiumList) {
if (podium.getName().equals(input[0])) {
podiumInput = podium;
}
}
startTijd = input[1];
endTijd = input[2];
artists = input[3].split("/");
for (String artistName : artists) {
for (Artist artist : this.artistList) {
if (artist.getName().equals(artistName)) {
list.add(artist);
}
}
}
populariteit = Integer.parseInt(input[4]);
this.performanceList.add(new Performance(podiumInput, startTijd, endTijd, list, populariteit));
list.clear();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
public ArrayList<Artist> getArtistList() {
return artistList;
}
public ArrayList<Podium> getPodiumList() {
return podiumList;
}
public ArrayList<Performance> getPerformanceList() {
return performanceList;
}
public void addPodium(Podium podium) {
if (podiumList.size() < 7) {
this.podiumList.add(podium);
}
}
public void addArtist(Artist artist) {
this.artistList.add(artist);
}
public void addPerformance(Performance performance) {
if (checkForOverlap(performance)) {
this.performanceList.add(performance);
}
}
public void removePerformance(Performance performance) {
performanceList.remove(performance);
}
//methode voor het controleren of er geen dubbele boeking is
public boolean checkForOverlap(Performance performance) {
if (performance.getStartTime() >= performance.getEndTime()) {
return false;
}
int startTime = performance.getStartTime();
int endTime = performance.getEndTime();
for (Performance p : performanceList) {
int pStartTime = p.getStartTime();
int pEndTime = p.getEndTime();
if (endTime >= pStartTime && endTime <= pEndTime || startTime >= pStartTime && startTime <= pEndTime) {
if (p.getPodium().equals(performance.getPodium()) || p.getArtist().equals(performance.getArtist())) {
return false;
}
}
}
return true;
}
//methode voor het controleren of er geen dubbele boeking is voor de setters
public boolean checkForOverlapSetter(Performance performance, Performance updatedPerformance) {
if (updatedPerformance.getStartTime() >= updatedPerformance.getEndTime()) {
return false;
}
int startTime = updatedPerformance.getStartTime();
int endTime = updatedPerformance.getEndTime();
for (Performance p : performanceList) {
int pStartTime = p.getStartTime();
int pEndTime = p.getEndTime();
if (p.equals(performance)) {
continue;
}
if (endTime >= pStartTime && endTime <= pEndTime || startTime >= pStartTime && startTime <= pEndTime) {
if (p.getPodium().equals(updatedPerformance.getPodium()) || p.getArtist().equals(updatedPerformance.getArtist())) {
return false;
}
}
}
return true;
}
public ArrayList<Performance> getLivePerformances(String hour, String minutes) {
ArrayList<Performance> performances = new ArrayList<>();
for (Performance performance : this.performanceList) {
if (performance.isLive(hour, minutes)) {
performances.add(performance);
}
}
return performances;
}
@Override
public String toString() {
return "Agenda: " +
"Artiesten: " + artistList +
", Podia: " + podiumList +
", Optredens: " + performanceList;
}
}
| Jahper/FestivalPlanner | src/Data/Agenda.java | 2,114 | //methode voor het controleren of er geen dubbele boeking is
| line_comment | nl | package Data;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class Agenda {
private final ArrayList<Artist> artistList;
private final ArrayList<Podium> podiumList;
private final ArrayList<Performance> performanceList;
private final File artistFile;
private final File podiumFile;
private final File performanceFile;
public Agenda() {
this.artistList = new ArrayList<>();
this.podiumList = new ArrayList<>();
this.performanceList = new ArrayList<>();
this.artistFile = new File("Files/Artist.txt");
this.podiumFile = new File("Files/Podium.txt");
this.performanceFile = new File("Files/Performance.txt");
}
public void save() {
String fileName = this.artistFile.getPath();
try (PrintWriter print = new PrintWriter(fileName)) {
for (Artist artist : this.artistList) {
print.print(artist.getName());
print.print("_");
print.println(artist.getGenre());
}
} catch (Exception e) {
e.printStackTrace();
}
fileName = podiumFile.getPath();
try (PrintWriter print = new PrintWriter(fileName)) {
for (Podium podium : podiumList) {
print.println(podium.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
fileName = performanceFile.getPath();
try (PrintWriter print = new PrintWriter(fileName)) {
for (Performance performance : performanceList) {
print.print(performance.getPodium().getName());
print.print("_");
print.print(performance.getStartTimeGui());
print.print("_");
print.print(performance.getEndTimeGui());
print.print("_");
for (Artist artist : performance.getArtists()) {
print.print(artist.getName());
print.print("/");
}
print.print("_");
print.println(performance.getPopularity());
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
public void load() {
artistList.clear();
String name;
String genre;
String[] input;
try (Scanner scanner = new Scanner(this.artistFile)) {
while (scanner.hasNext()) {
input = scanner.nextLine().split("_");
name = input[0];
genre = input[1];
this.artistList.add(new Artist(name, genre));
}
} catch (Exception exception) {
exception.printStackTrace();
}
this.podiumList.clear();
try (Scanner scanner = new Scanner(this.podiumFile)) {
while (scanner.hasNext()) {
this.podiumList.add(new Podium(scanner.nextLine()));
}
} catch (Exception exception) {
exception.printStackTrace();
}
this.performanceList.clear();
Podium podiumInput = new Podium("Undefined");
String startTijd;
String endTijd;
int populariteit;
String[] artists;
ArrayList<Artist> list = new ArrayList<>();
try (Scanner scanner1 = new Scanner(this.performanceFile)) {
while (scanner1.hasNext()) {
input = scanner1.nextLine().split("_");
for (Podium podium : this.podiumList) {
if (podium.getName().equals(input[0])) {
podiumInput = podium;
}
}
startTijd = input[1];
endTijd = input[2];
artists = input[3].split("/");
for (String artistName : artists) {
for (Artist artist : this.artistList) {
if (artist.getName().equals(artistName)) {
list.add(artist);
}
}
}
populariteit = Integer.parseInt(input[4]);
this.performanceList.add(new Performance(podiumInput, startTijd, endTijd, list, populariteit));
list.clear();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
public ArrayList<Artist> getArtistList() {
return artistList;
}
public ArrayList<Podium> getPodiumList() {
return podiumList;
}
public ArrayList<Performance> getPerformanceList() {
return performanceList;
}
public void addPodium(Podium podium) {
if (podiumList.size() < 7) {
this.podiumList.add(podium);
}
}
public void addArtist(Artist artist) {
this.artistList.add(artist);
}
public void addPerformance(Performance performance) {
if (checkForOverlap(performance)) {
this.performanceList.add(performance);
}
}
public void removePerformance(Performance performance) {
performanceList.remove(performance);
}
//methode voor<SUF>
public boolean checkForOverlap(Performance performance) {
if (performance.getStartTime() >= performance.getEndTime()) {
return false;
}
int startTime = performance.getStartTime();
int endTime = performance.getEndTime();
for (Performance p : performanceList) {
int pStartTime = p.getStartTime();
int pEndTime = p.getEndTime();
if (endTime >= pStartTime && endTime <= pEndTime || startTime >= pStartTime && startTime <= pEndTime) {
if (p.getPodium().equals(performance.getPodium()) || p.getArtist().equals(performance.getArtist())) {
return false;
}
}
}
return true;
}
//methode voor het controleren of er geen dubbele boeking is voor de setters
public boolean checkForOverlapSetter(Performance performance, Performance updatedPerformance) {
if (updatedPerformance.getStartTime() >= updatedPerformance.getEndTime()) {
return false;
}
int startTime = updatedPerformance.getStartTime();
int endTime = updatedPerformance.getEndTime();
for (Performance p : performanceList) {
int pStartTime = p.getStartTime();
int pEndTime = p.getEndTime();
if (p.equals(performance)) {
continue;
}
if (endTime >= pStartTime && endTime <= pEndTime || startTime >= pStartTime && startTime <= pEndTime) {
if (p.getPodium().equals(updatedPerformance.getPodium()) || p.getArtist().equals(updatedPerformance.getArtist())) {
return false;
}
}
}
return true;
}
public ArrayList<Performance> getLivePerformances(String hour, String minutes) {
ArrayList<Performance> performances = new ArrayList<>();
for (Performance performance : this.performanceList) {
if (performance.isLive(hour, minutes)) {
performances.add(performance);
}
}
return performances;
}
@Override
public String toString() {
return "Agenda: " +
"Artiesten: " + artistList +
", Podia: " + podiumList +
", Optredens: " + performanceList;
}
}
|
206367_4 | package sr.unasat.bewakingsBedrijf.app.scherm.bewaker;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.bewaker.Bewaker;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.bewaker.BewakerDatabase;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.rooster.RoosterDatabase;
import sr.unasat.bewakingsBedrijf.app.scherm.algemeen.StartScherm;
import sr.unasat.bewakingsBedrijf.app.scherm.rooster.RoosterScherm;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
/**
* Created by Jair on 5/31/2016.
*/
public class BewakerScherm extends JFrame {
BewakerDatabase bewakerDatabase = null;
JPanel viewAllPan = new JPanel(new BorderLayout()), viewBewakerPan= new JPanel(new BorderLayout()),
updateBewakerPan= new JPanel(new BorderLayout()), newBewakerPan= new JPanel(new BorderLayout()),
deleteBewakerPan= new JPanel(new BorderLayout()), homePan= new JPanel();
JTabbedPane jTabbedPane= new JTabbedPane(SwingConstants.LEFT);
ArrayList bewakerArrayList= new ArrayList<String>();
ArrayList<Bewaker> bewakerArraylistObject= new ArrayList();
ArrayList <Integer> bewakerArrayListID = new ArrayList();
private JList outputList;
private DefaultListModel listModel;
private DefaultTableModel listTableModel;
private JTable outputTable;
ImageIcon allIcon= new ImageIcon(getClass().getResource("allBew.png"));
ImageIcon deleteIcon= new ImageIcon(getClass().getResource("deleteBew.png"));
ImageIcon newIcon= new ImageIcon(getClass().getResource("newBew.png"));
ImageIcon updateIcon= new ImageIcon(getClass().getResource("updateBew.png"));
ImageIcon viewIcon= new ImageIcon(getClass().getResource("viewBew.png"));
ImageIcon homeIcon= new ImageIcon(getClass().getResource("home.png"));
public BewakerScherm(){
jTabbedPane.addTab("all bewakers",allIcon,viewAllPan);
jTabbedPane.addTab("view bewaker",viewIcon, viewBewakerPan);
jTabbedPane.addTab("update bewaker",updateIcon ,updateBewakerPan);
jTabbedPane.addTab("new Bewaker",newIcon, newBewakerPan);
jTabbedPane.addTab("delete Bewaker",deleteIcon, deleteBewakerPan);
jTabbedPane.addTab("home",homeIcon, homePan);
viewAllPanel();
getContentPane().setBackground(new Color(7, 84, 127));
jTabbedPane.setBackground(new Color(148, 178, 173));
add(jTabbedPane);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(900,500);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
jTabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (viewAllPan.isShowing()){
viewAllPanel();
}else{
viewAllPan.removeAll();
}
if (viewBewakerPan.isShowing()){
viewBewakerPanel();
}else {
viewBewakerPan.removeAll();
}
if (updateBewakerPan.isShowing()){
updateBewakerPanel();
}else{
updateBewakerPan.removeAll();
}
if (newBewakerPan.isShowing()){
newBewakerPanel();
}else {
newBewakerPan.removeAll();
}
if (homePan.isShowing()){
setVisible(false);
new StartScherm();
}
if (deleteBewakerPan.isShowing()){
deleteBewakerPanel();
}else{
deleteBewakerPan.removeAll();
deleteBewakerPanel();
}
}
});
}
public void viewAllPanel(){
JPanel outputPanel= new JPanel();
JButton viewAllBut= new JButton("view all");
outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));
listTableModel = new DefaultTableModel();
String[] colnames = {"bewaker", "adress", "mail", "phone"};
Vector colnamesV = new Vector(Arrays.asList(colnames));
outputTable = new JTable(null, colnamesV);
JScrollPane tablePanel = new JScrollPane(outputTable);
tablePanel.setPreferredSize(new Dimension(800, 150));
outputPanel.add(tablePanel);
outputTable.setBackground(new Color(148, 178, 173));
viewAllPan.add(outputPanel, BorderLayout.CENTER);
viewAllPan.add(viewAllBut, BorderLayout.SOUTH);
viewAllBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (bewakerDatabase == null){
bewakerDatabase = new BewakerDatabase();
}
if (!bewakerDatabase.isInitialised()){
bewakerDatabase.initialiseer();
}
if (bewakerDatabase.isInitialised()){
bewakerDatabase.selectAll();
}
listTableModel = (DefaultTableModel) outputTable.getModel();
listTableModel.setRowCount(0);
Iterator itrTable = bewakerDatabase.selectAll().iterator();
while (itrTable.hasNext()) {
Bewaker record = (Bewaker) itrTable.next();
String[] colData = new String[4];
//{"id", "bewaker", "adres", "mail", "telefoon"};
//colData[0] = Integer.valueOf(record.getId()).toString();
colData[0] = record.getBewaker_naam();
colData[1] = record.getBewaker_adres();
colData[2] = record.getBewaker_mail();
colData[3] = record.getBewaker_telefoon();
listTableModel.addRow(colData);
}
outputTable.setModel(listTableModel);
}
});
}
public void viewBewakerPanel(){
buildArrays();
//{"bewaker", "adres", "mail", "telefoon"};
JPanel uperPanel=new JPanel(), outputPanel= new JPanel(new GridBagLayout());
JButton findBut = new JButton("find");
JLabel nameLabel=new JLabel("name : "),namefield=new JLabel(), adressLabel=new JLabel("adress : "),
adressField=new JLabel(), mailLabel=new JLabel("mail : "), mailField=new JLabel(),
phoneLabel=new JLabel("phone : "), phoneField=new JLabel();
JComboBox jComboBox= new JComboBox(new DefaultComboBoxModel(bewakerArrayList.toArray()));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.set(30,30,30,30);
gbc.gridx=0;
gbc.gridy=0;
outputPanel.add(nameLabel,gbc);
gbc.gridx=1;
outputPanel.add(namefield,gbc);
gbc.gridx=0;
gbc.gridy=-1;
outputPanel.add(adressLabel, gbc);
gbc.gridx=1;
outputPanel.add(adressField,gbc);
gbc.gridx=0;
gbc.gridy=-2;
outputPanel.add(mailLabel,gbc);
gbc.gridx=1;
outputPanel.add(mailField,gbc);
gbc.gridx=0;
gbc.gridy=-3;
outputPanel.add(phoneLabel,gbc);
gbc.gridx=1;
outputPanel.add(phoneField,gbc);
uperPanel.add(jComboBox);
uperPanel.add(findBut);
uperPanel.setBackground(new Color(137,191,198));
outputPanel.setBackground(new Color(137,191,198));
viewBewakerPan.add(uperPanel, BorderLayout.NORTH);
viewBewakerPan.add(outputPanel, BorderLayout.CENTER);
findBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int i = jComboBox.getSelectedIndex();
int record = bewakerArrayListID.get(i);
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
// Initialiseer de bewakerDatabase alleen als het moet
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
// Alleen als de bewakeren database is geinitialiseerd dan verder
if (bewakerDatabase.isInitialised()) {
namefield.setText(bewakerDatabase.selectBewaker(record).getBewaker_naam());
adressField.setText(bewakerDatabase.selectBewaker(record).getBewaker_adres());
mailField.setText(bewakerDatabase.selectBewaker(record).getBewaker_mail());
phoneField.setText(bewakerDatabase.selectBewaker(record).getBewaker_telefoon());
}
}});
}
public void updateBewakerPanel(){
buildArrays();
//{"bewaker", "adres", "mail", "telefoon"};
JPanel uperPanel=new JPanel(), outputPanel= new JPanel(new GridBagLayout()),updatePanel= new JPanel();
JButton findBut = new JButton("find"), updateBut= new JButton("update");
JLabel nameLabel=new JLabel("name : "), adressLabel=new JLabel("adress : "), mailLabel=new JLabel("mail : "), phoneLabel=new JLabel("phone : ");
JTextField namefield = new JTextField(15),adressField = new JTextField(15),mailField = new JTextField(15),phoneField = new JTextField(15);
JComboBox jComboBox= new JComboBox(new DefaultComboBoxModel(bewakerArrayList.toArray()));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.set(30,30,30,30);
gbc.gridx=0;
gbc.gridy=0;
outputPanel.add(nameLabel,gbc);
gbc.gridx=1;
outputPanel.add(namefield,gbc);
gbc.gridx=0;
gbc.gridy=-1;
outputPanel.add(adressLabel, gbc);
gbc.gridx=1;
outputPanel.add(adressField,gbc);
gbc.gridx=0;
gbc.gridy=-2;
outputPanel.add(mailLabel,gbc);
gbc.gridx=1;
outputPanel.add(mailField,gbc);
gbc.gridx=0;
gbc.gridy=-3;
outputPanel.add(phoneLabel,gbc);
gbc.gridx=1;
outputPanel.add(phoneField,gbc);
updatePanel.add(updateBut,gbc);
uperPanel.add(jComboBox);
uperPanel.add(findBut);
uperPanel.setBackground(new Color(137,191,198));
outputPanel.setBackground(new Color(137,191,198));
updatePanel.setBackground(new Color(137,191,198));
updateBewakerPan.add(uperPanel, BorderLayout.NORTH);
updateBewakerPan.add(outputPanel, BorderLayout.CENTER);
updateBewakerPan.add(updatePanel, BorderLayout.SOUTH);
findBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int i = jComboBox.getSelectedIndex();
int record = bewakerArrayListID.get(i);
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
// Initialiseer de bewakerDatabase alleen als het moet
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
// Alleen als de bewakeren database is geinitialiseerd dan verder
if (bewakerDatabase.isInitialised()) {
namefield.setText(bewakerDatabase.selectBewaker(record).getBewaker_naam());
adressField.setText(bewakerDatabase.selectBewaker(record).getBewaker_adres());
mailField.setText(bewakerDatabase.selectBewaker(record).getBewaker_mail());
phoneField.setText(bewakerDatabase.selectBewaker(record).getBewaker_telefoon());
}
}});
updateBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int i = jComboBox.getSelectedIndex();
bewakerArraylistObject.get(i).setBewaker_naam(namefield.getText());
bewakerArraylistObject.get(i).setBewaker_adres(adressField.getText());
bewakerArraylistObject.get(i).setBewaker_mail(mailField.getText());
bewakerArraylistObject.get(i).setBewaker_telefoon(phoneField.getText());
if (!namefield.getText().isEmpty()) {
if (!adressField.getText().isEmpty()) {
if (!phoneField.getText().isEmpty()) {
if (!mailField.getText().isEmpty()) {
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
if (bewakerDatabase.isInitialised()) {
bewakerDatabase.updateBewaker(bewakerArraylistObject.get(i));
JOptionPane.showMessageDialog(updateBewakerPan,"bewaker updated");
updateBewakerPan.removeAll();
updateBewakerPanel();
}
}else{JOptionPane.showMessageDialog(updateBewakerPan, "mail is empty");}
}else{JOptionPane.showMessageDialog(updateBewakerPan, "phone is empty");}
}else {JOptionPane.showMessageDialog(updateBewakerPan, "adress is empty");}
}else{JOptionPane.showMessageDialog(updateBewakerPan,"name is empty");}
}});
}
public void newBewakerPanel(){
JPanel outputPanel= new JPanel(new GridBagLayout()),updatePanel= new JPanel();
JButton saveBut= new JButton("save");
JLabel nameLabel=new JLabel("name : "), adressLabel=new JLabel("adress : "), mailLabel=new JLabel("mail : "), phoneLabel=new JLabel("phone : ");
JTextField namefield = new JTextField(15),adressField = new JTextField(15),mailField = new JTextField(15),phoneField = new JTextField(15);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.set(30,30,30,30);
gbc.gridx=0;
gbc.gridy=0;
outputPanel.add(nameLabel,gbc);
gbc.gridx=1;
outputPanel.add(namefield,gbc);
gbc.gridx=0;
gbc.gridy=-1;
outputPanel.add(adressLabel, gbc);
gbc.gridx=1;
outputPanel.add(adressField,gbc);
gbc.gridx=0;
gbc.gridy=-2;
outputPanel.add(mailLabel,gbc);
gbc.gridx=1;
outputPanel.add(mailField,gbc);
gbc.gridx=0;
gbc.gridy=-3;
outputPanel.add(phoneLabel,gbc);
gbc.gridx=1;
outputPanel.add(phoneField,gbc);
updatePanel.add(saveBut,gbc);
outputPanel.setBackground(new Color(137,191,198));
updatePanel.setBackground(new Color(137,191,198));
newBewakerPan.add(outputPanel, BorderLayout.CENTER);
newBewakerPan.add(updatePanel, BorderLayout.SOUTH);
saveBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Bewaker bewaker= new Bewaker();
bewaker.setBewaker_naam(namefield.getText());
bewaker.setBewaker_adres(adressField.getText());
bewaker.setBewaker_mail(mailField.getText());
bewaker.setBewaker_telefoon(phoneField.getText());
if (!namefield.getText().isEmpty()) {
if (!adressField.getText().isEmpty()) {
if (!phoneField.getText().isEmpty()) {
if (!mailField.getText().isEmpty()) {
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
if (bewakerDatabase.isInitialised()) {
bewakerDatabase.insertBewaker(bewaker);
JOptionPane.showMessageDialog(updateBewakerPan,"bewaker saved");
newBewakerPan.removeAll();
newBewakerPanel();
}
}else{JOptionPane.showMessageDialog(updateBewakerPan, "mail is empty");}
}else{JOptionPane.showMessageDialog(updateBewakerPan, "phone is empty");}
}else {JOptionPane.showMessageDialog(updateBewakerPan, "adress is empty");}
}else{JOptionPane.showMessageDialog(updateBewakerPan,"name is empty");}
}
});
}
public void deleteBewakerPanel(){
buildArrays();
//{"bewaker", "adres", "mail", "telefoon"};
JPanel uperPanel=new JPanel(), outputPanel= new JPanel(new GridBagLayout()),updatePanel= new JPanel();
JButton findBut = new JButton("find"), deleteBut= new JButton("delete");
JLabel nameLabel=new JLabel("name : "), adressLabel=new JLabel("adress : "), mailLabel=new JLabel("mail : "), phoneLabel=new JLabel("phone : ");
JLabel namefield = new JLabel(),adressField = new JLabel(),mailField = new JLabel(),phoneField = new JLabel();
JComboBox jComboBox= new JComboBox(new DefaultComboBoxModel(bewakerArrayList.toArray()));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.set(30,30,30,30);
gbc.gridx=0;
gbc.gridy=0;
outputPanel.add(nameLabel,gbc);
gbc.gridx=1;
outputPanel.add(namefield,gbc);
gbc.gridx=0;
gbc.gridy=-1;
outputPanel.add(adressLabel, gbc);
gbc.gridx=1;
outputPanel.add(adressField,gbc);
gbc.gridx=0;
gbc.gridy=-2;
outputPanel.add(mailLabel,gbc);
gbc.gridx=1;
outputPanel.add(mailField,gbc);
gbc.gridx=0;
gbc.gridy=-3;
outputPanel.add(phoneLabel,gbc);
gbc.gridx=1;
outputPanel.add(phoneField,gbc);
updatePanel.add(deleteBut,gbc);
uperPanel.add(jComboBox);
uperPanel.add(findBut);
uperPanel.setBackground(new Color(137,191,198));
outputPanel.setBackground(new Color(137,191,198));
updatePanel.setBackground(new Color(137,191,198));
deleteBewakerPan.add(uperPanel, BorderLayout.NORTH);
deleteBewakerPan.add(outputPanel, BorderLayout.CENTER);
deleteBewakerPan.add(updatePanel, BorderLayout.SOUTH);
findBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int i = jComboBox.getSelectedIndex();
int record = bewakerArrayListID.get(i);
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
// Initialiseer de bewakerDatabase alleen als het moet
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
// Alleen als de bewakeren database is geinitialiseerd dan verder
if (bewakerDatabase.isInitialised()) {
namefield.setText(bewakerDatabase.selectBewaker(record).getBewaker_naam());
adressField.setText(bewakerDatabase.selectBewaker(record).getBewaker_adres());
mailField.setText(bewakerDatabase.selectBewaker(record).getBewaker_mail());
phoneField.setText(bewakerDatabase.selectBewaker(record).getBewaker_telefoon());
}
}});
deleteBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int i = jComboBox.getSelectedIndex();
if (JOptionPane.showConfirmDialog(null, "Are you sure?", "WARNING",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
int record = bewakerArrayListID.get(i);
RoosterDatabase roosterDatabase = new RoosterDatabase();
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (roosterDatabase.isInitialised()) {
int lastindex = roosterDatabase.selectAll().get(roosterDatabase.selectAll().size() - 1).getId();
for (int a = 0; a < lastindex + 1; a++) {
if (bewakerDatabase.selectBewaker(record).getId() == roosterDatabase.selectRooster(a).getBewaker_fk()) {
roosterDatabase.deleteRooster(a);
}
}
// bewaker.bewaker database instantie is alleen 1 keer nodig
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
// Initialiseer de bewakerDatabase alleen als het moet
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
// Alleen als de bewakeren database is geinitialiseerd dan verder
if (bewakerDatabase.isInitialised()) {
bewakerDatabase.deleteBewaker(record);
deleteBewakerPan.removeAll();
deleteBewakerPanel();
JOptionPane.showMessageDialog(deleteBewakerPan, "bewaker deleted");
} else {
JOptionPane.showMessageDialog(deleteBewakerPan, "bewaker not deleted");
}
}}
}});
}
public void buildArrays(){
bewakerArraylistObject.clear();
bewakerArrayList.clear();
bewakerArrayListID.clear();
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
Iterator<Bewaker> itrBewaker = bewakerDatabase.selectAll().iterator();
while (itrBewaker.hasNext()) {
Bewaker i = (Bewaker) itrBewaker.next();
bewakerArraylistObject.add(i);
bewakerArrayList.add(i.getBewaker_naam());
bewakerArrayListID.add(i.getId());
}
}
}
| JairJosafath/BP | beroepsProduct/datakeeper/src/sr/unasat/bewakingsBedrijf/app/scherm/bewaker/BewakerScherm.java | 6,707 | // Initialiseer de bewakerDatabase alleen als het moet | line_comment | nl | package sr.unasat.bewakingsBedrijf.app.scherm.bewaker;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.bewaker.Bewaker;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.bewaker.BewakerDatabase;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.rooster.RoosterDatabase;
import sr.unasat.bewakingsBedrijf.app.scherm.algemeen.StartScherm;
import sr.unasat.bewakingsBedrijf.app.scherm.rooster.RoosterScherm;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
/**
* Created by Jair on 5/31/2016.
*/
public class BewakerScherm extends JFrame {
BewakerDatabase bewakerDatabase = null;
JPanel viewAllPan = new JPanel(new BorderLayout()), viewBewakerPan= new JPanel(new BorderLayout()),
updateBewakerPan= new JPanel(new BorderLayout()), newBewakerPan= new JPanel(new BorderLayout()),
deleteBewakerPan= new JPanel(new BorderLayout()), homePan= new JPanel();
JTabbedPane jTabbedPane= new JTabbedPane(SwingConstants.LEFT);
ArrayList bewakerArrayList= new ArrayList<String>();
ArrayList<Bewaker> bewakerArraylistObject= new ArrayList();
ArrayList <Integer> bewakerArrayListID = new ArrayList();
private JList outputList;
private DefaultListModel listModel;
private DefaultTableModel listTableModel;
private JTable outputTable;
ImageIcon allIcon= new ImageIcon(getClass().getResource("allBew.png"));
ImageIcon deleteIcon= new ImageIcon(getClass().getResource("deleteBew.png"));
ImageIcon newIcon= new ImageIcon(getClass().getResource("newBew.png"));
ImageIcon updateIcon= new ImageIcon(getClass().getResource("updateBew.png"));
ImageIcon viewIcon= new ImageIcon(getClass().getResource("viewBew.png"));
ImageIcon homeIcon= new ImageIcon(getClass().getResource("home.png"));
public BewakerScherm(){
jTabbedPane.addTab("all bewakers",allIcon,viewAllPan);
jTabbedPane.addTab("view bewaker",viewIcon, viewBewakerPan);
jTabbedPane.addTab("update bewaker",updateIcon ,updateBewakerPan);
jTabbedPane.addTab("new Bewaker",newIcon, newBewakerPan);
jTabbedPane.addTab("delete Bewaker",deleteIcon, deleteBewakerPan);
jTabbedPane.addTab("home",homeIcon, homePan);
viewAllPanel();
getContentPane().setBackground(new Color(7, 84, 127));
jTabbedPane.setBackground(new Color(148, 178, 173));
add(jTabbedPane);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(900,500);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
jTabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (viewAllPan.isShowing()){
viewAllPanel();
}else{
viewAllPan.removeAll();
}
if (viewBewakerPan.isShowing()){
viewBewakerPanel();
}else {
viewBewakerPan.removeAll();
}
if (updateBewakerPan.isShowing()){
updateBewakerPanel();
}else{
updateBewakerPan.removeAll();
}
if (newBewakerPan.isShowing()){
newBewakerPanel();
}else {
newBewakerPan.removeAll();
}
if (homePan.isShowing()){
setVisible(false);
new StartScherm();
}
if (deleteBewakerPan.isShowing()){
deleteBewakerPanel();
}else{
deleteBewakerPan.removeAll();
deleteBewakerPanel();
}
}
});
}
public void viewAllPanel(){
JPanel outputPanel= new JPanel();
JButton viewAllBut= new JButton("view all");
outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));
listTableModel = new DefaultTableModel();
String[] colnames = {"bewaker", "adress", "mail", "phone"};
Vector colnamesV = new Vector(Arrays.asList(colnames));
outputTable = new JTable(null, colnamesV);
JScrollPane tablePanel = new JScrollPane(outputTable);
tablePanel.setPreferredSize(new Dimension(800, 150));
outputPanel.add(tablePanel);
outputTable.setBackground(new Color(148, 178, 173));
viewAllPan.add(outputPanel, BorderLayout.CENTER);
viewAllPan.add(viewAllBut, BorderLayout.SOUTH);
viewAllBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (bewakerDatabase == null){
bewakerDatabase = new BewakerDatabase();
}
if (!bewakerDatabase.isInitialised()){
bewakerDatabase.initialiseer();
}
if (bewakerDatabase.isInitialised()){
bewakerDatabase.selectAll();
}
listTableModel = (DefaultTableModel) outputTable.getModel();
listTableModel.setRowCount(0);
Iterator itrTable = bewakerDatabase.selectAll().iterator();
while (itrTable.hasNext()) {
Bewaker record = (Bewaker) itrTable.next();
String[] colData = new String[4];
//{"id", "bewaker", "adres", "mail", "telefoon"};
//colData[0] = Integer.valueOf(record.getId()).toString();
colData[0] = record.getBewaker_naam();
colData[1] = record.getBewaker_adres();
colData[2] = record.getBewaker_mail();
colData[3] = record.getBewaker_telefoon();
listTableModel.addRow(colData);
}
outputTable.setModel(listTableModel);
}
});
}
public void viewBewakerPanel(){
buildArrays();
//{"bewaker", "adres", "mail", "telefoon"};
JPanel uperPanel=new JPanel(), outputPanel= new JPanel(new GridBagLayout());
JButton findBut = new JButton("find");
JLabel nameLabel=new JLabel("name : "),namefield=new JLabel(), adressLabel=new JLabel("adress : "),
adressField=new JLabel(), mailLabel=new JLabel("mail : "), mailField=new JLabel(),
phoneLabel=new JLabel("phone : "), phoneField=new JLabel();
JComboBox jComboBox= new JComboBox(new DefaultComboBoxModel(bewakerArrayList.toArray()));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.set(30,30,30,30);
gbc.gridx=0;
gbc.gridy=0;
outputPanel.add(nameLabel,gbc);
gbc.gridx=1;
outputPanel.add(namefield,gbc);
gbc.gridx=0;
gbc.gridy=-1;
outputPanel.add(adressLabel, gbc);
gbc.gridx=1;
outputPanel.add(adressField,gbc);
gbc.gridx=0;
gbc.gridy=-2;
outputPanel.add(mailLabel,gbc);
gbc.gridx=1;
outputPanel.add(mailField,gbc);
gbc.gridx=0;
gbc.gridy=-3;
outputPanel.add(phoneLabel,gbc);
gbc.gridx=1;
outputPanel.add(phoneField,gbc);
uperPanel.add(jComboBox);
uperPanel.add(findBut);
uperPanel.setBackground(new Color(137,191,198));
outputPanel.setBackground(new Color(137,191,198));
viewBewakerPan.add(uperPanel, BorderLayout.NORTH);
viewBewakerPan.add(outputPanel, BorderLayout.CENTER);
findBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int i = jComboBox.getSelectedIndex();
int record = bewakerArrayListID.get(i);
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
// Initialiseer de<SUF>
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
// Alleen als de bewakeren database is geinitialiseerd dan verder
if (bewakerDatabase.isInitialised()) {
namefield.setText(bewakerDatabase.selectBewaker(record).getBewaker_naam());
adressField.setText(bewakerDatabase.selectBewaker(record).getBewaker_adres());
mailField.setText(bewakerDatabase.selectBewaker(record).getBewaker_mail());
phoneField.setText(bewakerDatabase.selectBewaker(record).getBewaker_telefoon());
}
}});
}
public void updateBewakerPanel(){
buildArrays();
//{"bewaker", "adres", "mail", "telefoon"};
JPanel uperPanel=new JPanel(), outputPanel= new JPanel(new GridBagLayout()),updatePanel= new JPanel();
JButton findBut = new JButton("find"), updateBut= new JButton("update");
JLabel nameLabel=new JLabel("name : "), adressLabel=new JLabel("adress : "), mailLabel=new JLabel("mail : "), phoneLabel=new JLabel("phone : ");
JTextField namefield = new JTextField(15),adressField = new JTextField(15),mailField = new JTextField(15),phoneField = new JTextField(15);
JComboBox jComboBox= new JComboBox(new DefaultComboBoxModel(bewakerArrayList.toArray()));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.set(30,30,30,30);
gbc.gridx=0;
gbc.gridy=0;
outputPanel.add(nameLabel,gbc);
gbc.gridx=1;
outputPanel.add(namefield,gbc);
gbc.gridx=0;
gbc.gridy=-1;
outputPanel.add(adressLabel, gbc);
gbc.gridx=1;
outputPanel.add(adressField,gbc);
gbc.gridx=0;
gbc.gridy=-2;
outputPanel.add(mailLabel,gbc);
gbc.gridx=1;
outputPanel.add(mailField,gbc);
gbc.gridx=0;
gbc.gridy=-3;
outputPanel.add(phoneLabel,gbc);
gbc.gridx=1;
outputPanel.add(phoneField,gbc);
updatePanel.add(updateBut,gbc);
uperPanel.add(jComboBox);
uperPanel.add(findBut);
uperPanel.setBackground(new Color(137,191,198));
outputPanel.setBackground(new Color(137,191,198));
updatePanel.setBackground(new Color(137,191,198));
updateBewakerPan.add(uperPanel, BorderLayout.NORTH);
updateBewakerPan.add(outputPanel, BorderLayout.CENTER);
updateBewakerPan.add(updatePanel, BorderLayout.SOUTH);
findBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int i = jComboBox.getSelectedIndex();
int record = bewakerArrayListID.get(i);
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
// Initialiseer de bewakerDatabase alleen als het moet
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
// Alleen als de bewakeren database is geinitialiseerd dan verder
if (bewakerDatabase.isInitialised()) {
namefield.setText(bewakerDatabase.selectBewaker(record).getBewaker_naam());
adressField.setText(bewakerDatabase.selectBewaker(record).getBewaker_adres());
mailField.setText(bewakerDatabase.selectBewaker(record).getBewaker_mail());
phoneField.setText(bewakerDatabase.selectBewaker(record).getBewaker_telefoon());
}
}});
updateBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int i = jComboBox.getSelectedIndex();
bewakerArraylistObject.get(i).setBewaker_naam(namefield.getText());
bewakerArraylistObject.get(i).setBewaker_adres(adressField.getText());
bewakerArraylistObject.get(i).setBewaker_mail(mailField.getText());
bewakerArraylistObject.get(i).setBewaker_telefoon(phoneField.getText());
if (!namefield.getText().isEmpty()) {
if (!adressField.getText().isEmpty()) {
if (!phoneField.getText().isEmpty()) {
if (!mailField.getText().isEmpty()) {
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
if (bewakerDatabase.isInitialised()) {
bewakerDatabase.updateBewaker(bewakerArraylistObject.get(i));
JOptionPane.showMessageDialog(updateBewakerPan,"bewaker updated");
updateBewakerPan.removeAll();
updateBewakerPanel();
}
}else{JOptionPane.showMessageDialog(updateBewakerPan, "mail is empty");}
}else{JOptionPane.showMessageDialog(updateBewakerPan, "phone is empty");}
}else {JOptionPane.showMessageDialog(updateBewakerPan, "adress is empty");}
}else{JOptionPane.showMessageDialog(updateBewakerPan,"name is empty");}
}});
}
public void newBewakerPanel(){
JPanel outputPanel= new JPanel(new GridBagLayout()),updatePanel= new JPanel();
JButton saveBut= new JButton("save");
JLabel nameLabel=new JLabel("name : "), adressLabel=new JLabel("adress : "), mailLabel=new JLabel("mail : "), phoneLabel=new JLabel("phone : ");
JTextField namefield = new JTextField(15),adressField = new JTextField(15),mailField = new JTextField(15),phoneField = new JTextField(15);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.set(30,30,30,30);
gbc.gridx=0;
gbc.gridy=0;
outputPanel.add(nameLabel,gbc);
gbc.gridx=1;
outputPanel.add(namefield,gbc);
gbc.gridx=0;
gbc.gridy=-1;
outputPanel.add(adressLabel, gbc);
gbc.gridx=1;
outputPanel.add(adressField,gbc);
gbc.gridx=0;
gbc.gridy=-2;
outputPanel.add(mailLabel,gbc);
gbc.gridx=1;
outputPanel.add(mailField,gbc);
gbc.gridx=0;
gbc.gridy=-3;
outputPanel.add(phoneLabel,gbc);
gbc.gridx=1;
outputPanel.add(phoneField,gbc);
updatePanel.add(saveBut,gbc);
outputPanel.setBackground(new Color(137,191,198));
updatePanel.setBackground(new Color(137,191,198));
newBewakerPan.add(outputPanel, BorderLayout.CENTER);
newBewakerPan.add(updatePanel, BorderLayout.SOUTH);
saveBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Bewaker bewaker= new Bewaker();
bewaker.setBewaker_naam(namefield.getText());
bewaker.setBewaker_adres(adressField.getText());
bewaker.setBewaker_mail(mailField.getText());
bewaker.setBewaker_telefoon(phoneField.getText());
if (!namefield.getText().isEmpty()) {
if (!adressField.getText().isEmpty()) {
if (!phoneField.getText().isEmpty()) {
if (!mailField.getText().isEmpty()) {
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
if (bewakerDatabase.isInitialised()) {
bewakerDatabase.insertBewaker(bewaker);
JOptionPane.showMessageDialog(updateBewakerPan,"bewaker saved");
newBewakerPan.removeAll();
newBewakerPanel();
}
}else{JOptionPane.showMessageDialog(updateBewakerPan, "mail is empty");}
}else{JOptionPane.showMessageDialog(updateBewakerPan, "phone is empty");}
}else {JOptionPane.showMessageDialog(updateBewakerPan, "adress is empty");}
}else{JOptionPane.showMessageDialog(updateBewakerPan,"name is empty");}
}
});
}
public void deleteBewakerPanel(){
buildArrays();
//{"bewaker", "adres", "mail", "telefoon"};
JPanel uperPanel=new JPanel(), outputPanel= new JPanel(new GridBagLayout()),updatePanel= new JPanel();
JButton findBut = new JButton("find"), deleteBut= new JButton("delete");
JLabel nameLabel=new JLabel("name : "), adressLabel=new JLabel("adress : "), mailLabel=new JLabel("mail : "), phoneLabel=new JLabel("phone : ");
JLabel namefield = new JLabel(),adressField = new JLabel(),mailField = new JLabel(),phoneField = new JLabel();
JComboBox jComboBox= new JComboBox(new DefaultComboBoxModel(bewakerArrayList.toArray()));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.set(30,30,30,30);
gbc.gridx=0;
gbc.gridy=0;
outputPanel.add(nameLabel,gbc);
gbc.gridx=1;
outputPanel.add(namefield,gbc);
gbc.gridx=0;
gbc.gridy=-1;
outputPanel.add(adressLabel, gbc);
gbc.gridx=1;
outputPanel.add(adressField,gbc);
gbc.gridx=0;
gbc.gridy=-2;
outputPanel.add(mailLabel,gbc);
gbc.gridx=1;
outputPanel.add(mailField,gbc);
gbc.gridx=0;
gbc.gridy=-3;
outputPanel.add(phoneLabel,gbc);
gbc.gridx=1;
outputPanel.add(phoneField,gbc);
updatePanel.add(deleteBut,gbc);
uperPanel.add(jComboBox);
uperPanel.add(findBut);
uperPanel.setBackground(new Color(137,191,198));
outputPanel.setBackground(new Color(137,191,198));
updatePanel.setBackground(new Color(137,191,198));
deleteBewakerPan.add(uperPanel, BorderLayout.NORTH);
deleteBewakerPan.add(outputPanel, BorderLayout.CENTER);
deleteBewakerPan.add(updatePanel, BorderLayout.SOUTH);
findBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int i = jComboBox.getSelectedIndex();
int record = bewakerArrayListID.get(i);
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
// Initialiseer de bewakerDatabase alleen als het moet
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
// Alleen als de bewakeren database is geinitialiseerd dan verder
if (bewakerDatabase.isInitialised()) {
namefield.setText(bewakerDatabase.selectBewaker(record).getBewaker_naam());
adressField.setText(bewakerDatabase.selectBewaker(record).getBewaker_adres());
mailField.setText(bewakerDatabase.selectBewaker(record).getBewaker_mail());
phoneField.setText(bewakerDatabase.selectBewaker(record).getBewaker_telefoon());
}
}});
deleteBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int i = jComboBox.getSelectedIndex();
if (JOptionPane.showConfirmDialog(null, "Are you sure?", "WARNING",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
int record = bewakerArrayListID.get(i);
RoosterDatabase roosterDatabase = new RoosterDatabase();
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (roosterDatabase.isInitialised()) {
int lastindex = roosterDatabase.selectAll().get(roosterDatabase.selectAll().size() - 1).getId();
for (int a = 0; a < lastindex + 1; a++) {
if (bewakerDatabase.selectBewaker(record).getId() == roosterDatabase.selectRooster(a).getBewaker_fk()) {
roosterDatabase.deleteRooster(a);
}
}
// bewaker.bewaker database instantie is alleen 1 keer nodig
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
// Initialiseer de bewakerDatabase alleen als het moet
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
// Alleen als de bewakeren database is geinitialiseerd dan verder
if (bewakerDatabase.isInitialised()) {
bewakerDatabase.deleteBewaker(record);
deleteBewakerPan.removeAll();
deleteBewakerPanel();
JOptionPane.showMessageDialog(deleteBewakerPan, "bewaker deleted");
} else {
JOptionPane.showMessageDialog(deleteBewakerPan, "bewaker not deleted");
}
}}
}});
}
public void buildArrays(){
bewakerArraylistObject.clear();
bewakerArrayList.clear();
bewakerArrayListID.clear();
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
Iterator<Bewaker> itrBewaker = bewakerDatabase.selectAll().iterator();
while (itrBewaker.hasNext()) {
Bewaker i = (Bewaker) itrBewaker.next();
bewakerArraylistObject.add(i);
bewakerArrayList.add(i.getBewaker_naam());
bewakerArrayListID.add(i.getId());
}
}
}
|
164172_4 | import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Scanner;
/**
* This class is to create, access and modify Project objects. It links to the
* projectManagementSystem class.
*
* @author Jason Kelderman
* @version 1.1
*/
public class Project {
// Attributes
String projectNumber;
String projectName;
String buildingType;
String buildingAddress;
String erfNumber;
BigDecimal totalFee;
BigDecimal totalPaid;
LocalDate deadline;
// Person class created separately
Person architect;
Person projectManager;
Person structuralEngineer;
Person customer;
boolean completed;
// Methods
// Create 'Project' object
/**
* Primary constructor for creating Project objects. <br>
* Taking input from the user, object attributes are set
*
* @param input <br>
* Scanner object which has been platform sanitised by
* accounting for \r and \n characters as appropriate.
* @param numberInput <br>
* Second Scanner object for reading numbers. Implemented as
* sanitising of first Scanner object caused an error when
* inputting numbers
*
*/
public Project(Scanner input, Scanner numberInput, ArrayList<Person> people) {
System.out.println("\nPlease enter the customers first name:");
String customerFirstName = input.next();
System.out.println("\nPlease enter the customers last name:");
String customerLastName = input.next();
String customerFullName = customerFirstName + " " + customerLastName;
Person existingCustomer = Person.personSearch(people, customerFullName, "customer");
if (existingCustomer == null) {
this.customer = new Person("Customer", customerFirstName, customerLastName, input);
} else {
this.customer = existingCustomer;
people.add(existingCustomer);
}
System.out.println("\nPlease enter the project number:");
this.projectNumber = input.next();
System.out.println("\nPlease enter the type of building required:");
this.buildingType = input.next();
System.out.println("\nPlease enter the project name, or 'no' to autogenerate:");
String projectNameChoice = input.next();
if (projectNameChoice.equalsIgnoreCase("no")) {
this.projectName = buildingType + " " + customer.lastName;
} else {
this.projectName = projectNameChoice;
}
System.out.println("\nPlease enter the building physical address:");
this.buildingAddress = input.next().replace(", ", "; ");
System.out.println("\nPlease enter the type of building ERF number:");
this.erfNumber = input.next();
System.out.println("\nPlease enter the job fee:");
this.totalFee = numberInput.nextBigDecimal();
System.out.println("\nPlease enter how much the customer has paid to date:");
this.totalPaid = numberInput.nextBigDecimal();
setDate(numberInput);
System.out.println("\nPlease enter the architect first name:");
String architectFirstName = input.next();
System.out.println("\nPlease enter the architect last name:");
String architectLastName = input.next();
String architectFullName = architectFirstName + " " + architectLastName;
Person existingArchitect = Person.personSearch(people, architectFullName, "architect");
if (existingArchitect == null) {
this.architect = new Person("Architect", architectFirstName, architectLastName, input);
} else {
this.architect = existingArchitect;
people.add(existingArchitect);
}
System.out.println("\nPlease enter the Project Manager first name:");
String projectManagerFirstName = input.next();
System.out.println("\nPlease enter the Project Manager last name:");
String projectManagerLastName = input.next();
String projectManagerFullName = projectManagerFirstName + " " + projectManagerLastName;
Person existingProjectManager = Person.personSearch(people, projectManagerFullName, "project manager");
if (existingProjectManager == null) {
this.projectManager = new Person("Project Manager", projectManagerFirstName, projectManagerLastName, input);
} else {
this.projectManager = existingProjectManager;
people.add(existingProjectManager);
}
System.out.println("\nPlease enter the Structural Engineer first name:");
String structuralEngineerFirstName = input.next();
System.out.println("\nPlease enter the Structural Engineer last name:");
String structuralEngineerLastName = input.next();
String structuralEngineerFullName = structuralEngineerFirstName + " " + structuralEngineerLastName;
Person existingStructuralEngineer = Person.personSearch(people, structuralEngineerFullName,
"structural engineer");
if (existingStructuralEngineer == null) {
this.structuralEngineer = new Person("Structural Engineer", structuralEngineerFirstName,
structuralEngineerLastName, input);
} else {
this.structuralEngineer = existingStructuralEngineer;
people.add(existingStructuralEngineer);
}
this.completed = false;
}
private void setDate(Scanner numberInput) {
// While loop to get valid date input
while (true) {
LocalDate today = LocalDate.now();
int thisYear = today.getYear();
int thisMonth = today.getMonthValue();
int thisDay = today.getDayOfMonth();
int dueYear;
int dueMonth;
int dueDay;
int maxNumberOfDays = 0;
// While loop to get year
while (true) {
System.out.println("\nPlease enter the year the project is due:");
dueYear = numberInput.nextInt();
if (dueYear < thisYear) {
System.out.println("Deadline year cannot be before current year. Please try again.");
} else {
break;
}
}
// While loop to get current month and determine maximum number of days in month
while (true) {
System.out.println(
"\nPlease enter the month, using 1 for January to 12 for December, the project is due:");
dueMonth = numberInput.nextInt();
if (dueYear == thisYear && dueMonth < thisMonth) {
System.out.println("Deadline month cannot be before current month. Please try again.");
} else if (dueMonth < 1 || dueMonth > 12) {
System.out.println("Deadline month value invalid. Please try again.");
} else {
break;
}
}
// Switch statement to determine number of days in month
switch (dueMonth) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
maxNumberOfDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
maxNumberOfDays = 30;
break;
case 2:
// Check if given due year is a leap year
if (((dueYear % 4 == 0) && !(dueYear % 100 == 0)) || (dueYear % 400 == 0))
maxNumberOfDays = 29;
else
maxNumberOfDays = 28;
break;
default:
System.out.println("Please try again.");
break;
}
while (true) {
System.out.println("\nPlease enter the day of the month the project is due:");
dueDay = numberInput.nextInt();
if (dueYear == thisYear && dueMonth == thisMonth && dueDay <= thisDay) {
System.out.println("Deadline month cannot be before current month. Please try again.");
} else if (dueDay > maxNumberOfDays) {
System.out.println("Deadline day cannot exceed days of deadline month. Please try again.");
} else {
break;
}
}
this.deadline = LocalDate.of(dueYear, dueMonth, dueDay);
break;
}
}
// Overload for project constructor to create objects of already logged projects
/**
* Overload constructor method for creating an object from previously logged
* project.
*
* @param loggedProject <br>
* CSV string containing details of project
* @param persons <br>
* ArrayList of Person objects
*/
public Project(String loggedProject, ArrayList<Person> persons) {
loggedProject = loggedProject.strip();
String[] existingProject = loggedProject.split(", ");
this.projectNumber = existingProject[0];
this.buildingType = existingProject[1];
this.projectName = existingProject[3];
this.buildingAddress = existingProject[4];
this.erfNumber = existingProject[5];
this.totalFee = new BigDecimal(existingProject[6]);
this.totalPaid = new BigDecimal(existingProject[7]);
this.deadline = LocalDate.parse(existingProject[8]);
for (Person element : persons) {
if (element.getDesignation().equalsIgnoreCase("customer")
&& element.getName().equalsIgnoreCase(existingProject[2])) {
this.customer = element;
} else if (element.getDesignation().equalsIgnoreCase("architect")
&& element.getName().equalsIgnoreCase(existingProject[9])) {
this.architect = element;
} else if (element.getDesignation().equalsIgnoreCase("project manager")
&& element.getName().equalsIgnoreCase(existingProject[10])) {
this.projectManager = element;
}
if (element.getDesignation().equalsIgnoreCase("structural engineer")
&& element.getName().equalsIgnoreCase(existingProject[11])) {
this.structuralEngineer = element;
}
}
this.completed = Boolean.parseBoolean(existingProject[12]);
}
// Call each attribute
/**
*
* @return string attribute projectNumber
*/
public String getProjectNumber() {
return projectNumber;
}
/**
*
* @return string attribute projectName
*/
public String getProjectName() {
return projectName;
}
/**
*
* @return string attribute buildingType
*/
public String getBuildingType() {
return buildingType;
}
/**
*
* @return string attribute buildingAddress
*/
public String getBuildingAddress() {
return buildingAddress;
}
/**
*
* @return string attribute erfNumber
*/
public String getErfNumber() {
return erfNumber;
}
/**
*
* @return float attribute totalFee
*/
public BigDecimal getTotalFee() {
return totalFee;
}
/**
*
* @return float attribute totalPaid
*/
public BigDecimal getTotalPaid() {
return totalPaid;
}
/**
*
* @return localdate attribute deadline
*/
public LocalDate getDeadline() {
return deadline;
}
/**
*
* @return person attribute architect
*/
public Person getArchitect() {
return architect;
}
/**
*
* @return person attribute project manager
*/
public Person getProjectManager() {
return projectManager;
}
/**
*
* @return person attribute structural engineer
*/
public Person getStructuralEngineer() {
return structuralEngineer;
}
/**
*
* @return person attribute customer
*/
public Person getCustomer() {
return customer;
}
// Call all attributes
/**
* Method to obtain a string detailing all project details in an easy-to-read
* format
*
* @return String
*/
public String toString() {
String output = "";
for (int i = 0; i <= 50; i++) {
output += "*";
}
output += "\nProject Number:\n\t" + projectNumber;
output += "\nProject Name:\n\t" + projectName;
output += "\nBuilding Type:\n\t" + buildingType;
output += "\nBuilding Address:\n\t" + buildingAddress.replace("; ", "\n\t");
output += "\nERF Number:\n\t" + erfNumber;
output += String.format("\nTotal Fee:\n\tR%.2f", totalFee);
output += String.format("\nTotal Paid:\n\tR%.2f", totalPaid);
output += String.format("\nTotal Outstanding:\n\tR%.2f", (totalFee.subtract(totalPaid)));
output += "\nDeadline:\n\t" + deadline;
output += "\nArchitect:\n\t" + architect.getName();
output += "\nProject Manager:\n\t" + projectManager.getName();
output += "\nStructural Engineer:\n\t" + structuralEngineer.getName();
output += "\nCustomer:\n\t" + customer.getName();
if (!completed) {
output += "\nProject completed:\n\tNo";
} else {
output += "\nProject completed:\n\tYes";
}
output += "\n";
return output;
}
/**
* Method to obtain a string detailing all project details in CSV format
*
* @return String
*/
public String toOutput() {
String Output = projectNumber + ", " + buildingType + ", " + customer.getName() + ", " + projectName + ", "
+ buildingAddress + ", " + erfNumber + ", " + totalFee + ", " + totalPaid + ", " + deadline + ", "
+ architect.getName() + ", " + projectManager.getName() + ", " + structuralEngineer.getName() + ", "
+ completed + "\n";
return Output;
}
// Add functionality to change project deadline
/**
* Method to allow user to update project deadline
*
* @param numberInput <br>
* Scanner object to obtain user input
*/
public void updateDeadline(Scanner numberInput) {
setDate(numberInput);
}
// Add functionality to change fee paid to date
/**
* Method to allow user to pay into a job
*
* @param numberInput <br>
* Scanner object to obtain user input
*/
public void updateTotalPaid(Scanner numberInput) {
System.out.println(String.format("\nFee outstanding: R%.2f", (this.totalFee.subtract(this.totalPaid))));
System.out.println("\nHow much is the client paying into the account?");
BigDecimal paid = numberInput.nextBigDecimal();
System.out.println();
this.totalPaid = totalPaid.add(paid);
}
// Add functionality to update contractor details
/**
* Method to update contractor details or assign a new contractor to a project
*
* @param input <br>
* Scanner to obtain user input
* @param people <br>
* ArrayList of type Person
*
*/
public String updateProjectManager(Scanner input, ArrayList<Person> people) {
String option = "";
while (true) {
System.out.println("\nPlease select from the following:");
System.out.println("Amend \t- amend current project manager details");
System.out.println("Change \t- assign a different project manager from the system");
System.out.println("New \t- assign a new project manager");
System.out.println("Exit \t- return to main menu");
String choice = input.next();
if (choice.equalsIgnoreCase("amend")) {
option = "amend";
Person oldDetails = Person.personSearch(people, projectManager.getName(), "project manager");
System.out.println("\nWhat is the project manager first name?\n");
oldDetails.setFirstName(input);
System.out.println("What is the project manager last name?\n");
oldDetails.setLastName(input);
System.out.print("What is the project manager phone number?\n");
oldDetails.setPhoneNumber(input);
System.out.print("What is the project manager email address?\n");
oldDetails.setEmail(input);
System.out.print("What is the project manager address?\n");
oldDetails.setAddress(input);
this.projectManager = oldDetails;
people.add(oldDetails);
break;
} else if (choice.equalsIgnoreCase("change")) {
option = "change";
System.out.println("\nThese are the currently registered project managers:\n");
for (Person element : people) {
if (element.designation.equalsIgnoreCase("project manager")) {
System.out.println(element.personDetails());
}
}
while (true) {
System.out.println(
"Please enter the full name of the project manager you would like to assign to this project:");
String newManagerName = input.next();
Person newManager = Person.personSearch(people, newManagerName, "project manager");
if (newManager != null) {
this.projectManager = newManager;
people.add(newManager);
break;
}
}
break;
} else if (choice.equalsIgnoreCase("new")) {
option = "new";
System.out.println("Please enter the new project manager first name:");
String firstName = input.next();
System.out.println("Please enter the new project manager last name:");
String lastName = input.next();
Person replacementProjectManager = new Person("Project Manager", firstName, lastName, input);
this.projectManager = replacementProjectManager;
people.add(replacementProjectManager);
break;
} else if (choice.equalsIgnoreCase("exit")) {
break;
} else {
System.out.println("\nYour input did not match a given option. Please try again.\n");
}
}
return option;
}
// Add functionality to finalise project
/**
* Static method to mark project as complete, remove it from list of current
* projects, add it to list of <br>
* completed projects and generate a customer invoice if any fees are
* outstanding
*
* @param finaliseProject <br>
* Project object to be finalised
* @throws IOException <br>
* IOException thrown if FileWriter encounters an error
*/
public static String finalise(Project finaliseProject) throws IOException {
System.out.println();
// Set completed attribute to true
finaliseProject.completed = true;
// Generate invoice if there are outstanding fees
if ((finaliseProject.totalFee.compareTo(finaliseProject.totalPaid)) > 0) {
try {
// Variable to name generated invoice as projectNumber
String fileName = String.format("%s-%s.txt", finaliseProject.customer.getLastName(),
finaliseProject.projectNumber);
// Create File object linked to "Completed_projects.txt"
File invoice = new File(fileName);
// Create FileWriter object
FileWriter invoiceWriter = new FileWriter(invoice);
// generate invoice document if not present
invoice.createNewFile();
String toInvoice = "\tPOISED INVOICE\n";
toInvoice += "invoice addressed to:\n";
toInvoice += finaliseProject.customer.getPerson() + "\n";
toInvoice += "Date completed: " + LocalDate.now() + "\n";
toInvoice += finaliseProject.toString();
invoiceWriter.write(toInvoice);
invoiceWriter.close();
} catch (IOException e) {
System.out.println("Error encountered: invoice file could not be created");
}
}
String forDatabase = "'" + finaliseProject.projectNumber + "'";
forDatabase += ", '" + finaliseProject.projectName + "'";
forDatabase += ", '" + finaliseProject.buildingType + "'";
forDatabase += ", '" + finaliseProject.buildingAddress + "'";
forDatabase += ", '" + finaliseProject.erfNumber + "'";
forDatabase += ", " + finaliseProject.totalFee.toString();
forDatabase += ", " + finaliseProject.totalPaid.toString();
forDatabase += ", '" + finaliseProject.deadline + "'";
forDatabase += ", '" + LocalDate.now() + "'";
forDatabase += ", '" + finaliseProject.architect.getName() + "'";
forDatabase += ", '" + finaliseProject.customer.getName() + "'";
forDatabase += ", '" + finaliseProject.projectManager.getName() + "'";
forDatabase += ", '" + finaliseProject.structuralEngineer.getName() + "'";
forDatabase += ", '" + finaliseProject.completed + "'";
return forDatabase;
}
// Add functionality to search through objects by project name or project number
/**
* Method to search through list of projects by attributes projectName or
* projectNumber
*
* @param projectsList <br>
* Array containing all current projects
* @param input <br>
* Scanner object to accept user input
* @return Project
*/
public static Project projectSearch(ArrayList<Project> projectsList, Scanner input) {
while (true) {
System.out
.println("Please enter a project name, project number, or 'list' to view all valid search terms:");
String searchTerm = input.nextLine();
if (searchTerm.equalsIgnoreCase("list")) {
for (Project all : projectsList) {
System.out.println("Project Number: " + all.getProjectNumber() + "\nProject Name: "
+ all.getProjectName() + "\n");
}
System.out.println();
} else {
for (Project all : projectsList) {
if (searchTerm.equalsIgnoreCase(all.getProjectName())
|| searchTerm.equalsIgnoreCase(all.getProjectNumber())) {
int index = projectsList.indexOf(all);
Project toBeEdited = projectsList.remove(index);
return toBeEdited;
}
}
System.out.println("Your input did not match a listed project. Please try again.\n");
}
}
}
/**
*
* @return string attribute argument for updating projects database
*/
public String toDatabase() {
String values = "'" + projectNumber + "'";
values += ", '" + projectName + "'";
values += ", '" + buildingType + "'";
values += ", '" + buildingAddress + "'";
values += ", '" + erfNumber + "'";
values += ", " + totalFee;
values += ", " + totalPaid;
values += ", '" + deadline + "'";
values += ", '" + architect.getName() + "'";
values += ", '" + customer.getName() + "'";
values += ", '" + projectManager.getName() + "'";
values += ", '" + structuralEngineer.getName() + "'";
values += ", '" + completed + "'";
return values;
}
}
| JakJak90/projectManagementSystem | Project.java | 6,372 | // While loop to get valid date input
| line_comment | nl | import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Scanner;
/**
* This class is to create, access and modify Project objects. It links to the
* projectManagementSystem class.
*
* @author Jason Kelderman
* @version 1.1
*/
public class Project {
// Attributes
String projectNumber;
String projectName;
String buildingType;
String buildingAddress;
String erfNumber;
BigDecimal totalFee;
BigDecimal totalPaid;
LocalDate deadline;
// Person class created separately
Person architect;
Person projectManager;
Person structuralEngineer;
Person customer;
boolean completed;
// Methods
// Create 'Project' object
/**
* Primary constructor for creating Project objects. <br>
* Taking input from the user, object attributes are set
*
* @param input <br>
* Scanner object which has been platform sanitised by
* accounting for \r and \n characters as appropriate.
* @param numberInput <br>
* Second Scanner object for reading numbers. Implemented as
* sanitising of first Scanner object caused an error when
* inputting numbers
*
*/
public Project(Scanner input, Scanner numberInput, ArrayList<Person> people) {
System.out.println("\nPlease enter the customers first name:");
String customerFirstName = input.next();
System.out.println("\nPlease enter the customers last name:");
String customerLastName = input.next();
String customerFullName = customerFirstName + " " + customerLastName;
Person existingCustomer = Person.personSearch(people, customerFullName, "customer");
if (existingCustomer == null) {
this.customer = new Person("Customer", customerFirstName, customerLastName, input);
} else {
this.customer = existingCustomer;
people.add(existingCustomer);
}
System.out.println("\nPlease enter the project number:");
this.projectNumber = input.next();
System.out.println("\nPlease enter the type of building required:");
this.buildingType = input.next();
System.out.println("\nPlease enter the project name, or 'no' to autogenerate:");
String projectNameChoice = input.next();
if (projectNameChoice.equalsIgnoreCase("no")) {
this.projectName = buildingType + " " + customer.lastName;
} else {
this.projectName = projectNameChoice;
}
System.out.println("\nPlease enter the building physical address:");
this.buildingAddress = input.next().replace(", ", "; ");
System.out.println("\nPlease enter the type of building ERF number:");
this.erfNumber = input.next();
System.out.println("\nPlease enter the job fee:");
this.totalFee = numberInput.nextBigDecimal();
System.out.println("\nPlease enter how much the customer has paid to date:");
this.totalPaid = numberInput.nextBigDecimal();
setDate(numberInput);
System.out.println("\nPlease enter the architect first name:");
String architectFirstName = input.next();
System.out.println("\nPlease enter the architect last name:");
String architectLastName = input.next();
String architectFullName = architectFirstName + " " + architectLastName;
Person existingArchitect = Person.personSearch(people, architectFullName, "architect");
if (existingArchitect == null) {
this.architect = new Person("Architect", architectFirstName, architectLastName, input);
} else {
this.architect = existingArchitect;
people.add(existingArchitect);
}
System.out.println("\nPlease enter the Project Manager first name:");
String projectManagerFirstName = input.next();
System.out.println("\nPlease enter the Project Manager last name:");
String projectManagerLastName = input.next();
String projectManagerFullName = projectManagerFirstName + " " + projectManagerLastName;
Person existingProjectManager = Person.personSearch(people, projectManagerFullName, "project manager");
if (existingProjectManager == null) {
this.projectManager = new Person("Project Manager", projectManagerFirstName, projectManagerLastName, input);
} else {
this.projectManager = existingProjectManager;
people.add(existingProjectManager);
}
System.out.println("\nPlease enter the Structural Engineer first name:");
String structuralEngineerFirstName = input.next();
System.out.println("\nPlease enter the Structural Engineer last name:");
String structuralEngineerLastName = input.next();
String structuralEngineerFullName = structuralEngineerFirstName + " " + structuralEngineerLastName;
Person existingStructuralEngineer = Person.personSearch(people, structuralEngineerFullName,
"structural engineer");
if (existingStructuralEngineer == null) {
this.structuralEngineer = new Person("Structural Engineer", structuralEngineerFirstName,
structuralEngineerLastName, input);
} else {
this.structuralEngineer = existingStructuralEngineer;
people.add(existingStructuralEngineer);
}
this.completed = false;
}
private void setDate(Scanner numberInput) {
// While loop<SUF>
while (true) {
LocalDate today = LocalDate.now();
int thisYear = today.getYear();
int thisMonth = today.getMonthValue();
int thisDay = today.getDayOfMonth();
int dueYear;
int dueMonth;
int dueDay;
int maxNumberOfDays = 0;
// While loop to get year
while (true) {
System.out.println("\nPlease enter the year the project is due:");
dueYear = numberInput.nextInt();
if (dueYear < thisYear) {
System.out.println("Deadline year cannot be before current year. Please try again.");
} else {
break;
}
}
// While loop to get current month and determine maximum number of days in month
while (true) {
System.out.println(
"\nPlease enter the month, using 1 for January to 12 for December, the project is due:");
dueMonth = numberInput.nextInt();
if (dueYear == thisYear && dueMonth < thisMonth) {
System.out.println("Deadline month cannot be before current month. Please try again.");
} else if (dueMonth < 1 || dueMonth > 12) {
System.out.println("Deadline month value invalid. Please try again.");
} else {
break;
}
}
// Switch statement to determine number of days in month
switch (dueMonth) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
maxNumberOfDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
maxNumberOfDays = 30;
break;
case 2:
// Check if given due year is a leap year
if (((dueYear % 4 == 0) && !(dueYear % 100 == 0)) || (dueYear % 400 == 0))
maxNumberOfDays = 29;
else
maxNumberOfDays = 28;
break;
default:
System.out.println("Please try again.");
break;
}
while (true) {
System.out.println("\nPlease enter the day of the month the project is due:");
dueDay = numberInput.nextInt();
if (dueYear == thisYear && dueMonth == thisMonth && dueDay <= thisDay) {
System.out.println("Deadline month cannot be before current month. Please try again.");
} else if (dueDay > maxNumberOfDays) {
System.out.println("Deadline day cannot exceed days of deadline month. Please try again.");
} else {
break;
}
}
this.deadline = LocalDate.of(dueYear, dueMonth, dueDay);
break;
}
}
// Overload for project constructor to create objects of already logged projects
/**
* Overload constructor method for creating an object from previously logged
* project.
*
* @param loggedProject <br>
* CSV string containing details of project
* @param persons <br>
* ArrayList of Person objects
*/
public Project(String loggedProject, ArrayList<Person> persons) {
loggedProject = loggedProject.strip();
String[] existingProject = loggedProject.split(", ");
this.projectNumber = existingProject[0];
this.buildingType = existingProject[1];
this.projectName = existingProject[3];
this.buildingAddress = existingProject[4];
this.erfNumber = existingProject[5];
this.totalFee = new BigDecimal(existingProject[6]);
this.totalPaid = new BigDecimal(existingProject[7]);
this.deadline = LocalDate.parse(existingProject[8]);
for (Person element : persons) {
if (element.getDesignation().equalsIgnoreCase("customer")
&& element.getName().equalsIgnoreCase(existingProject[2])) {
this.customer = element;
} else if (element.getDesignation().equalsIgnoreCase("architect")
&& element.getName().equalsIgnoreCase(existingProject[9])) {
this.architect = element;
} else if (element.getDesignation().equalsIgnoreCase("project manager")
&& element.getName().equalsIgnoreCase(existingProject[10])) {
this.projectManager = element;
}
if (element.getDesignation().equalsIgnoreCase("structural engineer")
&& element.getName().equalsIgnoreCase(existingProject[11])) {
this.structuralEngineer = element;
}
}
this.completed = Boolean.parseBoolean(existingProject[12]);
}
// Call each attribute
/**
*
* @return string attribute projectNumber
*/
public String getProjectNumber() {
return projectNumber;
}
/**
*
* @return string attribute projectName
*/
public String getProjectName() {
return projectName;
}
/**
*
* @return string attribute buildingType
*/
public String getBuildingType() {
return buildingType;
}
/**
*
* @return string attribute buildingAddress
*/
public String getBuildingAddress() {
return buildingAddress;
}
/**
*
* @return string attribute erfNumber
*/
public String getErfNumber() {
return erfNumber;
}
/**
*
* @return float attribute totalFee
*/
public BigDecimal getTotalFee() {
return totalFee;
}
/**
*
* @return float attribute totalPaid
*/
public BigDecimal getTotalPaid() {
return totalPaid;
}
/**
*
* @return localdate attribute deadline
*/
public LocalDate getDeadline() {
return deadline;
}
/**
*
* @return person attribute architect
*/
public Person getArchitect() {
return architect;
}
/**
*
* @return person attribute project manager
*/
public Person getProjectManager() {
return projectManager;
}
/**
*
* @return person attribute structural engineer
*/
public Person getStructuralEngineer() {
return structuralEngineer;
}
/**
*
* @return person attribute customer
*/
public Person getCustomer() {
return customer;
}
// Call all attributes
/**
* Method to obtain a string detailing all project details in an easy-to-read
* format
*
* @return String
*/
public String toString() {
String output = "";
for (int i = 0; i <= 50; i++) {
output += "*";
}
output += "\nProject Number:\n\t" + projectNumber;
output += "\nProject Name:\n\t" + projectName;
output += "\nBuilding Type:\n\t" + buildingType;
output += "\nBuilding Address:\n\t" + buildingAddress.replace("; ", "\n\t");
output += "\nERF Number:\n\t" + erfNumber;
output += String.format("\nTotal Fee:\n\tR%.2f", totalFee);
output += String.format("\nTotal Paid:\n\tR%.2f", totalPaid);
output += String.format("\nTotal Outstanding:\n\tR%.2f", (totalFee.subtract(totalPaid)));
output += "\nDeadline:\n\t" + deadline;
output += "\nArchitect:\n\t" + architect.getName();
output += "\nProject Manager:\n\t" + projectManager.getName();
output += "\nStructural Engineer:\n\t" + structuralEngineer.getName();
output += "\nCustomer:\n\t" + customer.getName();
if (!completed) {
output += "\nProject completed:\n\tNo";
} else {
output += "\nProject completed:\n\tYes";
}
output += "\n";
return output;
}
/**
* Method to obtain a string detailing all project details in CSV format
*
* @return String
*/
public String toOutput() {
String Output = projectNumber + ", " + buildingType + ", " + customer.getName() + ", " + projectName + ", "
+ buildingAddress + ", " + erfNumber + ", " + totalFee + ", " + totalPaid + ", " + deadline + ", "
+ architect.getName() + ", " + projectManager.getName() + ", " + structuralEngineer.getName() + ", "
+ completed + "\n";
return Output;
}
// Add functionality to change project deadline
/**
* Method to allow user to update project deadline
*
* @param numberInput <br>
* Scanner object to obtain user input
*/
public void updateDeadline(Scanner numberInput) {
setDate(numberInput);
}
// Add functionality to change fee paid to date
/**
* Method to allow user to pay into a job
*
* @param numberInput <br>
* Scanner object to obtain user input
*/
public void updateTotalPaid(Scanner numberInput) {
System.out.println(String.format("\nFee outstanding: R%.2f", (this.totalFee.subtract(this.totalPaid))));
System.out.println("\nHow much is the client paying into the account?");
BigDecimal paid = numberInput.nextBigDecimal();
System.out.println();
this.totalPaid = totalPaid.add(paid);
}
// Add functionality to update contractor details
/**
* Method to update contractor details or assign a new contractor to a project
*
* @param input <br>
* Scanner to obtain user input
* @param people <br>
* ArrayList of type Person
*
*/
public String updateProjectManager(Scanner input, ArrayList<Person> people) {
String option = "";
while (true) {
System.out.println("\nPlease select from the following:");
System.out.println("Amend \t- amend current project manager details");
System.out.println("Change \t- assign a different project manager from the system");
System.out.println("New \t- assign a new project manager");
System.out.println("Exit \t- return to main menu");
String choice = input.next();
if (choice.equalsIgnoreCase("amend")) {
option = "amend";
Person oldDetails = Person.personSearch(people, projectManager.getName(), "project manager");
System.out.println("\nWhat is the project manager first name?\n");
oldDetails.setFirstName(input);
System.out.println("What is the project manager last name?\n");
oldDetails.setLastName(input);
System.out.print("What is the project manager phone number?\n");
oldDetails.setPhoneNumber(input);
System.out.print("What is the project manager email address?\n");
oldDetails.setEmail(input);
System.out.print("What is the project manager address?\n");
oldDetails.setAddress(input);
this.projectManager = oldDetails;
people.add(oldDetails);
break;
} else if (choice.equalsIgnoreCase("change")) {
option = "change";
System.out.println("\nThese are the currently registered project managers:\n");
for (Person element : people) {
if (element.designation.equalsIgnoreCase("project manager")) {
System.out.println(element.personDetails());
}
}
while (true) {
System.out.println(
"Please enter the full name of the project manager you would like to assign to this project:");
String newManagerName = input.next();
Person newManager = Person.personSearch(people, newManagerName, "project manager");
if (newManager != null) {
this.projectManager = newManager;
people.add(newManager);
break;
}
}
break;
} else if (choice.equalsIgnoreCase("new")) {
option = "new";
System.out.println("Please enter the new project manager first name:");
String firstName = input.next();
System.out.println("Please enter the new project manager last name:");
String lastName = input.next();
Person replacementProjectManager = new Person("Project Manager", firstName, lastName, input);
this.projectManager = replacementProjectManager;
people.add(replacementProjectManager);
break;
} else if (choice.equalsIgnoreCase("exit")) {
break;
} else {
System.out.println("\nYour input did not match a given option. Please try again.\n");
}
}
return option;
}
// Add functionality to finalise project
/**
* Static method to mark project as complete, remove it from list of current
* projects, add it to list of <br>
* completed projects and generate a customer invoice if any fees are
* outstanding
*
* @param finaliseProject <br>
* Project object to be finalised
* @throws IOException <br>
* IOException thrown if FileWriter encounters an error
*/
public static String finalise(Project finaliseProject) throws IOException {
System.out.println();
// Set completed attribute to true
finaliseProject.completed = true;
// Generate invoice if there are outstanding fees
if ((finaliseProject.totalFee.compareTo(finaliseProject.totalPaid)) > 0) {
try {
// Variable to name generated invoice as projectNumber
String fileName = String.format("%s-%s.txt", finaliseProject.customer.getLastName(),
finaliseProject.projectNumber);
// Create File object linked to "Completed_projects.txt"
File invoice = new File(fileName);
// Create FileWriter object
FileWriter invoiceWriter = new FileWriter(invoice);
// generate invoice document if not present
invoice.createNewFile();
String toInvoice = "\tPOISED INVOICE\n";
toInvoice += "invoice addressed to:\n";
toInvoice += finaliseProject.customer.getPerson() + "\n";
toInvoice += "Date completed: " + LocalDate.now() + "\n";
toInvoice += finaliseProject.toString();
invoiceWriter.write(toInvoice);
invoiceWriter.close();
} catch (IOException e) {
System.out.println("Error encountered: invoice file could not be created");
}
}
String forDatabase = "'" + finaliseProject.projectNumber + "'";
forDatabase += ", '" + finaliseProject.projectName + "'";
forDatabase += ", '" + finaliseProject.buildingType + "'";
forDatabase += ", '" + finaliseProject.buildingAddress + "'";
forDatabase += ", '" + finaliseProject.erfNumber + "'";
forDatabase += ", " + finaliseProject.totalFee.toString();
forDatabase += ", " + finaliseProject.totalPaid.toString();
forDatabase += ", '" + finaliseProject.deadline + "'";
forDatabase += ", '" + LocalDate.now() + "'";
forDatabase += ", '" + finaliseProject.architect.getName() + "'";
forDatabase += ", '" + finaliseProject.customer.getName() + "'";
forDatabase += ", '" + finaliseProject.projectManager.getName() + "'";
forDatabase += ", '" + finaliseProject.structuralEngineer.getName() + "'";
forDatabase += ", '" + finaliseProject.completed + "'";
return forDatabase;
}
// Add functionality to search through objects by project name or project number
/**
* Method to search through list of projects by attributes projectName or
* projectNumber
*
* @param projectsList <br>
* Array containing all current projects
* @param input <br>
* Scanner object to accept user input
* @return Project
*/
public static Project projectSearch(ArrayList<Project> projectsList, Scanner input) {
while (true) {
System.out
.println("Please enter a project name, project number, or 'list' to view all valid search terms:");
String searchTerm = input.nextLine();
if (searchTerm.equalsIgnoreCase("list")) {
for (Project all : projectsList) {
System.out.println("Project Number: " + all.getProjectNumber() + "\nProject Name: "
+ all.getProjectName() + "\n");
}
System.out.println();
} else {
for (Project all : projectsList) {
if (searchTerm.equalsIgnoreCase(all.getProjectName())
|| searchTerm.equalsIgnoreCase(all.getProjectNumber())) {
int index = projectsList.indexOf(all);
Project toBeEdited = projectsList.remove(index);
return toBeEdited;
}
}
System.out.println("Your input did not match a listed project. Please try again.\n");
}
}
}
/**
*
* @return string attribute argument for updating projects database
*/
public String toDatabase() {
String values = "'" + projectNumber + "'";
values += ", '" + projectName + "'";
values += ", '" + buildingType + "'";
values += ", '" + buildingAddress + "'";
values += ", '" + erfNumber + "'";
values += ", " + totalFee;
values += ", " + totalPaid;
values += ", '" + deadline + "'";
values += ", '" + architect.getName() + "'";
values += ", '" + customer.getName() + "'";
values += ", '" + projectManager.getName() + "'";
values += ", '" + structuralEngineer.getName() + "'";
values += ", '" + completed + "'";
return values;
}
}
|
127151_14 | // Copyright (c) 2014 by B.W. van Schooten, [email protected]
package net.tmtg.glesjs;
import android.os.Bundle;
import android.app.Activity;
import android.app.Application;
import android.hardware.*;
import android.view.*;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.content.Intent;
import android.net.Uri;
import android.content.Context;
import android.opengl.*;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.util.Log;
public class MainActivity extends Activity {
static boolean surface_already_created=false;
MyGLSurfaceView mView=null;
MyRenderer mRen=null;
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
GlesJSUtils.init(this);
mView = new MyGLSurfaceView(getApplication());
// Try to hang on to GL context
mView.setPreserveEGLContextOnPause(true);
setContentView(mView);
}
@Override protected void onPause() {
super.onPause();
//mView.setVisibility(View.GONE);
mView.onPause();
GlesJSUtils.pauseAudio();
}
@Override protected void onResume() {
super.onResume();
mView.onResume();
GlesJSUtils.resumeAudio();
}
/*@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && mView.getVisibility() == View.GONE) {
mView.setVisibility(View.VISIBLE);
}
}*/
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
return GameController.onKeyDown(keyCode,event);
}
@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
return GameController.onKeyUp(keyCode,event);
}
@Override public boolean onGenericMotionEvent(MotionEvent event) {
return GameController.onGenericMotionEvent(event);
}
class MyGLSurfaceView extends GLSurfaceView {
public MyGLSurfaceView(Context context){
super(context);
setEGLContextClientVersion(2);
// Set the Renderer for drawing on the GLSurfaceView
mRen = new MyRenderer();
setRenderer(mRen);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
// queue event, and handle it from the renderer thread later
// to avoid concurrency handling
if (mRen!=null) mRen.queueTouchEvent(me);
return true;
}
}
class MyRenderer implements GLSurfaceView.Renderer {
static final int MAXQUEUELEN = 6;
Object queuelock = new Object();
MotionEvent [] motionqueue = new MotionEvent [MAXQUEUELEN];
int motionqueue_len = 0;
public void queueTouchEvent(MotionEvent ev) {
synchronized (queuelock) {
if (motionqueue_len >= MAXQUEUELEN) return;
motionqueue[motionqueue_len++] = MotionEvent.obtain(ev);
}
}
static final int MAXTOUCHES=8;
int [] touchids = new int[MAXTOUCHES];
double [] touchx = new double[MAXTOUCHES];
double [] touchy = new double[MAXTOUCHES];
int touchlen = 0;
public void handleTouchEvent(MotionEvent me) {
// XXX We should mask out the pointer id info in some of the
// action codes. Since 2.2, we should use getActionMasked for
// this.
// use MotionEventCompat to do this?
int action = me.getActionMasked();
int ptridx = me.getActionIndex();
// Default coord is the current coordinates of an arbitrary active
// pointer.
double x = me.getX(ptridx);
double y = me.getY(ptridx);
// on a multitouch, touches after the first touch are also
// considered mouse-down flanks.
boolean press = action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_POINTER_DOWN;
// boolean down = press || action == MotionEvent.ACTION_MOVE;
// Alcatel pop:
// down event: 0
// move event: 2
// up event: 9.
// ACTION_UP=1, ACTION_POINTER_UP=6
//boolean release = (action & ( MotionEvent.ACTION_UP)) != 0;
// Normal:
boolean release = action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_POINTER_UP;
int ptrid=0;
try {
ptrid = me.getPointerId(ptridx);
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
return;
}
// pass multitouch coordinates before touch event
int pointerCount = me.getPointerCount();
// signal start multitouch info
GlesJSLib.onMultitouchCoordinates(-1,0,0);
for (int p = 0; p < pointerCount; p++) {
try {
int pid = me.getPointerId(p);
GlesJSLib.onMultitouchCoordinates(pid,me.getX(p),me.getY(p));
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
}
}
// signal end coordinate info, start button info
//GlesJSLib.onMultitouchCoordinates(-2,0,0);
// single touch / press-release info
// !press && !release means move
GlesJSLib.onTouchEvent(ptrid,x,y,press,release);
// signal end touch info
GlesJSLib.onMultitouchCoordinates(-3,0,0);
}
public void onDrawFrame(GL10 gl) {
GameController.startOfFrame();
// handle events in the render thread
synchronized (queuelock) {
for (int i=0; i<motionqueue_len; i++) {
if (motionqueue[i]!=null) {
handleTouchEvent(motionqueue[i]);
motionqueue[i].recycle();
motionqueue[i] = null;
}
}
motionqueue_len = 0;
}
for (int i=0; i<GameController.NR_PLAYERS; i++) {
GameController con = GameController.getControllerByPlayer(i);
if (con.isConnected()) {
//System.out.println("##################active@@@@@"+i);
boolean [] buttons = con.getButtons();
float [] axes = con.getAxes();
GlesJSLib.onControllerEvent(i,true,buttons,axes);
} else {
GlesJSLib.onControllerEvent(i,false,null,null);
}
/* FOR TESTING:
} else if (i==0) {
boolean [] buttons = new boolean[]
{true,false,true,false,true,false,true};
float [] axes = new float[]
{9,8,7,6,5};
GlesJSLib.onControllerEvent(i,true,buttons,axes);
}
*/
}
GlesJSLib.onDrawFrame();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
GameController.init(MainActivity.this);
GlesJSLib.onSurfaceChanged(width, height);
surface_already_created=true;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
if (surface_already_created) {
// gl context was lost -> we can't handle that yet
// -> commit suicide
// TODO generate contextlost event in JS
System.err.println("GL context lost. Cannot restore. Exiting.");
System.exit(0);
}
// Do nothing.
}
}
}
| JakeCoxon/glesjs | src/net/tmtg/glesjs/MainActivity.java | 2,284 | // move event: 2 | line_comment | nl | // Copyright (c) 2014 by B.W. van Schooten, [email protected]
package net.tmtg.glesjs;
import android.os.Bundle;
import android.app.Activity;
import android.app.Application;
import android.hardware.*;
import android.view.*;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.content.Intent;
import android.net.Uri;
import android.content.Context;
import android.opengl.*;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.util.Log;
public class MainActivity extends Activity {
static boolean surface_already_created=false;
MyGLSurfaceView mView=null;
MyRenderer mRen=null;
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
GlesJSUtils.init(this);
mView = new MyGLSurfaceView(getApplication());
// Try to hang on to GL context
mView.setPreserveEGLContextOnPause(true);
setContentView(mView);
}
@Override protected void onPause() {
super.onPause();
//mView.setVisibility(View.GONE);
mView.onPause();
GlesJSUtils.pauseAudio();
}
@Override protected void onResume() {
super.onResume();
mView.onResume();
GlesJSUtils.resumeAudio();
}
/*@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && mView.getVisibility() == View.GONE) {
mView.setVisibility(View.VISIBLE);
}
}*/
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
return GameController.onKeyDown(keyCode,event);
}
@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
return GameController.onKeyUp(keyCode,event);
}
@Override public boolean onGenericMotionEvent(MotionEvent event) {
return GameController.onGenericMotionEvent(event);
}
class MyGLSurfaceView extends GLSurfaceView {
public MyGLSurfaceView(Context context){
super(context);
setEGLContextClientVersion(2);
// Set the Renderer for drawing on the GLSurfaceView
mRen = new MyRenderer();
setRenderer(mRen);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
// queue event, and handle it from the renderer thread later
// to avoid concurrency handling
if (mRen!=null) mRen.queueTouchEvent(me);
return true;
}
}
class MyRenderer implements GLSurfaceView.Renderer {
static final int MAXQUEUELEN = 6;
Object queuelock = new Object();
MotionEvent [] motionqueue = new MotionEvent [MAXQUEUELEN];
int motionqueue_len = 0;
public void queueTouchEvent(MotionEvent ev) {
synchronized (queuelock) {
if (motionqueue_len >= MAXQUEUELEN) return;
motionqueue[motionqueue_len++] = MotionEvent.obtain(ev);
}
}
static final int MAXTOUCHES=8;
int [] touchids = new int[MAXTOUCHES];
double [] touchx = new double[MAXTOUCHES];
double [] touchy = new double[MAXTOUCHES];
int touchlen = 0;
public void handleTouchEvent(MotionEvent me) {
// XXX We should mask out the pointer id info in some of the
// action codes. Since 2.2, we should use getActionMasked for
// this.
// use MotionEventCompat to do this?
int action = me.getActionMasked();
int ptridx = me.getActionIndex();
// Default coord is the current coordinates of an arbitrary active
// pointer.
double x = me.getX(ptridx);
double y = me.getY(ptridx);
// on a multitouch, touches after the first touch are also
// considered mouse-down flanks.
boolean press = action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_POINTER_DOWN;
// boolean down = press || action == MotionEvent.ACTION_MOVE;
// Alcatel pop:
// down event: 0
// move event:<SUF>
// up event: 9.
// ACTION_UP=1, ACTION_POINTER_UP=6
//boolean release = (action & ( MotionEvent.ACTION_UP)) != 0;
// Normal:
boolean release = action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_POINTER_UP;
int ptrid=0;
try {
ptrid = me.getPointerId(ptridx);
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
return;
}
// pass multitouch coordinates before touch event
int pointerCount = me.getPointerCount();
// signal start multitouch info
GlesJSLib.onMultitouchCoordinates(-1,0,0);
for (int p = 0; p < pointerCount; p++) {
try {
int pid = me.getPointerId(p);
GlesJSLib.onMultitouchCoordinates(pid,me.getX(p),me.getY(p));
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
}
}
// signal end coordinate info, start button info
//GlesJSLib.onMultitouchCoordinates(-2,0,0);
// single touch / press-release info
// !press && !release means move
GlesJSLib.onTouchEvent(ptrid,x,y,press,release);
// signal end touch info
GlesJSLib.onMultitouchCoordinates(-3,0,0);
}
public void onDrawFrame(GL10 gl) {
GameController.startOfFrame();
// handle events in the render thread
synchronized (queuelock) {
for (int i=0; i<motionqueue_len; i++) {
if (motionqueue[i]!=null) {
handleTouchEvent(motionqueue[i]);
motionqueue[i].recycle();
motionqueue[i] = null;
}
}
motionqueue_len = 0;
}
for (int i=0; i<GameController.NR_PLAYERS; i++) {
GameController con = GameController.getControllerByPlayer(i);
if (con.isConnected()) {
//System.out.println("##################active@@@@@"+i);
boolean [] buttons = con.getButtons();
float [] axes = con.getAxes();
GlesJSLib.onControllerEvent(i,true,buttons,axes);
} else {
GlesJSLib.onControllerEvent(i,false,null,null);
}
/* FOR TESTING:
} else if (i==0) {
boolean [] buttons = new boolean[]
{true,false,true,false,true,false,true};
float [] axes = new float[]
{9,8,7,6,5};
GlesJSLib.onControllerEvent(i,true,buttons,axes);
}
*/
}
GlesJSLib.onDrawFrame();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
GameController.init(MainActivity.this);
GlesJSLib.onSurfaceChanged(width, height);
surface_already_created=true;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
if (surface_already_created) {
// gl context was lost -> we can't handle that yet
// -> commit suicide
// TODO generate contextlost event in JS
System.err.println("GL context lost. Cannot restore. Exiting.");
System.exit(0);
}
// Do nothing.
}
}
}
|
103461_4 | package czwarta.obiektowosc.manytomanyatrybut.zadanie11kwietnia;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
/*
* Klient kupuje produkty. Klient ma imie nazwisko i rozmiar koszulki. Produkt ma
* nazwe, cene i jesli jest to koszulka to wymiar.
* Klient moze miec wiele produktow,
* produkt moze miec jednego klienta.
* 1) Napisz metode ktora znajduje klienta ktory wydal najwiecej.
* 2) napisz metode ktora zwroci liste klientow ktorzy kupili koszulke z nike
* 3) napisz metode ktora zwroci liste klientow ktorzy kupili koszulki nike ale nie na swoj rozmiar
*/
Client client1 = new Client("Kuba", "Mroczka", "L");
Client client2 = new Client("Szymon", "Pawlak", "M");
System.out.println(client1);
// tutaj stworzyłem dwie koszulkim tylko
Product product1 = new Product("Iphone", 5000.0, "Electronics", client1);
Product product2 = new Product("Tv", 8000.0, "Electronics", client1);
Product product3 = new Product("T-shirt Nike", 20000.0, "T-shirt", "M", client2);
Product product4 = new Product("T-shirt Nike", 250.0, "T-shirt", "L", client2);
Product product5 = new Product("Headphones", 500.0, "Electronics", client1);
Product product6 = new Product("Headphones", 500.0, "Electronics", client2);
System.out.println(product1);
System.out.println(client1.getPurchasedProducts());
System.out.println("-------------------------------------");
//1
List<Client> clients = Client.getClients();
System.out.println(clients);
System.out.println(findTopSpender(clients));
// System.out.println(findTopSpender(client1,client2));
//2
System.out.println(findClientsByNikeShirt(clients));
// System.out.println(findClientsByNikeShirt(client1, client2));
//3
System.out.println("rozmiary koszulek");
System.out.println(findMismatchedNikeShirtClients(clients));
}
//zadanie1
//todo zrefaktorowac ta metode, powinna miec tylko pole topSpender
//pole maxTotalSpending jest nadmiarowe
//pole totalSpending tez
public static Client findTopSpender(List<Client> clients) {
Client topSpender = null;
double maxTotalSpending = 0;
for (Client client : clients) {
double totalSpending = client.howMuchClientSpend();
if (totalSpending > maxTotalSpending) {
maxTotalSpending = totalSpending;
topSpender = client;
}
}
return topSpender;
}
//zadanie2
public static List<Client> findClientsByNikeShirt(List<Client> clients) {
List<Client> clientsWithNikeShirt = new ArrayList<>();
for (Client client : clients) {
if (client.hasTshirtForGivenMake("nike")) {
clientsWithNikeShirt.add(client);
}
}
return clientsWithNikeShirt;
}
//zadanie3
public static List<Client> findMismatchedNikeShirtClients(List<Client> clients) {
List<Client> mismatchedClients = new ArrayList<>();
for (Client client : findClientsByNikeShirt(clients)) {
if (!client.getTShirtSize().equalsIgnoreCase(client.getPurchasedProducts().get(0).getSize())) {
mismatchedClients.add(client);
}
}
return mismatchedClients;
}
// napisz metode ktora zwroci liste klientow ktorzy kupili koszulki nike ale nie na swoj rozmiar
public static List<Client> findClientsWithMismatchedPurchase(List<Client> clients, String make) {
List<Client> clientsWithClothesForGivenMake = new ArrayList<>();
for (Client client: clients) {
if (client.hasTshirtForGivenMake(make)) {
clientsWithClothesForGivenMake.add(client);
}
}
List<Client> mismatchedClients = new ArrayList<>();
for (Client client : clientsWithClothesForGivenMake) {
for (Product product : client.getPurchasedProducts()) {
if (product.getSize().equalsIgnoreCase(client.getTShirtSize())) {
mismatchedClients.add(client);
}
}
}
return mismatchedClients;
}
}
| JakubMroczka/kurs | src/czwarta/obiektowosc/manytomanyatrybut/zadanie11kwietnia/Main.java | 1,383 | //pole totalSpending tez | line_comment | nl | package czwarta.obiektowosc.manytomanyatrybut.zadanie11kwietnia;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
/*
* Klient kupuje produkty. Klient ma imie nazwisko i rozmiar koszulki. Produkt ma
* nazwe, cene i jesli jest to koszulka to wymiar.
* Klient moze miec wiele produktow,
* produkt moze miec jednego klienta.
* 1) Napisz metode ktora znajduje klienta ktory wydal najwiecej.
* 2) napisz metode ktora zwroci liste klientow ktorzy kupili koszulke z nike
* 3) napisz metode ktora zwroci liste klientow ktorzy kupili koszulki nike ale nie na swoj rozmiar
*/
Client client1 = new Client("Kuba", "Mroczka", "L");
Client client2 = new Client("Szymon", "Pawlak", "M");
System.out.println(client1);
// tutaj stworzyłem dwie koszulkim tylko
Product product1 = new Product("Iphone", 5000.0, "Electronics", client1);
Product product2 = new Product("Tv", 8000.0, "Electronics", client1);
Product product3 = new Product("T-shirt Nike", 20000.0, "T-shirt", "M", client2);
Product product4 = new Product("T-shirt Nike", 250.0, "T-shirt", "L", client2);
Product product5 = new Product("Headphones", 500.0, "Electronics", client1);
Product product6 = new Product("Headphones", 500.0, "Electronics", client2);
System.out.println(product1);
System.out.println(client1.getPurchasedProducts());
System.out.println("-------------------------------------");
//1
List<Client> clients = Client.getClients();
System.out.println(clients);
System.out.println(findTopSpender(clients));
// System.out.println(findTopSpender(client1,client2));
//2
System.out.println(findClientsByNikeShirt(clients));
// System.out.println(findClientsByNikeShirt(client1, client2));
//3
System.out.println("rozmiary koszulek");
System.out.println(findMismatchedNikeShirtClients(clients));
}
//zadanie1
//todo zrefaktorowac ta metode, powinna miec tylko pole topSpender
//pole maxTotalSpending jest nadmiarowe
//pole totalSpending<SUF>
public static Client findTopSpender(List<Client> clients) {
Client topSpender = null;
double maxTotalSpending = 0;
for (Client client : clients) {
double totalSpending = client.howMuchClientSpend();
if (totalSpending > maxTotalSpending) {
maxTotalSpending = totalSpending;
topSpender = client;
}
}
return topSpender;
}
//zadanie2
public static List<Client> findClientsByNikeShirt(List<Client> clients) {
List<Client> clientsWithNikeShirt = new ArrayList<>();
for (Client client : clients) {
if (client.hasTshirtForGivenMake("nike")) {
clientsWithNikeShirt.add(client);
}
}
return clientsWithNikeShirt;
}
//zadanie3
public static List<Client> findMismatchedNikeShirtClients(List<Client> clients) {
List<Client> mismatchedClients = new ArrayList<>();
for (Client client : findClientsByNikeShirt(clients)) {
if (!client.getTShirtSize().equalsIgnoreCase(client.getPurchasedProducts().get(0).getSize())) {
mismatchedClients.add(client);
}
}
return mismatchedClients;
}
// napisz metode ktora zwroci liste klientow ktorzy kupili koszulki nike ale nie na swoj rozmiar
public static List<Client> findClientsWithMismatchedPurchase(List<Client> clients, String make) {
List<Client> clientsWithClothesForGivenMake = new ArrayList<>();
for (Client client: clients) {
if (client.hasTshirtForGivenMake(make)) {
clientsWithClothesForGivenMake.add(client);
}
}
List<Client> mismatchedClients = new ArrayList<>();
for (Client client : clientsWithClothesForGivenMake) {
for (Product product : client.getPurchasedProducts()) {
if (product.getSize().equalsIgnoreCase(client.getTShirtSize())) {
mismatchedClients.add(client);
}
}
}
return mismatchedClients;
}
}
|
204795_2 | /*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.commons.assets;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.IntAttribute;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.PropertiesUtils;
import com.mbrlabs.mundus.commons.assets.meta.Meta;
import net.mgsx.gltf.scene3d.attributes.PBRColorAttribute;
import net.mgsx.gltf.scene3d.attributes.PBRFloatAttribute;
import net.mgsx.gltf.scene3d.attributes.PBRTextureAttribute;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;
/**
* @author Marcus Brummer
* @version 09-10-2016
*/
public class MaterialAsset extends Asset {
private static final ObjectMap<String, String> MAP = new ObjectMap<>();
public static final String EXTENSION = ".mat";
// property keys
public static final String PROP_DIFFUSE_COLOR = "diffuse.color";
public static final String PROP_DIFFUSE_TEXTURE = "diffuse.texture";
public static final String PROP_MAP_NORMAL = "map.normal";
public static final String PROP_MAP_EMISSIVE_COLOR = "emissive.color";
public static final String PROP_MAP_EMISSIVE_TEXTURE = "emissive.texture";
public static final String PROP_METAL_ROUGH_TEXTURE = "metallicRoughTexture";
public static final String PROP_OCCLUSION_TEXTURE = "occlusionTexture";
public static final String PROP_ROUGHNESS = "roughness";
public static final String PROP_OPACITY = "opacity";
public static final String PROP_METALLIC = "metallic";
public static final String PROP_ALPHA_TEST = "alphaTest";
public static final String PROP_NORMAL_SCALE = "normalScale";
public static final String PROP_SHADOW_BIAS = "shadowBias";
public static final String PROP_CULL_FACE = "cullFace";
// ids of dependent assets
private String diffuseTextureID;
private String normalMapID;
private String emissiveTextureID;
private String metallicRoughnessTextureID;
private String occlusionTextureID;
// Possible values are GL_FRONT_AND_BACK, GL_BACK, GL_FRONT, or -1 to inherit default
private int cullFace = -1;
private Color diffuseColor = Color.WHITE.cpy();
private Color emissiveColor = Color.BLACK.cpy();
private TextureAsset diffuseTexture;
private TextureAsset normalMap;
private TextureAsset emissiveTexture;
private TextureAsset metallicRoughnessTexture;
private TextureAsset occlusionTexture;
public TexCoordInfo diffuseTexCoord = new TexCoordInfo("diffuse");
public TexCoordInfo normalTexCoord = new TexCoordInfo("map");
public TexCoordInfo emissiveTexCoord = new TexCoordInfo("emissive");
public TexCoordInfo metallicRoughnessTexCoord = new TexCoordInfo("metallicRoughTexture");
public TexCoordInfo occlusionTexCoord = new TexCoordInfo("occlusionTexture");
private float roughness = 1f;
private float metallic = 0f;
private float opacity = 1f;
private float alphaTest = 0f;
private float normalScale = 1f;
private float shadowBias = 0.4f;
public MaterialAsset(Meta meta, FileHandle assetFile) {
super(meta, assetFile);
}
@Override
public void load() {
MAP.clear();
try {
Reader reader = file.reader();
PropertiesUtils.load(MAP, reader);
reader.close();
try {
String value = MAP.get(PROP_ROUGHNESS, null);
if (value != null) {
roughness = Float.parseFloat(value);
}
value = MAP.get(PROP_OPACITY, null);
if (value != null) {
opacity = Float.parseFloat(value);
}
value = MAP.get(PROP_METALLIC, null);
if (value != null) {
metallic = Float.parseFloat(value);
}
value = MAP.get(PROP_ALPHA_TEST, null);
if (value != null) {
alphaTest = Float.parseFloat(value);
}
value = MAP.get(PROP_NORMAL_SCALE, null);
if (value != null) {
normalScale = Float.parseFloat(value);
}
value = MAP.get(PROP_SHADOW_BIAS, null);
if (value != null) {
shadowBias = Float.parseFloat(value);
}
value = MAP.get(PROP_CULL_FACE, null);
if (value != null) {
cullFace = Integer.parseInt(value);
}
populateTexCoordInfo(diffuseTexCoord);
populateTexCoordInfo(normalTexCoord);
populateTexCoordInfo(emissiveTexCoord);
populateTexCoordInfo(metallicRoughnessTexCoord);
populateTexCoordInfo(occlusionTexCoord);
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
// diffuse color
String diffuseHex = MAP.get(PROP_DIFFUSE_COLOR);
if (diffuseHex != null) {
diffuseColor = Color.valueOf(diffuseHex);
}
// emissive color
String emissiveHex = MAP.get(PROP_MAP_EMISSIVE_COLOR);
if (emissiveHex != null) {
emissiveColor = Color.valueOf(emissiveHex);
}
// asset dependencies
diffuseTextureID = MAP.get(PROP_DIFFUSE_TEXTURE, null);
normalMapID = MAP.get(PROP_MAP_NORMAL, null);
metallicRoughnessTextureID = MAP.get(PROP_METAL_ROUGH_TEXTURE, null);
emissiveTextureID = MAP.get(PROP_MAP_EMISSIVE_TEXTURE, null);
occlusionTextureID = MAP.get(PROP_OCCLUSION_TEXTURE, null);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void load(AssetManager assetManager) {
// No async loading for materials right now
load();
}
private void populateTexCoordInfo(TexCoordInfo texCoordInfo) {
String value = MAP.get(texCoordInfo.PROP_UV, null);
if (value != null) {
texCoordInfo.uvIndex = Integer.parseInt(value);
}
value = MAP.get(texCoordInfo.PROP_OFFSET_U, null);
if (value != null) {
texCoordInfo.offsetU = Float.parseFloat(value);
}
value = MAP.get(texCoordInfo.PROP_OFFSET_V, null);
if (value != null) {
texCoordInfo.offsetV = Float.parseFloat(value);
}
value = MAP.get(texCoordInfo.PROP_SCALE_U, null);
if (value != null) {
texCoordInfo.scaleU = Float.parseFloat(value);
}
value = MAP.get(texCoordInfo.PROP_SCALE_V, null);
if (value != null) {
texCoordInfo.scaleV = Float.parseFloat(value);
}
value = MAP.get(texCoordInfo.PROP_ROTATION_UV, null);
if (value != null) {
texCoordInfo.rotationUV = Float.parseFloat(value);
}
}
/**
* Applies this material asset to the libGDX material.
*
* @param material the material to apply
* @return the material with asset attributes applied
*/
public Material applyToMaterial(Material material) {
return applyToMaterial(material, false);
}
/**
* Applies this material asset to the libGDX material.
*
* @param material the material to apply
* @param terrain whether this material is for a terrain
* @return the material with asset attributes applied
*/
public Material applyToMaterial(Material material, boolean terrain) {
if (diffuseColor != null) {
material.set(PBRColorAttribute.createBaseColorFactor(diffuseColor));
}
if (emissiveColor != null) {
material.set(PBRColorAttribute.createEmissive(emissiveColor));
}
if (!terrain) {
// Terrain materials use these for splat base
if (diffuseTexture != null) {
material.set(getTextureAttribute(PBRTextureAttribute.BaseColorTexture, diffuseTexture.getTexture(), diffuseTexCoord));
} else {
material.remove(PBRTextureAttribute.BaseColorTexture);
}
if (normalMap != null) {
material.set(getTextureAttribute(PBRTextureAttribute.NormalTexture, normalMap.getTexture(), normalTexCoord));
} else {
material.remove(PBRTextureAttribute.NormalTexture);
}
if (emissiveTexture != null) {
material.set(getTextureAttribute(PBRTextureAttribute.EmissiveTexture, emissiveTexture.getTexture(), emissiveTexCoord));
} else {
material.remove(PBRTextureAttribute.EmissiveTexture);
}
if (metallicRoughnessTexture != null) {
material.set(getTextureAttribute(PBRTextureAttribute.MetallicRoughnessTexture, metallicRoughnessTexture.getTexture(), metallicRoughnessTexCoord));
} else {
material.remove(PBRTextureAttribute.MetallicRoughnessTexture);
}
if (occlusionTexture != null) {
material.set(getTextureAttribute(PBRTextureAttribute.OcclusionTexture, occlusionTexture.getTexture(), occlusionTexCoord));
} else {
material.remove(PBRTextureAttribute.OcclusionTexture);
}
} else {
// Apply texCoords for terrains
PBRTextureAttribute diffuse = (PBRTextureAttribute) material.get(PBRTextureAttribute.BaseColorTexture);
if (diffuse != null) {
setTexCoordInfo(diffuse, diffuseTexCoord);
}
PBRTextureAttribute normal = (PBRTextureAttribute) material.get(PBRTextureAttribute.NormalTexture);
if (normal != null) {
setTexCoordInfo(normal, normalTexCoord);
}
}
material.set(PBRFloatAttribute.createRoughness(roughness));
material.set(PBRFloatAttribute.createMetallic(metallic));
material.set(PBRFloatAttribute.createNormalScale(normalScale));
material.set(new PBRFloatAttribute(PBRFloatAttribute.ShadowBias, shadowBias / 255f));
if (cullFace != -1) {
material.set(IntAttribute.createCullFace(cullFace));
} else {
material.remove(IntAttribute.CullFace);
}
if (opacity < 1f) {
material.set(new BlendingAttribute(true, opacity));
} else {
if (alphaTest == 0) {
material.remove(BlendingAttribute.Type);
}
}
if (alphaTest > 0) {
material.set(PBRFloatAttribute.createAlphaTest(alphaTest));
// We need blending attribute to trip the blendedFlag in shader
material.set(new BlendingAttribute(false, opacity));
} else {
material.remove(PBRFloatAttribute.AlphaTest);
if (opacity == 1f) {
material.remove(BlendingAttribute.Type);
}
}
return material;
}
/**
* Create a PBRTextureAttribute for the given type and populate it with
* the texture and TexCoordInfo
*/
private PBRTextureAttribute getTextureAttribute(long type, Texture texture, TexCoordInfo texCoord) {
PBRTextureAttribute attr = new PBRTextureAttribute(type, texture);
setTexCoordInfo(attr, texCoord);
return attr;
}
private void setTexCoordInfo(PBRTextureAttribute attr, TexCoordInfo texCoord) {
attr.uvIndex = texCoord.uvIndex;
attr.offsetU = texCoord.offsetU;
attr.offsetV = texCoord.offsetV;
attr.scaleU = texCoord.scaleU;
attr.scaleV = texCoord.scaleV;
attr.rotationUV = texCoord.rotationUV;
}
public float getRoughness() {
return roughness;
}
public void setRoughness(float roughness) {
this.roughness = roughness;
}
public float getMetallic() {
return metallic;
}
public void setMetallic(float metallic) {
this.metallic = metallic;
}
public float getOpacity() {
return opacity;
}
public void setOpacity(float opacity) {
this.opacity = opacity;
}
public float getAlphaTest() {
return alphaTest;
}
public void setAlphaTest(float alphaTest) {
this.alphaTest = alphaTest;
}
public float getNormalScale() {
return normalScale;
}
public void setNormalScale(float normalScale) {
this.normalScale = normalScale;
}
public float getShadowBias() {
return shadowBias;
}
public void setShadowBias(float shadowBias) {
this.shadowBias = shadowBias;
}
public TextureAsset getNormalMap() {
return normalMap;
}
public void setNormalMap(TextureAsset normalMap) {
this.normalMap = normalMap;
if (normalMap != null) {
this.normalMapID = normalMap.getID();
} else {
this.normalMapID = null;
}
}
public TextureAsset getDiffuseTexture() {
return diffuseTexture;
}
public void setDiffuseTexture(TextureAsset diffuseTexture) {
this.diffuseTexture = diffuseTexture;
if (diffuseTexture != null) {
this.diffuseTextureID = diffuseTexture.getID();
} else {
this.diffuseTextureID = null;
}
}
public TextureAsset getEmissiveTexture() {
return emissiveTexture;
}
public void setEmissiveTexture(TextureAsset emissiveTexture) {
this.emissiveTexture = emissiveTexture;
if (emissiveTexture != null) {
this.emissiveTextureID = emissiveTexture.getID();
} else {
this.emissiveTextureID = null;
}
}
public Color getEmissiveColor() {
return emissiveColor;
}
public TextureAsset getMetallicRoughnessTexture() {
return metallicRoughnessTexture;
}
public void setMetallicRoughnessTexture(TextureAsset metallicRoughnessTexture) {
this.metallicRoughnessTexture = metallicRoughnessTexture;
if (metallicRoughnessTexture != null) {
this.metallicRoughnessTextureID = metallicRoughnessTexture.getID();
} else {
this.metallicRoughnessTextureID = null;
}
}
public TextureAsset getOcclusionTexture() {
return occlusionTexture;
}
public void setOcclusionTexture(TextureAsset occlusionTexture) {
this.occlusionTexture = occlusionTexture;
if (occlusionTexture != null) {
this.occlusionTextureID = occlusionTexture.getID();
} else {
this.occlusionTextureID = null;
}
}
public Color getDiffuseColor() {
return diffuseColor;
}
public int getCullFace() {
return cullFace;
}
public void setCullFace(int cullFace) {
this.cullFace = cullFace;
}
@Override
public void resolveDependencies(Map<String, Asset> assets) {
if (diffuseTextureID != null && assets.containsKey(diffuseTextureID)) {
diffuseTexture = (TextureAsset) assets.get(diffuseTextureID);
}
if (normalMapID != null && assets.containsKey(normalMapID)) {
normalMap = (TextureAsset) assets.get(normalMapID);
}
if (emissiveTextureID != null && assets.containsKey(emissiveTextureID)) {
emissiveTexture = (TextureAsset) assets.get(emissiveTextureID);
}
if (metallicRoughnessTextureID != null && assets.containsKey(metallicRoughnessTextureID)) {
metallicRoughnessTexture = (TextureAsset) assets.get(metallicRoughnessTextureID);
}
if (occlusionTextureID != null && assets.containsKey(occlusionTextureID)) {
occlusionTexture = (TextureAsset) assets.get(occlusionTextureID);
}
}
@Override
public void applyDependencies() {
// nothing to apply
}
@Override
public void dispose() {
// nothing to dispose
}
@Override
public boolean usesAsset(Asset assetToCheck) {
if (assetToCheck instanceof TextureAsset) {
if (fileMatch(diffuseTexture, assetToCheck)) return true;
if (fileMatch(normalMap, assetToCheck)) return true;
if (fileMatch(emissiveTexture, assetToCheck)) return true;
if (fileMatch(metallicRoughnessTexture, assetToCheck)) return true;
return fileMatch(occlusionTexture, assetToCheck);
}
return false;
}
private boolean fileMatch(Asset childAsset, Asset assetToCheck) {
return childAsset != null && childAsset.getFile().path().equals(assetToCheck.getFile().path());
}
public void duplicateMaterialAsset(MaterialAsset materialAsset) {
this.setRoughness(materialAsset.getRoughness());
this.setOpacity(materialAsset.getOpacity());
this.setMetallic(materialAsset.getMetallic());
this.setAlphaTest(materialAsset.getAlphaTest());
this.setNormalScale(materialAsset.getNormalScale());
this.setShadowBias(materialAsset.getShadowBias());
this.setCullFace(materialAsset.getCullFace());
this.diffuseTexCoord = materialAsset.diffuseTexCoord.deepCopy();
this.normalTexCoord = materialAsset.normalTexCoord.deepCopy();
this.emissiveTexCoord = materialAsset.emissiveTexCoord.deepCopy();
this.metallicRoughnessTexCoord = materialAsset.metallicRoughnessTexCoord.deepCopy();
this.occlusionTexCoord = materialAsset.occlusionTexCoord.deepCopy();
if (materialAsset.getDiffuseColor() != null) {
this.diffuseColor = materialAsset.getDiffuseColor().cpy();
}
if (materialAsset.getEmissiveColor() != null) {
this.emissiveColor = materialAsset.getEmissiveColor().cpy();
}
this.setDiffuseTexture(materialAsset.getDiffuseTexture());
this.setNormalMap(materialAsset.getNormalMap());
this.setMetallicRoughnessTexture(materialAsset.getMetallicRoughnessTexture());
this.setEmissiveTexture(materialAsset.getEmissiveTexture());
this.setOcclusionTexture(materialAsset.getOcclusionTexture());
}
}
| JamesTKhan/Mundus | commons/src/main/com/mbrlabs/mundus/commons/assets/MaterialAsset.java | 5,488 | // ids of dependent assets | line_comment | nl | /*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.commons.assets;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.IntAttribute;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.PropertiesUtils;
import com.mbrlabs.mundus.commons.assets.meta.Meta;
import net.mgsx.gltf.scene3d.attributes.PBRColorAttribute;
import net.mgsx.gltf.scene3d.attributes.PBRFloatAttribute;
import net.mgsx.gltf.scene3d.attributes.PBRTextureAttribute;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;
/**
* @author Marcus Brummer
* @version 09-10-2016
*/
public class MaterialAsset extends Asset {
private static final ObjectMap<String, String> MAP = new ObjectMap<>();
public static final String EXTENSION = ".mat";
// property keys
public static final String PROP_DIFFUSE_COLOR = "diffuse.color";
public static final String PROP_DIFFUSE_TEXTURE = "diffuse.texture";
public static final String PROP_MAP_NORMAL = "map.normal";
public static final String PROP_MAP_EMISSIVE_COLOR = "emissive.color";
public static final String PROP_MAP_EMISSIVE_TEXTURE = "emissive.texture";
public static final String PROP_METAL_ROUGH_TEXTURE = "metallicRoughTexture";
public static final String PROP_OCCLUSION_TEXTURE = "occlusionTexture";
public static final String PROP_ROUGHNESS = "roughness";
public static final String PROP_OPACITY = "opacity";
public static final String PROP_METALLIC = "metallic";
public static final String PROP_ALPHA_TEST = "alphaTest";
public static final String PROP_NORMAL_SCALE = "normalScale";
public static final String PROP_SHADOW_BIAS = "shadowBias";
public static final String PROP_CULL_FACE = "cullFace";
// ids of<SUF>
private String diffuseTextureID;
private String normalMapID;
private String emissiveTextureID;
private String metallicRoughnessTextureID;
private String occlusionTextureID;
// Possible values are GL_FRONT_AND_BACK, GL_BACK, GL_FRONT, or -1 to inherit default
private int cullFace = -1;
private Color diffuseColor = Color.WHITE.cpy();
private Color emissiveColor = Color.BLACK.cpy();
private TextureAsset diffuseTexture;
private TextureAsset normalMap;
private TextureAsset emissiveTexture;
private TextureAsset metallicRoughnessTexture;
private TextureAsset occlusionTexture;
public TexCoordInfo diffuseTexCoord = new TexCoordInfo("diffuse");
public TexCoordInfo normalTexCoord = new TexCoordInfo("map");
public TexCoordInfo emissiveTexCoord = new TexCoordInfo("emissive");
public TexCoordInfo metallicRoughnessTexCoord = new TexCoordInfo("metallicRoughTexture");
public TexCoordInfo occlusionTexCoord = new TexCoordInfo("occlusionTexture");
private float roughness = 1f;
private float metallic = 0f;
private float opacity = 1f;
private float alphaTest = 0f;
private float normalScale = 1f;
private float shadowBias = 0.4f;
public MaterialAsset(Meta meta, FileHandle assetFile) {
super(meta, assetFile);
}
@Override
public void load() {
MAP.clear();
try {
Reader reader = file.reader();
PropertiesUtils.load(MAP, reader);
reader.close();
try {
String value = MAP.get(PROP_ROUGHNESS, null);
if (value != null) {
roughness = Float.parseFloat(value);
}
value = MAP.get(PROP_OPACITY, null);
if (value != null) {
opacity = Float.parseFloat(value);
}
value = MAP.get(PROP_METALLIC, null);
if (value != null) {
metallic = Float.parseFloat(value);
}
value = MAP.get(PROP_ALPHA_TEST, null);
if (value != null) {
alphaTest = Float.parseFloat(value);
}
value = MAP.get(PROP_NORMAL_SCALE, null);
if (value != null) {
normalScale = Float.parseFloat(value);
}
value = MAP.get(PROP_SHADOW_BIAS, null);
if (value != null) {
shadowBias = Float.parseFloat(value);
}
value = MAP.get(PROP_CULL_FACE, null);
if (value != null) {
cullFace = Integer.parseInt(value);
}
populateTexCoordInfo(diffuseTexCoord);
populateTexCoordInfo(normalTexCoord);
populateTexCoordInfo(emissiveTexCoord);
populateTexCoordInfo(metallicRoughnessTexCoord);
populateTexCoordInfo(occlusionTexCoord);
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
// diffuse color
String diffuseHex = MAP.get(PROP_DIFFUSE_COLOR);
if (diffuseHex != null) {
diffuseColor = Color.valueOf(diffuseHex);
}
// emissive color
String emissiveHex = MAP.get(PROP_MAP_EMISSIVE_COLOR);
if (emissiveHex != null) {
emissiveColor = Color.valueOf(emissiveHex);
}
// asset dependencies
diffuseTextureID = MAP.get(PROP_DIFFUSE_TEXTURE, null);
normalMapID = MAP.get(PROP_MAP_NORMAL, null);
metallicRoughnessTextureID = MAP.get(PROP_METAL_ROUGH_TEXTURE, null);
emissiveTextureID = MAP.get(PROP_MAP_EMISSIVE_TEXTURE, null);
occlusionTextureID = MAP.get(PROP_OCCLUSION_TEXTURE, null);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void load(AssetManager assetManager) {
// No async loading for materials right now
load();
}
private void populateTexCoordInfo(TexCoordInfo texCoordInfo) {
String value = MAP.get(texCoordInfo.PROP_UV, null);
if (value != null) {
texCoordInfo.uvIndex = Integer.parseInt(value);
}
value = MAP.get(texCoordInfo.PROP_OFFSET_U, null);
if (value != null) {
texCoordInfo.offsetU = Float.parseFloat(value);
}
value = MAP.get(texCoordInfo.PROP_OFFSET_V, null);
if (value != null) {
texCoordInfo.offsetV = Float.parseFloat(value);
}
value = MAP.get(texCoordInfo.PROP_SCALE_U, null);
if (value != null) {
texCoordInfo.scaleU = Float.parseFloat(value);
}
value = MAP.get(texCoordInfo.PROP_SCALE_V, null);
if (value != null) {
texCoordInfo.scaleV = Float.parseFloat(value);
}
value = MAP.get(texCoordInfo.PROP_ROTATION_UV, null);
if (value != null) {
texCoordInfo.rotationUV = Float.parseFloat(value);
}
}
/**
* Applies this material asset to the libGDX material.
*
* @param material the material to apply
* @return the material with asset attributes applied
*/
public Material applyToMaterial(Material material) {
return applyToMaterial(material, false);
}
/**
* Applies this material asset to the libGDX material.
*
* @param material the material to apply
* @param terrain whether this material is for a terrain
* @return the material with asset attributes applied
*/
public Material applyToMaterial(Material material, boolean terrain) {
if (diffuseColor != null) {
material.set(PBRColorAttribute.createBaseColorFactor(diffuseColor));
}
if (emissiveColor != null) {
material.set(PBRColorAttribute.createEmissive(emissiveColor));
}
if (!terrain) {
// Terrain materials use these for splat base
if (diffuseTexture != null) {
material.set(getTextureAttribute(PBRTextureAttribute.BaseColorTexture, diffuseTexture.getTexture(), diffuseTexCoord));
} else {
material.remove(PBRTextureAttribute.BaseColorTexture);
}
if (normalMap != null) {
material.set(getTextureAttribute(PBRTextureAttribute.NormalTexture, normalMap.getTexture(), normalTexCoord));
} else {
material.remove(PBRTextureAttribute.NormalTexture);
}
if (emissiveTexture != null) {
material.set(getTextureAttribute(PBRTextureAttribute.EmissiveTexture, emissiveTexture.getTexture(), emissiveTexCoord));
} else {
material.remove(PBRTextureAttribute.EmissiveTexture);
}
if (metallicRoughnessTexture != null) {
material.set(getTextureAttribute(PBRTextureAttribute.MetallicRoughnessTexture, metallicRoughnessTexture.getTexture(), metallicRoughnessTexCoord));
} else {
material.remove(PBRTextureAttribute.MetallicRoughnessTexture);
}
if (occlusionTexture != null) {
material.set(getTextureAttribute(PBRTextureAttribute.OcclusionTexture, occlusionTexture.getTexture(), occlusionTexCoord));
} else {
material.remove(PBRTextureAttribute.OcclusionTexture);
}
} else {
// Apply texCoords for terrains
PBRTextureAttribute diffuse = (PBRTextureAttribute) material.get(PBRTextureAttribute.BaseColorTexture);
if (diffuse != null) {
setTexCoordInfo(diffuse, diffuseTexCoord);
}
PBRTextureAttribute normal = (PBRTextureAttribute) material.get(PBRTextureAttribute.NormalTexture);
if (normal != null) {
setTexCoordInfo(normal, normalTexCoord);
}
}
material.set(PBRFloatAttribute.createRoughness(roughness));
material.set(PBRFloatAttribute.createMetallic(metallic));
material.set(PBRFloatAttribute.createNormalScale(normalScale));
material.set(new PBRFloatAttribute(PBRFloatAttribute.ShadowBias, shadowBias / 255f));
if (cullFace != -1) {
material.set(IntAttribute.createCullFace(cullFace));
} else {
material.remove(IntAttribute.CullFace);
}
if (opacity < 1f) {
material.set(new BlendingAttribute(true, opacity));
} else {
if (alphaTest == 0) {
material.remove(BlendingAttribute.Type);
}
}
if (alphaTest > 0) {
material.set(PBRFloatAttribute.createAlphaTest(alphaTest));
// We need blending attribute to trip the blendedFlag in shader
material.set(new BlendingAttribute(false, opacity));
} else {
material.remove(PBRFloatAttribute.AlphaTest);
if (opacity == 1f) {
material.remove(BlendingAttribute.Type);
}
}
return material;
}
/**
* Create a PBRTextureAttribute for the given type and populate it with
* the texture and TexCoordInfo
*/
private PBRTextureAttribute getTextureAttribute(long type, Texture texture, TexCoordInfo texCoord) {
PBRTextureAttribute attr = new PBRTextureAttribute(type, texture);
setTexCoordInfo(attr, texCoord);
return attr;
}
private void setTexCoordInfo(PBRTextureAttribute attr, TexCoordInfo texCoord) {
attr.uvIndex = texCoord.uvIndex;
attr.offsetU = texCoord.offsetU;
attr.offsetV = texCoord.offsetV;
attr.scaleU = texCoord.scaleU;
attr.scaleV = texCoord.scaleV;
attr.rotationUV = texCoord.rotationUV;
}
public float getRoughness() {
return roughness;
}
public void setRoughness(float roughness) {
this.roughness = roughness;
}
public float getMetallic() {
return metallic;
}
public void setMetallic(float metallic) {
this.metallic = metallic;
}
public float getOpacity() {
return opacity;
}
public void setOpacity(float opacity) {
this.opacity = opacity;
}
public float getAlphaTest() {
return alphaTest;
}
public void setAlphaTest(float alphaTest) {
this.alphaTest = alphaTest;
}
public float getNormalScale() {
return normalScale;
}
public void setNormalScale(float normalScale) {
this.normalScale = normalScale;
}
public float getShadowBias() {
return shadowBias;
}
public void setShadowBias(float shadowBias) {
this.shadowBias = shadowBias;
}
public TextureAsset getNormalMap() {
return normalMap;
}
public void setNormalMap(TextureAsset normalMap) {
this.normalMap = normalMap;
if (normalMap != null) {
this.normalMapID = normalMap.getID();
} else {
this.normalMapID = null;
}
}
public TextureAsset getDiffuseTexture() {
return diffuseTexture;
}
public void setDiffuseTexture(TextureAsset diffuseTexture) {
this.diffuseTexture = diffuseTexture;
if (diffuseTexture != null) {
this.diffuseTextureID = diffuseTexture.getID();
} else {
this.diffuseTextureID = null;
}
}
public TextureAsset getEmissiveTexture() {
return emissiveTexture;
}
public void setEmissiveTexture(TextureAsset emissiveTexture) {
this.emissiveTexture = emissiveTexture;
if (emissiveTexture != null) {
this.emissiveTextureID = emissiveTexture.getID();
} else {
this.emissiveTextureID = null;
}
}
public Color getEmissiveColor() {
return emissiveColor;
}
public TextureAsset getMetallicRoughnessTexture() {
return metallicRoughnessTexture;
}
public void setMetallicRoughnessTexture(TextureAsset metallicRoughnessTexture) {
this.metallicRoughnessTexture = metallicRoughnessTexture;
if (metallicRoughnessTexture != null) {
this.metallicRoughnessTextureID = metallicRoughnessTexture.getID();
} else {
this.metallicRoughnessTextureID = null;
}
}
public TextureAsset getOcclusionTexture() {
return occlusionTexture;
}
public void setOcclusionTexture(TextureAsset occlusionTexture) {
this.occlusionTexture = occlusionTexture;
if (occlusionTexture != null) {
this.occlusionTextureID = occlusionTexture.getID();
} else {
this.occlusionTextureID = null;
}
}
public Color getDiffuseColor() {
return diffuseColor;
}
public int getCullFace() {
return cullFace;
}
public void setCullFace(int cullFace) {
this.cullFace = cullFace;
}
@Override
public void resolveDependencies(Map<String, Asset> assets) {
if (diffuseTextureID != null && assets.containsKey(diffuseTextureID)) {
diffuseTexture = (TextureAsset) assets.get(diffuseTextureID);
}
if (normalMapID != null && assets.containsKey(normalMapID)) {
normalMap = (TextureAsset) assets.get(normalMapID);
}
if (emissiveTextureID != null && assets.containsKey(emissiveTextureID)) {
emissiveTexture = (TextureAsset) assets.get(emissiveTextureID);
}
if (metallicRoughnessTextureID != null && assets.containsKey(metallicRoughnessTextureID)) {
metallicRoughnessTexture = (TextureAsset) assets.get(metallicRoughnessTextureID);
}
if (occlusionTextureID != null && assets.containsKey(occlusionTextureID)) {
occlusionTexture = (TextureAsset) assets.get(occlusionTextureID);
}
}
@Override
public void applyDependencies() {
// nothing to apply
}
@Override
public void dispose() {
// nothing to dispose
}
@Override
public boolean usesAsset(Asset assetToCheck) {
if (assetToCheck instanceof TextureAsset) {
if (fileMatch(diffuseTexture, assetToCheck)) return true;
if (fileMatch(normalMap, assetToCheck)) return true;
if (fileMatch(emissiveTexture, assetToCheck)) return true;
if (fileMatch(metallicRoughnessTexture, assetToCheck)) return true;
return fileMatch(occlusionTexture, assetToCheck);
}
return false;
}
private boolean fileMatch(Asset childAsset, Asset assetToCheck) {
return childAsset != null && childAsset.getFile().path().equals(assetToCheck.getFile().path());
}
public void duplicateMaterialAsset(MaterialAsset materialAsset) {
this.setRoughness(materialAsset.getRoughness());
this.setOpacity(materialAsset.getOpacity());
this.setMetallic(materialAsset.getMetallic());
this.setAlphaTest(materialAsset.getAlphaTest());
this.setNormalScale(materialAsset.getNormalScale());
this.setShadowBias(materialAsset.getShadowBias());
this.setCullFace(materialAsset.getCullFace());
this.diffuseTexCoord = materialAsset.diffuseTexCoord.deepCopy();
this.normalTexCoord = materialAsset.normalTexCoord.deepCopy();
this.emissiveTexCoord = materialAsset.emissiveTexCoord.deepCopy();
this.metallicRoughnessTexCoord = materialAsset.metallicRoughnessTexCoord.deepCopy();
this.occlusionTexCoord = materialAsset.occlusionTexCoord.deepCopy();
if (materialAsset.getDiffuseColor() != null) {
this.diffuseColor = materialAsset.getDiffuseColor().cpy();
}
if (materialAsset.getEmissiveColor() != null) {
this.emissiveColor = materialAsset.getEmissiveColor().cpy();
}
this.setDiffuseTexture(materialAsset.getDiffuseTexture());
this.setNormalMap(materialAsset.getNormalMap());
this.setMetallicRoughnessTexture(materialAsset.getMetallicRoughnessTexture());
this.setEmissiveTexture(materialAsset.getEmissiveTexture());
this.setOcclusionTexture(materialAsset.getOcclusionTexture());
}
}
|
108464_13 | package IPSEN2.models.address;
/**
* Created by mdbaz on 21-09-2015.
*/
public class Address {
private int addressID;
private String street;
private String houseNumber; //Huisnummer is een String ivm huisnummers die letters erachter kunnen hebben
private String zipCode;
private String city;
private String country;
/**
* Instantiates a new Address.
*
* @param addressID the address id
*/
public Address(int addressID) {
this.addressID = addressID;
this.street = null;
this.houseNumber = null;
this.zipCode = null;
this.city = null;
this.country = null;
}
/**
* Instantiates a new Address.
*
* @param addressID the address id
* @param street the street
* @param houseNumber the house number
* @param zipCode the zip code
* @param city the city
* @param country the country
*/
public Address(int addressID, String street, String houseNumber, String zipCode, String city, String country) {
this.addressID = addressID;
this.street = street;
this.houseNumber = houseNumber;
this.zipCode = zipCode;
this.city = city;
this.country = country;
}
/**
* Check if only id boolean.
*
* @return the boolean
*/
public boolean checkIfOnlyID() {
return street == null && houseNumber == null && zipCode == null && city == null && country == null;
}
/**
* Gets street.
*
* @return the street
*/
//Getters
public String getStreet() {
return street;
}
/**
* Gets house number.
*
* @return the house number
*/
public String getHouseNumber() {
return houseNumber;
}
/**
* Gets zip code.
*
* @return the zip code
*/
public String getZipCode() {
return zipCode;
}
/**
* Gets city.
*
* @return the city
*/
public String getCity() {
return city;
}
/**
* Gets address id.
*
* @return the address id
*/
public int getAddressID() {
return addressID;
}
/**
* Gets country.
*
* @return the country
*/
public String getCountry() {
return country;
}
/**
* Sets street.
*
* @param street the street
*/
//Setters
public void setStreet(String street) {
this.street = street;
}
/**
* Sets house number.
*
* @param houseNumber the house number
*/
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
/**
* Sets zip code.
*
* @param zipCode the zip code
*/
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
/**
* Sets city.
*
* @param city the city
*/
public void setCity(String city) {
this.city = city;
}
/**
* Sets address id.
*
* @param addressID the address id
*/
public void setAddressID(int addressID) {
this.addressID = addressID;
}
/**
* Sets country.
*
* @param country the country
*/
public void setCountry(String country) {
this.country = country;
}
}
| JamieKalloe/Lions-Club-Wijnfestijn | src/IPSEN2/models/address/Address.java | 966 | /**
* Sets zip code.
*
* @param zipCode the zip code
*/ | block_comment | nl | package IPSEN2.models.address;
/**
* Created by mdbaz on 21-09-2015.
*/
public class Address {
private int addressID;
private String street;
private String houseNumber; //Huisnummer is een String ivm huisnummers die letters erachter kunnen hebben
private String zipCode;
private String city;
private String country;
/**
* Instantiates a new Address.
*
* @param addressID the address id
*/
public Address(int addressID) {
this.addressID = addressID;
this.street = null;
this.houseNumber = null;
this.zipCode = null;
this.city = null;
this.country = null;
}
/**
* Instantiates a new Address.
*
* @param addressID the address id
* @param street the street
* @param houseNumber the house number
* @param zipCode the zip code
* @param city the city
* @param country the country
*/
public Address(int addressID, String street, String houseNumber, String zipCode, String city, String country) {
this.addressID = addressID;
this.street = street;
this.houseNumber = houseNumber;
this.zipCode = zipCode;
this.city = city;
this.country = country;
}
/**
* Check if only id boolean.
*
* @return the boolean
*/
public boolean checkIfOnlyID() {
return street == null && houseNumber == null && zipCode == null && city == null && country == null;
}
/**
* Gets street.
*
* @return the street
*/
//Getters
public String getStreet() {
return street;
}
/**
* Gets house number.
*
* @return the house number
*/
public String getHouseNumber() {
return houseNumber;
}
/**
* Gets zip code.
*
* @return the zip code
*/
public String getZipCode() {
return zipCode;
}
/**
* Gets city.
*
* @return the city
*/
public String getCity() {
return city;
}
/**
* Gets address id.
*
* @return the address id
*/
public int getAddressID() {
return addressID;
}
/**
* Gets country.
*
* @return the country
*/
public String getCountry() {
return country;
}
/**
* Sets street.
*
* @param street the street
*/
//Setters
public void setStreet(String street) {
this.street = street;
}
/**
* Sets house number.
*
* @param houseNumber the house number
*/
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
/**
* Sets zip code.<SUF>*/
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
/**
* Sets city.
*
* @param city the city
*/
public void setCity(String city) {
this.city = city;
}
/**
* Sets address id.
*
* @param addressID the address id
*/
public void setAddressID(int addressID) {
this.addressID = addressID;
}
/**
* Sets country.
*
* @param country the country
*/
public void setCountry(String country) {
this.country = country;
}
}
|