Example usage for org.apache.commons.fileupload FileItem getContentType

List of usage examples for org.apache.commons.fileupload FileItem getContentType

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getContentType.

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

Usage

From source file:org.springframework.web.multipart.commons.CommonsFileUploadSupport.java

/**
 * Parse the given List of Commons FileItems into a Spring MultipartParsingResult,
 * containing Spring MultipartFile instances and a Map of multipart parameter.
 * @param fileItems the Commons FileIterms to parse
 * @param encoding the encoding to use for form fields
 * @return the Spring MultipartParsingResult
 * @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)
 *//*from w w  w .  j  a v a2  s  .  c o m*/
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>();
    Map<String, String[]> multipartParameters = new HashMap<>();
    Map<String, String> multipartParameterContentTypes = new HashMap<>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value;
            String partEncoding = determineEncoding(fileItem.getContentType(), encoding);
            try {
                value = fileItem.getString(partEncoding);
            } catch (UnsupportedEncodingException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                            + "' with encoding '" + partEncoding + "': using platform default");
                }
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
            multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType());
        } else {
            // multipart file field
            CommonsMultipartFile file = createMultipartFile(fileItem);
            multipartFiles.add(file.getName(), file);
            if (logger.isDebugEnabled()) {
                logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                        + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                        + file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);
}

From source file:org.structr.web.servlet.UploadServlet.java

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {

    try (final Tx tx = StructrApp.getInstance().tx()) {

        if (!ServletFileUpload.isMultipartContent(request)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getOutputStream()//w ww  .  j  a va2s.  com
                    .write("ERROR (400): Request does not contain multipart content.\n".getBytes("UTF-8"));
            return;
        }

        final SecurityContext securityContext = getConfig().getAuthenticator()
                .initializeAndExamineRequest(request, response);

        if (securityContext.getUser(false) == null && Boolean.FALSE.equals(Boolean.parseBoolean(
                StructrApp.getConfigurationValue("UploadServlet.allowAnonymousUploads", "false")))) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getOutputStream().write("ERROR (403): Anonymous uploads forbidden.\n".getBytes("UTF-8"));
            return;
        }

        // Ensure access mode is frontend
        securityContext.setAccessMode(AccessMode.Frontend);

        request.setCharacterEncoding("UTF-8");

        // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
        response.setCharacterEncoding("UTF-8");

        // don't continue on redirects
        if (response.getStatus() == 302) {
            return;
        }

        final String pathInfo = request.getPathInfo();
        String type = null;

        if (StringUtils.isNotBlank(pathInfo)) {

            type = SchemaHelper.normalizeEntityName(StringUtils.stripStart(pathInfo.trim(), "/"));

        }

        uploader.setFileSizeMax(MEGABYTE
                * Long.parseLong(StructrApp.getConfigurationValue("UploadServlet.maxFileSize", MAX_FILE_SIZE)));
        uploader.setSizeMax(MEGABYTE * Long
                .parseLong(StructrApp.getConfigurationValue("UploadServlet.maxRequestSize", MAX_REQUEST_SIZE)));

        response.setContentType("text/html");
        final PrintWriter out = response.getWriter();

        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();

        final Map<String, Object> params = new HashMap<>();

        while (fileItemsIterator.hasNext()) {

            final FileItem item = fileItemsIterator.next();

            if (item.isFormField()) {

                params.put(item.getFieldName(), item.getString());

            } else {

                try {

                    final String contentType = item.getContentType();
                    boolean isImage = (contentType != null && contentType.startsWith("image"));
                    boolean isVideo = (contentType != null && contentType.startsWith("video"));

                    // Override type from path info
                    if (params.containsKey(NodeInterface.type.jsonName())) {
                        type = (String) params.get(NodeInterface.type.jsonName());
                    }

                    final Class cls = type != null ? SchemaHelper.getEntityClassForRawType(type)
                            : (isImage ? Image.class
                                    : (isVideo ? VideoFile.class : org.structr.dynamic.File.class));

                    final String name = item.getName().replaceAll("\\\\", "/");

                    final org.structr.dynamic.File newFile = FileHelper.createFile(securityContext,
                            IOUtils.toByteArray(item.getInputStream()), contentType, cls);
                    newFile.setProperty(AbstractNode.name, PathHelper.getName(name));

                    if (!newFile.validatePath(securityContext, null)) {
                        newFile.setProperty(AbstractNode.name,
                                name.concat("_").concat(FileHelper.getDateString()));
                    }

                    PropertyMap additionalProperties = PropertyMap.inputTypeToJavaType(securityContext, cls,
                            params);

                    for (PropertyKey key : additionalProperties.keySet()) {

                        newFile.setProperty(key, additionalProperties.get(key));

                    }

                    // upload trigger
                    newFile.notifyUploadCompletion();

                    // Just write out the uuids of the new files
                    out.write(newFile.getUuid());

                } catch (IOException ex) {
                    logger.log(Level.WARNING, "Could not upload file", ex);
                }

            }

        }

        tx.success();

    } catch (FrameworkException | IOException | FileUploadException t) {

        t.printStackTrace();
        logger.log(Level.SEVERE, "Exception while processing request", t);
        UiAuthenticator.writeInternalServerError(response);
    }
}

