Score keeping for a basic Minecraft plugin - java

I can't seem to find a way to store a simple scoring system for a user identifier and their score. I've tried storing it in a string and in a file, but I couldn't get it to work properly.
Here's the relevant code
public class ShiftGame extends JavaPlugin implements Listener {
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
}
#EventHandler
public void onPlayerSneak(PlayerToggleSneakEvent e){
Player player = e.getPlayer();
String name = player.getDisplayName();
if(e.isSneaking() == false){
try {
PrintWriter out;
System.out.println("Writing to data file..");
out = new PrintWriter("PlayerShiftAmounts.txt");
out.println(name);
out.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
}

Minecraft has some config file class: FileConfiguration and YamlConfiguration, so I think you don't need to use java.io.*, and realy needn't to worry about file writing.
FileConfiguration config = YamlConfiguration.loadConfiguration(file);
If you sure have to log something many times a second , I think you should try to use cache or just make a variable in Java , instead of writing into file or database every time.. I don't know why you need to log a list of which player are pressing shift?

Related

Update hashset from .txt while app is running

The goal is to block access to the page from the list of IP addresses. This list is in the file list.txt.
I made the service that checks IP from request and with HashSet of "unwanted" addresses, but subgoal is "catch on the fly" this list.txt. What I mean: if I add some IP to this file, it should be blocked without restarting application. And I have not ideas how to solve this, cause my app refreshes this list only after restart. My code is below
#Service
public class BlackListService {
public Set<String> loadBlackList() {
java.util.Set<java.lang.String> blackList = new HashSet<>();
InputStream resource = null;
try {
resource = new ClassPathResource(
"blacklist.txt").getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource))) {
blackList = reader.lines().collect(Collectors.toSet());
for (java.lang.String address:
blackList) {
System.out.println(address);
}
} catch (IOException e) {
e.printStackTrace();
}
return blackList;
}
public boolean isNowAllowedIP(Set<String> blackList, String requestIP) {
return blackList.contains(requestIP);
}
}
And controller:
#Controller
public class MainController {
private final BlackListService blackListService;
public MainController(BlackListService blackListService) {
this.blackListService = blackListService;
}
#GetMapping("/")
public String mainPage(HttpServletRequest request, Model model) {
Set<String> blackList = blackListService.loadBlackList();
if (blackListService.isNowAllowedIP(blackList, request.getRemoteAddr())) {
Logger logger = Logger.getLogger("Access logs");
logger.warning("Access disallowed");
model.addAttribute("message", request.getRemoteAddr() + ": Access disallowed");
return "index";
}
model.addAttribute("message", "Access allowed");
return "index";
}
}
Can someone help with this "subgoal"?
In loadBlackList() you are reading a resource from the classpath. Could this be picking up a file built into your jar file or build dir which is not the file you are editing? I would try changing loadBlackList() to use FileReader and a path on the file system rather than a path within the classpath instead of InputStreamReader.
What you need is a recurring background job that will reload your blacklist after you change it. This blog will discusses a "modern" approach for doing it with Spring.
Save the last modified time for the file when your program starts and you first load it. See this for checking the file modified time.
Schedule the background job to run every minute (or 5 or whatever is frequent enough for your needs).
When the job runs check the current last updated time on the file and if its different than the saved one, then its time to reload your list.

Android Java saving to file returning IOException

