GWT GoogleMaps Hide Default Layers Using Styles - java

I'm using GWT and the GWT GoogleMaps API (v3.8.0). I have everything up and running perfectly.
However, I'd like to disable a few of the default features that come with GoogleMaps, such as street names, the ability to click on restaurants, etc. Basically I'd like a very barebones map layer that I add my own custom layers to.
I thought I could do this using Styles. I'm trying to use a MapTypeStyler with visibility off with a MapTypeStyle of whatever type I wanted to disable (in this test case, MapTypeStyle.ROAD).
Here is the test code I'm trying to get running:
package com.test.client;
import com.google.gwt.ajaxloader.client.AjaxLoader;
import com.google.gwt.ajaxloader.client.AjaxLoader.AjaxLoaderOptions;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Document;
import com.google.maps.gwt.client.GoogleMap;
import com.google.maps.gwt.client.LatLng;
import com.google.maps.gwt.client.MapOptions;
import com.google.maps.gwt.client.MapTypeId;
import com.google.maps.gwt.client.MapTypeStyle;
import com.google.maps.gwt.client.MapTypeStyleElementType;
import com.google.maps.gwt.client.MapTypeStyleFeatureType;
import com.google.maps.gwt.client.MapTypeStyler;
public class GwtTest implements EntryPoint {
#Override
public void onModuleLoad() {
AjaxLoaderOptions options = AjaxLoaderOptions.newInstance();
options.setOtherParms("sensor=false");
Runnable callback = new Runnable() {
public void run() {
createMap();
}
};
AjaxLoader.loadApi("maps", "3", callback, options);
}
public void createMap() {
JsArray<MapTypeStyle> styles = (JsArray<MapTypeStyle>) JsArray.<MapTypeStyle>createArray();
JsArray<MapTypeStyler> roadStylers = (JsArray<MapTypeStyler>) JsArray.<MapTypeStyler>createArray();
MapTypeStyler roadStyler = MapTypeStyler.visibility("off");
roadStylers.push(roadStyler);
MapTypeStyle roadStyle = MapTypeStyle.create();
roadStyle.setStylers(roadStylers);
roadStyle.setFeatureType(MapTypeStyleFeatureType.ROAD); //this is line 43
roadStyle.setElementType(MapTypeStyleElementType.ALL);
styles.push(roadStyle);
MapOptions mapOpts = MapOptions.create();
mapOpts.setZoom(4);
mapOpts.setCenter(LatLng.create(37.09024, -95.712891));
mapOpts.setMapTypeId(MapTypeId.TERRAIN);
mapOpts.setStreetViewControl(false);
mapOpts.setStyles(styles);
final GoogleMap map = GoogleMap.create(Document.get().getElementById("map_canvas"), mapOpts);
}
}
However, when I run that, I get an Exception:
14:49:52.756 [ERROR] [gwttest] Uncaught exception escaped
java.lang.ExceptionInInitializerError: null
at com.test.client.GwtTest.createMap(GwtTest.java:43)
at com.test.client.GwtTest$1.run(GwtTest.java:25)
at com.google.gwt.ajaxloader.client.ExceptionHelper.runProtected(ExceptionHelper.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException: null
at com.google.maps.gwt.client.MapTypeStyleFeatureType$.register(MapTypeStyleFeatureType.java:227)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:338)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:576)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:284)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.maps.gwt.client.MapTypeStyleFeatureType$.create(MapTypeStyleFeatureType.java)
at com.google.maps.gwt.client.MapTypeStyleFeatureType$.<clinit>(MapTypeStyleFeatureType.java:39)
at com.test.client.GwtTest.createMap(GwtTest.java:43)
at com.test.client.GwtTest$1.run(GwtTest.java:25)
at com.google.gwt.ajaxloader.client.ExceptionHelper.runProtected(ExceptionHelper.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Thread.java:745)
The weird thing is, the Exception seems to be internal to GoogleMaps, so I don't really know what's going on?
Am I doing something obviously dumb with the Styles?
Edit: I've also asked this question on the GWT Forum.

