I call two methods void at the same time, the problem is that the second method I call is not executed, only the first call works fine. The only difference is the parameters
Which calls the method :
private void calculateDistributorRabat(InvoiceHeader invoice, Distributor distributor) {
insertRabatToWallet(distributor.getUser(), invoice.getPurchaseOrder());
insertRabatToWallet(distributor.getBranchOffice().getUser(), invoice.getPurchaseOrder());
}
This is the void method that is being called :
private void insertRabatToWallet(User user, PurchaseOrder purchaseOrder) {
Map<ProductType, Rabat> rabatMap = rabatService.getRabatMapPayPo(user.getUserType());
Wallet wallet = walletDao.findByUser(user);
if (wallet == null) {
wallet = new Wallet();
wallet.setUser(user);
}
for (PurchaseOrderDetail pd : purchaseOrder.getPurchaseOrderDetails()) {
Rabat rabat = rabatMap.get(pd.getProductType());
if (rabat == null) {
continue;
}
BigDecimal rabatAmount = rabat.getNominal().multiply(new BigDecimal(pd.getProductQty()));
wallet.setTotalDebet(wallet.getTotalDebet().add(rabatAmount));
wallet.setCurrentAmount(wallet.getCurrentAmount().add(rabatAmount));
WalletTransaction wt = new WalletTransaction();
wt.setAmount(rabatAmount);
wt.setDescription("Rabat " + user.getUserType() + " [" + purchaseOrder.getPurchaseOrderNumber()
+ "] (" + pd.getProductType().getCode()
+ "): Rp." + rabat.getNominal().setScale(0).toString()
+ " x " + pd.getProductQty());
wallet.addWalletTransaction(wt);
walletDao.save(wallet);
}
}
Related
Alright, so I'm trying to check if a Boolean is True or False and I've initialized it with "true", and then I change it to "false" later. That wouldn't cause problems, right? Well, there is one problem: The code to check that is being run within a thread. Currently this is how I'm doing this:
Boolean eye = true;
Thread outputSomeInfo = new Thread(new Runnable(){
public void run(){
String gameFrameTitle = gameFrame.getTitle();
String gameFrameSize = String.valueOf(gameFrame.getSize());
String doorSize = String.valueOf(doorImage.getSize());
String doorLocation = String.valueOf(doorImage.getLocation());
String gameFrameIcon = String.valueOf(iconURL);
String actualGameFrameIcon = gameFrameIcon.substring(gameFrameIcon.indexOf("/")+1);
actualGameFrameIcon.trim();
Boolean threadEye = true;
System.out.println("JFrame Title: " + gameFrameTitle);
System.out.println("JFrame Icon: " + actualGameFrameIcon);
System.out.println("JFrame Size: " + gameFrameSize);
System.out.println("Door Size: " + doorSize);
System.out.println("Door Location: " + doorLocation);
while (true) {
if (!gameFrameTitle.equalsIgnoreCase(gameFrame.getTitle())) {
gameFrameTitle = gameFrame.getTitle();
System.out.println("JFrame Title: " + gameFrameTitle);
}
if (threadEye && !eye) {
threadEye = false;
String gameFrameIcon2 = String.valueOf(doorLoc);
String actualGameFrameIcon2 = gameFrameIcon2.substring(gameFrameIcon2.indexOf("/")+1);
actualGameFrameIcon2.trim();
actualGameFrameIcon = actualGameFrameIcon2;
gameFrameIcon = gameFrameIcon2;
System.out.println("JFrame Icon: " + actualGameFrameIcon);
}
if (!gameFrameSize.equalsIgnoreCase(String.valueOf(gameFrame.getSize()))) {
gameFrameSize = String.valueOf(gameFrame.getSize());
System.out.println("JFrame Size: " + gameFrameSize);
}
if (!doorSize.equalsIgnoreCase(String.valueOf(doorImage.getSize()))) {
doorSize = String.valueOf(doorImage.getSize());
System.out.println("Door Size: " + doorSize);
}
if (!doorLocation.equalsIgnoreCase(String.valueOf(doorImage.getLocation()))) {
doorLocation = String.valueOf(doorImage.getLocation());
System.out.println("Door Location: " + doorLocation);
}
// System.out.println("JFrame Size: " + gameFrame.getSize() + "\nJFrame Title: " + gameFrame.getTitle() + "\nDoor Location: " + doorImage.getLocation() + "\nDoor Size: " + doorImage.getSize());
}
}
});
outputSomeInfo.start();
(Anything used within this thread that isn't also defined in the thread was defined before defining the thread. "eye" is changed after defining the thread, but that shouldn't matter since the thread runs forever.)
What I expect:
A program that tells me the path to the program's current icon when it changes (icon changes only once and there are only 2 possible icons, always being changed in the same order so it shouldn't matter that it's hardcoded?)
What I get:
Main.java:52: error: local variables referenced from an inner class must be final or effectively final
if (threadEye && !eye) {
^
1 error
error: compilation failed
From what I can tell, what I need is a way to use non-final variables within threads?
I got it! Fixed code:
final AtomicBoolean eye = new AtomicBoolean();
eye.set(true);
Thread outputSomeInfo = new Thread(new Runnable(){
public void run(){
String gameFrameTitle = gameFrame.getTitle();
String gameFrameSize = String.valueOf(gameFrame.getSize());
String doorSize = String.valueOf(doorImage.getSize());
String doorLocation = String.valueOf(doorImage.getLocation());
String gameFrameIcon = String.valueOf(doorLoc);
String actualGameFrameIcon = gameFrameIcon.substring(gameFrameIcon.indexOf("/")+1);
actualGameFrameIcon.trim();
Boolean threadEye = true;
System.out.println("JFrame Title: " + gameFrameTitle);
System.out.println("JFrame Icon: " + actualGameFrameIcon);
System.out.println("JFrame Size: " + gameFrameSize);
System.out.println("Door Size: " + doorSize);
System.out.println("Door Location: " + doorLocation);
while (true) {
String eyeToString = String.valueOf(eye);
if (!gameFrameTitle.equalsIgnoreCase(gameFrame.getTitle())) {
gameFrameTitle = gameFrame.getTitle();
System.out.println("JFrame Title: " + gameFrameTitle);
}
if (String.valueOf(eye.get()).equalsIgnoreCase("false")) {
if (threadEye) {
threadEye = false;
String gameFrameIcon2 = String.valueOf(iconURL);
String actualGameFrameIcon2 = gameFrameIcon2.substring(gameFrameIcon2.indexOf("/") + 1);
actualGameFrameIcon2.trim();
actualGameFrameIcon = actualGameFrameIcon2;
gameFrameIcon = gameFrameIcon2;
System.out.println("JFrame Icon: " + actualGameFrameIcon2);
}
}
if (!gameFrameSize.equalsIgnoreCase(String.valueOf(gameFrame.getSize()))) {
gameFrameSize = String.valueOf(gameFrame.getSize());
System.out.println("JFrame Size: " + gameFrameSize);
}
if (!doorSize.equalsIgnoreCase(String.valueOf(doorImage.getSize()))) {
doorSize = String.valueOf(doorImage.getSize());
System.out.println("Door Size: " + doorSize);
}
if (!doorLocation.equalsIgnoreCase(String.valueOf(doorImage.getLocation()))) {
doorLocation = String.valueOf(doorImage.getLocation());
System.out.println("Door Location: " + doorLocation);
}
// System.out.println("JFrame Size: " + gameFrame.getSize() + "\nJFrame Title: " + gameFrame.getTitle() + "\nDoor Location: " + doorImage.getLocation() + "\nDoor Size: " + doorImage.getSize());
}
}
});
outputSomeInfo.start();
You can use below code to initialize array and use eye[0] when you want value of the variable.
final Boolean[] eye = {true};
OR use eye.get() using below code
AtomicReference<Boolean> eye = new AtomicReference<>(true);
Can not determine where the main cause of this exception. I did everything according to Spring in Action book. What is wrong with these lines of code?
private static final String PREFIX_SELECT_SQL = "SELECT ID, " +
"CATEGORY_ID, " +
"STATE_ID, " +
"TASK_DESCRIPTION, " +
"CREATION_TASK_DATE, " +
"START_TASK_DATE, " +
"END_TASK_DATE, " +
"USER_ID FROM tasks ";
public Task findOneTask(int taskId) {
Task task = jdbc.queryForObject(PREFIX_SELECT_SQL
+ "WHERE ID = " + taskId + ";", this::mapRowToTaskTable, taskId);
return task;
}
private Task mapRowToTaskTable(ResultSet resultSet, int i) throws SQLException {
Task task = new Task();
task.setTaskId(resultSet.getInt("ID"));
task.setUserId(resultSet.getInt("USER_ID"));
task.setDescription(resultSet.getString("TASK_DESCRIPTION"));
task.setCategoryId(resultSet.getInt("CATEGORY_ID"));
task.setStateId(resultSet.getInt("STATE_ID"));
task.setStartDate(resultSet.getTimestamp("START_TASK_DATE").toLocalDateTime());
if (resultSet.getTimestamp("END_TASK_DATE") != null) {
task.setEndDate(resultSet.getTimestamp("END_TASK_DATE").toLocalDateTime());
} else {
task.setEndDate(null);
}
task.setCreateDate(resultSet.getTimestamp("CREATION_TASK_DATE").toLocalDateTime());
return task;
}
You are already passing to jdbc.queryForObject query with concrete value, but not a parameter.
Select ...
from ...
where id = 123
Change findOneTask to:
public Task findOneTask(int taskId) {
Task task = jdbc.queryForObject(PREFIX_SELECT_SQL
+ "WHERE ID = ?;", this::mapRowToTaskTable, taskId);
return task;
}
I have a bean class that successfully retrieves a string value from another class.= (It prints it just fine within the bean class)
When I try and call that class/string it returns as null.
Here is the relevant code:
public class cityModel implements Serializable {
private String fajr;
public void setFajr(String fajr) {
this.fajr= fajr;
}
public String getFajr() {
return fajr;
}
}
public void mutePrayerTime(View view) {
cityModel cityObj= new cityModel();
String fajr=cityObj.getFajr();
Log.d("LOGCAT", "" + cityObj.getFajr());
//StringBuilder newFajr = new StringBuilder(fajr);
//newFajr.delete(2,5);
//Log.d("newFajr", String.valueOf(newFajr));
// Intent alarm = new Intent(AlarmClock.ACTION_SET_ALARM);
//alarm.putExtra(AlarmClock.EXTRA_HOUR, fajr );
}
the Log.d tag LOGCAT returns as null
edit:
Code that the bean class retrieves the string from:
protected void outputTimings(JSONArray jsonArray) {
String[] prayers = {"fajr", "shurooq", "dhuhr", "asr", "maghrib", "isha"};
cityModel cityObj;
try {
cityObj= new cityModel();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject cityObject =
jsonArray.getJSONObject(i);
result = result + "fajr" + " : "
+ cityObject.getString("fajr") + "\n" + result + "shurooq" + " : "
+ cityObject.getString("shurooq") + "\n" + result + "dhuhr" + " : "
+ cityObject.getString("dhuhr") + "\n" + result + "asr" + " : "
+ cityObject.getString("asr") + "\n" + result + "maghrib" + " : "
+ cityObject.getString("maghrib") + "\n" + result + "isha" + " : "
+ cityObject.getString("isha") + "\n";
cityObj.setFajr(""+cityObject.getString("fajr"));
}
Have a look in this method:
public void mutePrayerTime(View view) {
cityModel cityObj= new cityModel();
String fajr=cityObj.getFajr();
Log.d("LOGCAT", "" + cityObj.getFajr());
//StringBuilder newFajr = new StringBuilder(fajr);
//newFajr.delete(2,5);
//Log.d("newFajr", String.valueOf(newFajr));
// Intent alarm = new Intent(AlarmClock.ACTION_SET_ALARM);
//alarm.putExtra(AlarmClock.EXTRA_HOUR, fajr );
}
You're just creating cityObj like this cityModel cityObj= new cityModel(); at that point all its properties are null that's why you're seeing null in your log. You should pass the cityObj from your outputTimings method to the mutePrayerTime method:
public void mutePrayerTime(View view,cityModel cityObj) {
Log.d("LOGCAT", "" + cityObj.getFajr());
//StringBuilder newFajr = new StringBuilder(fajr);
//newFajr.delete(2,5);
//Log.d("newFajr", String.valueOf(newFajr));
// Intent alarm = new Intent(AlarmClock.ACTION_SET_ALARM);
//alarm.putExtra(AlarmClock.EXTRA_HOUR, fajr );
}
and then in outputTimings:
cityObj.setFajr(""+cityObject.getString("fajr"));
someObj.mutePrayerTime(view, cityObj);
Is it possible to store all test cases which have failed in a hashmap, and then call all values stored in the map at the end of a class?
Variable:
private HashMap<String, Integer> serverStatusMap = new HashMap<String, Integer>();
After Method Code:
#AfterMethod
public void trackServerStatus(ITestResult testResult) {
if (testResult.getStatus() == ITestResult.FAILURE) {
try {
String testName = this.getClass().getSimpleName().toString();
int serverStatus = ServerStatus.getResponseCode(basePage.getCurrentURL());
int i = 0;
while(i < serverStatusMap.size()) {
serverStatusMap.put(testName, serverStatus);
i++;
}
//serverStatusMap.put(testName, serverStatus);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Calling the stored values in the map After class:
#AfterClass
public void sendEmailBasedOnFailure(ITestContext context) throws WebDriverException, Exception {
String tempTime = new SimpleDateFormat("hh.mm.ss").format(new Date());
if(context.getFailedTests().size() > 0) {
SendEmailFile.sendEmailReport(
"TIME: " + tempTime + " | " + this.getClass().getPackage().toString(),
"TIME: " + tempTime + " | " + this.getClass().getPackage().toString() + " | " + "CLASS NAME: "
+ this.getClass().getSimpleName().toString() + "\n\n" +
"TOTAL NUMBER FAILED TESTS: " + context.getFailedTests().size() + "\n\n" +
"FAILED TEST CASES: " + context.getFailedTests().getAllMethods().toString() + "\n\n" +
serverStatusMap.toString());
}
Look at the last line of code: 'serverStatusMap.toString()'
Current Output of the Map:
{}
I do not understand what you are trying to do.
Do you want to send an email with failed tests?
Why not using the appropriate features like Listener or Reporter?
Have a look on the documentation about logging.
You have initialized variable "serverStatusMap". From below code
int i =0;
while(i < serverStatusMap.size()) {
serverStatusMap.put(testName, serverStatus);
i++;
}
I can see that i=0 and also serverStatusMap.size()=0. So it will never enter in while loop. so Finally when you print map there is nothing inside map. You need to change your while condition.
I am making a Minecraft Server Plugin using the Bukkit Api.
Basically when my server stops, I use the onDisable() to store two hashmap contents to a config, then when the server starts, I use the onEnable() to take that info from the config and put it back in the HashMaps. That doesn't work.
Here are my methods: the saveBans is in the onDisable() and the loadBans is in the onEnable():
public class utilReloadSave {
static settingsmanager settings = settingsmanager.getInstance();
public static void saveBans() {
ArrayList<String> bans = new ArrayList<String>();
for (UUID play : Cooldown.cooldownPlayers.keySet()) {
settings.getConfig().set("bans." + play, Cooldown.getTime(play, "TempBan"));
bans.add(play.toString());
}
settings.getConfig().set("banlist", bans);
settings.saveConfig();
}
public static void loadBans() {
FileConfiguration config = settings.getConfig();
ArrayList<String> bans = (ArrayList<String>) config.getStringList("banlist");
for (String uuid : bans) {
Cooldown.cooldownPlayers.put(UUID.fromString(uuid), new utilCooldown(UUID.fromString(uuid), config.getInt("bans." + uuid), System.currentTimeMillis()));
}
config.set("bans", null);
config.set("banlist", null);
settings.saveConfig();
}
}
That seems to work. The problem is I use a onPlayerJoin Event:
#EventHandler
public void onLogin(PlayerLoginEvent e) {
Player play = e.getPlayer();
if (play.isBanned()) {
if (Cooldown.isCooling(play.getUniqueId(), "TempBan")) {
File player = new File(basic.plugin.getDataFolder() + "/players/" + play.getUniqueId() + ".yml");
FileConfiguration config = YamlConfiguration.loadConfiguration(player);
List<String> list = config.getStringList("banned.temp.reason");
String reason = list.get(list.size()-1);
if (Cooldown.getTime(play.getUniqueId(), "TempBan") < 60000L) {
e.disallow(PlayerLoginEvent.Result.KICK_BANNED, ChatColor.YELLOW + "" + ChatColor.BOLD + "You are still banned for " + Cooldown.getRemaining(play.getUniqueId(), "TempBan") + " seconds." + ChatColor.RED + " Reason: " + reason);
return;}
if (Cooldown.getTime(play.getUniqueId(), "TempBan") < 3600000L) {
e.disallow(PlayerLoginEvent.Result.KICK_BANNED, ChatColor.YELLOW + "" + ChatColor.BOLD + "You are still banned for " + Cooldown.getRemaining(play.getUniqueId(), "TempBan") + " minutes." + ChatColor.RED + " Reason: " + reason);
return;}
if (Cooldown.getTime(play.getUniqueId(), "TempBan") < 86400000L) {
e.disallow(PlayerLoginEvent.Result.KICK_BANNED, ChatColor.YELLOW + "" + ChatColor.BOLD + "You are still banned for " + Cooldown.getRemaining(play.getUniqueId(), "TempBan") + " hours." + ChatColor.RED + " Reason: " + reason);
return;}
e.disallow(PlayerLoginEvent.Result.KICK_BANNED, ChatColor.YELLOW + "" + ChatColor.BOLD + "You are still banned for " + Cooldown.getRemaining(play.getUniqueId(), "TempBan") + " days." + ChatColor.RED + " Reason: " + reason);
return;
} else {
File player = new File(basic.plugin.getDataFolder() + "/players/" + play.getUniqueId() + ".yml");
FileConfiguration config = YamlConfiguration.loadConfiguration(player);
List<String> list = config.getStringList("banned.perm.reason");
String reason = list.get(list.size()-1);
e.disallow(PlayerLoginEvent.Result.KICK_BANNED, ChatColor.YELLOW + "" + ChatColor.BOLD + "You are permanentely banned! " + ChatColor.RED + "" + ChatColor.BOLD + "Reason: " + reason);
return;
}
}
}
which will check if there is something in the Hashmap but there isn't since it returns the else statement.
public static HashMap<UUID, utilCooldown> cooldownPlayers = new HashMap<UUID, utilCooldown>();
public static void add(UUID player, String ability, long seconds, long systime) {
if(!cooldownPlayers.containsKey(player)) cooldownPlayers.put(player, new utilCooldown(player));
if(isCooling(player, ability)) return;
cooldownPlayers.get(player);
utilCooldown.cooldownMap.put(ability, new utilCooldown(player, seconds * 1000, System.currentTimeMillis()));
}
public static boolean isCooling(UUID player, String ability) {
if(!cooldownPlayers.containsKey(player)) return false;
if(!utilCooldown.cooldownMap.containsKey(ability)) return false;
return true;
}
public static double getRemaining(UUID player, String ability) {
if(!cooldownPlayers.containsKey(player)) return 0.0;
if(!utilCooldown.cooldownMap.containsKey(ability)) return 0.0;
return utilTime.convert((utilCooldown.cooldownMap.get(ability).seconds + utilCooldown.cooldownMap.get(ability).systime) - System.currentTimeMillis(), TimeUnit.BEST, 1);
}
public static void removeCooldown(UUID key, String ability) {
if(!cooldownPlayers.containsKey(key)) {
return;
}
if(!utilCooldown.cooldownMap.containsKey(ability)) {
return;
}
utilCooldown.cooldownMap.remove(ability);
}
#SuppressWarnings("deprecation")
public static void handleCooldowns() {
if(cooldownPlayers.isEmpty()) {
return;
}
for(Iterator<UUID> it = cooldownPlayers.keySet().iterator(); it.hasNext();) {
UUID key = it.next();
cooldownPlayers.get(key);
for(Iterator<String> iter = utilCooldown.cooldownMap.keySet().iterator(); iter.hasNext();) {
String name = iter.next();
if(getRemaining(key, name) <= 0.0) {
OfflinePlayer p = Bukkit.getOfflinePlayer(key);
p.setBanned(false);
removeCooldown(key, name);
}
}
}
}
public static long getTime(UUID player, String ability) {
return (utilCooldown.cooldownMap.get(ability).seconds + utilCooldown.cooldownMap.get(ability).systime) - System.currentTimeMillis();
}
I assume:
You have tested that the ArrayList in loadBans is not empty - before blaming the HashMap.
You have also checked whether or not these methods loadBans and saveBans are being called.
You have manually opened the config files to see what's in there.
You can use Debug-mode or extensively use System.out.println(...) for debugging. Whenever something is null or empty, while it shouldn't be - try to go back and see where it wasn't null or empty.