I have updated NetBeans to version 12. My Application was created in Java 8. I use now java 14. All is running but this:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
at javax.xml.bind.JAXB.unmarshal(JAXB.java:171)
I raead many posts in Google but i can’t hit a solution.
This error occurs only if i run in NetBeans app. If i compile my app and run it it works without errors.
I habe also downloaded jaxb-api-2.3.1.jar and added to library.
Edit: Alos tryed jaxb-api-2.4.0-b180830.0359.jar. No success.
But realy crasy is, if i run my app in Terminal i get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/JAXB
Only on click on myApp.jar in my current folder it runs without any error:
Has any body an idea?
What is a solution for this behavior?
Thanks in advance.
Edit:
For now i found a solution but whith this WARNING:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.sun.xml.bind.v2.runtime.reflect.opt.Injector$1 (file:/Applications/NetBeans/Apache%20NetBeans%2012.0.app/Contents/Resources/NetBeans/netbeans/ide/modules/ext/jaxb/jaxb-impl.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int)
WARNING: Please consider reporting this to the maintainers of com.sun.xml.bind.v2.runtime.reflect.opt.Injector$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
this appears if i use this JAXB 2.2.5.jar library.
Don’t work wit JAXB versions as described above.
My app runs now with 2.2.5 but how long?
Sorry but i have no idea how i can inform the developer. i.g. Sun or Marven or whoever. I true this issue is known there. But i’s bad that it isn’t fixt yet. :(
This ist my code:
package Tools;
import Enums.Property;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JOptionPane;
import static Tools.Device.Director;
import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Device {
#Override
public String toString() {
return DeviceName;
}
/**
*
*/
public static final String Separator = FileHandler.getFileSeparator();
public static File Director = new File(Property.datarefBaseFile.getValue().substring(0, Property.datarefBaseFile.getValue().lastIndexOf(Separator)) + Separator + "Devices" + Separator);
#XmlElement
public String DeviceName;
#XmlElement
public String DevicePosX;
#XmlElement
public String DevicePosY;
#XmlElement
public String DeviceWidth;
#XmlElement
public String DeviceHeight;
#XmlElement
public String DeviceBackgroundImage;
#XmlElement
public String DeviceScaleX;
#XmlElement
public String DeviceScaleY;
public List<ControlProps> controlsProps;
public static Device load(String file) {
return JAXB.unmarshal(new File(Director, file), Device.class);
}
public static File getDirector() {
return Director;
}
public void save() {
Director.mkdir();
File file = new File(Director, DeviceName + ".xml");
File fileback = new File(Director, DeviceName + ".bak");
if (fileback.exists()) {
fileback.delete();
System.out.println(String.format("Device %s old deleted! %s", fileback, Utils.ShowTime()));
}
file.renameTo(fileback);
if (fileback.exists()) {
System.out.println(String.format("Device %s new created! %s", fileback, Utils.ShowTime()));
}
if (!file.exists()) {
JAXB.marshal(this, file);
String msg = String.format("Device %s saved! %s", file, Utils.ShowTime());
System.out.println(msg);
}
if (!file.exists()) {
String msg = String.format("Fatal error: %s was deleted an not created new!\nDevice crashed.\nRestore from %s file. %s", file, fileback, Utils.ShowTime());
System.out.println(msg);
MsgBox.error(msg);
}
if (!fileback.exists()) {
String msg = String.format("Warning! Backupfile: %s was not created yet! %s", fileback, Utils.ShowTime());
System.out.println(msg);
MsgBox.error(msg);
}
// JOptionPane.showMessageDialog(null, msg);
// LogFile.log(Level.INFO, new String[] {file.toString() + " saved"});
}
public int delete() {
File fileBak = new File(Director, DeviceName + ".creater.bak");
File file = new File(Director, DeviceName + ".xml");
int response = 0;
String msg = String.format("Delete this device: %s?", DeviceName);
response = JOptionPane.showConfirmDialog(null, msg, "Confirm",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.YES_OPTION && file.exists()) {
file.renameTo(fileBak);
file.delete();
msg = String.format("File: %s deleted\nBackupfile %s was created!", file, fileBak);
JOptionPane.showMessageDialog(null, msg);
} else {
msg = String.format("%s not deleted file: %s", DeviceName, file);
JOptionPane.showMessageDialog(null, msg);
}
return response;
}
public Device() {
controlsProps = new LinkedList<>();
}
public ControlProps find(String name) {
for (ControlProps prop : controlsProps) {
if (prop.ControlName.equals(name)) {
return prop;
}
}
throw new IllegalArgumentException("ControlName not found");
}
public void deleteControl(ControlProps controlProps) {
String name = controlProps.ControlName;
if (controlsProps.remove(controlProps)) {
save();
System.out.println(name + " deleted");
//LogFile.log(Level.INFO, new String[]{name + " deleted"});
}
}
}
I am trying to migrate credentials from Jenkins to another credentials store.
I want to read the credentials from the Jenkins store, and have found this script (https://github.com/tkrzeminski/jenkins-groovy-scripts/blob/master/show-all-credentials.groovy
The script does the job OK for SystemCredentialsProvider credentials for the global domain at root level.
But my credentials are stored in a Folder, so the script does not work for me.
I am using the Jenkins script console to execute the script.
If I navigate to the Jenkins Credentials configuration page and hover over the icon for one of my credential entries, the tooltip says "Folder Credentials Provider".
====================================================
Question: How do I read all of the the credentials from a Folder in Jenkins?
====================================================
Please see script, below:
import jenkins.model.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl
import org.jenkinsci.plugins.plaincredentials.StringCredentials
import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl
def showRow = { credentialType, secretId, username = null, password = null, description = null ->
println("${credentialType} : ".padLeft(20) + secretId?.padRight(38)+" | " +username?.padRight(20)+" | " +password?.padRight(40) + " | " +description)
}
// set Credentials domain name (null means is it global)
domainName = null
credentialsStore = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0]?.getStore()
domain = new Domain(domainName, null, Collections.<DomainSpecification>emptyList())
credentialsStore?.getCredentials(domain).each{
if(it instanceof UsernamePasswordCredentialsImpl)
showRow("user/password", it.id, it.username, it.password?.getPlainText(), it.description)
else if(it instanceof BasicSSHUserPrivateKey)
showRow("ssh priv key", it.id, it.passphrase?.getPlainText(), it.privateKeySource?.getPrivateKey(), it.description)
else if(it instanceof AWSCredentialsImpl)
showRow("aws", it.id, it.accessKey, it.secretKey?.getPlainText(), it.description)
else if(it instanceof StringCredentials)
showRow("secret text", it.id, it.secret?.getPlainText(), '', it.description)
else if(it instanceof FileCredentialsImpl)
showRow("secret file", it.id, it.content?.text, '', it.description)
else
showRow("something else", it.id, '', '', '')
}
return
i simply created a Java class to retrieve the credentials from either global or folder scope:
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.hudson.plugins.folder.Folder
class JenkinsCredentials
{
/**
* this method gets a 'StandardUsernamePasswordCredentials' for a userName, the 'StandardUsernamePasswordCredentials' object
* have 2 fields - user and password, which can be used to login to other systems,
* the username is searched for first in the global jenkins level, and if not found then it is searched at the folder level
*/
public static StandardUsernamePasswordCredentials getCredentialsByUsername(String userName, String fromFolder) throws Exception
{
List credsList = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, Jenkins.getInstance());
if(credsList == null || credsList.size() == 0)
{
credsList = getFolderLevelCredentialsList(fromFolder);
}
return credsList.findResult { it.username == userName ? it : null };
}
/**
* this method gets a 'StandardUsernamePasswordCredentials' for a userID, the 'StandardUsernamePasswordCredentials' object
* have 2 fields - user and password, which can be used to login to other systems,
* the userID is searched for first in the global jenkins level, and if not found then it is searched at the folder level
*/
public static StandardUsernamePasswordCredentials getCredentialsByID(String userID, String fromFolder) throws Exception
{
List credsList = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, Jenkins.getInstance());
if(credsList == null || credsList.size() == 0)
{
credsList = getFolderLevelCredentialsList(fromFolder);
}
return credsList.findResult { it.id == userID ? it : null };
}
/**
* this method gets a 'StandardUsernamePasswordCredentials' for a userName, the 'StandardUsernamePasswordCredentials' object
* have 2 fields - user and password, which can be used to login to other systems,
* the username is searched for at the folder level who's name we provided as 'fromFolder'
*/
public static StandardUsernamePasswordCredentials getFolderCredentialsByUsername(String userName, String fromFolder) throws Exception
{
List credsList = getFolderLevelCredentialsList(fromFolder);
return credsList.findResult { it.username == userName ? it : null };
}
/**
* this method gets a 'StandardUsernamePasswordCredentials' for a userID, the 'StandardUsernamePasswordCredentials' object
* have 2 fields - user and password, which can be used to login to other systems,
* the userID is searched for at the folder level who's name we provided as 'fromFolder'
*/
public static StandardUsernamePasswordCredentials getFolderCredentialsByID(String userID, String fromFolder) throws Exception
{
List credsList = getFolderLevelCredentialsList(fromFolder);
return credsList.findResult { it.id == userID ? it : null };
}
/**
* this method gets a list of credentials set at a folder level, the method receives the folder name to get the credentials from
*/
public static List getFolderLevelCredentialsList(String folderName)
{
return CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, getFolderItem(folderName));
}
/**
* this method fetch a 'Folder' item from jenkins instance by a folder name
* it then can be used in the other methods to search for a user credentials at that folder level
*/
public static Folder getFolderItem(String folderName)
{
def allJenkinsItems = Jenkins.getInstance().getItems();
for (currentJenkinsItem in allJenkinsItems)
{
if(currentJenkinsItem instanceof Folder)
{
if(((Folder)currentJenkinsItem).getFullName().contains(folderName))
{
return (Folder)currentJenkinsItem;
}
}
}
}
}
then you can use it like this:
get credentials for userName 'shay bc' from folder named 'MyJenkinsFolder':
// get the credentials
StandardUsernamePasswordCredentials shaybcCredentials = JenkinsCredentials.getFolderCredentialsByUsername("shay bc", "MyJenkinsFolder")
// login to some system using the credentials
sshSession.login(shaybcCredentials.getUsername(), shaybcCredentials.getPassword())
get credentials for userID 'sbc' from folder named 'MyJenkinsFolder':
// get the credentials
StandardUsernamePasswordCredentials sbcCredentials = JenkinsCredentials.getFolderCredentialsByID("sbc", "MyJenkinsFolder")
// login to some system using the credentials
sshSession.login(sbcCredentials.getUsername(), sbcCredentials.getPassword())
The class shared by #Shaybc was most of the solution, and although a commenter suggested it was not a complete solution by itself, I was able to guess how to implement it correctly into such a complete solution in my own Groovy script.
The Folder returned by JenkinsCredentials.getFolderItem('foldername') is taking the same string slug as your folder is addressed by in Jenkins. So if you have a folder with a descriptive name, and a slug, like "Folder Name" and "foldername", the right string to use to retrieve the folder itself is "foldername".
The example provided here shows how to retrieve credentials from the global store, this is Jenkins.instance – for complete documentation the script they provide is copied here:
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
def jenkinsCredentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.Credentials.class,
Jenkins.instance,
null,
null
);
for (creds in jenkinsCredentials) {
println(jenkinsCredentials.id)
}
So, start your script by defining class JenkinsCredentials as #Shaybc described, then instead of calling CredentialsProvider.lookupCredentials with Jenkins.instance, retrieve the folder and pass it in there instead.
My folder was called "ft" and (skipping over the import/boilerplate at the top and the definition of JenkinsCredentials helper class,) the remainder of my invocation in the Groovy script looked like:
def folder = JenkinsCredentials.getFolderItem('ft');
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.Credentials.class,
folder,
null,
null
);
for (c in creds) {
println(c.id + ": " + c.description)
}
Hope this helped someone! and by the way, if your credentials are stored in a file instead of a string, you have one more step... the file will not have any useful content in the "description" attribute, you need the byte stream stored at c.getContent()
So, that final loop with some metaprogramming to dynamically check for the availability of a getContent() method to call:
for (c in creds) {
if (c.metaClass.respondsTo(c, 'getContent')) {
println(
IOUtils.toString(c.getContent(), StandardCharsets.UTF_8)
)
}
println(c.id + ": " + c.description)
}
That last part was borrowed from this answer, which shows as well how you can import StandardCharsets and IOUtils: https://stackoverflow.com/a/42360792/661659
Just to add to this really awesome class from #Shaybc... If you're like me and have nested folders, you'll want to change up the Class method getFolderItem to recurse into all of the "sub-folders"... Otherwise you'll only ever get a return/hit on the top-level (root) Jenkins items.
Here's what that looks like, replacing the getFolderItem method and adding a getFolderItemRecursively method to do the work.
private static Folder getFolderItemRecursively(Folder folder, String folderName) {
for (nestedItem in folder.getItems()) {
if (nestedItem instanceof Folder) {
if(nestedItem.getFullName().contains(folderName)) {
return nestedItem;
} else {
def recurse = getFolderItemRecursively(nestedItem, folderName);
if (recurse instanceof Folder) {
return recurse;
}
}
}
}
}
public static Folder getFolderItem(String folderName)
{
for (item in Jenkins.getInstance().getItems())
{
if(item instanceof Folder)
{
if(item.getFullName().contains(folderName))
{
return item;
} else {
def recurse = getFolderItemRecursively(item, folderName);
if (recurse instanceof Folder) {
return recurse;
}
}
}
}
}
import jenkins.model.*
import hudson.model.ModelObject
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl
import org.jenkinsci.plugins.plaincredentials.StringCredentials
import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl
import com.cloudbees.hudson.plugins.folder.Folder
class DeepCredentialsPrinter {
private static final boolean DEBUG = false;
private final out;
private final Set<CredentialsStore> visitedStores = new HashSet<>();
DeepCredentialsPrinter(out) {
this.out = out;
}
private void start() {
process(Jenkins.getInstance())
}
private void process(ItemGroup group) {
printCreds(group);
List<ItemGroup> items = group.getItems();
if (items == null || items.isEmpty()) {
return;
}
for (item in items) {
if (item instanceof ItemGroup) {
process(item);
} else if (item instanceof Item) {
printCreds(item)
} else {
if (DEBUG) {
out.println("[DEBUG] unsupported item type: " + item.getClass().getCanonicalName());
}
}
}
}
private void printCreds(ModelObject model) {
for (store in CredentialsProvider.lookupStores(model)) {
if (visitedStores.add(store)) { // only visit new stores
print(model.getFullName(), store.getCredentials(Domain.global()));
}
}
}
private void print(String fullname, List<Credentials> creds) {
if (creds.isEmpty()) {
if (DEBUG) {
out.println("[DEBUG] No credentials in /" + fullname);
}
} else {
for (c in creds) {
out.println("Folder: /" + fullname)
out.println(" id: " + c.id)
if (c.properties.description) {
out.println(" description: " + c.description)
}
if (c.properties.username) {
out.println(" username: " + c.username)
}
if (c.properties.password) {
out.println(" password: " + c.password)
}
if (c.properties.passphrase) {
out.println(" passphrase: " + c.passphrase)
}
if (c.properties.secret) {
out.println(" secret: " + c.secret)
}
if (c.properties.secretBytes) {
out.println(" secretBytes: ")
out.println("\n" + new String(c.secretBytes.getPlainData()))
}
if (c.properties.privateKeySource) {
out.println(" privateKey: " + c.getPrivateKey())
}
if (c.properties.apiToken) {
out.println(" apiToken: " + c.apiToken)
}
if (c.properties.token) {
out.println(" token: " + c.token)
}
out.println("")
}
}
}
}
new DeepCredentialsPrinter(getBinding().out).start();
From all the above comments, Here is the code to list all the folder level credentials which prints all properties based on type of credential
Somewhat related to the original ask, I needed to do the inventory of all credentials stored in Jenkins. None of the answers so far have provided a solution that works out-of-the-box to dump all Jenkins credentials...
Based on the elements of answers provided by #TimWelch and #Kingdon, I wrote the following groovy (admin) script, which prints all credentials IDs and their type starting from the root folder to the deepest folders (recursive), while also avoiding printing duplicates:
import jenkins.model.*
import hudson.model.ModelObject
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl
import org.jenkinsci.plugins.plaincredentials.StringCredentials
import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl
import com.cloudbees.hudson.plugins.folder.Folder
class DeepCredentialsPrinter {
private static final boolean DEBUG = false;
private final out;
private final Set<CredentialsStore> visitedStores = new HashSet<>();
DeepCredentialsPrinter(out) {
this.out = out;
}
private void start() {
out.println("Folder,Credentials Type,Credentials ID") // header
process(Jenkins.getInstance())
}
private void process(ItemGroup group) {
printCreds(group);
List<ItemGroup> items = group.getItems();
if (items == null || items.isEmpty()) {
return;
}
for (item in items) {
if (item instanceof ItemGroup) {
process(item);
} else if (item instanceof Item) {
printCreds(item)
} else {
if (DEBUG) {
out.println("[DEBUG] unsupported item type: " + item.getClass().getCanonicalName());
}
}
}
}
private void printCreds(ModelObject model) {
for (store in CredentialsProvider.lookupStores(model)) {
if (visitedStores.add(store)) { // only visit new stores
print(model.getFullName(), store.getCredentials(Domain.global()));
}
}
}
private void print(String fullname, List<Credentials> creds) {
if (creds.isEmpty()) {
if (DEBUG) {
out.println("[DEBUG] No credentials in /" + fullname);
}
} else {
for (c in creds) {
out.printf("/%s,%s,%s\n", fullname, c.getClass().getSimpleName(), c.id)
}
}
}
}
new DeepCredentialsPrinter(getBinding().out).start();
gist: https://gist.github.com/fabienrenaud/349764873855533abc71b7fadafdf29e
The printCreds method can easily be extended to print more data for each secret type.
Trying to code a Minecraft Plugin and when I run the /fakeop in game I get an external error. The /fakeop (playername) works though
public class CortexTroll extends JavaPlugin {
#Override
public void onEnable() {}
#Override
public void onDisable() {}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("fakeop")) {
Player player = (Player) sender;
Player target = Bukkit.getServer().getPlayer(args[0]);
if (args.length == 0) {
player.sendMessage("Specify a player to Op. /fakeop <target>");
return true;
}
player.sendMessage("Fake Opped " + args[0]);
Bukkit.broadcastMessage(ChatColor.GRAY + "[" + player.getName() + ": Opped " + args[0] + "]");
target.sendMessage(ChatColor.YELLOW + "You are now op!");
}
return true;
}
}
Error:
Illuminatiiiiii issued server command: /fakeop [21:33:10 ERROR]: null
org.bukkit.command.CommandException: Unhandled exception executing
command 'fakeop' in plugin CortexTroll v1.0
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46)
~[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141)
~[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at org.bukkit.craftbukkit.v1_10_R1.CraftServer.dispatchCommand(CraftServer.java:646)
~[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at net.minecraft.server.v1_10_R1.PlayerConnection.handleCommand(PlayerConnection.java:1351)
[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at net.minecraft.server.v1_10_R1.PlayerConnection.a(PlayerConnection.java:1186)
[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at net.minecraft.server.v1_10_R1.PacketPlayInChat.a(PacketPlayInChat.java:45)
[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at net.minecraft.server.v1_10_R1.PacketPlayInChat.a(PacketPlayInChat.java:1)
[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at net.minecraft.server.v1_10_R1.PlayerConnectionUtils$1.run(SourceFile:13)
[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_91]
at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_91]
at net.minecraft.server.v1_10_R1.SystemUtils.a(SourceFile:45) [spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at net.minecraft.server.v1_10_R1.MinecraftServer.D(MinecraftServer.java:733)
[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at net.minecraft.server.v1_10_R1.DedicatedServer.D(DedicatedServer.java:399)
[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at net.minecraft.server.v1_10_R1.MinecraftServer.C(MinecraftServer.java:672)
[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at net.minecraft.server.v1_10_R1.MinecraftServer.run(MinecraftServer.java:571)
[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_91] Caused by: java.lang.ArrayIndexOutOfBoundsException: 0
at us.thecortex.cortextroll.CortexTroll.onCommand(CortexTroll.java:29)
~[?:?]
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44)
~[spigot-1.10.2.jar:git-Spigot-5391d73-00359a1]
Because im not allowed to comment jet, here is what you could try: Move the line below after the if-statement that checks if args.length is 0
public Class CortexTroll extends JavaPlugin{
#Override
public void onEnable() {}
#Override
public void onDisable() {}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("fakeop")) {
Player player = (Player) sender;
if (args.length == 0) {
player.sendMessage("Specify a player to Op. /fakeop <target>");
return true;
}
Player target = Bukkit.getServer().getPlayer(args[0]); // Is now below the if-statement
player.sendMessage("Fake Opped " + args[0]);
Bukkit.broadcastMessage(ChatColor.GRAY + "[" + player.getName() + ": Opped " + args[0] + "]");
target.sendMessage(ChatColor.YELLOW + "You are now op!");
}
return true;
}
}
Why should this fix the error?
If you execute /fakeop without any argument, args has the length of 0. If you try to access the args[0], you get a ArrayIndexOutOfBoundsException because it wants a Array with length 1.
EDIT: Thanks for pointing out that it isn't a NullPointer.
Just wanted to try Cassandra Java driver from eclipse and copied a sample code from "Practical Cassandra"
But faced error below output by eclipse:
Exception in thread "main" java.lang.NoClassDefFoundError: io/netty/util/Timer
at com.datastax.driver.core.Configuration$Builder.build(Configuration.java:294)
at com.datastax.driver.core.Cluster$Builder.getConfiguration(Cluster.java:1247)
at com.datastax.driver.core.Cluster.<init>(Cluster.java:116)
at com.datastax.driver.core.Cluster.buildFrom(Cluster.java:181)
at com.datastax.driver.core.Cluster$Builder.build(Cluster.java:1264)
at SampleApp.connect(SampleApp.java:13)
at SampleApp.main(SampleApp.java:64)
Caused by: java.lang.ClassNotFoundException: io.netty.util.Timer
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 7 more
here is the sample code:
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
public class SampleApp {
private Cluster cluster;
private Session session;
public void connect(String node) {
cluster = Cluster.builder().addContactPoint(node).build();
Metadata metadata = cluster.getMetadata();
System.out.printf("Cluster: %s\n", metadata.getClusterName());
for ( Host host : metadata.getAllHosts() ) {
System.out.printf("Host: %s \n",host.getAddress());
}
session = cluster.connect();
}
public void close(){
cluster.close();
}
public void createSchema(){
session.execute("CREATE KEYSPACE IF NOT EXISTS portfolio_demo " +
"WITH REPLICATION 5 { ‘class’: ‘SimpleStrategy’, " +
"'replication_factor’: 1 };");
session.execute("CREATE TABLE IF NOT EXISTS portfolio_demo.portfolio (" +
"portfolio_id UUID, ticker TEXT, " +
"current_price DECIMAL, current_change DECIMAL, " +
"current_change_percent FLOAT, " +
"PRIMARY KEY(portfolio_id, ticker));");
}
public void loadData(){
session.execute("INSERT INTO portfolio_demo.portfolio " +
"(portfolio_id, ticker, current_price, " +
" current_change, current_change_percent) VALUES " +
"(756716f7-2e54-4715-9f00-91dcbea6cf50, ‘GOOG’, " +
" 889.07, -4.00, -0.45);");
session.execute("INSERT INTO portfolio_demo.portfolio " +
"(portfolio_id, ticker, current_price, " +
" current_change, current_change_percent) VALUES " +
"(756716f7-2e54-4715-9f00-91dcbea6cf50, ‘AMZN’, " +
" 297.92, -0.94, -0.31);");
}
public void printResults(){
ResultSet results = session.execute("SELECT * FROM " +
"portfolio_demo.portfolio WHERE portfolio_id 5 " +
"756716f7-2e54-4715-9f00-91dcbea6cf50;");
for (Row row : results) {
System.out.println(String.format("%-7s\t%-7s\t%-7s\t%-7s \n%s",
"Ticker", "Price", "Change", "PCT",
"........1........1........1........"));
System.out.println(String.format("%-7s\t%0.2f\t%0.2f\t%0.2f",
row.getString("ticker"),
row.getDecimal("current_price"),
row.getDecimal("current_change"),
row.getFloat("current_change_percent") ));
}
}
public static void main(String[] args) {
SampleApp client = new SampleApp();
client.connect("127.0.0.1");
client.createSchema();
client.loadData();
client.printResults();
client.close();
}
}
And I also added several external JARs which are downloaded or comes with eclipse:
cassandra-driver-core-3.0.0.jar
guava-18.0.jar
netty-3.10.6.Final-20160303.120156-121.jar
org.apache.log4j_1.2.15.v201012070815.jar (from eclipse plugin)
org.slf4j.api_1.7.2.v20121108-1250.jar (from eclipse plugin)
org.slf4j.impl.log4j12_1.7.2.v20131105-2200.jar (from eclipse plugin)
I saw the same questions about the netty error but still could not figure out what was wrong with my code.
Thanks a lot.
This is the wrong Netty version. Version 3.0.0 of the driver uses 4.0.33.
You can view the driver's dependencies in the POM. The properties such as ${netty.version} are defined in the parent POM.
I want to send a sms using a usb modem through my java application. I tried smslib and i couldn't do my task.
I tried using following code..
I did the external configurations as mentioned also..
So can u please help me on using smslib ina 64bit machine.
package sms;
import org.smslib.AGateway;
import org.smslib.IOutboundMessageNotification;
import org.smslib.Library;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.modem.SerialModemGateway;
public class Sms{
public void doIt() throws Exception
{
OutboundNotification outboundNotification = new OutboundNotification();
System.out.println("Example: Send message from a serial gsm modem.");
System.out.println(Library.getLibraryDescription());
System.out.println("Version: " + Library.getLibraryVersion());
SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM39", 115200, "Huawei", "");
gateway.setInbound(true);
gateway.setOutbound(true);
gateway.setSimPin("0000");
gateway.setSmscNumber("+947100003");
Service.getInstance().setOutboundMessageNotification(outboundNotification);
Service.getInstance().addGateway(gateway);
Service.getInstance().startService();
System.out.println();
System.out.println("Modem Information:");
System.out.println(" Manufacturer: " + gateway.getManufacturer());
System.out.println(" Model: " + gateway.getModel());
System.out.println(" Serial No: " + gateway.getSerialNo());
System.out.println(" SIM IMSI: " + gateway.getImsi());
System.out.println(" Signal Level: " + gateway.getSignalLevel() + " dBm");
System.out.println(" Battery Level: " + gateway.getBatteryLevel() + "%");
System.out.println();
// Send a message synchronously.
OutboundMessage msg = new OutboundMessage("+94755466860", "Hello from SMSLib!");
Service.getInstance().sendMessage(msg);
System.out.println(msg);
System.out.println("Now Sleeping - Hit <enter> to terminate.");
System.in.read();
Service.getInstance().stopService();
}
public class OutboundNotification implements IOutboundMessageNotification{
public void process(AGateway gateway, OutboundMessage msg){
System.out.println("Outbound handler called from Gateway: " + gateway.getGatewayId());
System.out.println(msg);
}
}
public static void main(String args[]){
Sms app = new Sms();
try{
app.doIt();
}
catch (Exception e){
e.printStackTrace();
}
}
}
I get the following error
log4j:WARN No appenders could be found for logger (smslib).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "Thread-3" java.lang.ExceptionInInitializerError
at org.smslib.modem.SerialModemDriver.connectPort(SerialModemDriver.java:69)
at org.smslib.modem.AModemDriver.connect(AModemDriver.java:114)
at org.smslib.modem.ModemGateway.startGateway(ModemGateway.java:189)
at org.smslib.Service$1Starter.run(Service.java:277)
Caused by: java.lang.RuntimeException: CommPortIdentifier class not found
at org.smslib.helper.CommPortIdentifier.<clinit>(CommPortIdentifier.java:76)
... 4 more