I've been sitting here since 3 days now. Trying to figure out what's wrong with my code.
I have tried multiple solutions and tried to research my problem on multiple platforms. Nothing helped.
I always get a long error message in the console:
[JDA MainWS-ReadThread] ERROR JDA - One of the EventListeners had an uncaught exception
java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at java.base/java.util.Collections$UnmodifiableList.get(Collections.java:1347)
at de.ayahuascasuppe.commands.Kick.onMessageReceived(Kick.java:31)
at net.dv8tion.jda.api.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:358)
at net.dv8tion.jda.api.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:96)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handleInternally(EventManagerProxy.java:88)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handle(EventManagerProxy.java:70)
at net.dv8tion.jda.internal.JDAImpl.handleEvent(JDAImpl.java:163)
at net.dv8tion.jda.internal.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:111)
at net.dv8tion.jda.internal.handle.SocketHandler.handle(SocketHandler.java:36)
at net.dv8tion.jda.internal.requests.WebSocketClient.onDispatch(WebSocketClient.java:953)
at net.dv8tion.jda.internal.requests.WebSocketClient.onEvent(WebSocketClient.java:840)
at net.dv8tion.jda.internal.requests.WebSocketClient.handleEvent(WebSocketClient.java:818)
at net.dv8tion.jda.internal.requests.WebSocketClient.onBinaryMessage(WebSocketClient.java:992)
at com.neovisionaries.ws.client.ListenerManager.callOnBinaryMessage(ListenerManager.java:385)
at com.neovisionaries.ws.client.ReadingThread.callOnBinaryMessage(ReadingThread.java:276)
at com.neovisionaries.ws.client.ReadingThread.handleBinaryFrame(ReadingThread.java:996)
at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:755)
at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:108)
at com.neovisionaries.ws.client.ReadingThread.runMain(ReadingThread.java:64)
at com.neovisionaries.ws.client.WebSocketThread.run(WebSocketThread.java:45)
[JDA MainWS-ReadThread] ERROR JDA - One of the EventListeners had an uncaught exception
java.lang.IllegalStateException: This message event did not happen in a guild
at net.dv8tion.jda.api.events.message.GenericMessageEvent.getGuild(GenericMessageEvent.java:154)
at de.ayahuascasuppe.commands.Kick.onMessageReceived(Kick.java:30)
at net.dv8tion.jda.api.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:358)
at net.dv8tion.jda.api.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:96)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handleInternally(EventManagerProxy.java:88)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handle(EventManagerProxy.java:70)
at net.dv8tion.jda.internal.JDAImpl.handleEvent(JDAImpl.java:163)
at net.dv8tion.jda.internal.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:111)
at net.dv8tion.jda.internal.handle.SocketHandler.handle(SocketHandler.java:36)
at net.dv8tion.jda.internal.requests.WebSocketClient.onDispatch(WebSocketClient.java:953)
at net.dv8tion.jda.internal.requests.WebSocketClient.onEvent(WebSocketClient.java:840)
at net.dv8tion.jda.internal.requests.WebSocketClient.handleEvent(WebSocketClient.java:818)
at net.dv8tion.jda.internal.requests.WebSocketClient.onBinaryMessage(WebSocketClient.java:992)
at com.neovisionaries.ws.client.ListenerManager.callOnBinaryMessage(ListenerManager.java:385)
at com.neovisionaries.ws.client.ReadingThread.callOnBinaryMessage(ReadingThread.java:276)
at com.neovisionaries.ws.client.ReadingThread.handleBinaryFrame(ReadingThread.java:996)
at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:755)
at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:108)
at com.neovisionaries.ws.client.ReadingThread.runMain(ReadingThread.java:64)
at com.neovisionaries.ws.client.WebSocketThread.run(WebSocketThread.java:45)
So I tried creating a new class. with exact the same code I had, and at the beginning it worked, especially these lines of code worked, which didn't work prior:
if (!author.hasPermission(Permission.KICK_MEMBERS)) {
channel.sendMessage("**ERROR**: You don't have permission to kick people!").queue();
return;
}
if (event.getMessage().getMentionedMembers().isEmpty()) {
channel.sendMessage("**ERROR**: You must mention who you want to be kicked").queue();
return;
}
if (args.length < 2) {
channel.sendMessage("**ERROR**: Correct usage: `" + Main.prefix + "kick <#User> <reason>").queue();
return;
}
Now I added a few things here and there, and then It just stopped working again. I deleted everything I added to the code to the point where the code was working, and it still didn't worked.
at de.ayahuascasuppe.commands.Kick.onMessageReceived(Kick.java:31)
refers to:
mentioned = event.getMessage().getMentionedMembers().get(0);
Here my full code:
Prefix = "u!"
logChannel = "984832326947197008"
package de.ayahuascasuppe.commands;
import java.awt.Color;
import java.time.OffsetDateTime;
import java.util.Random;
import de.ayahuascasupe.de.main.Main;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.entities.PrivateChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class Kick extends ListenerAdapter {
protected Member mentioned;
Random randNum = new Random();
public void onMessageReceived(MessageReceivedEvent event) {
String[] args = event.getMessage().getContentStripped().split(" ");
String authorName = event.getAuthor().getName();
String authorAvatar = event.getAuthor().getAvatarUrl();
String message = event.getMessage().getContentStripped();
MessageChannel channel = event.getChannel();
Member author = event.getMessage().getMember();
Guild guild = event.getGuild();
mentioned = event.getMessage().getMentions().getMembers().get(0);
// add code here:
if (message.startsWith(Main.prefix + "kick")) {
if (!author.hasPermission(Permission.KICK_MEMBERS)) {
channel.sendMessage("**ERROR**: You don't have permission to kick people!").queue();
return;
}
if (event.getMessage().getMentions().getMembers().isEmpty()) {
channel.sendMessage("**ERROR**: You must mention who you want to be kicked").queue();
return;
}
if (args.length < 2) {
channel.sendMessage("**ERROR**: Correct usage: `" + Main.prefix + "kick <#User> <reason>").queue();
return;
}
// event.getGuild().kick(event.getMentionedMembers().get(0).getId(),
// reason).queue();
channel.sendMessage(
"**SUCCESS**: You have kicked " + mentioned.getAsMention() + " from the Discord server.").queue();
EmbedBuilder embed = new EmbedBuilder();
embed.setTitle(event.getAuthor().getName() + " kicked " + mentioned.getEffectiveName(), null);
embed.setDescription("**Action**: Kick\n\nUser " + mentioned.getAsMention() + " got kicked by "
+ event.getAuthor().getAsMention() + " from the Discord server.\n\nReason: " + "reason");
embed.setThumbnail(event.getGuild().getIconUrl());
embed.setAuthor(authorName, null, authorAvatar);
embed.setColor(Color.RED);
embed.setFooter(Main.embedFooter);
embed.setTimestamp(OffsetDateTime.now());
event.getGuild().getTextChannelById(Main.logChannel).sendMessageEmbeds(embed.build()).queue();
embed.clear();
PrivateChannel dm = mentioned.getUser().openPrivateChannel().complete();
EmbedBuilder embedDM = new EmbedBuilder();
embedDM.setTitle("You got kicked from the Discord server.", null);
embedDM.setDescription("Hello buddy. It seems like you got kicked from the " + guild.getName()
+ " Discord.\nDon't worry. You are not banned. You can use the invite link to join the Discord again.\n\nReason for the kick: "
+ "reason");
embedDM.setThumbnail(event.getGuild().getIconUrl());
embedDM.setColor(Color.RED);
embedDM.setFooter(Main.embedFooter);
embedDM.setTimestamp(OffsetDateTime.now());
dm.sendMessageEmbeds(embedDM.build()).queue();
embedDM.clear();
}
}
}
Information:
JavaSE-17
JDA Version: 5.0.0-alpha.4
The problem not with kick command, the problem is that in your event there's no any mentioned members in the message.
mentioned = event.getMessage().getMentionedMembers().get(0);
Try to use a debugger to see what the event you receive from JDA. Probably, you receive another kind of event (not the new message one), or you don't mention anybody, like it doing by in Discord - #user.
Also, do not share your access tokens on public resources, like Stackoverflow, even if it was revoked :)
Reading the exception tells you the problem
java.lang.IllegalStateException: This message event did not happen in a guild
This means you got a message event for a direct message, which means you cannot get member mentions from it.
Related
I would like to understand why a variable of type com.ibm.jms.JMSTextMessage is printed with truncated content and ellipses (...) when converted to string.
I have this code in a JSR223 Sampler in JMeter:
import com.ibm.msg.client.jms.JmsConnectionFactory
import com.ibm.msg.client.jms.JmsFactoryFactory
import com.ibm.msg.client.wmq.WMQConstants
import javax.jms.Session
import javax.jms.TextMessage
def hostName = "127.0.0.1"
def hostPort = 1414
def channelName = "DEV.APP.SVRCONN"
def queueManagerName = "QM1"
def queueName = "DEV.QUEUE.1"
def ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER)
def cf = ff.createConnectionFactory()
cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, hostName)
cf.setIntProperty(WMQConstants.WMQ_PORT, hostPort)
cf.setStringProperty(WMQConstants.WMQ_CHANNEL, channelName)
cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT)
def connInboundQueue = cf.createConnection("user", "password")
def sessInboundQueue = connInboundQueue.createSession(false, Session.AUTO_ACKNOWLEDGE)
def payload = "AAA:+.? '\n" +
"ABC+ABCD:1+ABCDEFG:ZZ+ABCDEF:ZZ+123456:2042+12345678901++ABCD'\n" +
"DEF+ABCD+LH+FVKJUB+20000:2042+Y1234567+UN+D:21B'\n" +
"GHI+1+ABCD:D:11A:AA:ABCD+ABCD12345678901123ABC123456'\n" +
"JKL+745'\n" +
"HHH+TN:IIAA891011213531235BNM422244:::001'\n" +
"CCC+NT+++ABCDEFGHIJKLMNOPQRS'\n" +
"STU+00123456789012:UF+0000000000:GY'\n" +
"VXY+50+MI1234+++MI'\n" +
"AAA+235+ABC'\n" +
"BBB+200:3202062000:301'\n" +
"FFF+90+USA'\n" +
"BBB+232:2101051135:201'\n" +
"CCC+FF+++AaBaBa001:TEST1'\n" +
"DDD+3++G'\n" +
"EEE+329:711013'\n" +
"FFF+178+XXX'\n" +
"FFF+179+YYY'\n" +
"GGG+2+ZZZ'\n" +
"HHH+BXG:ABCDEF'\n" +
"HHH+ABC:12AB3E01234E8UD8'\n" +
"III+P:110:111+100000001'\n" +
"EEE+36:281105'\n" +
"FFF+91+ASD'\n" +
"VVV+50:2'\n" +
"XXX+0011+1'\n" +
"YYY+1+U0123456'\n" +
"ZZZ+1+U1234560002'\n"
TextMessage msg = sessInboundQueue.createTextMessage()
msg.setText(payload)
log.info(msg.toString())
log.info(msg.getClass().toString())
log.info(msg.getText())
I would like to understand why log.info(msg.toString()) does not print the whole text content and show ellipses after some point (...)
If I do log.info(msg.getText()), I can see the whole text message.
Here is the print outcome in jmeter's console:
2021-10-31 22:05:25,491 INFO o.a.j.p.j.s.J.JSR223 Sampler - Producer - Inbound Queue:
JMSMessage class: jms_text
JMSType: null
JMSDeliveryMode: 2
JMSDeliveryDelay: 0
JMSDeliveryTime: 1635710725481
JMSExpiration: 0
JMSPriority: 4
JMSMessageID: ID:414d5120514d312020202020202020201f537d6101c31040
JMSTimestamp: 1635710725481
JMSCorrelationID: 1757416553
JMSDestination: queue:///DEV.QUEUE.1
JMSReplyTo: null
JMSRedelivered: false
JMSXAppID: 4.1\bin\ApacheJMeter.jar
JMSXDeliveryCount: 0
JMSXUserID: mquser1
JMS_IBM_PutApplType: 28
JMS_IBM_PutDate: 20211031
JMS_IBM_PutTime: 20052548
AAA:+.? '
ABC+ABCD:1+ABCDEFG:ZZ+ABCDEF:ZZ+123456:2042+12345678901++ABCD'
DEF+ABCD+LH+FVKJUB+20000:20 ...
2021-10-31 22:05:25,491 INFO o.a.j.p.j.s.J.JSR223 Sampler - Producer - Inbound Queue: class com.ibm.jms.JMSTextMessage
2021-10-31 22:05:25,491 INFO o.a.j.p.j.s.J.JSR223 Sampler - Producer - Inbound Queue: AAA:+.? '
ABC+ABCD:1+ABCDEFG:ZZ+ABCDEF:ZZ+123456:2042+12345678901++ABCD'
DEF+ABCD+LH+FVKJUB+20000:2042+Y1234567+UN+D:21B'
GHI+1+ABCD:D:11A:AA:ABCD+ABCD12345678901123ABC123456'
JKL+745'
HHH+TN:IIAA891011213531235BNM422244:::001'
CCC+NT+++ABCDEFGHIJKLMNOPQRS'
STU+00123456789012:UF+0000000000:GY'
VXY+50+MI1234+++MI'
AAA+235+ABC'
BBB+200:3202062000:301'
FFF+90+USA'
BBB+232:2101051135:201'
CCC+FF+++AaBaBa001:TEST1'
DDD+3++G'
EEE+329:711013'
FFF+178+XXX'
FFF+179+YYY'
GGG+2+ZZZ'
HHH+BXG:ABCDEF'
HHH+ABC:12AB3E01234E8UD8'
III+P:110:111+100000001'
EEE+36:281105'
FFF+91+ASD'
VVV+50:2'
XXX+0011+1'
YYY+1+U0123456'
ZZZ+1+U1234560002'
According to the IBM documentation com.ibm.jms.JMSTextMessage inherits the toString() implementation from com.ibm.jms.JMSMessage and the JavaDoc for that method says:
Gets a String containing a formatted version of the message header.
My guess is that the body is cut off simply because toString() is really just meant to give you the header. However, only IBM would know for sure why it works that way. To be clear, there is no guarantee that toString() will (or should) return the entire body of the message.
If you really want to inspect the body of the text message you should invoke getText(). This method is required to return the body of the text-message according to the JMS JavaDoc as well as IBM's own JavaDoc. Both state:
Gets the String containing this message's data. The default value is null.
I'm trying to execute the following code using JDK 17.0.1. I have ensured the JDK 17 is on the class path.
Here is the code i'm executing:
import jdk.incubator.foreign.MemoryAddress;
import jdk.incubator.foreign.MemoryHandles;
import jdk.incubator.foreign.MemorySegment;
import jdk.incubator.foreign.ResourceScope;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
public class PanamaMain {
public static void main (String[] args) {
MemoryAddress address = MemorySegment.allocateNative(4, ResourceScope.newImplicitScope()).address();
VarHandle handle = MemoryHandles.varHandle(int.class, ByteOrder.nativeOrder());
int value = (int) handle.get(address); //This line throws the exception mentioned above.
System.out.println("Memory Value: " + value);
}
}
The cause of the exception is: java.lang.UnsatisfiedLinkError: 'java.lang.Object java.lang.invoke.VarHandle.get(java.lang.Object[])'
Exception Details
I saw some replies on a similar exception suggesting using the java.library.path system property but I got an error that the java.library.path is an invalid flag.
I would appreciate your help/tips on this issue! Thank you in advance for your time!
The VarHandle.get method is expecting a MemorySegment (not MemoryAddress) and offset in bytes within the segment. The layouts of standard C types are found in CLinker.C_XXX so you don't need to hardcode byte size of int as 4.
Assuming that your PATH is correct for launching JDK17 then this should work:
MemorySegment segment = MemorySegment.allocateNative(CLinker.C_INT, ResourceScope.newImplicitScope());
VarHandle handle = MemoryHandles.varHandle(int.class, ByteOrder.nativeOrder());
handle.set(segment, 0, 4567);
int value = (int)handle.get(segment, 0);
System.out.println("Memory Value: " + value + " = 0x"+Integer.toHexString(value));
Prints:
Memory Value: 4567 = 0x11d7
In JDK17 you can also use MemoryAccess to set or get values from allocated MemorySegment. , and could change to:
MemorySegment segment = MemorySegment.allocateNative(CLinker.C_INT, ResourceScope.newImplicitScope());
MemoryAccess.setInt(segment, -1234);
int value = MemoryAccess.getInt(segment);
System.out.println("Memory Value: " + value + " = 0x"+Integer.toHexString(value));
Prints
Memory Value: -1234 = 0xfffffb2e
Note that the API has changed, so the equivalent code in JDK18+ will be different.
I've been trying to add a reaction roles command to my discord bot. But strangely it isn't working properly.
But the problem is that it worked six months ago. I haven't changed anything in my code.
The code stops here: Emote emote = emotes.get(0);
My class:
package de.nameddaniel.bot.commands;
import java.util.List;
import de.nameddaniel.bot.main.LiteSQL;
import de.nameddaniel.bot.main.Utils;
import de.nameddaniel.bot.types.ServerCommand;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Emote;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.TextChannel;
public class ReactionRolesCommand implements ServerCommand {
#Override
public void performCommand(Member m, TextChannel channel, Message msg) {
//!rr channel messageid :ok: ...
String[] args = msg.getContentDisplay().split(" ");
if(m.hasPermission(Permission.MANAGE_ROLES)) {
if(args.length >= 5) {
List<TextChannel> channels = msg.getMentionedChannels();
List<Role> roles = msg.getMentionedRoles();
List<Emote> emotes = msg.getEmotes();
System.out.println("3");
TextChannel tc = msg.getMentionedChannels().get(0);
String messageIDString = args[1];
Role role = roles.get(0);
System.out.println("1");
try {
long messageID = Long.parseLong(messageIDString);
Emote emote = emotes.get(0);
tc.addReactionById(messageID, emote).queue();
System.out.println("2");
LiteSQL.onUpdate("INSERT INTO reactroles(guildid, channelid, messageid, emote, roleid) "
+ "VALUES(" + channel.getGuild().getIdLong() + ", " + tc.getIdLong() + ", "
+ messageID + ", '" + emote.getId() + "', " + role.getIdLong() + ")");
Utils.Embed("Deiner Nachricht in " + msg.getMentionedChannels() + " wurde die Reaktion " + msg.getEmotes()
+ " hinzugefĆ¼gt.", channel, "Erfolgreich!");
}
catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("ReactionCommand");
}
}
else
Utils.Embed("Bitte benutze: !rr [MessageID] #channel [Emote] #Rolle", channel, "Falscher Syntax");
System.out.println(args.length);
}
else
msg.delete().queue();
}
}
The error Code:
3
1
[JDA [0 / 1] MainWS-ReadThread] ERROR JDA - One of the EventListeners had an uncaught exception
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at java.util.Collections$UnmodifiableList.get(Unknown Source)
at de.nameddaniel.bot.commands.ReactionRolesCommand.performCommand(ReactionRolesCommand.java:40)
at de.nameddaniel.bot.main.CommandManager.perform(CommandManager.java:43)
at de.nameddaniel.bot.listener.CommandListener.onMessageReceived(CommandListener.java:25)
at net.dv8tion.jda.api.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:430)
at net.dv8tion.jda.api.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:96)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handleInternally(EventManagerProxy.java:82)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handle(EventManagerProxy.java:69)
at net.dv8tion.jda.internal.JDAImpl.handleEvent(JDAImpl.java:147)
at net.dv8tion.jda.internal.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:122)
at net.dv8tion.jda.internal.handle.SocketHandler.handle(SocketHandler.java:36)
at net.dv8tion.jda.internal.requests.WebSocketClient.onDispatch(WebSocketClient.java:948)
at net.dv8tion.jda.internal.requests.WebSocketClient.onEvent(WebSocketClient.java:835)
at net.dv8tion.jda.internal.requests.WebSocketClient.handleEvent(WebSocketClient.java:813)
at net.dv8tion.jda.internal.requests.WebSocketClient.onBinaryMessage(WebSocketClient.java:986)
at com.neovisionaries.ws.client.ListenerManager.callOnBinaryMessage(ListenerManager.java:385)
at com.neovisionaries.ws.client.ReadingThread.callOnBinaryMessage(ReadingThread.java:276)
at com.neovisionaries.ws.client.ReadingThread.handleBinaryFrame(ReadingThread.java:996)
at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:755)
at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:108)
at com.neovisionaries.ws.client.ReadingThread.runMain(ReadingThread.java:64)
at com.neovisionaries.ws.client.WebSocketThread.run(WebSocketThread.java:45)
What I could figure out is, that my List emotes is empty. But I have no idea why..
Most of the code is in German. So ask me if you need a translation.
If there is anything missing also please tell me.
Hope you can help me, Daniel :D
The mistake was, that I confounded Emote with Emoji. So it has to be an Emoji instead of an emote.
package modifiedlines;
import edu.nyu.cs.javagit.api.DotGit;
import edu.nyu.cs.javagit.api.JavaGitConfiguration;
import edu.nyu.cs.javagit.api.JavaGitException;
import edu.nyu.cs.javagit.api.WorkingTree;
import edu.nyu.cs.javagit.api.commands.GitLogResponse;
import edu.nyu.cs.javagit.api.commands.GitStatus;
import edu.nyu.cs.javagit.api.commands.GitStatusOptions;
import edu.nyu.cs.javagit.api.commands.GitStatusResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
*
* #
author aryan000
*/
public class UseGit {
private static File repositoryDirectory;
private static DotGit dotGit;
public static void main(String s[]) throws JavaGitException, IOException
{
File f = new File("C:\\Program Files\\Git\\bin\\git.exe");
if(!f.exists())
{
System.out.println("does not exist");
}
else
System.out.println("exists at " + f.getPath());
JavaGitConfiguration.setGitPath("C:\\Program Files\\Git\\bin");
System.out.println("Git version : " + JavaGitConfiguration.getGitVersion());
// repositoryDirectory = new File("/home/aryan000/Desktop/retrofit");
repositoryDirectory = new File("/home/aryan000/Desktop/changeprone/changeprone");
System.out.println("Git Repository Location : " + repositoryDirectory.getAbsolutePath());
//get the instance of the dotGit Object
dotGit = DotGit.getInstance(repositoryDirectory);
// System.out.println("checking what i have got ");
// GitLogResponse.CommitFile com ;
// com = (GitLogResponse.CommitFile) dotGit.getLog();
//
// System.out.println(com);
WorkingTree wt = dotGit.getWorkingTree();
File workingTreePath = wt.getPath();
GitStatus gitStatus = new GitStatus();
GitStatusResponse status = gitStatus.status(workingTreePath);
System.out.println("status is : " + status);
File anotherFileDir = new File("/home/aryan000/Desktop/retrofit/test.txt");
GitStatusOptions options = new GitStatusOptions();
options.setOptOnly(true);
status = gitStatus.status(workingTreePath);
System.out.println("status is : " + status);
System.out.println("----- Print log to see our commit -----");
for (GitLogResponse.Commit c : dotGit.getLog()) {
System.out.println("commit id is : " + c.getSha());
System.out.println(" commit message is : " + c.getMessage());
System.out.println(" author of the commit is : " + c.getAuthor());
System.out.println(" date modified is : " + c.getDateString());
System.out.println(" number of files changed is : " + c.getFiles());
List<GitLogResponse.CommitFile> store = c.getFiles();
if(store!=null)
System.out.println("the number of files changed is : " + store.size());
System.out.println("list of files changed is : " + c.getFilesChanged());
System.out.println("total number of additions : " + c.getLinesDeleted());
System.out.println("total number of merger : " + c.getMergeDetails());
}
// for(GitLogResponse.CommitFile c : dotGit.getLog())
}
}
Output is shown as :
Exception in thread "main" edu.nyu.cs.javagit.api.JavaGitException: 100002: Invalid path to git specified. { path=[C:\Program Files\Git\bin] }
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:220)
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:247)
at modifiedlines.UseGit.main(UseGit.java:40)
Caused by: edu.nyu.cs.javagit.api.JavaGitException: 100002: Invalid path to git specified.
at edu.nyu.cs.javagit.api.JavaGitConfiguration.determineGitVersion(JavaGitConfiguration.java:81)
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:217)
... 2 more
Java Result: 1
My query is how to find git logs and the files changed due to a particular commit using a Java Program.
Can any 1 help me in this.
Please See : This code is working fine in Ubuntu i.e. no Path problem still I am unable to get the files changed during a commit. It is give me a List as a null.
This bug was opened a long time ago and just fixed it. Please give it a try , use master branch please, and let me know if it works for you.
In this case I am creating a plugin to learn, I need to know the following things.
What I want to do is to establish points on the map and at these points when another command will fall lightning.
1- For example: /thor setpoint 1, 2, 3, 4...
And in config created...
Lightning:
1:
x:
y:
z:
2:
x:
y:
z:
3... 6, 14..
The next three commands.
/thor delpoint 1, 2, 3... = Deleted point ID
/launch all = Launch all points
/launch ID = Only launch id
For now I managed to fall into a coordinate, single configuration file.
Thanks in advance
Main:
package me.alexbanper.thorproject.plugin;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
//import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
public class ThorProject extends JavaPlugin implements Listener {
public void onEnable(){
saveDefaultConfig();
}
public void onDisable(){
}
public boolean onCommand(CommandSender enviar, Command comando, String commandLabel, String[] args){
Player player = (Player) enviar;
if(enviar instanceof Player){
if(commandLabel.equalsIgnoreCase("trueno")){
if(player.hasPermission("trueno.comando")){
if(args.length == 0){
player.sendMessage(col("&aUtiliza:"));
player.sendMessage(col("&6/trueno iniciarahora &5Inicia los truenos"));
player.sendMessage(col("&6/trueno iniciartiempo SEGUNDOS &5Inicia con segundos"));
player.sendMessage(col("&6/trueno setpoint &5establece un punto"));
}else if(args.length == 1){
if(args[0].equalsIgnoreCase("setpoint")){
this.getConfig().set("Config" + ".Thor" + ".X", player.getLocation().getBlockX());
this.getConfig().set("Config" + ".Thor" + ".Y", player.getLocation().getBlockY());
this.getConfig().set("Config" + ".Thor" + My".Z", player.getLocation().getBlockZ());
//this.getConfig().set("Config" + ".World", player.getLocation().getWorld());
saveConfig();
player.sendMessage(col("&aSpawnPoint 1 set!"));
player.sendMessage("X: " + getConfig().getInt("Config.Thor.X"));
player.sendMessage("Y: " + getConfig().getInt("Config.Thor.Y"));
player.sendMessage("Z: " + getConfig().getInt("Config.Thor.Z"));
player.sendMessage("World: " + getConfig().getString("Config.World"));
}else if(args[0].equalsIgnoreCase("setpoint2")){
this.getConfig().set("Config" + ".Thor2" + ".X", player.getLocation().getBlockX());
this.getConfig().set("Config" + ".Thor2" + ".Y", player.getLocation().getBlockY());
this.getConfig().set("Config" + ".Thor2" + ".Z", player.getLocation().getBlockZ());
//this.getConfig().set("Config" + ".World", player.getLocation().getWorld());
saveConfig();
player.sendMessage(col("&aSpawnPoint 2 Set!"));
player.sendMessage("X: " + getConfig().getInt("Config.Thor2.X"));
player.sendMessage("Y: " + getConfig().getInt("Config.Thor2.Y"));
player.sendMessage("Z: " + getConfig().getInt("Config.Thor2.Z"));
player.sendMessage("World: " + getConfig().getString("Config.World"));
}
}
}else{enviar.sendMessage(col("&cAcceso Denegado!"));}
}else if(commandLabel.equalsIgnoreCase("it")){
int x = getConfig().getInt("Config.Thor.X");
int y = getConfig().getInt("Config.Thor.Y");
int z = getConfig().getInt("Config.Thor.Z");
int x2 = getConfig().getInt("Config.Thor2.X");
int y2 = getConfig().getInt("Config.Thor2.Y");
int z2 = getConfig().getInt("Config.Thor2.Z");
//Object world = getConfig().get("Config" + ".World");
Location light = new Location(null, x, y, z);
Location light2 = new Location(null, x2, y2, z2);
Bukkit.getServer().getWorld("world").strikeLightningEffect(light);
Bukkit.getServer().getWorld("world").strikeLightningEffect(light2);
player.sendMessage("All correct!");
}
}else{enviar.sendMessage("Only Players!");}
return false;
}
public static String col(String msg){
return ChatColor.translateAlternateColorCodes('&', msg);
}
}
/trueno = /thor (I speak Spanish)
First of all, you need to save the world name too or you cannot get the location at all later. For all, make a call to get the keyset and iterate through all of the locations. (Be careful how you do this, make sure you are using the correct keys)
Delete the map of the key when you need to delete a location. Lastly, get the corresponding key when selecting a specific ID.
There are plenty of videos you can google to understand the behavior of Bukkit's YAMLConfigiration class, but most of them are absolutely horrible. I found one that isn't AS bad for you. It is for config files, but the YAMLConfig class behaves very similarly. (I plan on doing some of my own tutorials this summer, but I am going to be VERY careful with following java conventions and correct practice unlike most of these youtubers)
Bukkit Coding ~ Episode 5: Configuration: https://youtu.be/SBvrpmNDr74
As a side note, the bukkit forums are a better place for bukkit development than stack overflow.
http://bukkit.org/forums/