Rename a file (file upload in servlet) - file

I'm trying to rename a file after upload but the error I get is:
File Upload Failed due to java.io.FileNotFoundException: C:\Users\Akhil\Documents\CryptographicSteganography\Image\toshaMon Dec 29 22:21:41 IST 2014.jpg (The filename, directory name, or volume label syntax is incorrect).
I went through almost all the possible related topics in stackoverflow as well as other sites but couldn't resolve this error.
my servlet class:
package FileUploadHandler;
import com.pointerunits.web.*;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
/**
* Servlet implementation class FileUploadServlet
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Date date = new Date();
String name = null;
public String UPLOAD_DIRECTORY = "";
/**
* #see HttpServlet#HttpServlet()
*/
public FileUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//process only if its multipart content
String FileType = (String)request.getSession().getAttribute("FileType");
//System.out.println(FileType);
String usrnam = (String) request.getSession().getAttribute("name");
//System.out.println(usrnam);
switch (FileType) {
case "image":
//UPLOAD_DIRECTORY = "C:/Users/Akhil/Downloads/SpringMain/SpringMain/WebContent/WEB-INF/Uploads/Image";
UPLOAD_DIRECTORY = "C:/Users/Akhil/Documents/CryptographicSteganography/Image";
break;
case "audio":
UPLOAD_DIRECTORY = "C:/Users/Akhil/Documents/CryptographicSteganography/Image";
break;
case "video":
UPLOAD_DIRECTORY = "C:/Users/Akhil/Documents/CryptographicSteganography/Image";
break;
default:
System.out.println("invalid path");
break;
}
//UPLOAD_DIRECTORY = getServletContext().getRealPath(UPLOAD_DIRECTORY);
//System.out.println(UPLOAD_DIRECTORY);
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
// System.out.println(getName());
String nam = usrnam+date.toString();
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = item.getName();
//System.out.println(name);
File uploadedFile = new File(UPLOAD_DIRECTORY+File.separator+nam+name.substring(name.indexOf('.')));
item.write(uploadedFile);
//File uploadedFile = new File(UPLOAD_DIRECTORY, name);
// item.write( new File(UPLOAD_DIRECTORY + File.separator + nam + name));
// System.out.println("uploaded file : "+uploadedFile.toString());
// System.out.println(nam);
// String f1 = uploadedFile.getAbsolutePath();
// System.out.println(f1);
//
// File oldName = new File(f1);
// //File newName = new File(UPLOAD_DIRECTORY+File.separator+nam+"."+FilenameUtils.getExtension(oldName.toString()));
// File newName = new File(UPLOAD_DIRECTORY,nam+name.substring(name.indexOf('.')));
// File uploadedFile = new File ("C:\\Users\\Akhil\\Documents\\CryptographicSteganography\\Image\\IMAG0187.jpg");
// File newName = new File("C:\\Users\\Akhil\\Documents\\CryptographicSteganography\\Image\\toshaMon Dec 29 22:01:40 IST 2014.jpg");
// boolean flag = uploadedFile.renameTo(newName);
//
// System.out.println(newName.toString());
//
//// File uploadedFile = new File(UPLOAD_DIRECTORY , nam);
//// item.write(uploadedFile);
//
}
}
System.out.println();
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
below is the .jsp webpage:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload File</title>
</head>
<h1><%
String FileType = request.getParameter("select");
out.println("File Type is: "+FileType);
session.setAttribute("FileType", FileType);
%>
</h1>
<body>
<body>
File:
<%if (FileType.equalsIgnoreCase("image")){%>
<form method="POST" action="FileUploadServlet" enctype="multipart/form-data" >
<input type="file" name="<%=session.getAttribute("FileType")%>" accept="image/*"> <br/>
<input type="submit" value="Upload" name="upload" >
</form>
<% }
else if (FileType.equalsIgnoreCase("audio")){%>
<form method="POST" action="FileUploadServlet" enctype="multipart/form-data" >
<input type="file" name="<%=session.getAttribute("FileType") %>" accept="audio/*" > <br/>
<input type="submit" value="Upload" name="upload" >
</form>
<% }
else if (FileType.equalsIgnoreCase("video")){%>
<form method="POST" action="FileUploadServlet" enctype="multipart/form-data" >
<input type="file" name="<%=session.getAttribute("FileType") %>" accept="video/*" > <br/>
<input type="submit" value="Upload" name="upload" >
</form>
<% }
%>
</body>
</body>
</html>
Sorry about that awful lot of comments:
my program was going through a testing phase

