despite being new to JDA I havent had any big problems till now, maybe I am just missing something crucial. To quickly explain what following code SHOULD do:
Whenever the bot gets started, the onGuildReady event creates an Object containing a loop which sends a single message to a specified channel and after 1 minute edits said message.
#Override
public void onGuildReady(GuildReadyEvent event) {
System.out.println("ON GUILD READY: " + event.getGuild());
new AutoController(event, channelid);
}
Now with my understanding, the guildReady event should enable me to send messages to specified channels in every guild my bot is connected to AND edit them or do stuff with them.
String messageId = null;
String channelId;
public AutoController(GuildReadyEvent event, String channelId){
this.event = event;
start();
}
#Override
public void run(){
try {
while (true) {
sleep((long) timer);
if(messageId == null){
event.getGuild().getTextChannelById(channelId).sendMessage("A").queue();
this.messageId = event.getGuild().getTextChannelById(channelId).getLatestMessageId();
}else{
event.getGuild().getTextChannelById(channelId).editMessageById(messageId,"B").queue();
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
Sending a message whenever the bot goes online works, but as soon as it gets in the 2nd loop where the edit should happen, it throws me an ErrorResponseException saying the message is unkknown.
[ForkJoinPool.commonPool-worker-1] ERROR RestAction - RestAction queue returned failure: [ErrorResponseException] 10008: Unknown Message net.dv8tion.jda.api.exceptions.ContextException at net.dv8tion.jda.api.exceptions.ContextException.here(ContextException.java:54) at net.dv8tion.jda.api.requests.Request.<init>(Request.java:73) at net.dv8tion.jda.internal.requests.RestActionImpl.queue(RestActionImpl.java:200) at net.dv8tion.jda.api.requests.RestAction.queue(RestAction.java:572) at net.dv8tion.jda.api.requests.RestAction.queue(RestAction.java:538) at org.gsbunker.controller.AutoController.run(AutoController.java:45)
I really dont understand why the message is unknown, ive already checked that the messageid and channelid are not null when passed - still getting the same error. the code is slightly simplified for understanding purposes, if questions occur feel free to ask. pleeeeeeeaase help me and my brain <3
Sitting back and relaxing your brain sometimes really is the best solution!
Putting the thread to sleep after queuing made sure that the message is online and ready for retrieval when executing the editMessage method
if(messageId == null){
event.getGuild().getTextChannelById(channelId).sendMessage("A").queue();
sleep(3000);
this.messageId = event.getGuild().getTextChannelById(channelId).getLatestMessageId();
}else{
event.getGuild().getTextChannelById(channelId).editMessageById(messageId,"B").queue();
}
after reviewing the documentation again, if found that the complete() method would be even better suited for a use case like this.
if(messageId == null){
event.getGuild().getTextChannelById(channelId).sendMessage("A").complete();
this.messageId = event.getGuild().getTextChannelById(channelId).getLatestMessageId();
}else{
event.getGuild().getTextChannelById(channelId).editMessageById(messageId,"B").queue();
}
yeeaahh not that big of a problem if you clear your head and stop forgetting java basics, happy coding :D
I need to validate if the user has been added successfully to a particular group. The only option I can think of is using exception handling. Is there a better way of using LDAP response codes of any type.
public boolean addMemberToGroup(String groupName, Person p) {
boolean status = false;
Name groupDn = buildGroupDn(groupName);
Name personDn = buildPersonDn(p);
try {
DirContextOperations ctx = ldapTemplate.lookupContext(groupDn);
ctx.addAttributeValue(UNIQUE_MEMBER, personDn);
ldapTemplate.modifyAttributes(ctx);
status = true;
}catch (Exception e) {
status =false;
}
return status;
}
Well here is how i used to proceed:
lookup the user i need to create on my active directory (returns false if it is true then the user already exists)
Create the user
look up the user again (returns true this time)
I'm not really sure how to ask the question, but I'm going to try here.
I've got a list of actions that could happen to a subject. The user of my system needs to approve these actions and does so by selecting (checkboxes) these actions and then clicking the Approve button. Some of these action might require extra data, so a new page is presented to the user. The user enters that new data. Then the backend sends the whole package off to the endpoint for modification on the database. Once completed, it will reload the page they were just on.
So this is how I have it setup:
Approve button jumps to the following method:
#PostMapping("ApproveActions")
public RedirectView approveActions(ModelandView mav, #ModelAttribute("pendingActions") PendingActionsForm pendingActions) {
boolean needsDetails = false;
ActionForm actionForm = new ActionForm();
// parse through each of the actions
pendingActions.forEach(action -> {
// verify if the action has been selected by the user.
if (action.isSelected()) {
// if needsDetails hasn't been set to true,
if (!needsDetails) {
// check to see if it is one of the special actions that needs more info
needsDetails = ActionTypes.NeedsDetails(action.typeId());
}
// build the data for the endpoint
actionForm.addActionData(action);
}
});
if (needsDetails) {
// load the new page
rv.setUrl("/extraActionDetails");
return rv; // This is not right, but it does get me to the new page.
// get data
// return to this point with that new data
actionForm.setExtraDetails(???);
}
actionService.ApproveActions(actionForm);
RedirectView rv = new RedirectView();
rv.setUrl("/subjects/" + pendingActions.getSubjectId() + "#actions-pending");
return rv;
}
The problem I'm having is I don't know how to do that part with // load the new page get data and return to this point with that new data. I've got the extra-details.jsp page built out. And it's controller can be called. Does this question make sense? Are there any tutorials out there that address this situation?
I need a uniqueID from a message Object to save this in my database.
Afterwards I´m able to search for this UID in my database and can add other properties, like "emailTrackingActive" etc.
a) Is there a possibility to get a whole UID for a Email Inbox or is it always only per folder? Currently I´m getting this as you can see in the code.
Currently I´m doing the following as you can see in the code:
After I´ve send the message, I copy the message into my "Sent" folder and then I want to get the UID and save it in the database.
With "EmailHelperClass" I´m getting Store etc.
I think it should be clear and I will not post this code...
private void copyIntoSentAndSaveInDatabase(EmailHelperClass email, final Message msg){
final Store store = email.getMailConfiguration().getWriteStore();
final Folder folder = (Folder) store.getFolder("Sent");
if (folder.exists() == false) {
folder.create(Folder.HOLDS_MESSAGES);
}
folder.open(Folder.READ_WRITE);
folder.appendMessages(new Message[] { msg });
// Get UniqueID
UIDFolder uf = (UIDFolder) folder;
Long messageId = uf.getUID(msg);
// Todo Update in DB etc
}
But now I´m getting the following error message:
java.util.NoSuchElementException: Message does not belong to this
folder
What is wrong here?
Hi all you need to change folder to IMAPFolder
final Store store = email.getMailConfiguration().getWriteStore();
final IMAPFolder folder = (IMAPFolder) store.getFolder("Sent");
folder.open(Folder.READ_WRITE)
with the help of this folder fetch all your messages i have write the below method to get the UID of the message
private long getMessagesUID(UIDFolder folder,javax.mail.message message){
try{
return folder.getUID(message)
}catch(Exception ex)
{
ex.printStackTrace();
}
Let me know in case of any query.
I am writing code for an Android app using Eclipse that is supposed to download an image from a URL (which is generated by the app, elsewhere in the code, using GPS information), then attach the newly downloaded image to an e-mail to be sent. I am able to, in general, accomplish this without much issue.
My problem is this: I only want one image downloaded by the app to be present in the device's external storage at any given time. Deleting the image after the email intent does not work, because because the app doesn't always call onStop or onDestroy when switching to another app to send the email. Time-sensitive deleting of the image will not work either, because I cannot assume that the user will send only one email from the app per hour. I want to give the user the freedom of sending as many of these emails (with one newly downloaded image, each) as they wish.
My current method (which works MOST of the time) is this: in the downloadFile method, simply check for the file's existence (I call it sensorMap.png), then delete it if it exists, before downloading a new one. This SHOULD ensure that there may be only one sensorMap.png image in external storage at any given time (EDIT: it does do this), and that when it comes time to attach the image to the email intent, there will be exactly one image ready to go. Instead, I see that sometimes a second sensorMap image is sometimes being downloaded into storage (i.e. "sensorMap-1.png"), OR the image cannot be attached to the email due to a "File size: 0 bytes" error, OR the image cannot be attached due to a "File does not exist" error. I am unsure what the difference between the latter two problems is. EDIT: Upon manually examining the contents of the directory I created, it seems that, as intended, I end up with only one image titled "sensorMap.png" at a time; it remains in the directory after the app closes, as expected. However, I still occasionally get the "File size: 0 bytes" message or the "File does not exist." message with no attached image, even though I see that the image DOES exist upon looking in directory afterwards. Other times, everything works just fine. It's rather bewildering.
In addition, there is an issue of the button which sends the email becoming unresponsive occasionally. Most of the time, it prompts the user to select an email client, as intended, but occasionally the button will LOOK as if clicked, but do nothing. When this happens, the logcat does not sense that the button was even clicked (I inserted a println statement to test it).
I am unsure of why my delete-before-download is not working flawlessly; the basic idea, at least, appears to be logically sound. Here is the code pertaining to my issue:
Code used to download file (in MainCountActivity.java):
//Function to download image given URL. Will use to attach image file to email.
public void downloadFile(String uRl) {
//delete existing file first so that only one sensorMap image exists in memory
//at any given time.
File file = new File(Environment.getExternalStorageDirectory()+"/SensorLocationImages");
File checkFile = new File(Environment.getExternalStorageDirectory()+"/SensorLocationImages/sensorMap.png");
if(checkFile.exists())
{
//debugging:
System.out.println("About to delete file!");
//deleteFiles(Environment.getExternalStorageDirectory()+"/SensorLocationImages");
checkFile.delete();
}
DownloadManager mgr = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Sensor Location Map")
.setDescription("Pinpointed is the location from which the log file was sent.")
.setDestinationInExternalPublicDir("/SensorLocationImages", "sensorMap.png");
mgr.enqueue(request);
}
public Activity getActivity() //I wasn't sure if this would work, but it did. Or at least appears to.
{ return this; }
Method to send email (in MainCountActivity.java):
public void sendEmail(String toAddress, String ccAddress, String bccAddress, String subject, String body, String attachmentMimeType) throws Exception{
try {
Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
emailIntent.setType(attachmentMimeType); //new
String sToAddress[] = { toAddress };
String sCCAddress[] = { ccAddress};
String sBCCAddress[] = { bccAddress };
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.putExtra(Intent.EXTRA_EMAIL, sToAddress);
emailIntent.putExtra(android.content.Intent.EXTRA_CC, sCCAddress);
emailIntent.putExtra(android.content.Intent.EXTRA_BCC, sBCCAddress);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
//get URI of logfile
File tempFile = new File(Environment.getExternalStorageDirectory () + MainCountActivity.dirPath);
Uri uri = Uri.fromFile(tempFile);
//create URI arraylist and add first URI
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(uri);
//get URI of map image and add to arraylist
//make sure it is there to attach
File file = new File(Environment.getExternalStorageDirectory()+"/SensorLocationImages");
do {
downloadFile(getMapLink());
//createDirectoryAndSaveFile(getBitmapFromURL(getMapLink()), "sensorMap.png");
} while (!file.exists());
uris.add(Uri.fromFile(new File(Environment
.getExternalStorageDirectory()
+ "/SensorLocationImages/sensorMap.png")));
//+ "/sdcard/SensorLocationImages/sensorMap.png")));
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(emailIntent);
}
catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
}
OnClick method, for my occasional button issue (In MaincountActivity.java):
public void onClick(View v){
switch(v.getId())
{
case R.id.textView1:
{
break;
}
case R.id.Reset:
{
//allowCounting will let the program know when to let it to count or not, depending if Start or Stop button are pressed.
logCount=0;
mCounter.setText("Total: 0");
mToggle.setChecked(false);
break;
}
/* case R.id.toggleButton:
{
break;
}*/
case R.id.SendEmail:
{
//for debugging purposes:
System.out.println("Email button being clicked!");
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
Toast.makeText(this, "GPS is enabled in your device", Toast.LENGTH_SHORT).show();
try {
sendEmail("","","","Sensor Log Info",getEmailBody(),"multipart/mixed");
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
showGPSAlertForEmail();
}
break;
}
}
Basically, I really want to know why my delete-then-download method has not worked every time. Logcat errors have provided no insight. Thank you for your time.