Basically my problem is: How do I display an error message on my page and cancel a download, when the generation of the file to download has failed.
Primefaces 7. I would be willing to update to 11 (which breaks some of my code ..) if I would see a method which achieves this in 11
<p:commandButton id="downloadButtonAllCSV" widgetVar="downloadButtonAllCSV" value="Download alle CSV" onclick="PrimeFaces.monitorDownload(start, stop)" icon="ui-icon-arrowthick-1-s" styleClass="button" update="#form">
<p:fileDownload value="#{reportingController.CSVAllGCG}" />
</p:commandButton>
<p:growl></p:growl>
<p:dialog widgetVar="csvError" header="Fehler bei CSV Erzeugung">
<h:outputText value="Fehler bei CSV Erzeugung"></h:outputText>
</p:dialog>
My bean code basically checks if the number of selected samples is smaller than some cofigured value to avoid an OutOfMemory. My problem is that the attempts to show some error on the web page in the else block do not work. Neither the growl, nor the dialog show up.
public StreamedContent getCSVAllGCG() {
InputStream targetStream = null;
String csv = "";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(GCGNachrichtDTO.REP_CSV_HEADER);
if (getAnzahl().intValue() < this.maxDownloads) {
List<GCGNachrichtDTO> allDtos = this.reportMessageDAO.findGCGNachichten(0, getAnzahl().intValue(), filter, true);
String dtoString = allDtos.stream().map(d -> d.getMonCSVString()).collect(Collectors.joining());
stringBuilder.append(dtoString);
csv = stringBuilder.toString();
targetStream = new ByteArrayInputStream(csv.getBytes());
} else {
String message = "Mehr als " + maxDownloads + " Eintraege koennen nicht verarbeitet werden";
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, message, message);
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
message += " Konfiguration mit gcg.monitoring.max.downloads. Ein zu hoher Wert kann zu einer OutOfMemoryError fuehren.";
log.info(message);
PrimeFaces.current().executeScript("PF('csvError').show()");
targetStream = new ByteArrayInputStream(message.getBytes());
}
return new DefaultStreamedContent(targetStream, "text/csv", "reporting.csv");
}
#adam:
<p:commandButton id="downloadButtonAllCSV" widgetVar="downloadButtonAllCSV" value="Download alle CSV" icon="ui-icon-arrowthick-1-s" styleClass="button" update="#form" actionListener="#{reportingController.actionCSVAllGCG()}">
<p:fileDownload value="#{reportingController.stream}" />
</p:commandButton>
public void actionCSVAllGCG() {
InputStream targetStream = null;
String csv = "";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(GCGNachrichtDTO.REP_CSV_HEADER);
if (getAnzahl().intValue() <= this.maxDownloads) {
List<GCGNachrichtDTO> allDtos = this.reportMessageDAO.findGCGNachichten(0, getAnzahl().intValue(), filter, true);
String dtoString = allDtos.stream().map(d -> d.getMonCSVString()).collect(Collectors.joining());
stringBuilder.append(dtoString);
csv = stringBuilder.toString();
targetStream = new ByteArrayInputStream(csv.getBytes());
} else {
String message = "Mehr als " + maxDownloads + " Eintraege koennen nicht verarbeitet werden";
log.info(message);
targetStream = new ByteArrayInputStream(message.getBytes());
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, message, message);
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
message += " Konfiguration mit gcg.monitoring.max.downloads. Ein zu hoher Wert kann zu einer OutOfMemoryError fuehren.";
log.info("------- ******** " + message);
PrimeFaces.current().executeScript("PF('csvError').show()");
}
this.stream = new DefaultStreamedContent(targetStream, "text/csv", "reporting.csv");
}
This does not work either, nothing happens...
Related
I have created a Discord bot for my Minecraft server. The bot connects to my Discord server. The problem is that it does not respond. (See code).
#Override
public void onMessageReceived(MessageReceivedEvent event) {
if(event.getAuthor().isBot() || event.isWebhookMessage()) return;
TextChannel textChannel = event.getGuild().getTextChannelById("850164284402040872");
String[] args = event.getMessage().getContentRaw().split(" ");
if(args[0].equalsIgnoreCase("!link")) {
if(event.getChannel().equals(textChannel)) {
if (Objects.requireNonNull(event.getMember()).getRoles().stream().filter(role -> role.getId().equals("834086832408625152")).findAny().orElse(null) != null) {
textChannel.sendMessage(":x: **|** Error! " + event.getAuthor().getAsMention() + ", du bist bereits verifiziert!").queue();
return;
}
if (uuidIdMap.containsValue(event.getAuthor().getId())) {
textChannel.sendMessage(":x: **|** Error! " + event.getAuthor().getAsMention() + ", du hast bereits einen Code generiert!").queue();
return;
}
if (args.length != 2) {
textChannel.sendMessage(":x: **|** Error! Du musst einen Spieler angeben!").queue();
return;
}
Player target = Bukkit.getPlayer(args[1]);
if (target == null) {
textChannel.sendMessage(":x: **|** Error! Der Spieler konnte nicht gefunden werden").queue();
return;
}
int n = 20;
uuidCodeMap.put(target.getUniqueId(), randomCode(n));
uuidIdMap.put(target.getUniqueId(), event.getAuthor().getId());
for(String code : uuidCodeMap.values()) {
event.getAuthor().openPrivateChannel().complete().sendMessage("Hey! Du hast erfolgreich einen Code generiert!\n" + "Benutze diesen Befehl: ``/discord " + code + "``").queue();
}
textChannel.sendMessage(":white_check_mark: **|** Ein Code wurde generiert. Schaue bitte nach.").queue();
}
}
}
I want to extract ALL the attachments of an .eml message which is encapsulated (Content-Type: message/rfc822) in the message InputStream
InputStream is = new FileInputStream(Path);
MimeMessage mime = new MimeMessage(null, is);
private String getAttachments(p) throws
MessagingException, IOException {
if ( p.isMimeType("multipart/*")) {
Multipart multiPart = (Multipart) p.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
String disp = part.getDisposition();
if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT) {
file_name = part.getFileName();
part.saveFile(Attachments_Folder + "\\" + MailFileName + "_" + file_name);
}
}
}
}
is.close()
Also, when the Content-Type is message/rfc822, the part.getFileName() is null and therefore the saved file has no extension and I don't know how to get this one.
MIME does not require every body part to have a file name. If the part doesn't have a file name and you need one, you'll have to make one up yourself.
Note also that you want to be very careful when using a file name that you get in an email message. It could be something unexpected or malicious, e.g., containing "../../../../../whatever".
I did it by adding a new filename to the included message as an .eml file and a recursion with the included message
import java.util.*;
import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.*;
import java.io.FileInputStream.*;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.Part;
import javax.mail.Multipart;
getAttachments(Path) ;
//function
private String getAttachments(path) throws
MessagingException, IOException {
InputStream is = new FileInputStream(path);
MimeMessage p = new MimeMessage(null, is);
if ( p.isMimeType("multipart/*")) {
// if (contentType.contains("multipart")) {
Multipart multiPart = (Multipart) p.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart)multiPart.getBodyPart(partCount);
String disp = part.getDisposition();
if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
file_name = part.contentType == "message/rfc822" ? "message_inclus" + partCount + ".eml" : MimeUtility.decodeText(part.getFileName());
exportedpath = Attachments_Folder + "/" + MailFileName + "_" + file_name;
part.saveFile(exportedpath);
if ( part.contentType == "message/rfc822" ) {
getAttachments(exportedpath)
}
}
}
}
is.close()
return 1
}
Better use org.apache.commons.mail.util.MimeMessageParser.
MimeMessageParser has as method called hasAttachments() which
returns true , if message has an attachments.
Then loop through the all attachments and check for content-type
message/rfc822 from getContentType().
Create new MimeMessage with the DataSource InputStream
final MimeMessage message = new MimeMessage(null,attachment.getInputStream());
Finally you have MimeMessage.
Maven Dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>RELEASE</version>
</dependency>
Code Sample:
public void readEmails() throws Exception{
// mail server connection parameters
String host = "host";
String user = "username";
String pwd = "pwd";
// connect to my pop3 inbox
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("pop3");
store.connect(host, user, pwd);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
// get the list of inbox messages
Message[] messages = inbox.getMessages();
if (messages.length == 0) System.out.println("No messages found.");
for (int i = 0; i < messages.length; i++) {
// stop after listing ten messages
if (i > 10) {
System.exit(0);
inbox.close(true);
store.close();
}
final MimeMessageParser mimeMessageParser = new MimeMessageParser((MimeMessage) messages[i]);
mimeMessageParser.parse();
if (mimeMessageParser.hasAttachments()) {
List<DataSource> attachmentList = mimeMessageParser.getAttachmentList();
System.out.println("Number of attachments: " +attachmentList.size());
for (DataSource attachment:attachmentList
) {
System.out.println("Name: "+attachment.getName()+" Content Type: "+attachment.getContentType());
if (attachment.getContentType().equals("message/rfc822")) {
final MimeMessage message = new MimeMessage(null,attachment.getInputStream());
System.out.println("Subject of the attached failure Mail:" + message.getSubject());
}
}
}
System.out.println("Message " + (i + 1));
System.out.println("From : " + messages[i].getFrom()[0]);
System.out.println("Subject : " + messages[i].getSubject());
System.out.println("Sent Date : " + messages[i].getSentDate());
System.out.println();
}
inbox.close(true);
store.close();
}
Hi I am trying to customize DBTrigger message in bean Here is code for it, it is displaying my customized message but as well it is displaying DBTrigger message below to my message, Kindly help me to get out of this.
public void saveLataActionListenerNew(ActionEvent actionEvent) {
System.out.println("----on click saved ");
try {
OperationBinding operationBinding = (OperationBinding)getBindings().getOperationBinding("Commit");
Object result = operationBinding.execute();
System.out.println("Errors : " + operationBinding.getErrors());
if (operationBinding.getErrors() != null) {
Iterator it = operationBinding.getErrors().iterator();
System.out.println("error = " + it);
System.out.println("size of Errors - " + operationBinding.getErrors().size());
while (it.hasNext()) {
DMLException error = (DMLException)it.next();
String errorCause = "" + error.getCause();
System.out.println("error.getCause() : " + errorCause);
if (errorCause != null && errorCause.contains("ORA-00001: unique constraint")) {
uniqueConstraint = "Lata is Exists for given State";
showMessage(uniqueConstraint, FacesMessage.SEVERITY_ERROR);
return;
}
}
}
uniqueConstraint = "Record is saved successfully";
showMessage(uniqueConstraint, FacesMessage.SEVERITY_INFO);
System.out.println("---record saved successfully");
// addPlaceCodePfl.setRendered(false);
// addPlaceCodePgl.clearInitialState();
// addPlaceCodePfl.
} catch (Exception e) {
uniqueConstraint = e.getMessage();
showMessage(uniqueConstraint, FacesMessage.SEVERITY_ERROR);
e.printStackTrace();
}
i have code:
Message[] arrayMessages = folderInbox.getMessages();
for (int i = 0; i < arrayMessages.length; i++) {
Message message = arrayMessages[i];
Address[] fromAddress = message.getFrom();
String from = fromAddress[0].toString();
String subject = message.getSubject();
String sentDate = message.getSentDate().toString();
String contentType = message.getContentType();
String messageContent = "";
// store attachment file name, separated by comma
String attachFiles = "";
if (contentType.contains("multipart")) {
// content may contain attachments
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
String fileName = part.getFileName();
attachFiles += fileName + ", ";
part.saveFile(saveDirectory + File.separator + fileName);
} else {
// this part may be the message content
messageContent = part.getContent().toString();
}
}
if (attachFiles.length() > 1) {
attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
}
}else if (contentType.contains("text/plain")|| contentType.contains("text/html")) {
Object content = message.getContent();
if (content != null) {
messageContent = content.toString();
}
}
// print out details of each message
System.out.println("Message #" + (i + 1) + ":");
System.out.println("\t From: " + from);
System.out.println("\t Subject: " + subject);
System.out.println("\t Sent Date: " + sentDate);
System.out.println("\t Typ wiadomosci: " + contentType);
System.out.println("\t Message: " + messageContent);
System.out.println("\t Attachments: " + attachFiles);
System.out.println("------------------------------------------------");
}
This code get email with attachment, i have problem with getting email type: multipart/related. Instead of messages i have:com.sun.mail.util.BASE64DecoderStream#f61227
or javax.mail.internet.MimeMultipart#7612a
A multipart/related part appears as Java type MimeMultipart.
I have problem with loading image from database to jsp view. It looks like action are execute but stop in middle.
I log when execute() method start and when its end. In log file i can see start this method but there are no end.
I have action:
public class ShowImageAction extends BaseAction {
private static final long serialVersionUID = 1L;
private static final Log LOG = LogFactory.getLog(ShowImageAction.class);
private int id;
public String execute() {
LOG.info("Enter execute()");
MessageBean messageBean = (MessageBean) sessionParameters
.get(SessionParameters.BANNER_EDIT);
IFiles filesEJB = EJBLocator.getFiles();
if (messageBean != null) {
id = messageBean.getBannerId();
}
FileBean file = filesEJB.file(id);
LOG.info("Id = " + id);
if (file != null) {
byte[] bytes = null;
try {
LOG.info("File: name = " + file.getName() + ". type = "
+ file.getType());
if (file.getImage() != null) {
bytes = FileUtils.readFileToByteArray(file.getImage());
HttpServletResponse response = ServletActionContext
.getResponse();
response.setContentType(file.getType());
OutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
} catch (IOException e) {
LOG.error(e);
}
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
LOG.info("Exit execute()");
return NONE;
}
jsp:
<div class="OneFilteringRow">
Podgląd<br />
<img src="/ebok-bm/ShowImageAction" alt="Podgląd banera" />
</div>
struts.xml
<action name="ShowImageAction"
class="pl.bm.action.content.ShowImageAction">
</action>
Problem was in:
FileBean file = filesEJB.file(id);
I get bytes from database and try to save it to tmpFile. Now I get bytes and writes them to a temporary file and immediately transmit it to the action and everything is ok.
Now I have:
FileBean file = filesEJB.file(id);
LOG.info("Id = " + id);
if (file != null) {
byte[] bytes = null;
try {
LOG.info("File: name = " + file.getName() + ". type = "
+ file.getType());
if (file.getImage() != null) {
**bytes = file.getImage();**
HttpServletResponse response = ServletActionContext
.getResponse();
response.setContentType(file.getType());
OutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
} catch (IOException e) {
LOG.error(e);
}
}
Switch to your own result implements Result class and write output here.Other in struts.xmlaction result type specified own with approx mate parameters.
refer:generate own image as action result