May be there is right issue, it cannot access the folder as it does not have right.
If this is not the case then.
You should try to remove space from the file name format data value to a format that does not contains any space Sample Format Date . Because space can create problems.
Before item.write(uploadedFile); check
if(!uploadedFile.exists()){
uploadedFile.createNewFile();
}

Related

"Required request part 'image' is not present in" error in springboot with reactjs

When i try to upload a image in react, and send it to a spring boot api to save the file in a database, I get the following errors in spring boot:
2022-12-04 03:25:28.610 WARN 15080 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'image' is not present]
2022-12-04 03:25:28.631 WARN 15080 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.LinkedHashMap<java.lang.String,java.util.List<java.lang.String>>` from Array value (token `JsonToken.START_ARRAY`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.LinkedHashMap<java.lang.String,java.util.List<java.lang.String>>` from Array value (token `JsonToken.START_ARRAY`)<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]]
Idk how to solve this. I've tried searching around, but havent found any answer. Im also unsure if the problem is in my react code or in my springboot code.
I think my error is in reactjs, because ive seen in other posts for people have somewhat the same problem, that their problem has been their react code. But I havent figured out what exactly might be wrong with my react code. Im also posting my spring boot code in case you may want to look at it,
My react code:
const FileUpload = () => {
const link = "http://localhost:8080/uploadimage?key"
var formData = new FormData()
const [fileName, setFilename] = useState("")
const [tags, setTags] = useState([])
{/* THIS IS CODE FOR SELECTING A FILE TO UPLOAD*/}
{/* IM TRYING TO DEFINE IMAGE BY PUTTING IT IN QUOTES IN FROMDATA.APPEND */}
const handleFile = (e) => {
setFilename(e.target.files[0].name)
console.log("handle file")
console.log(e.target.files[0])
formData.append("image", e.target.files[0])
}
const uploadFile = (e) => {
{/* THIS IS CODE FOR FILE UPLOADING*/}
console.log("sending...")
console.log(formData)
axios.post(
link,
formData, {
header: {
'Content-Type': 'multipart/form-data'
}
})
.then(res => {
console.log(res.data)
})
.catch(error => {
console.log(error)
})
{/* THIS IS CODE FOR SOMETHING ELSE; SOME TAGHANDLING */}
setTimeout(3000)
const taglink = "http://localhost:8080/givetags/" + fileName;
axios.post(taglink, tags)
.then(res => (
console.log(res.data)
))
}
{/* THIS IS CODE IS ALSO FOR SOMETHING ELSE*/}
function updateTags(e) {
const log = {...tags}
log[e.target.id] = e.target.value.split(" ")
setTags(log)
}
return (
<div>
<Container>
<Card.Title className='text-center mb-3'>Upload File</Card.Title>
<Form.Group controlId='file' className='mb-3'>
<Form.Control type='file' onChange={(e) => handleFile(e)}></Form.Control>
</Form.Group>
<Form.Group controlId='tags' className='mb-3'>
<Form.Control onChange={(e) => updateTags(e)} type="text" placeholder='Write tags'></Form.Control>
</Form.Group>
<Button onClick={(e) => uploadFile(e)}>Upload File</Button>
</Container>
<TagsConvention></TagsConvention>
</div>
)
}
export default FileUpload
This is my springboot code:
Controller:
#RestController
public class FileController {
#Autowired
private ImageServiceImpl service;
//==========================For uploading a file======================================
#CrossOrigin(origins = "http://localhost:3000")
#PostMapping("/uploadimage")
public ResponseEntity<?> uploadImage(#RequestParam("image") MultipartFile file) throws IOException {
String uploadImage = service.uploadImage(file);
return ResponseEntity.status(HttpStatus.OK)
.body(uploadImage);
}
#CrossOrigin(origins = "http://localhost:3000")
#GetMapping("/getimage/{fileName}")
public ResponseEntity<?> downloadImage(#PathVariable String fileName){
byte[] file=service.downloadImage(fileName);
System.out.println(file);
return ResponseEntity.status(HttpStatus.OK)
.contentType(MediaType.valueOf(service.getType(fileName)))
.body(file);
}
#CrossOrigin(origins = "http://localhost:3000")
#PostMapping("/givetags/{fileName}")
public ImageData giveImagetags(#PathVariable String fileName, #RequestBody Map<String, List<String>> tags) {
//return service.giveImageTags(fileName, tags);
//return service.giveImageTags(fileName, tags);
System.out.println(tags);
List<String> tagList = tags.get("tags");
return service.giveImageTags(fileName, tagList);
}
#CrossOrigin(origins = "http://localhost:3000")
#GetMapping("/getallimages")
public List<String> getAllImages() {
return service.getAllImages();
}
}
My model for the image:
#Entity
#Table(name = "ImageData")
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
public class ImageData implements Image{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long imageDataId;
private String name;
private String type;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name="file_has_tag",
joinColumns = {#JoinColumn(name="image_data_id")},
inverseJoinColumns = {#JoinColumn(name = "tag_id")})
#JsonIgnoreProperties("image_data")
private Set<Tag> tags;
#Lob
#Column(name = "image_data",length = 1000)
private byte[] data;
#Override
public String toString() {
return "ImageData{" +
"imageDataId=" + imageDataId +
", name='" + name + '\'' +
", type='" + type + '\'' +
", tags=" + tags +
'}';
}
}
Service function for uploading a file:
public String uploadImage(MultipartFile file) throws IOException {
ImageData imageData = imageDataRepository.save(ImageData.builder()
.name(file.getOriginalFilename())
.type(file.getContentType())
.data(ImageUtils.compressImage(file.getBytes())).build()); //"data" is from the model class
System.out.println(imageData.toString());
if (imageData != null) {
return "file uploaded successfully : " + file.getOriginalFilename();
}
return null;
}
functions in utils class for compressing image
public static byte[] compressImage(byte[] data) {
Deflater deflater = new Deflater();
deflater.setLevel(Deflater.BEST_COMPRESSION);
deflater.setInput(data);
deflater.finish();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] tmp = new byte[4*1024];
while (!deflater.finished()) {
int size = deflater.deflate(tmp);
outputStream.write(tmp, 0, size);
}
try {
outputStream.close();
} catch (Exception ignored) {
}
return outputStream.toByteArray();
}
Ive tried to change the value of formdata, and the key in "image" in fromdata.append, but I havent figured it out. Ive also tried to search up the problem, but people have had different syntax problems from me, so idk what might be the problem.
There are two questions:
(1)Required request part 'image' is not present, the problem should be the parameter name problem, The #RequestParam("image") prefix must be "image". You can check if some parameter names are image.
(2)JSON parse error: In my opinion, the main cause of the problem is the API: givetags, #RequestBody Map<String, List> tags, which is not translated properly when receiving the react parameter. You can try using List to receive arguments.

Allow users to upload and save file to my GCS Bucket using BlobstoreService, how to identify the uploaded files?

Please help.I'm trying to upload video file (.mp4) to GCS bucket using BlobstoreService.
The file is successfully uploaded and saved automatically in my GCS Bucket, and client received value "YES" for the key "upload_result".
The problem is that I don't know how to identify the uploaded file saved in my bucket by BlobstoreService and how to get other imformation such as 'foo'and 'bar' key-value from the request.
Document says that I can use BlobInfo#getGsObjectName() to get the name, but it seems that the method is not available now.
I can get the 'blobkey' from the request, but I think it works only for the Blobstore and not for GCS.
Yes, I can get the original file name, but the original name is lost in GCS and the object name is the only thing.
com.google.appengine.api.blobstore.BlobInfo
https://cloud.google.com/appengine/docs/java/javadoc/com/google/appengine/api/blobstore/BlobInfo.html#getGsObjectName--
///// JSP ///////
<%!
final String BUCKT_NAME = "my_bucket";
final long MAX_SIZE = 1024 * 1024 * 300;
String uploadURL;
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
UploadOptions uploadOptions = UploadOptions.Builder
.withGoogleStorageBucketName(BUCKET_NAME)
.maxUploadSizeBytes(MAX_SIZE);
uploadURL = blobstoreService.createUploadUrl("/handler", uploadOptions);
%>
///// HTML Form ///////
<form id="file_upload_form" action="" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file">
<button type="button">UPLOAD</button>
<input type="hidden" name="foo" value="bar"> <-- I want to upload additional information with the video file.
</form>
///// ajax ///////
function uploadFile(){
var fd = new FormData($('#file_upload_form').get(0));
$.ajax({
url: "<%=uploadURL %>",
type: 'POST',
data: fd,
processData: false,
contentType: false,
dataType: 'json'
})
.done(function( data ) {
if(data['upload_result'] == 'YES'){
//Do sometihng
}
else{
//Do something
}
});
}
///// SERVLET(Slim3 Controller) (/handler) ///////
private Navigation doPost() {
HttpServletRequest httpServletRequest = RequestLocator.get();
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(httpServletRequest);
List<BlobKey> blobKeys = blobs.get("uploaded_file");
BlobKey fileKey = blobKeys.get(0);
BlobInfoFactory blobInfoFactory = new BlobInfoFactory();
BlobInfo blobInfo = blobInfoFactory.loadBlobInfo(fileKey);
String originalFileName = blobInfo.getFilename();
long filesize = blobInfo.getSize();
//String gcsObjectName = blobInfo.getGsObjectName(); <<-- Most important thing is not available.
if(blobKey!=null){
String result = "{\"upload_result\":\"YES\"}";
response.setCharacterEncoding("utf-8");
response.setContentType("application/json");
try {
response.getWriter().println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
EDITED.
Use FileInfo instead of BlobInfo to get the generated GCS object name. Here is the working code for this case.
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
Map<String, List<FileInfo>> fileInfos = blobstoreService.getFileInfos(request);
List<FileInfo> infos = fileInfos.get("uploaded_file");
FileInfo info = infos.get(0);
String gcsObjectName = info.getGsObjectName(); // <--
The blob key is the unique identifier for both gcs and blobstore - more details here https://cloud.google.com/appengine/docs/java/blobstore/#Java_Using_the_Blobstore_API_with_Google_Cloud_Storage. For gcs you use the following
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
BlobKey blobKey = blobstoreService.createGsBlobKey(
"/gs/" + fileName.getBucketName() + "/" + fileName.getObjectName());
blobstoreService.serve(blobKey, resp);

how to Add attachment in ICS file

I tried to add attachment in ics file but it not showing in outlook when open it. I am trying to add attachment like when we send meeting request and add attachment in that from outlook, that attachment can view from calendar as well. This is my ics file :
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//appform.com//NONSGML kigkonsult.se iCalcreator 2.18//
METHOD:PUBLISH
X-WR-TIMEZONE:UTC
X-MS-OLK-FORCEINSPECTOROPEN:TRUE
BEGIN:VEVENT
UID:20160719T144014-694839744#appform.com
DTSTAMP:20160719T124014Z
ATTACH;FMTTYPE="application/msword; charset=binary";FILENAME=1468827330fCrj
O.doc:/var/www/html/basearch.appform.com/application/../public/uploads/146
8827330fCrjO.doc
ATTENDEE;RSVP=TRUE;SENT-BY="MAILTO:sajal#mailinator.com";CN=satyendra#hirest
orm.com;DIR="/var/www/html/app/application/../public/uplo
ads/1468827330fCrjO.doc";LANGUAGE=us-EN;X-AGENDA=Interview;X-LENGTH=30 min
:MAILTO:satyendra#mailinator.com
DESCRIPTION:Name: Dean Nestle Jones G\nVacancy: test\nEmployer: Zend\nDate:
Wednesday\, 20thJuly 2016\nTime: 1430 to 1500\n\nSubmit Feedback : http:/
/hirestorm.com/tms/a/Mg==/appid/NDU4/vacid/MTY4/candid/MTY=\n\nCandida
te CV : https://f12b1a775b358d1fc463-637e94f874af614e321f6.ssl.
cf2.rackcdn.com/1468827330fCrjO.doc\nOther Documents : https://f12b1a775
b358d1fc463-637e94f874af614cdn.com/146297361
8PwEwE.jpeg\n
DTSTART:20160720T090000Z
DTEND:20160720T093000Z
LOCATION:1 2 Elmshorn Schleswig-Holstein Germany
SEQUENCE:0
SUMMARY:New Interview Confirmed: Dean Nestle Jones G for test
BEGIN:VALARM
ACTION:PROCEDURE
DESCRIPTION:Name: Dean Nestle Jones G\nVacancy: test\nEmployer: Zend\nDate:
Wednesday\, 20thJuly 2016\nTime: 1430 to 1500\n\nSubmit Feedback : http:/
/hirestorm.com/tms/a/Mg==/appid/NDU4/vacid/MTY4/candid/MTY=\n\nCandida
te CV : https://f12b1a775b358d1fc463-637e94f874af614ce048a5e321d7d0f6.ssl.
cf2.rackcdn.com/1468827330fCrjO.doc\nOther Documents : https://f12b1a775
b358d1fc463-637e94f874af614ce048a5e32cdn.com/146297361
8PwEwE.jpeg\n
TRIGGER:-PT0H15M0S
END:VALARM
END:VEVENT
END:VCALENDAR
Your iCalendar file contains a reference to :
/var/www/html/basearch.appform.com/application/../public/uploads/1468827330fCrjO.doc
This would obviously be something on your machine. You're not embedding any file, you're just pasting a local path. Unless you have Outlook running on linux there's no way it can find that path.
I tried to do it in a simple java
import java.io.IOException;
import java.net.URI;
import java.text.ParseException;
import java.util.HashMap;
import javax.activation.DataHandler;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import com.tba.readProps.Constants;
import com.tba.readProps.ReadProps;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.parameter.Cn;
import net.fortuna.ical4j.model.parameter.Role;
import net.fortuna.ical4j.model.property.Attendee;
import net.fortuna.ical4j.model.property.CalScale;
import net.fortuna.ical4j.model.property.ProdId;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Version;
import net.fortuna.ical4j.util.RandomUidGenerator;
import net.fortuna.ical4j.util.UidGenerator;
public class EmailWithCalendar{
/**
* #param emailAddr
* #param subject
* #param message
*/
public static void sendHtmlEmail(String emailAddr, String subject, String message){
HashMap propertyValues = null;
String smtpHost = "";
try {
propertyValues = ReadProps.initializeProperties();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
smtpHost = (String) propertyValues.get(Constants.SMTP_HOST);
//ManagerPropertiesBean mgrProps = new ManagerPropertiesBean();
//String smtpHost = mgrProps.getMgrProperty("smtpHost");
try {
// start a session with given properties
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
Session mailSession = Session.getDefaultInstance(props, null);
String fromAddress = null;
fromAddress = (String) propertyValues.get(Constants.FROM_ADDRESS);
if(!"undefined".equals(fromAddress)){
InternetAddress fromAddr = new InternetAddress("test#test.com");
InternetAddress toAddr = new InternetAddress(emailAddr);
MimeMessage myMessage = new MimeMessage(mailSession);
String replyToAddress = null;
replyToAddress = (String) propertyValues.get(Constants.REPLY_ADDRESS);
InternetAddress replyToAddr[] = new InternetAddress[1];
if(!"undefined".equals(replyToAddress))
replyToAddr[0] = new InternetAddress(replyToAddress);
boolean isfromValid = true;
boolean isToValid = true;
boolean emailDomainCheck = true;
MimeBodyPart messageBodyPart =new MimeBodyPart();
messageBodyPart.setContent(message ,"text/html" );
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
myMessage.setContent(multipart);
if(emailDomainCheck==true)
{
myMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddr);
myMessage.setReplyTo(replyToAddr);
}
else
{
myMessage.setFrom(fromAddr);
myMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddr);
if(!"undefined".equals(replyToAddress))
myMessage.setReplyTo(replyToAddr);
}
myMessage.setSentDate(new java.util.Date());
myMessage.setSubject(subject);
messageBodyPart.setDataHandler(new DataHandler(
new ByteArrayDataSource(createEvent().toString(), "text/calendar")));// very important
//myMessage.setText(message);
// now send the message!
if(emailDomainCheck==true)
{
if(isfromValid==true && isToValid==true)
{
Transport.send(myMessage);
}
}
else
{
Transport.send(myMessage);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error occurred in ManagerEmailBean.sendHtmlEmail()");
}
}
private static Calendar createEvent() throws ParseException {
// Create the event
String eventName = "Progress Meeting";
//DateTime start = new DateTime(startDate.getTime());
//DateTime end = new DateTime(endDate.getTime());
// Create the date range which is desired.
DateTime start = new DateTime("20100101T070000Z");
DateTime end = new DateTime("20100201T070000Z");;
Period period = new Period(start, end);
VEvent meeting = new VEvent(start, end, eventName);
// add timezone info..
//meeting.getProperties().add(tz.getTimeZoneId());
// generate unique identifier..
UidGenerator ug = new RandomUidGenerator();
Uid uid = ug.generateUid();
meeting.getProperties().add(uid);
// add attendees..
Attendee dev1 = new Attendee(URI.create("mailto:dev1#test.com"));
dev1.getParameters().add(Role.REQ_PARTICIPANT);
dev1.getParameters().add(new Cn("Developer 1"));
meeting.getProperties().add(dev1);
Attendee dev2 = new Attendee(URI.create("mailto:dev2#test.com"));
dev2.getParameters().add(Role.OPT_PARTICIPANT);
dev2.getParameters().add(new Cn("Developer 2"));
meeting.getProperties().add(dev2);
// Create a calendar
net.fortuna.ical4j.model.Calendar icsCalendar = new net.fortuna.ical4j.model.Calendar();
icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
icsCalendar.getProperties().add(Version.VERSION_2_0);
icsCalendar.getProperties().add(CalScale.GREGORIAN);
// Add the event and print
icsCalendar.getComponents().add(meeting);
System.out.println(icsCalendar);
return icsCalendar;
}
public static void main(String[] args) {
sendHtmlEmail("dev.test#gmail.com", "Test", "sjgsfgsf<p>dshdfsdf</p>");
}
}

send array of data from POJO to JSP

I had a problem on printing array of data in JSP, heres what happend.
I created a POJO called: popArayCustOrd
public class popAryCustOrd {
public String prodkey,descrp,strgth,stkunt;
double rprice;
int quantity;
popAryCustOrd(String prodkey,String descrp,int quantity,Double rprice,String stkunt,String strgth){
this.prodkey = prodkey;
this.descrp = descrp;
this.quantity = quantity;
this.rprice = rprice;
this.stkunt = stkunt;
this.strgth = strgth;
}
public void setProdkey(String prodkey){
this.prodkey = prodkey;
}
public String getProdkey(){
return(this.prodkey);
}
public void setDescrp(String descrp){
this.descrp = descrp;
}
public String getDescrp(){
return(this.descrp);
}
public void setQuantity(int quantity){
this.quantity = quantity;
}
public int getQuantity(){
return(this.quantity);
}
public void setRprice(double rprice){
this.rprice = rprice;
}
public double getRprice(){
return(this.rprice);
}
public void setStkunt(String stkunt){
this.stkunt = stkunt;
}
public String getStkunt(){
return(this.stkunt);
}
public void setStrgth(String strgth){
this.strgth = strgth;
}
public String getStrgth(){
return(this.strgth);
}
}
and in my servlet file called seekprod.java I assigned data coming from the database within a method....
connx.rs.beforeFirst();
while(connx.rs.next()){
popAryCustOrd[] prodList = new popAryCustOrd[]{new popAryCustOrd(connx.rs.getString("prodkey"),connx.rs.getString("descrp"),connx.rs.getInt("quantity"),connx.rs.getDouble("retailp"),connx.rs.getString("stkunit"),connx.rs.getString("strength"))};
request.setAttribute("prodList", prodList);
}
RequestDispatcher dispatcher = request.getRequestDispatcher("preOrdFrm.jsp? inKey="+this.inKey+"&transkey=drugs");
dispatcher.forward(request, response);
.......
and my JSP to access the data is.....
<c:forEach items="${prodList}" var="paramx" >
<tr>
<td>${paramx.prodkey}</td>
<td style="text-align: center; word-wrap: break-word; word-break:break-all; text-overflow: ellipsis;overflow:hidden;white-space: normal; white-space: -webkit-pre-wrap;">${paramx.descrp}</td>
<td>${paramx.stkunt}</td>
<td>${paramx.strgth}</td>
<td>${paramx.rprice}</td>
<td>${paramx.quantity}</td>
<td><input type="hidden" name="agentId" value="<%=uID %>">
<input type="hidden" name="pcode" value=${paramx.prodkey}>
<input type="hidden" name="inKey" value=${param.inKey}>
<input type="hidden" name="transKey" value="sveOrd">
<input style="font-size:50px; height:55px; width:100px" type="number" name="desqty" min="1" required="" value="1"/></td>
<td><input style="font-size:20px; height:55px; width:100px" type="submit" name="transact" value="Save"/></td>
</tr>
</c:forEach>
eventually it works but I got only one result instead of three records from the database table, my syntax in sql is correct and i checked it many times and compared with the result. I dont know where part of my code to fix. Im very much glad if you could help me .?
while(connx.rs.next()){
popAryCustOrd[] prodList = new popAryCustOrd[]{new
popAryCustOrd(connx.rs.getString("prodkey"),connx.rs.getString("descrp"),connx.rs.getInt("quantity"),connx.rs.getDouble("retailp"),connx.rs.getString("stkunit"),connx.rs.getString("strength"))};
request.setAttribute("prodList", prodList);
}
think about this code it sets and then resets prodList attribute in the request object with every loop execution, so your jsp will recieve only the last value set to prodList.
It would be better to initialize an ArrayList outside the loop and add values to it and then after the loop use that list to set the attribute prodList in request object.

Saving a data:url of a PNG image locally using Google App Engine

I am using Google App Engine (python) and have a data: url of a PNG image available on the server. The PNG image was never in a file, as it was generated from some canvas code using toDataUrl() and ajaxed to the server. I would like to allow the user to click a button and be able to select a filename and save the PNG image locally. The Save As dialog box would supply a default filename.png. The target browser is FireFox. I have supplied sample code that doesn't work. There are several questions on stackoverflow that are somewhat like this one, but each is a little different.
I am setting content-disposition as attachment with a suggested filename. I set the header content-type to application/octet-stream. But I don't get the SaveAs dialog. What am I missing?
The app.yaml file is the standard
application: saveas
version: 1
runtime: python
api_version: 1
handlers:
- url: /.*
script: main.py
The index.html is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<script>
function saveAsPng()
{
var alldata;
var httpRequest;
var response;
var myheaders;
httprequest = new XMLHttpRequest();
if ( !httprequest )
{
alert("In saveAsPng, XMLHttpRequest failed.");
return;
}
/* Make this a json string */
alldata = JSON.stringify("no data");
try
{
httprequest.open('POST', '/handlebitmap', true);
httprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httprequest.setRequestHeader("Content-length", alldata.length);
httprequest.setRequestHeader("Connection", "close");
httprequest.onreadystatechange = function()
{
if ( httprequest.readyState == 4 )
{
if (httprequest.status == 200)
{
/* a status of 200 is good. */
response = null;
try
{
response = JSON.parse(httprequest.responseText);
}
catch (e)
{
response = httprequest.responseText;
}
if ( response == "error" )
{
alert("In saveAsPng callback, response == error");
return false;
}
else
{
/* This is the successful exit. */
//alert("response = " +response);
window.location.href = response;
return true;
}
}
else
{
/* httprequest.status was not 200, so must be an error. */
alert("saveAsPNG callback, status = " +httprequest.status);
return false;
}
} /* End of if where readyState was 4. */
} /* End of the callback function */
/* Make the actual request */
httprequest.send(alldata);
}
catch(e)
{
alert("In saveAsPng, Can't connect to the server");
}
} /* End of the saveAsPng function */
The python code is as follows:
# !/usr/bin/env python
import os
import base64
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
class MainPage(webapp.RequestHandler):
""" Renders the main template."""
def get(self):
template_values = { 'title':'Test Save As PNG', }
path = os.path.join(os.path.dirname(__file__), "index.html")
self.response.out.write(template.render(path, template_values))
class BitmapHandler(webapp.RequestHandler):
""" Shows the Save As with a default filename. """
def post(self):
origdata = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
urldata = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
decodeddata = base64.b64decode(urldata)
self.response.headers['Content-Type'] = 'application/octet-stream'
self.response.headers['Content-Disposition'] = 'attachment; filename="untitled.png"'
self.response.out.write(decodeddata)
def main():
app = webapp.WSGIApplication([
('/', MainPage),
('/handlebitmap',BitmapHandler),
], debug=True)
util.run_wsgi_app(app)
if __name__ == '__main__':
main()
{{title}}
Perhaps you want to change the "def post" to a "def get"? I just tried your sample and it seemed to be working as expected after that change (only tried /handlebitmap)

Resources