List of usage examples for org.apache.commons.fileupload FileItem get
byte[] get();
From source file:org.unitime.timetable.events.ApproveEventBackend.java
@Override public SaveOrApproveEventRpcResponse execute(ApproveEventRpcRequest request, EventContext context) { org.hibernate.Session hibSession = SessionDAO.getInstance().getSession(); Transaction tx = hibSession.beginTransaction(); try {//from w ww . java 2 s. c o m Session session = SessionDAO.getInstance().get(request.getSessionId(), hibSession); SaveOrApproveEventRpcResponse response = new SaveOrApproveEventRpcResponse(); Event event = (request.getEvent() == null || request.getEvent().getId() == null ? null : EventDAO.getInstance().get(request.getEvent().getId(), hibSession)); if (event == null) throw new GwtRpcException(MESSAGES.failedApproveEventNoEvent()); if (!request.hasMeetings()) throw new GwtRpcException(MESSAGES.failedApproveEventNoMeetings()); Date now = new Date(); Set<Meeting> affectedMeetings = new HashSet<Meeting>(); meetings: for (Iterator<Meeting> i = event.getMeetings().iterator(); i.hasNext();) { Meeting meeting = i.next(); for (MeetingInterface m : request.getMeetings()) { if (meeting.getUniqueId().equals(m.getId())) { response.addUpdatedMeeting(m); affectedMeetings.add(meeting); switch (request.getOperation()) { case REJECT: if (!context.hasPermission(meeting, Right.EventMeetingApprove)) throw new GwtRpcException( MESSAGES.failedApproveEventNoRightsToReject(toString(meeting))); // hibSession.delete(meeting); // i.remove(); meeting.setStatus(Meeting.Status.REJECTED); meeting.setApprovalDate(now); m.setApprovalDate(now); m.setApprovalStatus(meeting.getApprovalStatus()); hibSession.saveOrUpdate(meeting); break; case APPROVE: if (!context.hasPermission(meeting, Right.EventMeetingApprove)) throw new GwtRpcException( MESSAGES.failedApproveEventNoRightsToApprove(toString(meeting))); meeting.setStatus(Meeting.Status.APPROVED); meeting.setApprovalDate(now); m.setApprovalDate(now); m.setApprovalStatus(meeting.getApprovalStatus()); hibSession.saveOrUpdate(meeting); break; case CANCEL: switch (meeting.getEvent().getEventType()) { case Event.sEventTypeFinalExam: case Event.sEventTypeMidtermExam: if (!context.hasPermission(meeting, Right.EventMeetingCancelExam)) throw new GwtRpcException( MESSAGES.failedApproveEventNoRightsToCancel(toString(meeting))); break; case Event.sEventTypeClass: if (!context.hasPermission(meeting, Right.EventMeetingCancelClass)) throw new GwtRpcException( MESSAGES.failedApproveEventNoRightsToCancel(toString(meeting))); break; default: if (!context.hasPermission(meeting, Right.EventMeetingCancel)) throw new GwtRpcException( MESSAGES.failedApproveEventNoRightsToCancel(toString(meeting))); break; } meeting.setStatus(Meeting.Status.CANCELLED); meeting.setApprovalDate(now); m.setApprovalDate(now); m.setApprovalStatus(meeting.getApprovalStatus()); hibSession.saveOrUpdate(meeting); break; } continue meetings; } } } EventNote note = new EventNote(); note.setEvent(event); switch (request.getOperation()) { case APPROVE: note.setNoteType(EventNote.sEventNoteTypeApproval); break; case REJECT: note.setNoteType(EventNote.sEventNoteTypeRejection); break; case CANCEL: note.setNoteType(EventNote.sEventNoteTypeCancel); break; default: note.setNoteType(EventNote.sEventNoteTypeInquire); } note.setTimeStamp(now); note.setUser(context.getUser().getTrueName()); note.setUserId(context.getUser().getTrueExternalUserId()); note.setAffectedMeetings(affectedMeetings); note.setMeetings(EventInterface.toString(response.getUpdatedMeetings(), CONSTANTS, "\n", new EventInterface.DateFormatter() { Formats.Format<Date> dfShort = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_SHORT); Formats.Format<Date> dfLong = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_LONG); @Override public String formatFirstDate(Date date) { return dfShort.format(date); } @Override public String formatLastDate(Date date) { return dfLong.format(date); } })); if (request.hasMessage()) note.setTextNote(request.getMessage()); FileItem attachment = (FileItem) context.getAttribute(UploadServlet.SESSION_LAST_FILE); if (attachment != null) { note.setAttachedName(attachment.getName()); note.setAttachedFile(attachment.get()); note.setAttachedContentType(attachment.getContentType()); } event.getNotes().add(note); hibSession.saveOrUpdate(note); NoteInterface n = new NoteInterface(); n.setId(note.getUniqueId()); n.setDate(now); n.setMeetings(note.getMeetings()); n.setUser(context.getUser().getTrueName()); n.setType(NoteInterface.NoteType.values()[note.getNoteType()]); n.setNote(request.getMessage()); n.setAttachment(attachment == null ? null : attachment.getName()); n.setLink(attachment == null ? null : QueryEncoderBackend.encode("event=" + event.getUniqueId() + "¬e=" + note.getUserId())); response.addNote(n); if (event.getMeetings().isEmpty()) { response.setEvent(EventDetailBackend.getEventDetail( SessionDAO.getInstance().get(request.getSessionId(), hibSession), event, context)); response.getEvent().setId(null); hibSession.delete(event); } else { hibSession.update(event); response.setEvent(EventDetailBackend.getEventDetail(session, event, context)); } tx.commit(); tx = null; new EventEmail(request, response).send(context); return response; } catch (Exception ex) { if (tx != null) tx.rollback(); if (ex instanceof GwtRpcException) throw (GwtRpcException) ex; throw new GwtRpcException(ex.getMessage(), ex); } }
From source file:org.unitime.timetable.events.SaveEventBackend.java
@Override public SaveOrApproveEventRpcResponse execute(SaveEventRpcRequest request, EventContext context) { if (request.getEvent().hasContact() && (request.getEvent().getContact().getExternalId() == null || !request .getEvent().getContact().getExternalId().equals(context.getUser().getExternalUserId()))) { switch (request.getEvent().getType()) { case Special: case Course: case Unavailabile: context.checkPermission(Right.EventLookupContact); }// ww w. j av a2 s . c o m } if (request.getEvent().getId() == null) { // new even switch (request.getEvent().getType()) { case Special: context.checkPermission(Right.EventAddSpecial); break; case Course: context.checkPermission(Right.EventAddCourseRelated); break; case Unavailabile: context.checkPermission(Right.EventAddUnavailable); break; default: throw context.getException(); } } else { // existing event context.checkPermission(request.getEvent().getId(), "Event", Right.EventEdit); } // Check main contact email if (request.getEvent().hasContact() && request.getEvent().getContact().hasEmail()) { try { new InternetAddress(request.getEvent().getContact().getEmail(), true); } catch (AddressException e) { throw new GwtRpcException( MESSAGES.badEmailAddress(request.getEvent().getContact().getEmail(), e.getMessage())); } } // Check additional emails if (request.getEvent().hasEmail()) { String suffix = ApplicationProperty.EmailDefaultAddressSuffix.value(); for (String address : request.getEvent().getEmail().split("[\n,]")) { String email = address.trim(); if (email.isEmpty()) continue; if (suffix != null && email.indexOf('@') < 0) email += suffix; try { new InternetAddress(email, true); } catch (AddressException e) { throw new GwtRpcException(MESSAGES.badEmailAddress(address, e.getMessage())); } } } org.hibernate.Session hibSession = SessionDAO.getInstance().getSession(); Transaction tx = hibSession.beginTransaction(); try { Session session = SessionDAO.getInstance().get(request.getSessionId(), hibSession); Date now = new Date(); Event event = null; if (request.getEvent().getId() != null) { event = EventDAO.getInstance().get(request.getEvent().getId(), hibSession); } else { switch (request.getEvent().getType()) { case Special: event = new SpecialEvent(); break; case Course: event = new CourseEvent(); break; case Unavailabile: event = new UnavailableEvent(); break; default: throw new GwtRpcException( MESSAGES.failedSaveEventWrongType(request.getEvent().getType().getName(CONSTANTS))); } } SaveOrApproveEventRpcResponse response = new SaveOrApproveEventRpcResponse(); event.setEventName(request.getEvent().getName()); if (event.getEventName() == null || event.getEventName().isEmpty() && request.getEvent().getType() == EventType.Unavailabile) event.setEventName(MESSAGES.unavailableEventDefaultName()); event.setEmail(request.getEvent().getEmail()); if (context.hasPermission(Right.EventSetExpiration) || event.getExpirationDate() != null) event.setExpirationDate(request.getEvent().getExpirationDate()); event.setSponsoringOrganization(request.getEvent().hasSponsor() ? SponsoringOrganizationDAO.getInstance().get(request.getEvent().getSponsor().getUniqueId()) : null); if (event instanceof UnavailableEvent) { } else if (event instanceof SpecialEvent) { event.setMinCapacity(request.getEvent().getMaxCapacity()); event.setMaxCapacity(request.getEvent().getMaxCapacity()); } if (event.getAdditionalContacts() == null) { event.setAdditionalContacts(new HashSet<EventContact>()); } if (context.hasPermission(Right.EventLookupContact)) { Set<EventContact> existingContacts = new HashSet<EventContact>(event.getAdditionalContacts()); event.getAdditionalContacts().clear(); if (request.getEvent().hasAdditionalContacts()) for (ContactInterface c : request.getEvent().getAdditionalContacts()) { if (c.getExternalId() == null) continue; EventContact contact = null; for (EventContact x : existingContacts) if (c.getExternalId().equals(x.getExternalUniqueId())) { contact = x; break; } if (contact == null) { contact = (EventContact) hibSession .createQuery("from EventContact where externalUniqueId = :externalId") .setString("externalId", c.getExternalId()).setMaxResults(1).uniqueResult(); } if (contact == null) { contact = new EventContact(); contact.setExternalUniqueId(c.getExternalId()); contact.setFirstName(c.getFirstName()); contact.setMiddleName(c.getMiddleName()); contact.setLastName(c.getLastName()); contact.setAcademicTitle(c.getAcademicTitle()); contact.setEmailAddress(c.getEmail()); contact.setPhone(c.getPhone()); hibSession.save(contact); } event.getAdditionalContacts().add(contact); } } EventContact main = event.getMainContact(); if (main == null || main.getExternalUniqueId() == null || !main.getExternalUniqueId().equals(request.getEvent().getContact().getExternalId())) { main = (EventContact) hibSession .createQuery("from EventContact where externalUniqueId = :externalId") .setString("externalId", request.getEvent().getContact().getExternalId()).setMaxResults(1) .uniqueResult(); if (main == null) { main = new EventContact(); main.setExternalUniqueId(request.getEvent().getContact().getExternalId()); } } main.setFirstName(request.getEvent().getContact().getFirstName()); main.setMiddleName(request.getEvent().getContact().getMiddleName()); main.setLastName(request.getEvent().getContact().getLastName()); main.setAcademicTitle(request.getEvent().getContact().getAcademicTitle()); main.setEmailAddress(request.getEvent().getContact().getEmail()); main.setPhone(request.getEvent().getContact().getPhone()); hibSession.saveOrUpdate(main); event.setMainContact(main); if (event.getNotes() == null) event.setNotes(new HashSet<EventNote>()); if (event.getMeetings() == null) event.setMeetings(new HashSet<Meeting>()); Set<Meeting> remove = new HashSet<Meeting>(event.getMeetings()); TreeSet<Meeting> createdMeetings = new TreeSet<Meeting>(); Set<Meeting> cancelledMeetings = new TreeSet<Meeting>(); Set<Meeting> updatedMeetings = new TreeSet<Meeting>(); for (MeetingInterface m : request.getEvent().getMeetings()) { Meeting meeting = null; if (m.getApprovalStatus() == ApprovalStatus.Deleted) { if (!context.hasPermission(meeting, Right.EventMeetingDelete) && context.hasPermission(meeting, Right.EventMeetingCancel)) { // Cannot delete, but can cancel --> cancel the meeting instead m.setApprovalStatus(ApprovalStatus.Cancelled); } else { continue; } } if (m.getId() != null) for (Iterator<Meeting> i = remove.iterator(); i.hasNext();) { Meeting x = i.next(); if (m.getId().equals(x.getUniqueId())) { meeting = x; i.remove(); break; } } if (meeting != null) { if (m.getApprovalStatus().ordinal() != meeting.getApprovalStatus()) { switch (m.getApprovalStatus()) { case Cancelled: switch (meeting.getEvent().getEventType()) { case Event.sEventTypeFinalExam: case Event.sEventTypeMidtermExam: if (!context.hasPermission(meeting, Right.EventMeetingCancelExam)) throw new GwtRpcException( MESSAGES.failedApproveEventNoRightsToCancel(toString(meeting))); break; case Event.sEventTypeClass: if (!context.hasPermission(meeting, Right.EventMeetingCancelClass)) throw new GwtRpcException( MESSAGES.failedApproveEventNoRightsToCancel(toString(meeting))); break; default: if (!context.hasPermission(meeting, Right.EventMeetingCancel)) throw new GwtRpcException( MESSAGES.failedApproveEventNoRightsToCancel(toString(meeting))); break; } meeting.setStatus(Meeting.Status.CANCELLED); meeting.setApprovalDate(now); hibSession.update(meeting); cancelledMeetings.add(meeting); response.addCancelledMeeting(m); } } else { if (m.getStartOffset() != (meeting.getStartOffset() == null ? 0 : meeting.getStartOffset()) || m.getEndOffset() != (meeting.getStopOffset() == null ? 0 : meeting.getStopOffset())) { if (!context.hasPermission(meeting, Right.EventMeetingEdit)) throw new GwtRpcException( MESSAGES.failedSaveEventCanNotEditMeeting(toString(meeting))); meeting.setStartOffset(m.getStartOffset()); meeting.setStopOffset(m.getEndOffset()); hibSession.update(meeting); response.addUpdatedMeeting(m); updatedMeetings.add(meeting); } } } else { response.addCreatedMeeting(m); meeting = new Meeting(); meeting.setEvent(event); Location location = null; if (m.hasLocation()) { if (m.getLocation().getId() != null) location = LocationDAO.getInstance().get(m.getLocation().getId(), hibSession); else if (m.getLocation().getName() != null) location = Location.findByName(hibSession, request.getSessionId(), m.getLocation().getName()); } if (location == null) throw new GwtRpcException(MESSAGES.failedSaveEventNoLocation(toString(m))); meeting.setLocationPermanentId(location.getPermanentId()); meeting.setStatus(Meeting.Status.PENDING); meeting.setApprovalDate(null); if (!context.hasPermission(location, Right.EventLocation)) throw new GwtRpcException(MESSAGES.failedSaveEventWrongLocation(m.getLocationName())); if (request.getEvent().getType() == EventType.Unavailabile && !context.hasPermission(location, Right.EventLocationUnavailable)) throw new GwtRpcException(MESSAGES.failedSaveCannotMakeUnavailable(m.getLocationName())); if (m.getApprovalStatus() == ApprovalStatus.Approved && context.hasPermission(location, Right.EventLocationApprove)) { meeting.setStatus(Meeting.Status.APPROVED); meeting.setApprovalDate(now); } if (context.isPastOrOutside(m.getMeetingDate())) throw new GwtRpcException( MESSAGES.failedSaveEventPastOrOutside(getDateFormat().format(m.getMeetingDate()))); if (!context.hasPermission(location, Right.EventLocationOverbook)) { List<MeetingConflictInterface> conflicts = computeConflicts(hibSession, m, event.getUniqueId()); if (!conflicts.isEmpty()) throw new GwtRpcException( MESSAGES.failedSaveEventConflict(toString(m), toString(conflicts.get(0)))); } m.setApprovalDate(meeting.getApprovalDate()); m.setApprovalStatus(meeting.getApprovalStatus()); meeting.setStartPeriod(m.getStartSlot()); meeting.setStopPeriod(m.getEndSlot()); meeting.setStartOffset(m.getStartOffset()); meeting.setStopOffset(m.getEndOffset()); meeting.setClassCanOverride(true); meeting.setMeetingDate(m.getMeetingDate()); event.getMeetings().add(meeting); createdMeetings.add(meeting); } // automatic approval if (meeting.getApprovalDate() == null) { switch (request.getEvent().getType()) { case Unavailabile: case Class: case FinalExam: case MidtermExam: meeting.setStatus(Meeting.Status.APPROVED); meeting.setApprovalDate(now); break; } } } if (!remove.isEmpty()) { for (Iterator<Meeting> i = remove.iterator(); i.hasNext();) { Meeting m = i.next(); if (!context.hasPermission(m, Right.EventMeetingDelete)) { if (m.getStatus() == Status.CANCELLED || m.getStatus() == Status.REJECTED) { i.remove(); continue; } throw new GwtRpcException(MESSAGES.failedSaveEventCanNotDeleteMeeting(toString(m))); } MeetingInterface meeting = new MeetingInterface(); meeting.setId(m.getUniqueId()); meeting.setMeetingDate(m.getMeetingDate()); meeting.setDayOfWeek(Constants.getDayOfWeek(m.getMeetingDate())); meeting.setStartTime(m.getStartTime().getTime()); meeting.setStopTime(m.getStopTime().getTime()); meeting.setDayOfYear( CalendarUtils.date2dayOfYear(session.getSessionStartYear(), m.getMeetingDate())); meeting.setStartSlot(m.getStartPeriod()); meeting.setEndSlot(m.getStopPeriod()); meeting.setStartOffset(m.getStartOffset() == null ? 0 : m.getStartOffset()); meeting.setEndOffset(m.getStopOffset() == null ? 0 : m.getStopOffset()); meeting.setPast(context.isPastOrOutside(m.getStartTime())); meeting.setApprovalDate(m.getApprovalDate()); meeting.setApprovalStatus(m.getApprovalStatus()); if (m.getLocation() != null) { ResourceInterface location = new ResourceInterface(); location.setType(ResourceType.ROOM); location.setId(m.getLocation().getUniqueId()); location.setName(m.getLocation().getLabel()); location.setSize(m.getLocation().getCapacity()); location.setRoomType(m.getLocation().getRoomTypeLabel()); location.setBreakTime(m.getLocation().getEffectiveBreakTime()); location.setMessage(m.getLocation().getEventMessage()); location.setIgnoreRoomCheck(m.getLocation().isIgnoreRoomCheck()); meeting.setLocation(location); } response.addDeletedMeeting(meeting); } event.getMeetings().removeAll(remove); } EventInterface.DateFormatter df = new EventInterface.DateFormatter() { Formats.Format<Date> dfShort = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_SHORT); Formats.Format<Date> dfLong = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_LONG); @Override public String formatFirstDate(Date date) { return dfShort.format(date); } @Override public String formatLastDate(Date date) { return dfLong.format(date); } }; FileItem attachment = (FileItem) context.getAttribute(UploadServlet.SESSION_LAST_FILE); boolean attached = false; if (response.hasCreatedMeetings()) { EventNote note = new EventNote(); note.setEvent(event); note.setNoteType(event.getUniqueId() == null ? EventNote.sEventNoteTypeCreateEvent : EventNote.sEventNoteTypeAddMeetings); note.setTimeStamp(now); note.setUser(context.getUser().getTrueName()); note.setUserId(context.getUser().getTrueExternalUserId()); if (request.hasMessage()) note.setTextNote(request.getMessage()); note.setMeetings(EventInterface.toString(response.getCreatedMeetings(), CONSTANTS, "\n", df)); note.setAffectedMeetings(createdMeetings); event.getNotes().add(note); NoteInterface n = new NoteInterface(); n.setDate(now); n.setMeetings(note.getMeetings()); n.setUser(context.getUser().getTrueName()); n.setType(NoteInterface.NoteType.values()[note.getNoteType()]); n.setNote(note.getTextNote()); if (attachment != null) { note.setAttachedName(attachment.getName()); note.setAttachedFile(attachment.get()); note.setAttachedContentType(attachment.getContentType()); attached = true; n.setAttachment(attachment.getName()); } response.addNote(n); } if (response.hasUpdatedMeetings() || (!response.hasCreatedMeetings() && !response.hasDeletedMeetings() && !response.hasCancelledMeetings())) { EventNote note = new EventNote(); note.setEvent(event); note.setNoteType(EventNote.sEventNoteTypeEditEvent); note.setTimeStamp(now); note.setUser(context.getUser().getTrueName()); note.setUserId(context.getUser().getTrueExternalUserId()); note.setAffectedMeetings(updatedMeetings); if (request.hasMessage()) note.setTextNote(request.getMessage()); if (response.hasUpdatedMeetings()) note.setMeetings(EventInterface.toString(response.getUpdatedMeetings(), CONSTANTS, "\n", df)); event.getNotes().add(note); NoteInterface n = new NoteInterface(); n.setDate(now); n.setMeetings(note.getMeetings()); n.setUser(context.getUser().getTrueName()); n.setType(NoteInterface.NoteType.values()[note.getNoteType()]); n.setNote(note.getTextNote()); if (attachment != null && !attached) { note.setAttachedName(attachment.getName()); note.setAttachedFile(attachment.get()); note.setAttachedContentType(attachment.getContentType()); attached = true; n.setAttachment(attachment.getName()); } response.addNote(n); } if (response.hasDeletedMeetings()) { EventNote note = new EventNote(); note.setEvent(event); note.setNoteType(EventNote.sEventNoteTypeDeletion); note.setTimeStamp(now); note.setUser(context.getUser().getTrueName()); note.setUserId(context.getUser().getTrueExternalUserId()); if (request.hasMessage()) note.setTextNote(request.getMessage()); note.setMeetings(EventInterface.toString(response.getDeletedMeetings(), CONSTANTS, "\n", df)); event.getNotes().add(note); NoteInterface n = new NoteInterface(); n.setDate(now); n.setMeetings(note.getMeetings()); n.setUser(context.getUser().getTrueName()); n.setType(NoteInterface.NoteType.values()[note.getNoteType()]); n.setNote(note.getTextNote()); if (attachment != null && !attached) { note.setAttachedName(attachment.getName()); note.setAttachedFile(attachment.get()); note.setAttachedContentType(attachment.getContentType()); attached = true; n.setAttachment(attachment.getName()); } response.addNote(n); } if (response.hasCancelledMeetings()) { EventNote note = new EventNote(); note.setEvent(event); note.setNoteType(EventNote.sEventNoteTypeCancel); note.setTimeStamp(now); note.setUser(context.getUser().getTrueName()); note.setUserId(context.getUser().getTrueExternalUserId()); note.setAffectedMeetings(cancelledMeetings); if (request.hasMessage()) note.setTextNote(request.getMessage()); note.setMeetings(EventInterface.toString(response.getCancelledMeetings(), CONSTANTS, "\n", df)); event.getNotes().add(note); NoteInterface n = new NoteInterface(); n.setDate(now); n.setMeetings(note.getMeetings()); n.setUser(context.getUser().getTrueName()); n.setType(NoteInterface.NoteType.values()[note.getNoteType()]); n.setNote(note.getTextNote()); if (attachment != null && !attached) { note.setAttachedName(attachment.getName()); note.setAttachedFile(attachment.get()); note.setAttachedContentType(attachment.getContentType()); attached = true; n.setAttachment(attachment.getName()); } response.addNote(n); } if (request.getEvent().getType() == EventType.Course) { CourseEvent ce = (CourseEvent) event; ce.setReqAttendance(request.getEvent().hasRequiredAttendance()); if (ce.getRelatedCourses() == null) ce.setRelatedCourses(new HashSet<RelatedCourseInfo>()); else ce.getRelatedCourses().clear(); if (request.getEvent().hasRelatedObjects()) for (RelatedObjectInterface r : request.getEvent().getRelatedObjects()) { RelatedCourseInfo related = new RelatedCourseInfo(); related.setEvent(ce); if (r.getSelection() != null) { related.setOwnerId(r.getUniqueId()); related.setOwnerType(r.getType().ordinal()); related.setCourse(CourseOfferingDAO.getInstance().get(r.getSelection()[1], hibSession)); } else { switch (r.getType()) { case Course: related.setOwner(CourseOfferingDAO.getInstance().get(r.getUniqueId())); break; case Class: related.setOwner(Class_DAO.getInstance().get(r.getUniqueId())); break; case Config: related.setOwner(InstrOfferingConfigDAO.getInstance().get(r.getUniqueId())); break; case Offering: related.setOwner(InstructionalOfferingDAO.getInstance().get(r.getUniqueId())); break; } } ce.getRelatedCourses().add(related); } } if (event.getUniqueId() == null) { hibSession.save(event); response.setEvent(EventDetailBackend.getEventDetail( SessionDAO.getInstance().get(request.getSessionId(), hibSession), event, context)); } else if (event.getMeetings().isEmpty()) { response.setEvent(EventDetailBackend.getEventDetail( SessionDAO.getInstance().get(request.getSessionId(), hibSession), event, context)); response.getEvent().setId(null); hibSession.delete(event); } else { hibSession.update(event); response.setEvent(EventDetailBackend.getEventDetail( SessionDAO.getInstance().get(request.getSessionId(), hibSession), event, context)); } tx.commit(); new EventEmail(request, response).send(context); return response; } catch (Exception ex) { tx.rollback(); if (ex instanceof GwtRpcException) throw (GwtRpcException) ex; throw new GwtRpcException(ex.getMessage(), ex); } }
From source file:org.unitime.timetable.server.rooms.RoomPicturesBackend.java
@Override public RoomPictureResponse execute(RoomPictureRequest request, SessionContext context) { if (request.hasSessionId()) context = new EventContext(context, request.getSessionId()); RoomPictureResponse response = new RoomPictureResponse(); Map<Long, LocationPicture> temp = (Map<Long, LocationPicture>) context .getAttribute(RoomPictureServlet.TEMP_ROOM_PICTURES); org.hibernate.Session hibSession = LocationDAO.getInstance().getSession(); if (request.getOperation() == RoomPictureRequest.Operation.UPLOAD && request.getLocationId() == null) { final FileItem file = (FileItem) context.getAttribute(UploadServlet.SESSION_LAST_FILE); if (file != null) { if (temp == null) { temp = new HashMap<Long, LocationPicture>(); context.setAttribute(RoomPictureServlet.TEMP_ROOM_PICTURES, temp); }/*ww w .j av a2 s . c o m*/ LocationPicture picture = new RoomPicture(); picture.setDataFile(file.get()); String name = file.getName(); if (name.indexOf('.') >= 0) name = name.substring(0, name.lastIndexOf('.')); picture.setFileName(name); picture.setContentType(file.getContentType()); picture.setTimeStamp(new Date()); temp.put(-picture.getTimeStamp().getTime(), picture); response.addPicture(new RoomPictureInterface(-picture.getTimeStamp().getTime(), picture.getFileName(), picture.getContentType(), picture.getTimeStamp().getTime(), null)); } return response; } Location location = LocationDAO.getInstance().get(request.getLocationId(), hibSession); if (location == null) throw new GwtRpcException(MESSAGES.errorRoomDoesNotExist(request.getLocationId().toString())); response.setName(location.getLabel()); context.checkPermission(location, Right.RoomEditChangePicture); switch (request.getOperation()) { case LOAD: for (LocationPicture p : new TreeSet<LocationPicture>(location.getPictures())) response.addPicture(new RoomPictureInterface(p.getUniqueId(), p.getFileName(), p.getContentType(), p.getTimeStamp().getTime(), getPictureType(p.getType()))); boolean samePast = true, sameFuture = true; for (Location other : (List<Location>) hibSession .createQuery("from Location loc where permanentId = :permanentId and not uniqueId = :uniqueId") .setLong("uniqueId", location.getUniqueId()).setLong("permanentId", location.getPermanentId()) .list()) { if (!samePictures(location, other)) { if (other.getSession().getSessionBeginDateTime() .before(location.getSession().getSessionBeginDateTime())) { samePast = false; } else { sameFuture = false; } } if (!sameFuture) break; } if (samePast && sameFuture) response.setApply(Apply.ALL_SESSIONS); else if (sameFuture) response.setApply(Apply.ALL_FUTURE_SESSIONS); else response.setApply(Apply.THIS_SESSION_ONLY); for (AttachmentType type : AttachmentType.listTypes(AttachmentType.VisibilityFlag.ROOM_PICTURE_TYPE)) { response.addPictureType(RoomPicturesBackend.getPictureType(type)); } context.setAttribute(RoomPictureServlet.TEMP_ROOM_PICTURES, null); break; case SAVE: Map<Long, LocationPicture> pictures = new HashMap<Long, LocationPicture>(); for (LocationPicture p : location.getPictures()) pictures.put(p.getUniqueId(), p); for (RoomPictureInterface p : request.getPictures()) { LocationPicture picture = pictures.remove(p.getUniqueId()); if (picture == null && temp != null) { picture = temp.get(p.getUniqueId()); if (picture != null) { if (location instanceof Room) { ((RoomPicture) picture).setLocation((Room) location); ((Room) location).getPictures().add((RoomPicture) picture); } else { ((NonUniversityLocationPicture) picture).setLocation((NonUniversityLocation) location); ((NonUniversityLocation) location).getPictures() .add((NonUniversityLocationPicture) picture); } if (p.getPictureType() != null) picture.setType( AttachmentTypeDAO.getInstance().get(p.getPictureType().getId(), hibSession)); hibSession.saveOrUpdate(picture); } } else if (picture != null) { if (p.getPictureType() != null) picture.setType( AttachmentTypeDAO.getInstance().get(p.getPictureType().getId(), hibSession)); hibSession.saveOrUpdate(picture); } } for (LocationPicture picture : pictures.values()) { location.getPictures().remove(picture); hibSession.delete(picture); } hibSession.saveOrUpdate(location); if (request.getApply() != Apply.THIS_SESSION_ONLY) { for (Location other : (List<Location>) hibSession .createQuery( "from Location loc where permanentId = :permanentId and not uniqueId = :uniqueId") .setLong("uniqueId", location.getUniqueId()) .setLong("permanentId", location.getPermanentId()).list()) { if (request.getApply() == Apply.ALL_FUTURE_SESSIONS && other.getSession() .getSessionBeginDateTime().before(location.getSession().getSessionBeginDateTime())) continue; Set<LocationPicture> otherPictures = new HashSet<LocationPicture>(other.getPictures()); p1: for (LocationPicture p1 : location.getPictures()) { for (Iterator<LocationPicture> i = otherPictures.iterator(); i.hasNext();) { LocationPicture p2 = i.next(); if (samePicture(p1, p2)) { i.remove(); continue p1; } } if (location instanceof Room) { RoomPicture p2 = ((RoomPicture) p1).clonePicture(); p2.setLocation(other); ((Room) other).getPictures().add(p2); hibSession.saveOrUpdate(p2); } else { NonUniversityLocationPicture p2 = ((NonUniversityLocationPicture) p1).clonePicture(); p2.setLocation(other); ((NonUniversityLocation) other).getPictures().add(p2); hibSession.saveOrUpdate(p2); } } for (LocationPicture picture : otherPictures) { other.getPictures().remove(picture); hibSession.delete(picture); } hibSession.saveOrUpdate(other); } } hibSession.flush(); context.setAttribute(RoomPictureServlet.TEMP_ROOM_PICTURES, null); break; case UPLOAD: final FileItem file = (FileItem) context.getAttribute(UploadServlet.SESSION_LAST_FILE); if (file != null) { if (temp == null) { temp = new HashMap<Long, LocationPicture>(); context.setAttribute(RoomPictureServlet.TEMP_ROOM_PICTURES, temp); } LocationPicture picture = null; if (location instanceof Room) picture = new RoomPicture(); else picture = new NonUniversityLocationPicture(); picture.setDataFile(file.get()); String name = file.getName(); if (name.indexOf('.') >= 0) name = name.substring(0, name.lastIndexOf('.')); picture.setFileName(name); picture.setContentType(file.getContentType()); picture.setTimeStamp(new Date()); temp.put(-picture.getTimeStamp().getTime(), picture); response.addPicture(new RoomPictureInterface(-picture.getTimeStamp().getTime(), picture.getFileName(), picture.getContentType(), picture.getTimeStamp().getTime(), null)); } break; } return response; }
From source file:org.vuphone.vandyupon.media.incoming.event.ImageParser.java
public Notification parse(HttpServletRequest req) { if (req.getParameter("type").equalsIgnoreCase("eventimagepost")) { //get data from request String response = null;/*from www . ja va 2s .c o m*/ String callback = null; long time, eventId = 0; time = System.currentTimeMillis(); byte[] imageData = null; eventId = Long.parseLong(req.getParameter(EVENTID)); response = req.getParameter("resp"); callback = req.getParameter("callback"); if (ServletFileUpload.isMultipartContent(req)) { //process the multipart request File temp = new File("/temp"); if (!temp.exists()) { temp.mkdir(); } DiskFileItemFactory factory = new DiskFileItemFactory(5000000, temp); ServletFileUpload ul = new ServletFileUpload(factory); Iterator iter = null; HashMap<String, String> params = new HashMap<String, String>(); try { iter = ul.parseRequest(req).iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) params.put(item.getFieldName(), item.getString()); else //file upload imageData = item.get(); } } catch (FileUploadException e) { e.printStackTrace(); return null; } } else { eventId = Long.parseLong(req.getParameter(EVENTID)); response = req.getParameter("resp"); callback = req.getParameter("callback"); imageData = new byte[req.getContentLength() + 1]; try { ServletInputStream sis = req.getInputStream(); int read = 0; int readSoFar = 0; while ((read = sis.read(imageData, readSoFar, imageData.length - readSoFar)) != -1) { readSoFar += read; //logger_.log(Level.SEVERE, "Read " + String.valueOf(read) + " bytes this time. So Far " + String.valueOf(readSoFar)); } } catch (IOException excp) { logger_.log(Level.SEVERE, "Got IOException:" + excp.getMessage()); } } ImageNotification in = new ImageNotification(); in.setEventId(eventId); in.setTime(time); in.setBytes(imageData); in.setResponseType(response); in.setCallback(callback); return in; } else { return null; } }
From source file:org.wso2.carbon.ui.transports.fileupload.AbstractFileUploadExecutor.java
protected void parseRequest(HttpServletRequest request) throws FileUploadFailedException, FileSizeLimitExceededException { fileItemsMap.set(new HashMap<String, ArrayList<FileItemData>>()); formFieldsMap.set(new HashMap<String, ArrayList<String>>()); ServletRequestContext servletRequestContext = new ServletRequestContext(request); boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext); Long totalFileSize = 0L;/* w w w . ja v a 2 s.c o m*/ if (isMultipart) { List items; try { items = parseRequest(servletRequestContext); } catch (FileUploadException e) { String msg = "File upload failed"; log.error(msg, e); throw new FileUploadFailedException(msg, e); } boolean multiItems = false; if (items.size() > 1) { multiItems = true; } // Add the uploaded items to the corresponding maps. for (Iterator iter = items.iterator(); iter.hasNext();) { FileItem item = (FileItem) iter.next(); String fieldName = item.getFieldName().trim(); if (item.isFormField()) { if (formFieldsMap.get().get(fieldName) == null) { formFieldsMap.get().put(fieldName, new ArrayList<String>()); } try { formFieldsMap.get().get(fieldName).add(new String(item.get(), "UTF-8")); } catch (UnsupportedEncodingException ignore) { } } else { String fileName = item.getName(); if ((fileName == null || fileName.length() == 0) && multiItems) { continue; } if (fileItemsMap.get().get(fieldName) == null) { fileItemsMap.get().put(fieldName, new ArrayList<FileItemData>()); } totalFileSize += item.getSize(); if (totalFileSize < totalFileUploadSizeLimit) { fileItemsMap.get().get(fieldName).add(new FileItemData(item)); } else { throw new FileSizeLimitExceededException(getFileSizeLimit() / 1024 / 1024); } } } } }
From source file:org.wso2.rnd.nosql.UIHelper.java
/** * Upload image/* w w w . j ava 2s . com*/ * @param request * @param session * @throws FileUploadException */ public static void uploadImage(HttpServletRequest request, HttpSession session) throws FileUploadException { if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItems = servletFileUpload.parseRequest(request); FileItem fileItem = null; String recordId = null; String fileComment = null; Iterator it = fileItems.iterator(); while (it.hasNext()) { FileItem fileItemTemp = (FileItem) it.next(); if (!fileItemTemp.isFormField()) { fileItem = fileItemTemp; } else if ("recordId".equals(fileItemTemp.getFieldName())) { recordId = fileItemTemp.getString(); } else if ("fileComment".equals(fileItemTemp.getFieldName())) { fileComment = fileItemTemp.getString(); } } if (fileItem != null && recordId != null) { if (fileItem.getSize() > 0) { UUID blobId = UUID.randomUUID(); Blob blob = new Blob(); blob.setBlobId(blobId); blob.setComment("Scanned Emr Records"); blob.setFileName(fileItem.getName()); blob.setContentType(fileItem.getContentType()); blob.setFileSize(fileItem.getSize()); blob.setFileContent(fileItem.get()); blob.setTimeStamp(String.valueOf(System.currentTimeMillis())); //blob.setComment(fileComment); blob.setComment("Scanned Emr Records"); //save blob and update record EMRClient.getInstance().saveEmrBlob(blob); //set record blob ids EMRClient.getInstance().saveBlobRecord(recordId, blobId); //can not get all the columns in one row :( //EMRClient.getInstance().updateRecordBlob(recordId, blobId); } } } }
From source file:org.xsystem.sql2.http.impl.HttpHelper.java
public static Map formUpload(HttpServletRequest request) throws FileUploadException, UnsupportedEncodingException { Map ret = new HashMap(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); String paramName = item.getFieldName(); if (paramName.equalsIgnoreCase("skip")) { continue; }//w w w .j a v a 2 s . c o m if (paramName.equalsIgnoreCase("total")) { continue; } if (item.isFormField()) { String svalue = item.getString("UTF-8"); ret.put(paramName, svalue); } else { FileTransfer fileTransfer = new FileTransfer(); String fileName = item.getName(); String contentType = item.getContentType(); byte[] data = item.get(); fileTransfer.setFileName(fileName); String ft = Auxilary.getFileExtention(fileName); fileTransfer.setFileType(ft); fileTransfer.setContentType(contentType); fileTransfer.setData(data); ret.put(paramName, fileTransfer); } } return ret; }
From source file:org.xsystem.sql2.http.impl.HttpHelper.java
public static Map formUploadJson(HttpServletRequest request) throws FileUploadException, UnsupportedEncodingException { Map ret = new HashMap(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); String paramName = item.getFieldName(); if (item.isFormField()) { String svalue = item.getString("UTF-8"); Gson gson = RestApiTemplate.gsonBuilder.create(); Object jsonContext = gson.fromJson(svalue, Object.class); ret.put(paramName, jsonContext); } else {//from w w w. j a va2 s . co m FileTransfer fileTransfer = new FileTransfer(); String fileName = item.getName(); String contentType = item.getContentType(); byte[] data = item.get(); fileTransfer.setFileName(fileName); String ft = Auxilary.getFileExtention(fileName); fileTransfer.setFileType(ft); fileTransfer.setContentType(contentType); fileTransfer.setData(data); ret.put(paramName, fileTransfer); } } return ret; }
From source file:P5MX.Components.java
public static void ImportFile(HttpServletRequest request, HttpServletResponse response) { System.out.println("file"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); ServletOutputStream out = null;//from w ww . j ava 2s . c o m Integer UserId = 0; FileBLL fx = new FileBLL(); try { List items = upload.parseRequest(request); Iterator iter = items.iterator(); response.setContentType("text/html"); out = response.getOutputStream(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { UserId = Integer.valueOf(item.getString()); System.out.println("[ name :> " + item.getFieldName() + " ]"); System.out.println("[ value :> " + item.getString() + " ]"); } else { fx.setFilename(item.getName().split("\\.")[0]); fx.setFiletype(item.getName().split("\\.")[1]); fx.setData(item.get()); fx.setSize((int) item.getSize()); } } out.close(); } catch (FileUploadException | IOException fue) { } Integer FileId = InsertFile(fx); // file = SelectFileByName(file.getFilename()); System.out.println("[ generatedKey :: " + FileId + " ]"); AccessBLL ax = new AccessBLL(UserId, FileId); AccessDAL.GrantAccess(ax); TagDAL.InsertTag(new TagBLL(FileId, "Local")); System.out.println("Granted access!"); }
From source file:presentation.webgui.vitroappservlet.uploadService.UploadServlet.java
private void doFileUpload(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException { String fname = ""; HashMap<String, String> myFileRequestParamsHM = new HashMap<String, String>(); try {// w ww . jav a 2 s.com FileUploadListener listener = new FileUploadListener(request.getContentLength()); FileItemFactory factory = new MonitoredDiskFileItemFactory(listener); ServletFileUpload upload = new ServletFileUpload(factory); // upload.setSizeMax(83886080); /* the unit is bytes */ FileItem fileItem = null; fileItem = myrequestGetParameter(upload, request, myFileRequestParamsHM); String mode = myFileRequestParamsHM.get("mode"); session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats()); boolean hasError = false; if (fileItem != null) { /** * (for KML only files) ( not prefabs (collada) or icons or images) */ WstxInputFactory f = null; XMLStreamReader2 sr = null; SMInputCursor iroot = null; if (mode.equals("3dFile") || mode.equals("LinePlaceMarksFile") || mode.equals("RoomCenterPointsFile")) { f = new WstxInputFactory(); f.configureForConvenience(); // Let's configure factory 'optimally'... f.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE); f.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE); sr = (XMLStreamReader2) f.createXMLStreamReader(fileItem.getInputStream()); iroot = SMInputFactory.rootElementCursor(sr); // If we needed to store some information about preceding siblings, // we should enable tracking. (we need it for mygetElementValueStaxMultiple method) iroot.setElementTracking(SMInputCursor.Tracking.PARENTS); iroot.getNext(); if (!"kml".equals(iroot.getLocalName().toLowerCase())) { hasError = true; listener.getFileUploadStats().setCurrentStatus("finito"); session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats()); sendCompleteResponse(myFileRequestParamsHM, response, hasError, "Root element not kml, as expected, but " + iroot.getLocalName()); return; } } fname = ""; if (mode.equals("3dFile")) { if ((fileItem.getSize() / 1024) > 25096) { // with woodstox stax, file size should not be a problem. Let's put some limit however! hasError = true; listener.getFileUploadStats().setCurrentStatus("finito"); session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats()); sendCompleteResponse(myFileRequestParamsHM, response, hasError, "File is very large for XML handler to process!"); return; } fname = ""; String[] elementsToFollow = { "document", "name" }; Vector<String> resultValues = SMTools.mygetElementValueStax(iroot, elementsToFollow, 0); if (resultValues != null && !resultValues.isEmpty()) { fname = resultValues.elementAt(0); } if (!fname.equals("")) { // check for kml extension and Add it if necessary!! int lastdot = fname.lastIndexOf('.'); if (lastdot != -1) { if (lastdot == 0) // if it is the first char then ignore it and add an extension anyway { fname += ".kml"; } else if (lastdot < fname.length() - 1) { if (!(fname.substring(lastdot + 1).toLowerCase().equals("kml"))) { fname += ".kml"; } } else if (lastdot == fname.length() - 1) { fname += "kml"; } } else { fname += ".kml"; } String realPath = this.getServletContext().getRealPath("/"); int lastslash = realPath.lastIndexOf(File.separator); realPath = realPath.substring(0, lastslash); // too slow //FileWriter out = new FileWriter(realPath+File.separator+"KML"+File.separator+fname); //document.sendToWriter(out); // too slow //StringWriter outString = new StringWriter(); //document.sendToWriter(outString); //out.close(); // fast - do not process and store xml file, just store it. File outFile = new File(realPath + File.separator + "Models" + File.separator + "Large" + File.separator + fname); outFile.createNewFile(); FileWriter tmpoutWriter = new FileWriter(outFile); BufferedWriter buffWriter = new BufferedWriter(tmpoutWriter); buffWriter.write(new String(fileItem.get())); buffWriter.flush(); buffWriter.close(); tmpoutWriter.close(); } else { hasError = true; listener.getFileUploadStats().setCurrentStatus("finito"); session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats()); sendCompleteResponse(myFileRequestParamsHM, response, hasError, "No name tag found inside the KML file!"); return; } } else if (mode.equals("LinePlaceMarksFile")) { fname = ""; String[] elementsToFollow = { "document", "folder", "placemark", "point", "coordinates" }; Vector<String> resultValues = SMTools.mygetElementValueStax(iroot, elementsToFollow, 0); if (resultValues != null && resultValues.size() < 2) { hasError = true; listener.getFileUploadStats().setCurrentStatus("finito"); session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats()); sendCompleteResponse(myFileRequestParamsHM, response, hasError, "File does not contain 2 placemarks!"); return; } for (int i = 0; (i < resultValues.size()) && (i < 2); i++) { fname = fname + ":" + resultValues.elementAt(i); } } else if (mode.equals("RoomCenterPointsFile")) { fname = ""; // here: process PlaceMarks for rooms (centerpoints) in the building String[] elementsToFollow0 = { "document", "folder", "placemark", "point", "coordinates" }; String[] elementsToFollow1 = { "document", "folder", "placemark", "name" }; // add elements to follow for room names and coordinates Vector<String[]> elementsToFollow = new Vector<String[]>(); elementsToFollow.add(elementsToFollow0); elementsToFollow.add(elementsToFollow1); Vector<Vector<String>> resultValues = new Vector<Vector<String>>(); SMTools.mygetMultipleElementValuesStax(iroot, elementsToFollow, resultValues); Vector<String> resultValuesForCoords = resultValues.elementAt(0); Vector<String> resultValuesForNames = resultValues.elementAt(1); if (resultValuesForCoords == null || resultValuesForCoords.size() == 0 || resultValuesForNames == null || resultValuesForCoords.size() == 0 || resultValuesForCoords.size() != resultValuesForNames.size()) { hasError = true; listener.getFileUploadStats().setCurrentStatus("finito"); session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats()); sendCompleteResponse(myFileRequestParamsHM, response, hasError, "File does not contain valid data for rooms!"); return; } for (int i = 0; i < resultValuesForNames.size(); i++) { // since we use ; and ':' to seperate rooms, we replace the comma's in the rooms' names. if (resultValuesForNames.elementAt(i).indexOf(';') >= 0 || resultValuesForNames.elementAt(i).indexOf(':') >= 0) { String tmp = new String(resultValuesForNames.elementAt(i)); tmp.replace(';', ' '); tmp.replace(':', ' '); resultValuesForNames.set(i, tmp); } fname = fname + ";" + resultValuesForNames.elementAt(i) + ":" + resultValuesForCoords.elementAt(i); } } else if (mode.equals("DefaultIconfile") || mode.equals("DefaultPrefabfile") || mode.equals("SpecialValueIconfile") || mode.equals("SpecialValuePrefabfile") || mode.equals("NumericRangeIconfile") || mode.equals("NumericRangePrefabfile")) { fname = ""; if ((fileItem.getSize() / 1024) > 10096) { // no more than 10 Mbs of size for small prefabs or icons hasError = true; listener.getFileUploadStats().setCurrentStatus("finito"); session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats()); sendCompleteResponse(myFileRequestParamsHM, response, hasError, "File is very large!"); return; } fname = fileItem.getName(); if (!fname.equals("")) { String realPath = this.getServletContext().getRealPath("/"); int lastslash = realPath.lastIndexOf(File.separator); realPath = realPath.substring(0, lastslash); File outFile = new File(realPath + File.separator + "Models" + File.separator + "Media" + File.separator + fname); outFile.createNewFile(); /* FileWriter tmpoutWriter = new FileWriter(outFile); BufferedWriter buffWriter = new BufferedWriter(tmpoutWriter); buffWriter.write(new String(fileItem.get())); buffWriter.flush(); buffWriter.close(); tmpoutWriter.close(); */ fileItem.write(outFile); } else { hasError = true; listener.getFileUploadStats().setCurrentStatus("finito"); session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats()); sendCompleteResponse(myFileRequestParamsHM, response, hasError, "No valid name for uploaded file!"); return; } } fileItem.delete(); } if (!hasError) { sendCompleteResponse(myFileRequestParamsHM, response, hasError, fname); } else { hasError = true; sendCompleteResponse(myFileRequestParamsHM, response, hasError, "Could not process uploaded file. Please see log for details."); } } catch (Exception e) { boolean hasError = true; sendCompleteResponse(myFileRequestParamsHM, response, hasError, "::" + fname + "::" + e.getMessage()); } }