I found one workaround involving writing native JavaScript that bypasses the GoogleMaps GWT API:
package com.test.client;
import com.google.gwt.ajaxloader.client.AjaxLoader;
import com.google.gwt.ajaxloader.client.AjaxLoader.AjaxLoaderOptions;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Document;
import com.google.maps.gwt.client.GoogleMap;
import com.google.maps.gwt.client.LatLng;
import com.google.maps.gwt.client.MapOptions;
import com.google.maps.gwt.client.MapTypeId;
public class GwtTest implements EntryPoint {
#Override
public void onModuleLoad() {
AjaxLoaderOptions options = AjaxLoaderOptions.newInstance();
options.setOtherParms("sensor=false");
Runnable callback = new Runnable() {
public void run() {
createMap();
}
};
AjaxLoader.loadApi("maps", "3", callback, options);
}
public void createMap() {
MapOptions mapOpts = MapOptions.create();
mapOpts.setZoom(4);
mapOpts.setCenter(LatLng.create(37.09024, -95.712891));
mapOpts.setMapTypeId(MapTypeId.TERRAIN);
mapOpts.setStreetViewControl(false);
GoogleMap map = GoogleMap.create(Document.get().getElementById("map_canvas"), mapOpts);
styleMap(map);
}
public native void styleMap(GoogleMap map) /*-{
map.set('styles', [
{
"featureType": "road",
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "poi",
"stylers": [
{ "visibility": "off" }
]
},{
"stylers": [
{ "invert_lightness": true }
]
}
]);
}-*/;
}
I'd still be curious to find out if there's a pure Java workaround, but if anybody else has this problem, this native approach works. And it has the added bonus that it works directly with JSON you can export from the GoogleMaps Styling Wizard.

Related

org.powermock.reflect.exceptions.FieldNotFoundException