From source file:org.tinygroup.weblayer.webcontext.parser.valueparser.impl.ParameterParserImpl.java

private void fileItemFilter(String key, boolean[] filtering, Object value, List<Object> paramValues) {
    FileItem fileItem = ((ItemFileObject) value).getFileItem();
    FileItem processFileItem = fileItem;
    // //from  w  w w  .j a v a  2 s.c  o  m
    if (filtering != null) {
        for (int j = 0; j < filters.length; j++) {
            ParameterParserFilter filter = filters[j];

            if (filter instanceof UploadedFileFilter && filtering[j]) {
                processFileItem = ((UploadedFileFilter) filter).filter(key, processFileItem);
            }
        }
    }
    if (processFileItem == null) {
        remove(key, value);//?fileitem
        fileItems.remove(fileItem);
        fileItem.delete();
    } else {
        fileItem = processFileItem;
        if (!fileItem.isFormField() && fileItem.getContentType() != null) {//
            paramValues.add(value);
        }
    }
}

From source file:org.tolven.ajax.DocServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);/*  ww w.  j  a v a 2s. co m*/
    //  Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    Writer writer = response.getWriter();
    // Parse the request
    String returnTo = null;
    try {
        List<FileItem> items = upload.parseRequest(request);
        long id = 0;
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                if ("returnTo".equals(name))
                    returnTo = value;
            } else {
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                // TODO less than int bytes 
                int sizeInBytes = (int) item.getSize();
                AccountUser accountUser = TolvenRequest.getInstance().getAccountUser();
                DocBase doc = docBean.createNewDocument(contentType, "", accountUser);
                // Get the logged in user and set as the author
                Object obj = request.getSession().getAttribute(GeneralSecurityFilter.ACCOUNT_ID);
                if (obj == null)
                    throw new IllegalStateException(getClass() + ": Session ACCOUNT_ID is null");
                obj = request.getSession().getAttribute(GeneralSecurityFilter.TOLVENUSER_ID);
                if (obj == null)
                    throw new IllegalStateException(getClass() + ": Session TOLVENUSER_ID is null");
                String kbeKeyAlgorithm = propertyBean.getProperty(DocumentSecretKey.DOC_KBE_KEY_ALGORITHM_PROP);
                int kbeKeyLength = Integer
                        .parseInt(propertyBean.getProperty(DocumentSecretKey.DOC_KBE_KEY_LENGTH));

                if (isInMemory) {
                    doc.setAsEncryptedContent(item.get(), kbeKeyAlgorithm, kbeKeyLength);
                } else {
                    InputStream uploadedStream = item.getInputStream();
                    byte[] b = new byte[sizeInBytes];
                    uploadedStream.read(b);
                    doc.setAsEncryptedContent(b, kbeKeyAlgorithm, kbeKeyLength);
                    uploadedStream.close();
                }
                docBean.finalizeDocument(doc);
            }
            //             writer.write( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<html>\n" +
            writer.write("<html>\n" + "<head>"
                    + (returnTo == null ? " "
                            : "<meta http-equiv=\"refresh\" content=\"0; url=" + returnTo + "\"/>")
                    + "</head><body>\n" + id + "\n</body>\n</html>\n");
        }
    } catch (FileUploadException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        e.printStackTrace();
    } finally {
        request.setAttribute("activeWriter", writer);
        //         writer.close();
    }
}

