I am trying to make custom death messages when you get killed in certain ways. I want separate messages for when you get blown up by TNT or get blown up by a creeper. I tried debugging it and spawning a creeper and TNT and in the console it outputs the e.getEntity().getKiller() as null in the console. If I do e.getEntity().getKiller().getName(), it gives out an error.
here is my code for the debugger:
package me.Pale_Gray.BetterDeathMessages.deathmessages;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.PlayerDeathEvent;
public class DeathByTnt implements Listener{
#EventHandler
public void onPlayerDeath(PlayerDeathEvent e) {
String msg = e.getDeathMessage();
System.out.println((Player) e.getEntity().getKiller());
if (e.getEntity().getLastDamageCause().getCause().equals(DamageCause.ENTITY_EXPLOSION)) {
msg = ChatColor.translateAlternateColorCodes('&', "&cIt went off with a BANG!");
e.setDeathMessage(msg);
}
}
}
I am only asking to focus in on the System.out.println((Player) e.getEntity().getKiller()); because I know the if statement isn't selective on entities.
There are #Nullable annotations on methods and javadocs so you know what method can be null.
PlayerDeathEvent#getEntity#getKiller method returns Player so you don't need to cast Player object to it.
Otherwise, this method only returns Player, if it killed by another living Player.
Entity#getLastDamageCause method can return null
getCause() method returns an enum so you don't need to use equals, you only need == for comparing enum values.
You could check some other DamageCause fields, including ENTITY_EXPLOSION. Sometimes when creeper explodes the damage cause can be BLOCK_EXPLOSION, maybe because too far away.
Related
My application has a flow that in the end of it the method System.exit(int) is being called.
I'm trying to test this flow by running a test using TestNG.
However, when running the test I'm getting this weird message although the test was completed:
Just for finding the root cause, I removed the System.exit(int) from the real flow and the test passed as expected, so the problem here is the System.exit(int) method.
In order to solve this issue I've tried to mock the problematic method but couldn't find the right way to do it. Here is what I did
I added java.lang.System.class under #PrepareForTest in the tests class.
added PowerMockito.mockStatic(java.lang.System.class) in the test
I've tried to mock the method in two ways:
a.
PowerMockito.replace(PowerMockito.method(System.class, "exit", int.class))
.with((proxy, method, args) -> null);
When running this way looks like the mock is not working, because I'm getting the same message at the end of the test which I also got when not applying any mocks on System.exit(int)
b.
PowerMockito.doNothing().when(System.class, "exit", Mockito.any());
In this way I'm getting this exception at the beginning of the test:
org.powermock.reflect.exceptions.MethodNotFoundException: No method found with name 'exit' with parameter types: [ <none> ] in class java.lang.System.
I already mocked some methods in this ways, not sure why with System.exit(int) it is not working.
Any ideas?
Thanks
Interesting question, I didn't know either, but apparently this is possible without the use of Powermock, through the use of SecurityManagers. Quoting from the original post:
Today I was writing test for one of our command line tools, and I had
this problem where the method dumping everything, which I really
needed to be called since that’s the outcome I was checking, also
called System.exit(). I had to find a way to test this anyway. I
thought about using PowerMock and mocking system but that would have
been complicated because I would have to find the exact class calling
the System.exit(). So here is another solution to avoid the
System.exit to exit (yes that’s possible I didn’t know about that
either).
The secrets lays in the SecurityManager mechanism of Java, this class
not only allows you to check permissions, but also to check exit
event. Therefore you can throw an exception if you want to stop the
exit
Below is a full sample I tested in IJ. Please note the sample is supposed to fail on purpose with:
java.lang.AssertionError:
Expected: is <10>
but: was <5>
Expected :is <10>
Actual :<5>
package com.example;
import org.junit.Test;
import java.security.Permission;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
public class SystemExitTest {
#Test
public void shouldExitWithSpecificCode() {
//save the initial security manager (probably null)
SecurityManager initialSecurityManger = System.getSecurityManager();
try {
// set security manager
System.setSecurityManager(new NoExitSecurityManager());
// execute code under test
new MyClass().exit(5);
// ensure this point is not reached by any chance
fail("Should've thrown ExitException");
} catch (ExitException e) {
// validate exit code
assertThat(e.status, is(10)); // <== this fails on purpose
} finally {
// restore initial security manager (otherwise a new ExitException will be thrown when the JVM will actually exit)
System.setSecurityManager(initialSecurityManger);
}
}
// class under test
public static class MyClass {
public void exit(int code) {
System.exit(code);
}
}
// exception to be thrown by security manager when System.exit is called
public static class ExitException extends SecurityException {
public final int status;
public ExitException(int status) {
this.status = status;
}
}
// custom security manager
public static class NoExitSecurityManager extends SecurityManager {
#Override
public void checkPermission(Permission perm) {
}
#Override
public void checkPermission(Permission perm, Object context) {
}
#Override
public void checkExit(int status) {
super.checkExit(status);
throw new ExitException(status);
}
}
}
I'm new to Play Framework. I'm working on a basic project and i'm working now on the authentication function. I want to redirect the unauthorized user to the /login route.
I discover the Global.java class that allows me to control actions accross my project, in particular with onRequest function. I'm planning of using it to do the redirection.
I search several solutions on the web but I couldn't find a working one.
My class:
import play.*;
import play.mvc.Action;
import play.mvc.*;
import play.mvc.Http.*;
import play.mvc.Result.*;
import play.libs.F.*;
import static play.mvc.Results.*;
import play.mvc.Http.Request;
import java.lang.reflect.Method;
public class Global extends GlobalSettings {
#Override
public Action onRequest(Request request, Method actionMethod) {
//Check if the user is connected
if (request.cookie("PLAY_SESSION") == null && !request.path().startsWith("/login")) {
System.out.println("UNAUTHORIZED");
return new Action.Simple() {
#Override
public Result call(Context ctx) throws Throwable {
return redirect(controllers.routes.Application.index());
}
};
}
return super.onRequest(request, actionMethod);
}
}
I found this and i don't understand why Play! doesn't want to compile :
error: <anonymous Global$1> is not abstract and does not override abstract method call(Context) in Action
error: method does not override or implement a method from a supertype
I'm not casual with Play and i don't really understand the problem. Can someone help me please ? Thanks !
I haven't used Play Framework for a while now but I think that the problem is that in 2.2 they made Action to return Promise and not just Result. Hence there is your problem.
Check your version of Action.Simple.call() that it matches
Result call(Context ctx) throws Throwable
See the difference between
https://www.playframework.com/documentation/2.2.x/api/java/index.html
https://www.playframework.com/documentation/2.1.x/api/java/index.html
(look at the return type of the call method)
EDIT
I am not sure whether this is the best approach but it should work.
#Override
public F.Promise<Result> call(Context ctx) throws Throwable {
return F.Promise.pure(redirect(controllers.routes.Application.index()));
}
F.Promise.pure() can be used to convert a Result (or anything that implements it, like Results.Status for example) to a Promise.
Example, where ok() returns play.mvc.Results.Status:
F.Promise.pure(ok("[No Preview Available]"));
According to https://cloud.google.com/appengine/docs/java/tools/localunittesting#Writing_HRD_Datastore_Tests, "If your app uses the High Replication Datastore (HRD), you may want to write tests that verify your application's behavior in the face of eventual consistency. LocalDatastoreServiceTestConfig exposes options that make this easy." You're supposed to set setDefaultHighRepJobPolicyUnappliedJobPercentage(100) and then, "By setting the unapplied job percentage to 100, we are instructing the local datastore to operate with the maximum amount of eventual consistency. Maximum eventual consistency means writes will commit but always fail to apply, so global (non-ancestor) queries will consistently fail to see changes."
However, I don't think setDefaultHighRepJobPolicyUnappliedJobPercentage(100) works.
If it did, then my test case below, testEventualConsistency() should pass but it it fails on the second assertion. On the first assertion, I read back an object I've saved using an Objectify ancestor() query. It works as documented because the object is retrieved. However, the second assertion fails. In that assertion I've also read back the object I've saved but I haven't used an Objectify ancestor() query so it shouldn't retrieve anything because I've specified that no jobs should complete (i.e. the setDefaultHighRepJobPolicyUnappliedJobPercentage(100) setting).
EventualConsistencyTest Test Case
import static com.googlecode.objectify.ObjectifyService.begin;
import static com.googlecode.objectify.ObjectifyService.ofy;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.util.List;
import org.junit.Test;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.util.Closeable;
import com.netbase.followerdownloader.model.DownloadTask;
import com.netbase.followerdownloader.model.User;
public class EventualConsistencyTest {
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()
.setDefaultHighRepJobPolicyUnappliedJobPercentage(100));
#Test
public void testEventualConsistency() {
helper.setUp();
ObjectifyRegistrar.registerDataModel();
User user = new User();
user.id = 1L;
Closeable closeable1 = begin();
ofy().save().entity(user);
closeable1.close();
Closeable closeable2 = begin();
DownloadTask downloadTask = new DownloadTask();
downloadTask.owner = Ref.create(user);
ofy().save().entity(downloadTask);
closeable2.close();
Closeable closeable3 = ObjectifyService.begin();
List<DownloadTask> downloadTasks1 = ofy().load().type(DownloadTask.class).ancestor(user).list();
assertThat(downloadTasks1.size(), equalTo(1));
closeable3.close();
Closeable closeable4 = ObjectifyService.begin();
List<DownloadTask> downloadTasks2 = ofy().load().type(DownloadTask.class).list();
assertThat(downloadTasks2.size(), equalTo(0)); // THIS SHOULD PASS IF setDefaultHighRepJobPolicyUnappliedJobPercentage(100) WORKED
closeable4.close();
helper.tearDown();
}
}
User Definition
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
#Entity
public class User {
#Id public Long id;
public User () {
}
}
DownloadTask Definition
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Parent;
#Entity
public class DownloadTask {
#Id public Long id;
#Parent public Ref<User> owner;
public DownloadTask() {
}
}
Environment:
appengine-api-1.0-sdk-1.9.17.jar
appengine-testing-1.9.17.jar
appengine-api-stubs-1.9.17.jar
junit-4.11.jar
objectify-5.1.3.jar
In case I missed anything else important, here is a more exhaustive list:
My questions are:
Is setDefaultHighRepJobPolicyUnappliedJobPercentage(100) broken?
Does setDefaultHighRepJobPolicyUnappliedJobPercentage(100) not really work as documented? Does it in fact apply the job even though the documentation says it's not supposed to?
Is the value passed to setDefaultHighRepJobPolicyUnappliedJobPercentage() really supposed to be 100 and not maybe let's say, 1.0f?
Do Objectify ancestor queries not really work as documented?
The problem is explained by an observation at https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests :
"In the local environment, performing a get() of an Entity that belongs to an entity group with an unapplied write will always make the results of the unapplied write visible to subsequent global queries."
In this contect, this means the ancestor-query:
List<DownloadTask> downloadTasks1 = ofy().load().type(DownloadTask.class).ancestor(user).list();
which internally "performs a get() of an Entity that belongs to an entity group with an unapplied write" influences the behavior of the immediately-following global query:
List<DownloadTask> downloadTasks2 = ofy().load().type(DownloadTask.class).list();
To avoid your tests influencing each other, and in particular, interfering w/each other in this way, it's best to use a separate method per operation under test (each with all the needed setup and teardown parts), rather than having successive operations-under-test within a single test method.
I am fairly new to modding.
I want to create a sword that sets mobs or players on fire. I am using the hitEntity method and, I noticed the function is not even running. I tested it using the console. When I use the #Override notation before the hitEntity method it gives me an error:
The method hitEntity(ItemStack, EntityLiving, EntityLiving) of type BlazeSword must override or implement a supertype method
Here is my code:
package com.example.firstMod.tools;
import com.example.firstMod.FirstMod;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.DamageSource;
public class BlazeSword extends ItemSword {
public BlazeSword(int id, ToolMaterial blaze) {
super(blaze);
this.setCreativeTab(FirstMod.blazingMod);
this.setUnlocalizedName("blazeSword");
this.setTextureName(FirstMod.MODID+":"+"blaze_sword");
}
public boolean hitEntity(ItemStack par1itemstack, EntityLiving par2entityliving, EntityLiving par3entityliving){
par2entityliving.setFire(20);
return true;
}
}
If you get the error you said with #Override, so there is no such method in ItemSword. Look ItemSword class for the right hit method.
The hitEntity method isn't working because you never call it. You declare that it exists but you never run it. What you need to do is call your hitEntity method in your BlazeSword class using your requested variables.
In your BlazeSword class:
hitEntity(ItemStack par1itemstack, EntityLiving par2entityliving, EntityLiving par3entityliving)
Also, take out #Override since you aren't trying to find the hierarchy of the blaze sword.
Can someone give me an example how to use this enum. I'm trying to find out what I need to import and how I can use the methods of the following Enum:
http://docs.oracle.com/javaee/6/api/javax/ws/rs/core/Response.Status.html
You would need the correct package containing the enum definition. In this instance javax.ws.rs. Visit this post to know where to find it.
Can't find javax.ws.rs package in jdk
After you have added the .jar to your CLASSPATH you can simple import it
import javax.ws.rs.core.Response.Status;
Here goes one example in JSON:
public Response retrieveSomething(String uuid) {
Entity entity = service.getById(uuid);
if(entity == null) {
return Response.status(Response.Status.NOT_FOUND).entity("Entity not found for UUID: " + uuid).build();
}
String json = //convert entity to json
return Response.ok(json, MediaType.APPLICATION_JSON).build();
}
In many respects an enum is just like z regular class; the answer is practically the for how to use an enum as how to use a class:
Step 1: import the enum to your program:
import javax.ws.rs.core.Response.Status;
Step 2: Het a reference to an instance (unlike regular classes, you can't create an instance - that is done for you by the JVM), either from the enum:
Status status = Status.OK;
or as the returned value of a method:
Status status = response.getStatus();
Step 3: Invoke a method:
int code = status.getStatusCode();
Here is a very simple example using the Status enum:
First import Response:
import javax.ws.rs.core.Response;
Then your code...
public Response create() {
return Response.status(Response.Status.CONFLICT).build();
}