i know there's probably tons of these going around (and believe me i went through a lot when trying to get this right) but i cannot seem to get this going.
I'm trying to save a list of custom objects (cars) into a file on local storage and later on load them back by clicking a button.
I've been trying to use the FileOutputStream based on many sources i've read. of some reason this worked fine when tested using simple list of strings but when it comes to my self made objects i keep getting IO exception when trying to save. if anyone can take a look at my code and tell me what am i missing (spent over 20hr trying to sort this one myself with no luck).
P.S - saving and loading methods are being called by buttons which work fine so code was neglected.
public class Main extends Activity implements OnClickListener{
public static List<Car> carList = new ArrayList<Car>();
String FILENAME = "carListFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonView_saveb;
Button buttonView_loadb;
buttonView_saveb = (Button)findViewById(R.id.saveb);
buttonView_loadb = (Button)findViewById(R.id.loadb);
buttonView_saveb.setOnClickListener(this);
buttonView_loadb.setOnClickListener(this);
#Override
public void onClick(View view){
switch (view.getId()){
case R.id.saveb:
SaveData();
break;
case R.id.loadb:
LoadData();
break;
}
}
public void LoadData(){
ArrayList<car> toReturn;
FileInputStream fis;
try {
fis = openFileInput(FILENAME);
ObjectInputStream oi = new ObjectInputStream(fis);
toReturn = (ArrayList<Car>) oi.readObject();
oi.close();
} catch (FileNotFoundException e) {
System.out.println("Failed to load, file '"+FILENAME+"' not found");
} catch (ClassNotFoundException e) {
System.out.println("Failed to load from file '"+FILENAME+"', Class not found");
} catch (IOException e) {
System.out.println("Failed to load from file '"+FILENAME+"', I/O Exception")
}
}
// this method return io exception, no idea why
public void SaveData(){
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream of = new ObjectOutputStream(fos);
of.writeObject(diveLog);
of.flush();
of.close();
} catch (FileNotFoundException e) {
System.out.println("Failed to save, file '"+FILENAME+"' not found");
} catch (IOException e) {
System.out.println("Failed to save to file '"+FILENAME+"', I/O Exception");
}
}
}
no matter what i do this keep getting me IO exceptions.
also note that i have a button which is adding cars to the list so i wont save an empty list (although i don't see why that should matter).
Thanks to everyone who took the time to help me.
As it seems after adding the following line:
e.printStackTrace();
to the exception catchers and following the logCat output i found that Car could not be serialized. A quick research revealed that, since Car object came from a class (Car.java), that class has to implement 'serializable' in order to get serialized and later on be deserialized.
so at the Car.java file :
public class Car implements Serializable {
I came across a good explanation for the whole process, perfect for someone as new to java as i am:
https://www.youtube.com/watch?v=6MisF1sxBTo

Music in Java (start/stop)

Ok, so I am making a game and the music changes when you are in different regions or if there is an interruption, like with an AI.
So I have JUST learned how to make music showup in my program, and now I am trying to make it stop, but I am unsure how to, below is a snippet of code where the music plays and then I try to overwite it with new music when an action occurs.
public static void songs(String word) {
String temp = word;
if (temp.equals("start")) {
try {
try {
blah = new FileInputStream("C:/Users/Austin/Desktop/Storage/programimages/game/battle.wav");
} catch (Throwable e) {
e.printStackTrace();
}
AudioStream as = new AudioStream(blah);
AudioPlayer.player.start(as);
System.out.println("going");
} catch (IOException e) {
System.err.println(e);
}
}
if (temp.equals("stop")) {
try {
try {
blah = new FileInputStream("C:/Users/Austin/Desktop/Storage/programimages/game/silence.wav");
} catch (Throwable e) {
e.printStackTrace();
}
AudioStream as = new AudioStream(blah);
AudioPlayer.player.stop(as);
System.out.println("stopping");
} catch (IOException e) {
System.err.println(e);
}
}
}
This is the only method I have been able to find that has the music play, but if you guys have any other suggestions please let me know.
Again, I want to have sound affects and music going, and right now all that happens is one song will play, and it will not stop under any circumstance until it hits the very end of its length. I want to be able to stop songs whenever a new one should come on, and also allow sound affects to pop up.
Thanks!
(since I am stuck on this and need an answer now I will probably repost on one or two more java sites so I can get a response ASAP, thank you though!!!!)
EDITED CODE: (still does not stop the current stream, any more suggestions appreciated)
public static void songs(String word) throws IOException {
String temp = word;
if (temp.equals("go")) {
try {
blah = new FileInputStream("C:/Users/Austin/Desktop/Storage/programimages/game/battle.wav");
} catch (Throwable e) {
e.printStackTrace();
}
AudioStream as = new AudioStream(blah);
AudioPlayer.player.start(as);
System.out.println("going");
}
if (temp.equals("stop")) {
//don't try and do things with a null object!
if (as != null) {
AudioPlayer.player.stop(as);
System.out.println("stopping1");
}
System.out.println("stopping2");
AudioPlayer.player.stop(as);
}
}
Currently you're creating a new AudioStream in your stop branch and calling the stop method using this. This is a different object to the one that is currently playing. Try making the AudioStream a class variable, and calling stop on that instead.
EDIT: at the top of the class containing your code...
class YourClass {
//the class member variable
private AudioStream as;
//[etc...]
In your start branch:
// 'as' has already been defined above
as = new AudioStream(blah);
AudioPlayer.player.start(as);
System.out.println("going");
In your stop branch:
try
{
//don't try and do things with a null object!
if (as != null)
{
AudioPlayer.player.stop(as);
}
System.out.println("stopping");
}
catch (IOException e)
{
System.err.println(e);
}
You may have trouble with the static identifier on your method - if you're calling this from within an instantiated class you don't need this.
I can't even access these sun.audio Objects on my Eclipse IDE--I know they are in rt.jar, but there is header info about them being proprietary and such.
Can the Java Sound library (javax.sound.sampled) handle what you want to do? Both Clip and SourceDataLine allow one to stop playback. That is a more usual way of playing sound, if you want to use native Java.
Playback into is here:
http://docs.oracle.com/javase/tutorial/sound/playing.html
But the documentation, overall, is not exactly rich with examples. There's example code at this site
http://www.jsresources.org/
and plenty of people here who could help if you run into problems with the native Java approach.

Building JCoServer without Properties-File

I got another JCo-related question and hopefully finding help.
With JCo you can easily build up a connection like it is explained in the example sheets which came with the JCo-library. Unfortunately, the only way building a connection is handled with a created property file. It wouldn´t be that bad, if there wasn´t any sensible data in it. But at least, the password for the SAP user stands in the file, so it is a lack of safety in this way of connection-handling. The manual of JCo says so, too :
"For this example the destination configuration is stored in a file that is called by the program. In practice you should avoid this for security reasons."
but couldn´t find a working solution after all. There are a palmful threads about this theme, like this
http://forums.sdn.sap.com/thread.jspa?messageID=7303957
but none of them are helpful. I really can´t figure out a solution and neither find one. Actually I solved the security-problem with deleting the file after building the connection, but this is not a satisfying solution. There have to be a better way getting the parameter for the connection, especially when it stands in the manual, but I have no glue how.
Anybody already worked with JCo 3.0 and knows this problem?
Yes, that's possible. You have to create your own implementation of DestinationDataProvider and register it using Environment.registerDestinationDataProvider(). However your DDP obtains the connection data and credentials is up to you. Take a look at net.sf.rcer.conn.connections.ConnectionManager, there's a working example in there.
You need to
copy the private class starting on line 66 and adapt it to your own needs (that is, fetch the connection data from wherever you want to)
perform the registration (line 204) somewhere during the startup of your application
get the connection using some string identifier that will be passed to your DestinationDataProvider.
It's a bit confusing, it was dificult to me how to figure this too.
All you need is an object of type java.util.Properties to fill the desired fields, but it's up to ou how to fill this object.
I dit it through a ValueObject, I can fill this VO from a file, database, web form...
JCOProvider jcoProvider = null;
SAPVO sap = new SAPVO(); // Value Object
Properties properties = new Properties();
if(jcoProvider == null) {
// Get SAP config from DB
try {
sap = SAPDAO.getSAPConfig(); // DAO object that gets conn data from DB
} catch (Exception ex) {
throw new ConexionSAPException(ex.getMessage());
}
// Create new conn
jcoProvider = new JCOProvider();
}
properties.setProperty(DestinationDataProvider.JCO_ASHOST, sap.getJCO_ASHOST());
properties.setProperty(DestinationDataProvider.JCO_SYSNR, sap.getJCO_SYSNR());
properties.setProperty(DestinationDataProvider.JCO_CLIENT, sap.getJCO_CLIENT());
properties.setProperty(DestinationDataProvider.JCO_USER, sap.getJCO_USER());
properties.setProperty(DestinationDataProvider.JCO_PASSWD, sap.getJCO_PASSWD());
properties.setProperty(DestinationDataProvider.JCO_LANG, sap.getJCO_LANG());
// properties.setProperty(DestinationDataProvider.JCO_TRACE, "10");
try {
jcoProvider.changePropertiesForABAP_AS(properties);
} catch (Exception e) {
throw new ConexionSAPException(e.getMessage());
}
The JCOProvider class:
import com.sap.conn.jco.ext.DestinationDataEventListener;
import com.sap.conn.jco.ext.DestinationDataProvider;
import com.sap.conn.jco.ext.Environment;
import es.grupotec.ejb.util.ConexionSAPException;
import java.util.Properties;
public class JCOProvider implements DestinationDataProvider {
private String SAP_SERVER = "SAPSERVER";
private DestinationDataEventListener eventListener;
private Properties ABAP_AS_properties;
public JCOProvider() {
}
#Override
public Properties getDestinationProperties(String name) {
if (name.equals(SAP_SERVER) && ABAP_AS_properties != null) {
return ABAP_AS_properties;
} else {
return null;
}
// if(ABAP_AS_properties!=null) return ABAP_AS_properties;
// else throw new RuntimeException("Destination " + name + " is not available");
}
#Override
public boolean supportsEvents() {
return true;
}
#Override
public void setDestinationDataEventListener(DestinationDataEventListener eventListener) {
this.eventListener = eventListener;
}
public void changePropertiesForABAP_AS(Properties properties) throws ConexionSAPException {
try {
if (!Environment.isDestinationDataProviderRegistered()) {
if (ABAP_AS_properties == null) {
ABAP_AS_properties = properties;
}
Environment.registerDestinationDataProvider(this);
}
if (properties == null) {
if (eventListener != null) {
eventListener.deleted(SAP_SERVER);
}
ABAP_AS_properties = null;
} else {
ABAP_AS_properties = properties;
if (eventListener != null) {
eventListener.updated(SAP_SERVER);
}
}
} catch (Exception ex) {
throw new ConexionSAPException(ex.getMessage());
}
}
}
Regards

Tapestry dynamic generated image

My Tapestry5 application generate dynamically images with jFreeChart every day.
My problem is that i don't know how to show.
I have tried to save them into the webapp folder, but it seems impossible, no file is created inside.
I have tried a solution with StreamResponse without result.
Another one is about IEngineService but it seems to be only available for T4.
So, i would appreciate some help.
Thanks.
Ok i find where was the problem, here the solution, for the other class, please see Tapestry5: How To Stream An Existing Binary File.
public StreamResponse onImage() {
StreamResponse result = null;
if (graphic != null && graphic.getImage() != null) {
try {
InputStream input = new FileInputStream(graphic.getImage());
result = new PngInline(input, "test");
} catch (FileNotFoundException e) {
logger.error("Loading graphic image", e);
}
}
return result;
}
#Inject
private ComponentResources resources;
public Link getLink() {
return resources.createEventLink("image", new Object[]{});
}

Categories

Resources