From source file:org.tolven.web.MenuAction.java

/**
 * Add an attachment to the current menudataItem 
 * @return success/*  w w w  . java  2 s . co  m*/
 * @throws Exception 
 */
public String addAttachment() throws Exception {
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();
    FileItem upfile = (FileItem) request.getAttribute("upfile");
    if (upfile == null)
        return "fail";
    String contentType = upfile.getContentType();
    TolvenLogger.info("Upload, contentType: " + contentType, MenuAction.class);
    boolean isInMemory = upfile.isInMemory();
    int sizeInBytes = (int) upfile.getSize();
    DocBase doc = getDocumentLocal().createNewDocument(contentType, getAttachmentType(),
            TolvenRequest.getInstance().getAccountUser());
    doc.setSchemaURI(getAttachmentType());
    byte[] b;
    if (isInMemory) {
        b = upfile.get();
    } else {
        InputStream uploadedStream = upfile.getInputStream();
        b = new byte[sizeInBytes];
        uploadedStream.read(b);
        uploadedStream.close();
    }
    String kbeKeyAlgorithm = getTolvenPropertiesBean()
            .getProperty(DocumentSecretKey.DOC_KBE_KEY_ALGORITHM_PROP);
    int kbeKeyLength = Integer
            .parseInt(getTolvenPropertiesBean().getProperty(DocumentSecretKey.DOC_KBE_KEY_LENGTH));
    doc.setAsEncryptedContent(b, kbeKeyAlgorithm, kbeKeyLength);
    getDocBean().createFinalDocument(doc);
    getDocumentLocal().createAttachment(getDrilldownItemDoc(), doc, getAttachmentDescription(),
            TolvenRequest.getInstance().getAccountUser(), getNow());

    setAttachmentDescription(null);
    return "success";
}

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 {/* w  w  w. j  a va2  s.co 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() + "&note=" + 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.EventEmail.java

public void send(SessionContext context) throws UnsupportedEncodingException, MessagingException {
    try {// w w w.j  a v  a  2  s  .c  o m
        if (!request().isEmailConfirmation())
            return;

        if (ApplicationProperty.EmailConfirmationEvents.isFalse()) {
            response().info(MESSAGES.emailDisabled());
            return;
        }

        Email email = Email.createEmail();
        if (event().hasContact() && event().getContact().getEmail() != null
                && !event().getContact().getEmail().isEmpty())
            email.addRecipient(event().getContact().getEmail(), event().getContact().getName(MESSAGES));
        if (event().hasAdditionalContacts()) {
            for (ContactInterface contact : event().getAdditionalContacts()) {
                if (contact.getEmail() != null && !contact.getEmail().isEmpty())
                    email.addRecipient(contact.getEmail(), contact.getName(MESSAGES));
            }
        }
        if (event().hasSponsor() && event().getSponsor().hasEmail())
            email.addRecipientCC(event().getSponsor().getEmail(), event().getSponsor().getName());
        if (event().hasEmail()) {
            String suffix = ApplicationProperty.EmailDefaultAddressSuffix.value();
            for (String address : event().getEmail().split("[\n,]")) {
                if (!address.trim().isEmpty()) {
                    if (suffix != null && address.indexOf('@') < 0)
                        email.addRecipientCC(address.trim() + suffix, null);
                    else
                        email.addRecipientCC(address.trim(), null);
                }
            }
        }
        if (event().hasInstructors() && ApplicationProperty.EmailConfirmationEventInstructors.isTrue()) {
            for (ContactInterface contact : event().getInstructors()) {
                if (contact.getEmail() != null && !contact.getEmail().isEmpty())
                    email.addRecipientCC(contact.getEmail(), contact.getName(MESSAGES));
            }
        }
        if (event().hasCoordinators() && ApplicationProperty.EmailConfirmationEventCoordinators.isTrue()) {
            for (ContactInterface contact : event().getCoordinators()) {
                if (contact.getEmail() != null && !contact.getEmail().isEmpty())
                    email.addRecipientCC(contact.getEmail(), contact.getName(MESSAGES));
            }
        }

        if (ApplicationProperty.EmailConfirmationEventManagers.isTrue()) {
            Set<Long> locationIds = new HashSet<Long>();
            if (event().hasMeetings()) {
                for (MeetingInterface m : event().getMeetings()) {
                    if (m.hasLocation())
                        locationIds.add(m.getLocation().getId());
                }
            }
            if (response().hasDeletedMeetings()) {
                for (MeetingInterface m : response().getDeletedMeetings())
                    if (m.hasLocation())
                        locationIds.add(m.getLocation().getId());
            }
            org.hibernate.Session hibSession = SessionDAO.getInstance().getSession();
            NameFormat nf = NameFormat.fromReference(context.getUser().getProperty(UserProperty.NameFormat));
            for (TimetableManager m : (List<TimetableManager>) hibSession.createQuery(
                    "select distinct m from Location l inner join l.eventDepartment.timetableManagers m inner join m.managerRoles r where "
                            + "l.uniqueId in :locationIds and m.emailAddress is not null and r.receiveEmails = true and :permission in elements (r.role.rights)")
                    .setParameterList("locationIds", locationIds, new LongType())
                    .setString("permission", Right.EventLookupContact.name()).list()) {
                email.addRecipientCC(m.getEmailAddress(), nf.format(m));
            }
        }

        if (replyTo() != null) {
            email.setReplyTo(replyTo().getAddress(), replyTo().getPersonal());
        } else if (context != null && context.isAuthenticated() && context.getUser().getEmail() != null) {
            email.setReplyTo(context.getUser().getEmail(), context.getUser().getName());
        } else {
            email.setReplyTo(event().getContact().getEmail(), event().getContact().getName(MESSAGES));
        }

        if (event().getId() != null && ApplicationProperty.InboundEmailsEnabled.isTrue()
                && ApplicationProperty.InboundEmailsReplyToAddress.value() != null) {
            email.setSubject("[EVENT-" + Long.toHexString(event().getId()) + "] " + event().getName() + " ("
                    + event().getType().getName(CONSTANTS) + ")");
            email.addReplyTo(ApplicationProperty.InboundEmailsReplyToAddress.value(),
                    ApplicationProperty.InboundEmailsReplyToAddressName.value());
        } else {
            email.setSubject(event().getName() + " (" + event().getType().getName(CONSTANTS) + ")");
        }

        if (context != null) {
            final FileItem file = (FileItem) context.getAttribute(UploadServlet.SESSION_LAST_FILE);
            if (file != null) {
                email.addAttachment(new DataSource() {
                    @Override
                    public OutputStream getOutputStream() throws IOException {
                        throw new IOException("No output stream.");
                    }

                    @Override
                    public String getName() {
                        return file.getName();
                    }

                    @Override
                    public InputStream getInputStream() throws IOException {
                        return file.getInputStream();
                    }

                    @Override
                    public String getContentType() {
                        return file.getContentType();
                    }
                });
            }
        }

        if (attachment() != null)
            email.addAttachment(attachment());

        final String ical = icalendar();
        if (ical != null) {
            email.addAttachment(new DataSource() {
                @Override
                public OutputStream getOutputStream() throws IOException {
                    throw new IOException("No output stream.");
                }

                @Override
                public String getName() {
                    return "event.ics";
                }

                @Override
                public InputStream getInputStream() throws IOException {
                    return new ByteArrayInputStream(ical.getBytes("UTF-8"));
                }

                @Override
                public String getContentType() {
                    return "text/calendar; charset=UTF-8";
                }
            });
        }

        email.setHTML(message());

        Long eventId = (response().hasEventWithId() ? response().getEvent().getId()
                : request().getEvent().getId());
        if (eventId != null) {
            String messageId = sMessageId.get(eventId);
            if (messageId != null)
                email.setInReplyTo(messageId);
        }

        email.send();

        if (eventId != null) {
            String messageId = email.getMessageId();
            if (messageId != null)
                sMessageId.put(eventId, messageId);
        }

        response().info(MESSAGES.infoConfirmationEmailSent(
                event().hasContact() ? event().getContact().getName(MESSAGES) : "?"));
    } catch (Exception e) {
        response().error(MESSAGES.failedToSendConfirmationEmail(e.getMessage()));
        sLog.warn(MESSAGES.failedToSendConfirmationEmail(e.getMessage()), e);
    }
}

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);
        }//from www .  jav  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);
            }/* w ww  .j ava  2 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.vasanti.controller.DropZoneFileUpload.java

/**
 * @param request/*from   w ww .j  a  v  a 2 s  .  c o m*/
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response)
 *
 */