Good day I've got class with 2 methods: first is public GetLeadRequestsList - I want to test it, and second is private LeadRequestListResponse - used by first method. I mocked second method and called first one. Code of my test is here. When I run testGetLeadRequestsList, I catched
org.powermock.reflect.exceptions.FieldNotFoundException: No static field of type "org.mockito.internal.progress.MockingProgress" could be found in the class hierarchy of org.mockito.Mockito.
at org.powermock.reflect.internal.matcherstrategies.FieldTypeMatcherStrategy.notFound(FieldTypeMatcherStrategy.java:40)
at org.powermock.reflect.internal.WhiteboxImpl.findSingleFieldUsingStrategy(WhiteboxImpl.java:502)
at org.powermock.reflect.internal.WhiteboxImpl.findFieldInHierarchy(WhiteboxImpl.java:455)
at org.powermock.reflect.internal.WhiteboxImpl.getInternalState(WhiteboxImpl.java:576)
at org.powermock.reflect.Whitebox.getInternalState(Whitebox.java:347)
at org.powermock.api.mockito.internal.PowerMockitoCore.getMockingProgress(PowerMockitoCore.java:45)
at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)
at org.powermock.api.mockito.PowerMockito.doReturn(PowerMockito.java:790)
at ru.sbrf.sbi.ufs.business.rest.api.LeadRequestsControllerImplTest.setUp(LeadRequestsControllerImplTest.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:514)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:215)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:589)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:820)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1128)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:782)
at org.testng.TestRunner.run(TestRunner.java:632)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1244)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1169)
at org.testng.TestNG.run(TestNG.java:1064)
at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110)
error in testclass is in the String:
doReturn(leadRequestsResponse).when(mock, "LeadRequestListResponse", ArgumentMatchers.anyBoolean());
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.runner.RunWith;
import org.mockito.*;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.sbrf.sbi.ufs.poi.vo.ErrorMessage;
import ru.sbrf.sbi.ufs.poi.vo.LeadRequestData;
import ru.sbrf.sbi.ufs.poi.vo.LeadRequestListResponse;
import ru.sbrf.sbi.ufs.poi.vo.ResponseStatus;
import java.util.ArrayList;
import static org.powermock.api.mockito.PowerMockito.*;
import static org.testng.Assert.*;
public class LeadRequestsControllerImplTest {
#Spy
LeadRequestsControllerImpl mock = new LeadRequestsControllerImpl();
LeadRequestListResponse leadRequestsResponse;
#BeforeMethod
public void setUp() throws Exception {
leadRequestsResponse = new LeadRequestListResponse();
leadRequestsResponse.setResponseStatus(new ResponseStatus().withStatusCode(200L));
ArrayList<LeadRequestData> requests = new ArrayList<>();
requests.add(LeadRequestData.builder()
.companyName("НПО Помощь")
.lastName("Помоги")
.firstName("Себе")
.secondName("Сам")
.build());
leadRequestsResponse.setRequests(requests);
doReturn(leadRequestsResponse).when(mock, "LeadRequestListResponse", ArgumentMatchers.anyBoolean());
}
#Test
public void testGetLeadRequestsList() {
try {
String result = mock.getLeadRequestsList();
ObjectMapper mapper = new ObjectMapper();
String expect = mapper.writeValueAsString(leadRequestsResponse);
assertEquals(expect, result,"GetLeadRequestsList isn't correct.");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Maybe, anybody know how to check with Error.
Thank's in advance
I suppose you use not correct versions of mockito-core and powermock-api-mockito. Because FieldNotFoundException could be if using not compatible versions of these libraries. Please use support versions chart - https://github.com/powermock/powermock/wiki/Mockito#supported-versions
So you need check your versions and correct it.
Also you should do next things:
Add #RunWith(PowerMockRunner.class) and #PrepareForTest(LeadRequestsControllerImpl.class) before LeadRequestsControllerImplTest
Change from TestNG #BeforeMethod to JUnit annotations (for example #BeforeClass) because you can't mixed it.

Null pointer exception serenity behave root package

I am trying to run a simple bdd test using behave and serenity but i am getting a initialization error. It seems as though there is a package class which is null but i cannot figure out which one or is there something wrong with way i am initialising my code.
I have been serenity bdd documentation online
https://serenity-bdd.github.io/theserenitybook/latest/jbehave.html
directory tree
new output
Appreciate the help :)
Below is the stack trace and code.
ava.lang.NullPointerException
at net.serenitybdd.jbehave.RootPackage.forPackage(RootPackage.java:8)
at net.serenitybdd.jbehave.SerenityStories.getRootPackage(SerenityStories.java:220)
at net.serenitybdd.jbehave.SerenityStories.stepsFactory(SerenityStories.java:88)
at org.jbehave.core.ConfigurableEmbedder.configuredEmbedder(ConfigurableEmbedder.java:130)
at net.serenitybdd.jbehave.runners.SerenityReportingRunner.<init>(SerenityReportingRunner.java:68)
at net.serenitybdd.jbehave.runners.SerenityReportingRunner.<init>(SerenityReportingRunner.java:62)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:37)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.requests.ClassRequest.createRunner(ClassRequest.java:28)
at org.junit.internal.requests.MemoizingRequest.getRunner(MemoizingRequest.java:19)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
test.class
import net.thucydides.core.annotations.Managed;
import net.thucydides.core.annotations.Steps;
import org.jbehave.core.annotations.When;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
public class test {
#Managed()
WebDriver webDriver;
#Steps
GoogleSteps googleSteps;
#When("I open the page $value")
public void itest(String value) {
googleSteps.sendvalue(value);
}
}
GooglePage.class
import net.serenitybdd.core.annotations.findby.By;
import net.thucydides.core.annotations.DefaultUrl;
import net.thucydides.core.annotations.Step;
import net.thucydides.core.pages.PageObject;
import org.openqa.selenium.Keys;
#DefaultUrl("http://www.google.com")
public class GooglePage extends PageObject {
public void searchGoogle (String q) {
find(By.name("q")).sendKeys(q, Keys.ENTER);
}
}
GoogleSteps.class
import net.thucydides.core.annotations.Step;
public class GoogleSteps {
GooglePage googlePage;
#Step
public void open_page() {
googlePage.open();
}
#Step
public void sendvalue (String value) {
googlePage.searchGoogle(value);
}
}
GoogleRunner.class
import net.serenitybdd.jbehave.SerenityStory;
public class GoogleRunner extends SerenityStory {
}
serenity.properties file
webdriver.driver=chrome
webdriver.chrome.driver = /Users/aneesaiqbal/Downloads/chromedriver-2.exe
login.story
Narrative:
Testing google
Scenario: lets google
When I open the page hello

Java serialzing file not writing with Bukkit

So what I'm trying to do is use bukkit and a hashmap to save a player's name and their home location to be able to teleport to later. Currently the User._PlayerHomes hashmap will work, but once the server is shutdown and reloaded there is no file named User.ser and if you try to teleport to a home you previously set there is a lengthy error message I will post here.
[13:20:05 INFO]: Kalenpw issued server command: /khome
[13:20:05 ERROR]: null
org.bukkit.command.CommandException: Unhandled exception executing command 'khome' in plugin TestPlugin v1.0
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) ~[spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at org.bukkit.craftbukkit.v1_9_R1.CraftServer.dispatchCommand(CraftServer.java:645) ~[spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at net.minecraft.server.v1_9_R1.PlayerConnection.handleCommand(PlayerConnection.java:1350) [spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at net.minecraft.server.v1_9_R1.PlayerConnection.a(PlayerConnection.java:1185) [spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at net.minecraft.server.v1_9_R1.PacketPlayInChat.a(PacketPlayInChat.java:45) [spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at net.minecraft.server.v1_9_R1.PacketPlayInChat.a(PacketPlayInChat.java:1) [spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at net.minecraft.server.v1_9_R1.PlayerConnectionUtils$1.run(SourceFile:13) [spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [?:1.7.0_85]
at java.util.concurrent.FutureTask.run(FutureTask.java:262) [?:1.7.0_85]
at net.minecraft.server.v1_9_R1.SystemUtils.a(SourceFile:45) [spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at net.minecraft.server.v1_9_R1.MinecraftServer.D(MinecraftServer.java:721) [spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at net.minecraft.server.v1_9_R1.DedicatedServer.D(DedicatedServer.java:400) [spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at net.minecraft.server.v1_9_R1.MinecraftServer.C(MinecraftServer.java:660) [spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at net.minecraft.server.v1_9_R1.MinecraftServer.run(MinecraftServer.java:559) [spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at java.lang.Thread.run(Thread.java:745) [?:1.7.0_85]
Caused by: java.lang.NullPointerException
at org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer.teleport(CraftPlayer.java:457) ~[spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at org.bukkit.craftbukkit.v1_9_R1.entity.CraftEntity.teleport(CraftEntity.java:225) ~[spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
at com.Khalidor.testplugin.TestPluginCommandExecutor.onCommand(TestPluginCommandExecutor.java:161) ~[?:?]
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[spigot-1.9.2.jar:git-Spigot-5a40365-b70058a]
... 15 more
Here is all my relevant code I left out the User.java class and plugin.yml because that doesn't seem to be the issue because it works until the server gets restarted but if that would help let me know and I'll add it:
TestPlugin.java:
//#kalenpw
package com.Khalidor.testplugin;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
public final class TestPlugin extends JavaPlugin implements Listener {
MyConfigManager manager;
MyConfig homesConfig;
#Override
public void onEnable() {
// TODO insert logic for when plugin is enabled
getLogger().info("onEable has been invoked!");
getServer().getPluginManager().registerEvents(this, this);
this.getCommand("KHome").setExecutor(new TestPluginCommandExecutor(this));
this.getCommand("KSetHome").setExecutor(new TestPluginCommandExecutor(this));
manager = new MyConfigManager(this);
homesConfig = manager.getNewConfig("Homes.yml");
//Deserialize
try{
FileInputStream fileIn = new FileInputStream("User.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
User._PlayerHomes = (HashMap<String, Location>) in.readObject();
in.close();
fileIn.close();
}
catch(IOException i){
i.printStackTrace();
return;
}
catch(ClassNotFoundException c){
System.out.print("User class not found");
c.printStackTrace();
return;
}
}
#Override
public void onDisable() {
// when plugin is disabled
getLogger().info("onDisable has been invoked");
//Serialize object
try{
FileOutputStream fileOut = new FileOutputStream("User.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(User._PlayerHomes);
out.close();
fileOut.close();
System.out.println("Serialized data has been saved");
}
catch(IOException i){
i.printStackTrace();
}
}
}
TestPluginCommandExecutor.java
//#kalenpw
package com.Khalidor.testplugin;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import com.google.common.io.Files;
public class TestPluginCommandExecutor implements CommandExecutor {
private final TestPlugin plugin;
// All commands
private final String _KHome = "KHome";
private final String _KSetHome = "KSetHome";
ArrayList<String> _AllCommands = new ArrayList<String>();
// Error Messages
private final String _InvalidArguments = ChatColor.RED + "Error(00): Invalid argument!";
private final String _InvalidExecutor = ChatColor.RED + "Error(01): Can't execute command";
//public static HashMap<String, Location> playerHomes = new HashMap<String, Location>();
public TestPluginCommandExecutor(TestPlugin plugin) {
this.plugin = plugin;// store info
}
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase(_KHome)) {
if (sender instanceof Player) {
Player player = (Player) sender;
//Location homeLocation = playerHomes.get(player.getName());
Location homeLocation = User._PlayerHomes.get(player.getName());
player.teleport(homeLocation);
player.sendMessage("You were teleported home!");
return true;
}
}
if (cmd.getName().equalsIgnoreCase(_KSetHome)) {
if (sender instanceof Player) {
Player player = (Player) sender;
//playerHomes.put(player.getName(), player.getLocation());
//homesConfig.
player.sendMessage("Set your home!");
User._PlayerHomes.put(player.getName(), player.getLocation());
// //Save home to file
// Path playerHomesFile = Paths.get("PlayerHomes.txt");
// String playerName = player.getName();
// String playerX = String.valueOf(player.getLocation().getX());
// String playerY = String.valueOf(player.getLocation().getY());
// String playerZ = String.valueOf(player.getLocation().getZ());
//
//
// //List<String> playerInfo = Arrays.asList(playerName, playerX, playerY, playerZ);
// ArrayList<String> playerInfo = new ArrayList<String>();
// playerInfo.add(playerName);
//
//
// //Files.write(playerHomesFile, playerInfo, Charset.forName("UTF-8"));
// //Files.write(playerHomesFile, playerInfo, Charset.forName("UTF-8"), StandardOpenOption.APPEND);
return true;
}
}
sender.sendMessage(_InvalidExecutor);
return false;
}
}
Thanks for the help! I think I included all the relevant details but if anything is missing or you need clarification let me know and I'll edit.
Edit: The exception when trying to serilize locations:
[14:13:20 WARN]: at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1183)
[14:13:20 WARN]: at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
[14:13:20 WARN]: at java.util.HashMap.writeObject(HashMap.java:1129)
[14:13:20 WARN]: at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[14:13:20 WARN]: at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
[14:13:20 WARN]: at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[14:13:20 WARN]: at java.lang.reflect.Method.invoke(Method.java:606)
[14:13:20 WARN]: at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1030)
[14:13:20 WARN]: at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1495)
[14:13:20 WARN]: at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431)
[14:13:20 WARN]: at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177)
[14:13:20 WARN]: at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
[14:13:20 WARN]: at com.Khalidor.testplugin.TestPlugin.onDisable(TestPlugin.java:90)
[14:13:20 WARN]: at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:294)
[14:13:20 WARN]: at org.bukkit.plugin.java.JavaPluginLoader.disablePlugin(JavaPluginLoader.java:364)
[14:13:20 WARN]: at org.bukkit.plugin.SimplePluginManager.disablePlugin(SimplePluginManager.java:424)
[14:13:20 WARN]: at org.bukkit.plugin.SimplePluginManager.disablePlugins(SimplePluginManager.java:417)
[14:13:20 WARN]: at org.bukkit.craftbukkit.v1_9_R1.CraftServer.disablePlugins(CraftServer.java:340)
[14:13:20 WARN]: at net.minecraft.server.v1_9_R1.MinecraftServer.stop(MinecraftServer.java:454)
[14:13:20 WARN]: at net.minecraft.server.v1_9_R1.MinecraftServer.run(MinecraftServer.java:595)
[14:13:20 WARN]: at java.lang.Thread.run(Thread.java:745)
class Location, which you were trying to serialize, is not Serializable, and so you cannot simply dump it to file (as you yourself have found out here)
Your options are either to make Location serializable (if you can and it makes sense. i dont know this API), or serialize something else that is serializable in its place and then upon reading that something else convert that information to a Location.

Exception in Application Constructor while trying to use Media Player

I have written a code which will play music when a link on a webpage is found.
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javafx.application.*;
// * #author Archit
public abstract class WebCrawl extends Application{
public static void main(String[] args) throws IOException {
Application.launch(args);
int a=0;
try {
Document doc = Jsoup.connect("https://in.bookmyshow.com/ranchi").get();
org.jsoup.select.Elements links = doc.select("a");
for (Element e: links) {
if ((e.attr("abs:href").equals("https://in.bookmyshow.com/ranchi/movies/fan/ET00025074"))) {
try {
File f = new File("/Users/Archit/Documents/Music/campbell.wav");
Media hit = new Media(f.toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
} catch(Exception ex) {
System.out.println("Exception");
}
}
}
}
The error I am getting is this:
Exception in Application constructor java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Unable to construct Application instance: class webcrawl.WebCrawl
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:907)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.InstantiationException
at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:819)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
Exception running application webcrawl.WebCrawl
A window seems to open when I run the application but is automatically closed and this error appears.
I would really appreciate the help. Thank you.
You are starting an application from the WebCrawl class using Application.launch(String[]), so launch tries to create a WebCrawl instance, which it can't, since WebCrawl is abstract.
BTW: Placing code after the Application.launch call won't work, since after Application.launch is finished, the JavaFX platform will already have exited.
You can read about the application lifecycle in the Life-cycle section of the Application javadoc.
You need to call the code form the start method or later.
You can find a tutorial for a simple JavaFX application here: https://docs.oracle.com/javase/8/javafx/get-started-tutorial/hello_world.htm

Unable to open gpio direction interface (Raspberry/Java)

I am currently stuck with the following prob. The JAR & Pi4J Lib gets executed on a RasPi B+. I've been searching the web for hours without a result. Curiously looking forward to your reponses and support ;-)
Stacktrace:
Exception in thread "main" java.lang.RuntimeException: Unable to open GPIO direction interface for pin [1]: No such file or directory
at com.pi4j.wiringpi.GpioUtil.export(Native Method)
at com.pi4j.io.gpio.RaspiGpioProvider.export(RaspiGpioProvider.java:108)
at com.pi4j.io.gpio.impl.GpioPinImpl.export(GpioPinImpl.java:158)
at com.pi4j.io.gpio.impl.GpioControllerImpl.provisionPin(GpioControllerImpl.java:517)
at com.pi4j.io.gpio.impl.GpioControllerImpl.provisionDigitalOutputPin(GpioControllerImpl.java:669)
at com.pi4j.io.gpio.impl.GpioControllerImpl.provisionDigitalOutputPin(GpioControllerImpl.java:681)
at com.test.RemoteImpl.fahreVorwaerts(RemoteImpl.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
at sun.rmi.transport.Transport$1.run(Transport.java:178)
at sun.rmi.transport.Transport$1.run(Transport.java:175)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:174)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:557)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:812)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:671)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:744)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(Unknown Source)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(Unknown Source)
at com.sun.proxy.$Proxy0.fahreVorwaerts(Unknown Source)
at com.client.RMIClient.main(RMIClient.java:19)
package com.test;
The Code:
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import com.interf.test.TestRemote;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPin;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinDirection;
import com.pi4j.io.gpio.PinMode;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.trigger.GpioCallbackTrigger;
import com.pi4j.io.gpio.trigger.GpioPulseStateTrigger;
import com.pi4j.io.gpio.trigger.GpioSetStateTrigger;
import com.pi4j.io.gpio.trigger.GpioSyncStateTrigger;
import com.pi4j.io.gpio.event.GpioPinListener;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
import com.pi4j.io.gpio.event.PinEventType;
public class RemoteImpl extends UnicastRemoteObject implements TestRemote {
protected RemoteImpl() throws RemoteException {
super();
}
private static final long serialVersionUID = 1L;
#Override
public boolean isloginvalid(String username) throws RemoteException {
if (username.equals("test")) {
return true;
}
return false;
}
#Override
public void fahreVorwaerts(int dauer) throws RemoteException {
System.out.println("----- EXTCMD: VORWAERTS FAHREN "+"("+ dauer +"ms)" + "-----");
// GPIO CODE SECTION BEGINS
final GpioController gpio = GpioFactory.getInstance();
final GpioPinDigitalOutput pin_gpio01 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "MyLED", PinState.LOW);
pin_gpio01.pulse(dauer, true);
System.out.println("----- INFO: VORWAERTS FAHREN ENDE -----");
}
}
Life could have been so much easier if I'd just had a look on the GPIO numbering. There is no GPIO01!
Anyway, now it works by choosing an existing GPIO. Cheers :-)
Raspberry pi 3 B GPIO
pi4j; GPIO Input Error? "Unable to open GPIO edge interface for pin ??: No such file or directory"
-Solution-
Coding; gpio.setShutdownOptions(true) instead of myButton.setShutdownoptions(true) or gpio.shutdown()
Compile; Next, use the following command to compile this example program:
$ javac -classpath .:classes:/opt/pi4j/lib/'*' -d . ListenGpioExample.java
Execute the following command will run this example program:
$ sudo java -classpath .:classes:/opt/pi4j/lib/'*' ListenGpioExample
Run with sudo command
sudo java -jar yourjarname.jar

Categories

Resources