Error 'ImageGenerator' cannot be resolve - java

I am trying the following code but getting:
ImageGenerator cannot be resolved
I have imported the required libraries of JavaCV and OpenCV. Do I need to import more libraries? I have searched, but could not find it!
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.nio.ByteBuffer;
import javax.naming.Context;
enum Resolution {
NORMAL, HIGH
}
public class KinectCapture
{
private BufferedImage image = null;
private int imWidth, imHeight;
private int fps;
private boolean isReleased = true;
// when Kinect context has been released
// OpenNI
private Context context;
private ImageGenerator imageGen; **Here I am getting the error.**
public KinectCapture()
{ this(Resolution.NORMAL); }
public KinectCapture(Resolution res)
{ configOpenNI(res); }
private void configOpenNI(Resolution res)
// create context and image generator
{
try {
context = new Context();
// add the NITE Licence
License licence = new License("PrimeSense", "0KOIk2JeIBYClPWVnMoRKn5cdY4="); // vendor, key
context.addLicense(licence);
imageGen = ImageGenerator.create(context);

I cant find ImageGenerator in the JavaDoc so im assuming you either have a package given to you by your school or whatever, then you have to import that as well, or you need to create the Class ImageGenerator somewhere in your package.
EDIT: After some research, I found this: https://github.com/OpenNI/OpenNI/blob/master/Wrappers/OpenNI.java/src/org/openni/ImageGenerator.java

Related

Why is getItemInHand being crossed out (see image below)

I am new to creating minecraft plugins, however not new to programming, I am following a tutorial very thoroughly, the video has good ratings so it is trusted, when watching the video the guy has no problems what so ever (Youtube video on developing minecraft plugins) , so I did some research into solutions but always the line through the code.
Eclipse gives me the option for: #SuppressWarnings("deprecation") which allows the code to be used still but I would rather have no need of that usage.
Basically my question is why is there the need of the line going through the code and how do I find a solution to get rid of it.
Main class:
package com.jc1;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class Core extends JavaPlugin
{
public Permission pPermission = new Permission("playerAbilities.allowed");
#Override
public void onEnable()
{
new BlockListener(this);
PluginManager pm = getServer().getPluginManager();
pm.addPermission(pPermission);
}
#Override
public void onDisable()
{
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
if(cmd.getName().equalsIgnoreCase("giveitems") && sender instanceof Player)
{
Player p = (Player) sender;
if(p.hasPermission("playerAbilities.allowed"))
{
p.setItemInHand(new ItemStack(Material.DIAMOND_BOOTS));
}
return true;
}
return false;
}
}
Secondary class:
package com.jc1;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
public class BlockListener implements Listener
{
public BlockListener(Core plugin)
{
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
#EventHandler
public void onBlockPlace(BlockPlaceEvent e)
{
Player p = e.getPlayer();
if(!p.hasPermission("playerAbilities.allowed"))
{
e.setCancelled(true);
}
}
}
The method is deprecated, meaning that it is not recommended to be used anymore and is most likely replaced with another method.
Methods that are deprecated may still work as intended.
A simple search for the method reveals (this) documentation, stating:
players can duel wield now use the methods for the specific hand instead
which referes to the #see references:
getItemInMainHand() and getItemInOffHand().
Use this:
player.getInventory().getItemInMainHand()
Instead of:
player.getItemInHand()
Hope this helps! :D

AsyncLoader - wont accept 'this'

This is a follow up to a question I asked here.
I have copied and pasted this code from this tutorial. When I paste it into Android Studio, the 'this' parameter of of content.getLoadManager.initLoader() is highlighted in red and shows the following error:
Wrong 3rd Argument Type. Found 'com.example.carl.loaderDemo.FooLoaderClient', requried: 'android.app.LoaderManager.LoaderCallBacks
I've ran into this previously (see first link). I was hoping this tutorial would help but I just seem to be going in endless circles!
Can anyone point me in the right direction?!
package com.example.carl.loaderdemo;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
public class FooLoader extends AsyncTaskLoader {
public FooLoader(Context context, Bundle args) {
super(context);
// do some initializations here
}
public String loadInBackground() {
String result = "";
// ...
// do long running tasks here
// ...
return result;
}
}
class FooLoaderClient implements LoaderManager.LoaderCallbacks {
Activity context;
// to be used for support library:
// FragmentActivity context2;
public Loader onCreateLoader(int id, Bundle args) {
// init loader depending on id
return new FooLoader(context, args);
}
#Override
public void onLoadFinished(Loader loader, Object data) {
}
public void onLoaderReset(Loader loader) {
// ...
}
public void useLoader() {
Bundle args = new Bundle();
// ...
// fill in args
// ...
Loader loader =
context.getLoaderManager().initLoader(0, args, this);
// with support library:
// Loader loader =
// context2.getSupportLoaderManager().initLoader(0, args, this);
// call forceLoad() to start processing
loader.forceLoad();
}
}
Screenshot of error message:
There is a mismatch in your imports:
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
But you need
import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import android.content.Loader;
You cannot mix the support library with the android framework. Alternatively you can subclass FragmentActivity and call getSupportLoaderManager() instead.
You're implementing android.support.v4.app.LoaderManager.LoaderCallbacks but the client is expecting android.app.LoaderManager.LoaderCallbacks. You need to be consistent in which loader API you're using.

Textures do not appear

I am trying to add a texture to an item, yet the texture just doesn't appear. I have the texture made, and in the right file directory, but while in game it doesn't display. Thus, I think it's an error in my code.
For the whole class file, see below:
package Moonstone;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.util.EnumHelper;
#Mod(modid = "ms", name = "Moonstone", version = "1.0")
public class MoonstoneMain {
public static Item moonstone;
#EventHandler
public void preInit(FMLPreInitializationEvent event) {
//All init
moonstone = new Moonstone().setUnlocalizedName("Moonstone").setTextureName("moonstone").setMaxStac kSize(64);
GameRegistry.registerItem(moonstone, moonstone.getUnlocalizedName().substring(5));
}
#EventHandler
public void init(FMLInitializationEvent event) {
//Proxy, TileEntity, entity, GUI and packet registering
}
#EventHandler
public void postInit(FMLPostInitializationEvent event) {
}
public static CreativeTabs tabMoonstone = new CreativeTabs("tabMoonstone"){
#Override
public Item getTabIconItem(){
return new ItemStack(Items.stick).getItem();
}
};
}
For just the item, look below-
moonstone = new Moonstone().setUnlocalizedName("Moonstone").setTextureName("moonstone").setMaxStackSize(64);// I have tried with ms:moonstone and without, both don't work.
GameRegistry.registerItem(moonstone, moonstone.getUnlocalizedName().substring(5));
Recommended changes but not necessary:
First:
When registering the item you should remove the .substring(5),
having this in will name the item "Moons" instead of "Moonstone".
Second:
unlocalized names should always be lowercase and should be formatted
as modid_itemname
Third:
Package names should be lowercase, package moonstone
Fourth:
Your should make a Refstrings.java file and put the modid, version and name in it
package Moonstone
public RefStrings{
public static String NAME = "Moonstone";
public static String MODID = "ms";
public static String VERSION = "1.0";
}
Necessary changes:
Your setTextureName should be passed "ms:moonstone"
You didn't post your folder structure but it should look like this:
src/main/java/Moonstone/MoonstoneMain.java
src/main/resources/assests/ms/textures/items/moonstone.png
it is possible that some of the recommend changes will be what fixes the problem, minecraft can be a bit finicky with naming.

solution for getSystemService function at Android

I want to test something about usb devices, I try to write a small program, I am sure that it is wrong but this is not the point of this question.
I am sure that my imports are OK but the Android Studio refused to build this class with an error about the GetSystemService(). I have the message:
Error:(65, 43) error: cannot find symbol method getSystemService(String).
I used also an example from http://android-er.blogspot.de/2013/10/list-attached-usb-devices-in-usb-host.html and the Android Studio also has the same error but if i install the Apk from this website then it is running on my device, so i supposed that something is wrong at Android Studio.
Any good idea?
OFFTOPIC "QT Creator is light years better"
import android.content.Context;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbAccessory;
import android.os.ParcelFileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileDescriptor;
import android.util.Log;
public class DeviceOpenActivity {
private static final String TAG = "DeviceOpenActivity";
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbAccessory mAccessory;
ParcelFileDescriptor mFileDescriptor;
FileInputStream mInputStream;
FileOutputStream mOutputStream;
public static int fibonacci(int n) {
if (n<2) return n;
return fibonacci(n-1) + fibonacci(n-2);
}
private void openAccessory() {
Log.d(TAG, "openAccessory: " + mAccessory);
mFileDescriptor = usbManager.openAccessory(mAccessory);
if (mFileDescriptor != null) {
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
}
}
}
If you check the example that you provided, you will verify that there is a MainActivity class that extends Activity class, which by its turn extends indirectly from Context. In order to call getSystemService() you need to have an available Context. If you make your DeviceOpenActivity extend Activity, Android Studio will not complain anymore about your call.
Just leave your class declaration like this:
public class MainActivity extends Activity
Don't forget that you need to provide a XML layout for your Activity, as well as the Activity methods, like onCreate().

Dynamic Typecasting in Java

I'm writing a plugin for the Minecraft server implementation CraftBukkit, and I've come across a problem where I need to cast to a class that is found through reflection.
Here's the deal. The original code I wrote looked like this, with irrelevant parts removed:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import net.minecraft.server.v1_7_R3.EntityAnimal;
import net.minecraft.server.v1_7_R3.EntityHuman;
import org.bukkit.craftbukkit.v1_7_R3.entity.CraftAnimals;
import org.bukkit.craftbukkit.v1_7_R3.entity.CrafteEntity;
import org.bukkit.World;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Entity;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
public class Task extends BukkitRunnable {
private static final int MATING_DISTANCE = 14;
private final JavaPlugin plugin;
private final Random randomizer;
private boolean mateMode;
private double chance;
public Task(JavaPlugin plugin, double chance, boolean mateMode) {
this.plugin = plugin;
this.randomizer = new Random();
this.chance = chance;
this.mateMode = mateMode;
this.theTaskListener = listener;
}
public void run() {
List<World> worlds = plugin.getServer().getWorlds();
Iterator<World> worldIterator = worlds.iterator();
while (worldIterator.hasNext()) {
World world = worldIterator.next();
Collection<Animals> animals = world.getEntitiesByClass(Animals.class);
Iterator<Animals> animalIterator = animals.iterator();
while (animalIterator.hasNext()) {
Animals animal = (Animals) animalIterator.next();
EntityAnimal entity = (EntityAnimal) ((CraftEntity) ((CraftAnimals) animal)).getHandle();
EntityHuman feeder = null;
entity.f(feeder);
}
}
}
}
However, as you can see in the imports, this code imported the classes from only one version of the Minecraft server package - v1_7_R3. Now the problem is, I want to add support for more than that, and I want to be able to do that without creating separate versions of my plugin for each version of Minecraft. Despite the fact that most of the classes in the package are the same (at least ALL of those that I need) the package names are different, and therefore it can't be done with static imports (or at least I think so?)
So, I decided to use reflection in order to get the correct classes I need (this code is in another class):
private static final String[] requiredClasses = {
"net.minecraft.server.%s.EntityAnimal",
"net.minecraft.server.%s.EntityHuman",
"org.bukkit.craftbukkit.%s.entity.CraftAnimals",
"org.bukkit.craftbukkit.%s.entity.CraftEntity"
};
public static final String[] supportedVersions = {
"v1_7_R3",
"v1_7_R4"
};
public Class<?>[] initializeClasses() {
String correctVersion = null;
for (int i = 0; i < supportedVersions.length; i++) {
String version = supportedVersions[i];
boolean hadIssues = false;
for (int j = 0; j < requiredClasses.length; j++) {
String className = requiredClasses[j];
try {
Class.forName(String.format(className, version));
} catch (ClassNotFoundException e) {
getLogger().log(Level.INFO, String.format("The correct version isn't %s.", version));
hadIssues = true;
break;
}
}
if (!hadIssues) {
correctVersion = version;
break;
}
}
Class[] classes = new Class[requiredClasses.length];
if (correctVersion != null) {
getLogger().log(Level.INFO, String.format("The correct version is %s.", correctVersion));
for (int i = 0; i < requiredClasses.length; i++) {
String className = requiredClasses[i];
try {
classes[i] = Class.forName(String.format(className, correctVersion));
} catch (ClassNotFoundException e) {}
}
} else {
getLogger().log(Level.WARNING, "The version of Minecraft on this server is not supported.");
getLogger().log(Level.WARNING, "Due to this, the plugin will self-disable.");
getLogger().log(Level.WARNING, "To fix this issue, get build that supports your version.");
this.setEnabled(false);
}
return classes;
}
Now, this approach successfully retrieves the required classes in both versions currently supported. I passed these to the rewritten Task class using instance variables and an edited constructor, and I removed the version-specific imports:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import org.bukkit.World;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Entity;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
public class Task extends BukkitRunnable {
private static final int MATING_DISTANCE = 14;
private final JavaPlugin plugin;
private final Random randomizer;
private boolean mateMode;
private double chance;
private Class entityAnimal;
private Class entityHuman;
private Class craftAnimals;
private Class craftEntity;
public Task(JavaPlugin plugin, Class[] classes, double chance, boolean mateMode) {
this.plugin = plugin;
this.randomizer = new Random();
this.chance = chance;
this.mateMode = mateMode;
this.entityAnimal = classes[0];
this.entityHuman = classes[1];
this.craftAnimals = classes[2];
this.craftEntity = classes[3];
}
Now, how can I rewrite the Task.run() method so that it will use the reflection classes? There is a whole lot of typecasting involved and unfortunately it's all necessary due to the ridiculous amount of overloading in the Minecraft code. For example, the entity.f(EntityHuman human) method cannot simply be called by doing entity.f(null) because there are other overloading entity.f(Object object) methods.
I am open to all suggestions as I'm facing a dead-end here. If there is a better approach to the problem, I could change to that as well.
Thank you!
In an object oriented language, we have access to various design patterns that have been developed for exactly this purpose. We use two patterns in particular.
Adapter Pattern is used to provide the same interface to a number of different implementations. It is sometimes called a shim. You create one class per version of each server, importing libraries to each. The class implements an interface that they hold in common.
Factory Pattern is used to select among the adapter classes. You use whatever method you need to determine which server version you have, and it will create an object implementing the proper interface. The main code remains the same. It calls the factory to get an object that knows how to deal with the server.
The advantages of this approach are several. You don't pollute the name space by importing overlapping libraries. The main code is much less susceptible to change as new server versions are added; the only code that needs to be written is the new server shim and the factory that determines which adapter to produce.
Just a brainstorming idea. What if:
importing all supported versions
fully referencing the appropriate package's types
checking for the version that's targeted at a particular runtime (assumed it can be obtained somehow)
import net.minecraft.server.v1_7_R3.*;
import net.minecraft.server.v1_7_R4.*;
enum Version {
V1_7_R3,
V1_7_R4
}
Version currentVersion;
net.minecraft.server.v1_7_R3.EntityAnimal animal3;
net.minecraft.server.v1_7_R4.EntityAnimal animal4;
// obtain currentVersion
switch ( currentVersion ) {
case V1_7_R3:
animal3.method();
break;
case V1_7_R4:
animal4.method();
break;
}
This is somehow ugly, of course, but under the given circumstances it's the possibility that came into my mind first.
After reading Gerold Broser's response, I realized that I would have to somehow modify my approach in order to create some sort of a handler class that would carry out the version-specific operation - of course this would be an interface that would separately be implemented by a class per version.
However, this became a problem when I realized Maven wouldn't let me call two versions of the same groupid.artifactid object.
I quickly did some research and found mbaxter's Multiple Versions Tutorial as well as the AbstractionExamplePlugin implementation which perfectly demonstrates this approach.
The approach works perfectly and is what every Bukkit developer should use. Here's my finished plugin for further reference if necessary.

Categories