@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter writer = response.getWriter();

    String path = "";
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }
    bnimagesbn images = new bnimagesbn();

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    response.setContentType("application/json");
    JSONObject files = new JSONObject();
    try {
        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                FileItem colpostid = (FileItem) items.get(0);
                String COLPOSTID = colpostid.getString();
                if (COLPOSTID != null) {
                    images.setCOLPOSTID(COLPOSTID);
                    logger.info("COLPOSTID from View  is = " + COLPOSTID);
                } else if (COLPOSTID == null) {
                    RequestDispatcher rd = request
                            .getRequestDispatcher("/WEB-INF/views/services/error-page.jsp");
                    rd.forward(request, response);
                }
            } else if (!item.isFormField()) {
                String ImageName = "";
                String name = item.getName();
                String contentType = item.getContentType();
                logger.info("Content Type  of file is " + contentType);
                long size = item.getSize();
                logger.info("Size of file is " + size);
                String filetype = name.substring(name.lastIndexOf("."));
                SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
                String randomNum = Integer.toString(prng.nextInt());
                MessageDigest sha = MessageDigest.getInstance("SHA-1");
                byte[] result = sha.digest(randomNum.getBytes());
                ImageName = hexEncode(result) + filetype;
                logger.info(" ImageName1 is " + ImageName);
                if (name != null) {
                    if ((size < 9048576) && (("image/jpeg".equals(contentType))
                            || ("image/jpg".equals(contentType)) || ("image/gif".equals(contentType))
                            || ("image/png".equals(contentType)) || ("image/bmp".equals(contentType)))) {
                        images.setCOLIMAGENAME(ImageName);
                    }
                } else if (name == null) {
                    RequestDispatcher rd = request
                            .getRequestDispatcher("/WEB-INF/views/adultservices/error-page.jsp");
                    rd.forward(request, response);
                }

                File file = new File(ImagefileUploadPath, ImageName);
                item.write(file);
                path = file.getCanonicalPath();
                logger.info(" ImageName1 CanonicalPath is " + path);
                BufferedImage img = null;
                try {
                    img = ImageIO.read((new File(path)));
                } catch (IOException ex) {
                    logger.error("Logging IO Exception while creating thumbnail", ex);
                }
                BufferedImage thumbImg = Scalr.resize(img, Method.QUALITY, Mode.AUTOMATIC, 150, 150,
                        Scalr.OP_ANTIALIAS);
                File thumbnailfile = new File(ThumbnailFileUploadPath, ImageName);
                images.setCOLTHUMBNAILNAME(ImageName);
                ImageIO.write(thumbImg, "jpg", thumbnailfile);

                files.put("name", ImageName);
                //                    jsono.put("size", item.getSize());
                //                    jsono.put("url", "UploadServlet?getfile=" + ImageName);
                //                    jsono.put("thumbnail_url", "UploadServlet?getthumb=" + ImageName);
                //                    jsono.put("delete_url", "UploadServlet?delfile=" + ImageName);
                //                    jsono.put("delete_type", "GET");                    
                InsertImageInterface insert = new InsertImageInterface();
                count = insert.InsertImage(images);
                files.put("status", status);
                logger.info(files.toString());
            }
        }
    } catch (FileUploadException ex) {
        logger.error("Got the FileUpload Exception", ex);
    } catch (Exception ex) {
        logger.error("Got the Exception", ex);
    } finally {
        try {
            files.put("status", status);
            writer.write(files.toString());
            writer.close();
        } catch (JSONException ex) {
            logger.error("Got the JSONException", ex);
        }
    }

}