How to download PDDocument for example,
PDDocument has has 10 pages with document name as Test and now this has to downloaded as zip file inside should PDF doc as Test1, Test2... Test10 in a zip file named Test.zip.
ByteArrayOutputStream bytestream=new ByteArrayOutputStream()
PDDocument doc = new PDDocument();
Splitter splitter = new Splitter();
//I can do this splitting of each page as PDDocument
List<PDDocument> splitDocs = splitter.split(doc);
doc.save(bytestream);
doc.close()
return bytestream;
Related
I have my Django view where I upload the file from admin and users download it on the frontend when I download the file on the frontend the download is extension with only .xls i.e when I upload the file with .xlsx extension it is still downloading with .xls instead the file should be downloaded according to the extension either its xls or xlsx.
views.py
class myAPIView(APIView):
def get(self, request):
data = Model.objects.first()
filename = data.file.name
file_extention = filename.split('.')[-1]
response = HttpResponse(
data.file.path,
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = \
'attachment; filename="output_file"'+ file_extention
return response
This is the standard that you can apply(edit the content-type for you.)
class myAPIView(APIView):
def get(self, request):
data = Model.objects.first()
filename = data.file # or data.file.name based on your models.
file_extention = filename.split('.')[-1] # something which is seprated by dot. in the last
response = HttpResponse(
file_path,
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = \
'attachment; filename="output_file"'+ file_extention
return response
Although soap (free version) has an option to export document generated in response. Is there any groovy function to extract application/pdf file and store in my local folder ?
The following script should be able to save the attachment to a file.
Add the below script as Script Assertion to the current request step. Find the appropriate comments inline.
Source for the script is taken from here
/**
* Below script assertion will check
* if the response is not null
* there is an attachment
* and saves file to the specified location, by default saves into system temp
* directory
**/
//change file name as needed
def fileName = System.getProperty('java.io.tmpdir')+'/test.pdf'
//Get the response and check if the response is not null
def response = messageExchange.response
assert null != response, "response is null"
//Create output stream
def outFile = new FileOutputStream(new File(fileName))
//Check if there is one attachment in the response
assert 1 == messageExchange.responseAttachments.length, "Response attachments count not matching"
def ins = messageExchange.responseAttachments[0]?.inputStream
if (ins) {
//Save to file
com.eviware.soapui.support.Tools.writeAll( outFile, ins )
}
ins.close()
outFile.close()
I have a gradle.build where I am trying to:
read an XML file
use XmlSlurper to update an attribute in the read XML file
write the updated XML back to the originally parsed xml file.
The third step only works if I write the modified XML to a new non-existing XML file, but not the originally parsed XML file.
What is the simplest way to write the modified XML to the originally parsed XML file?
My code so far:
def inFile = file('file.xml')
def outFile = file('_file.xml')
def xml = new XmlSlurper().parse(inFile)
// update xml code here
def outBuilder = new StreamingMarkupBuilder()
def outWriter = outFile.newWriter()
XmlUtil.serialize(outBuilder.bind{ mkp.yield xml }, outWriter)
I would like outFile to be file.xml so that it overwrites the original XML file.
What happens if you do:
def inFile = file( 'file.xml' )
def xml = new XmlSlurper().parse( inFile )
xml.appendNode {
haha( 'tim_yates' )
}
inFile.withWriter { outWriter ->
XmlUtil.serialize( new StreamingMarkupBuilder().bind{ mkp.yield xml }, outWriter )
}
Is it just not written? (seems to work for me)
I'm trying to send an email using Java code but running from GroovyConsole. It works fine for when I just send an email without attachments but it fails as soon as I add in the multipart logic for attachments.
EDIT: I'm using Javamail version 1.4.7
This is the error I'm getting.
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed;
boundary="----=_Part_16_24710054.1375885523061"
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:891)
and it's happening on the line Transport.send(mimeMsg) below.
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
Properties properties = new Properties()
Session session
MimeMessage mimeMsg
properties.put("mail.smtp.host", "[my host ip]")
session = Session.getDefaultInstance(properties)
mimeMsg = new MimeMessage(session)
String recipient = "[to email address]"
mimeMsg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient))
mimeMsg.setSubject("This is the subject")
mimeMsg.setText("This is the message #1")
mimeMsg.setFrom(new InternetAddress("[from email address]"))
BodyPart messageBodyPart = new MimeBodyPart()
messageBodyPart.setText(mimeMsg.getContent())
Multipart multipart = new MimeMultipart()
String filePath = "[full & correct path to test.txt]"
DataSource source = new FileDataSource(filePath)
messageBodyPart.setDataHandler(new DataHandler(source))
String fileName = "test.txt"
messageBodyPart.setFileName("test.txt")
multipart.addBodyPart(messageBodyPart)
mimeMsg.setContent(multipart)
Transport.send(mimeMsg)
println "Message Sent!"
I think it's a classloader issue to do with the way GroovyConsole runs...
If I add the following #Grab and #GrabcConfig to the script, it works...
#Grab( 'javax.mail:mail:1.4.7' )
#GrabConfig(systemClassLoader=true, initContextClassLoader=true)
import javax.mail.*
import javax.mail.internet.*
import javax.activation.*
def props = new Properties().with { p ->
p.'mail.smtp.host' = 'my mail server'
p
}
def session = Session.getDefaultInstance( props )
def message = new MimeMessage( session )
message.addRecipient( Message.RecipientType.TO, new InternetAddress( 'to address' ) )
message.subject = 'This is the subject'
message.text = 'This is the message #1'
message.from = new InternetAddress( 'from address' )
def textpart = new MimeBodyPart()
textpart.text = 'This is the message #2'
def attachment = new MimeBodyPart()
attachment.dataHandler = new DataHandler( new FileDataSource( '/path/to/file.txt' ) )
attachment.fileName = 'file.txt'
def multi = new MimeMultipart()
multi.addBodyPart( textpart )
multi.addBodyPart( attachment )
message.content = multi
Transport.send( message )
Or, remove the two #Grab and #GrabConfig lines, and run it from the command line with:
groovy -cp /path/to/mail-1.4.7.jar:/path/to/activation-1.1.jar mail.groovy
I have solved the same problem by following steps.
1- Extract mail.jar file (you will get following folder after extracting jar file
com,javax,META-INF)
2- Put all the above folders in classes folder
3- Restart your web server.
How can I write the output of an object to a teststep (Soaprequest) in soapUI using XmlNodePrinter.
I have the below groovy script in which I have an input xml file. I perform file operations and then would like to write the object using xmlnodeprinter, to a teststep (soaprequest) in soapUI (highlighted in bold...not sure wat should be going in place of ---)
I tried writing to an external file which works (highlighted in green)
def alert = com.eviware.soapui.support.UISupport;
//Define a file pointer for groovy to handle the file operations.
def inputFile = new File("V:\\Sample\\Sample.xml")
if(!inputFile.exists())
{
//Display an alert if the file is not found.
alert.showInfoMessage("Input File 'Sample.xml' not found!");
}
else
{
xml=new XmlParser().parseText(inputFile.text)
def nodeToDel=xml.A.B.find{it.#C3='1'}
def parent = nodeToDel.parent()
parent.remove(nodeToDel)
//new XmlNodePrinter(new PrintWriter(new FileWriter(new File('V:\\Sample\\e.xml')))).print(parent)
new XmlNodePrinter(new PrintWriter(new FileWriter(---))).print(parent)
}
define a string writer
def sw = new StringWriter()
new XmlNodePrinter(new PrintWriter(sw)).print(parent)
def modifiedXml = sw.toString()
modifiedXml variable will contain the xml with deleted nodes which you can further use for your test step.