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

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

Introduction

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

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:com.kmetop.demsy.modules.ckfinder.FileUploadCommand.java

/**
 * /*from  w  ww. j a  va2 s.  c  o  m*/
 * @param request
 *            http request
 * @return true if uploaded correctly
 */
@SuppressWarnings("unchecked")
private boolean fileUpload(final HttpServletRequest request) {
    try {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            String path = configuration.getTypes().get(this.type).getPath() + this.currentFolder;

            this.fileName = getFileItemName(item);

            try {
                if (validateUploadItem(item, path)) {
                    boolean succ = saveTemporaryFile(path, item);
                    try {
                        saveToDB(item, configuration.getTypes().get(this.type).getUrl() + this.currentFolder);
                    } catch (Throwable e) {
                        log.error("??! ", e);
                    }
                    return succ;
                }
            } finally {
                // file should be deleted from temporary files automaticly
                // but in some cases the file was not deleted
                // but when file was deleted after item.write
                // then inputstream isn't available any more.
                try {
                    item.getOutputStream().close();
                    item.getInputStream().close();
                } catch (IOException e) {
                    // when input stream isn't avail
                    // you don't have to close it
                    // Probably if this issue will be fixed:
                    // https://issues.apache.org/jira/browse/FILEUPLOAD-191
                    // all code in finally can be deleted.
                }

                item.delete();
            }
        }
        return false;
    } catch (InvalidContentTypeException e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_CORRUPT;
        return false;
    } catch (IOFileUploadException e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
        return false;
    } catch (SizeLimitExceededException e) {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
        return false;
    } catch (FileSizeLimitExceededException e) {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
        return false;
    } catch (ConnectorException e) {
        this.errorCode = e.getErrorCode();
        return false;
    } catch (Exception e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
        return false;
    }

}

From source file:hu.sztaki.lpds.pgportal.portlets.credential.MyProxyPortlet.java

/**
 * Checks if the correct files exist and uploads the files to the MyProxy server.
 * @param req//from  w  w  w. ja  va 2  s . c  om
 * @param keyFile File containing the key
 * @param keyPass Key password
 * @param certFile File containing the cert
 * @param host String containing the MyProxy host
 * @param port String containing the MyProxy port
 * @param login String containing the login for MyProxy
 * @param pass String containing the password for MyProxy
 * @param lifetime String containing the proxy lifetiem
 * @param uDN Boolean: use DN or not
 * @param type String containing pem or p12.
 */
private void uploadPem(ActionRequest req, FileItem keyFile, String keyPass, FileItem certFile, String host,
        String port, String login, String pass, String lifetime, Boolean uDN, String type, boolean RFCEnabled) {

    ActionRequest request = req;
    FileItem kf = keyFile;
    FileItem cf = certFile;
    Boolean useDN = uDN;
    int iport, ilifetime;
    try {
        iport = Integer.parseInt(port);
        ilifetime = Integer.parseInt(lifetime);
        ilifetime = ilifetime * 3600;
        ilifetime = this.correctLifetime(ilifetime);
    } catch (Exception ex) {
        request.setAttribute("msg", "Port and lifetime must be numbers!");
        return;
    }

    if (type.equals("pem") && checkFile(req, "Key", keyFile) && checkFile(req, "Cert", certFile)
            && checkMyproxy(req, host, port, login, pass, lifetime, uDN)) {
        try {

            this.cm.uploadToServerInputStream(cf.getInputStream(), kf.getInputStream(), keyPass, login, pass,
                    ilifetime, host, iport, useDN, RFCEnabled);
            request.setAttribute("msg", "Upload successful.");
            //response.setRenderParameter("nextJSP",""credentialList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "Upload failed! Reason: " + e.getMessage());
            //response.setRenderParameter("nextJSP",""credentialList.jsp";
        }
    } else if (type.equals("p12") && checkFile(req, "P12", keyFile)
            && checkMyproxy(req, host, port, login, pass, lifetime, uDN)) {

        InputStream kIS = p12ToPem("k", keyFile, req.getRemoteUser(), keyPass);
        InputStream cIS = p12ToPem("c", keyFile, req.getRemoteUser(), keyPass);

        try {
            this.cm.uploadToServerInputStream(cIS, kIS, keyPass, login, pass, ilifetime, host, iport, useDN,
                    RFCEnabled);
            request.setAttribute("msg", "Upload successful.");
            //response.setRenderParameter("nextJSP",""credentialList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "Upload failed! Reason: " + e.getMessage());
            //jsp = "credentialList.jsp";
        }
    }
}

From source file:net.hillsdon.reviki.web.pages.impl.DefaultPageImpl.java

public View attach(final PageReference page, final ConsumedPath path, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new InvalidInputException("multipart request expected.");
    }//w w  w.java 2s. c o  m
    List<FileItem> items = getFileItems(request);
    try {
        if (items.size() > 4) {
            throw new InvalidInputException("One file at a time.");
        }
        String attachmentName = null;
        Long baseRevision = null;
        String attachmentMessage = null;
        FileItem file = null;
        for (FileItem item : items) {
            if (PARAM_ATTACHMENT_NAME.equals(item.getFieldName())) {
                attachmentName = item.getString().trim();
            }
            if (PARAM_BASE_REVISION.equals(item.getFieldName())) {
                baseRevision = RequestParameterReaders.getLong(item.getString().trim(), PARAM_BASE_REVISION);
            }
            if (PARAM_ATTACHMENT_MESSAGE.equals(item.getFieldName())) {
                attachmentMessage = item.getString().trim();
                if (attachmentMessage.length() == 0) {
                    attachmentMessage = null;
                }
            }
            if (!item.isFormField()) {
                file = item;
            }
        }
        if (baseRevision == null) {
            baseRevision = VersionedPageInfo.UNCOMMITTED;
        }

        if (file == null || file.getSize() == 0) {
            request.setAttribute("flash", ERROR_NO_FILE);
            return attachments(page, path, request, response);
        } else {
            InputStream in = file.getInputStream();
            try {
                // get the page from store - needed to get content of the special
                // pages which were not saved yet
                PageInfo pageInfo = _store.get(page, -1);
                // IE sends the full file path.
                storeAttachment(pageInfo, attachmentName, baseRevision, attachmentMessage,
                        FilenameUtils.getName(file.getName()), in);
                _store.expire(pageInfo);
                return new RedirectToPageView(_wikiUrls, page, "/attachments/");
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } finally {
        for (FileItem item : items) {
            item.delete();
        }
    }
}

From source file:com.example.app.ui.vtcrop.VTCropPictureEditor.java

@Nullable
private FileItem _getUIValue(@Nullable FileItem uiValue) {
    if (uiValue == null) {
        return null;
    }//  w  ww .  ja  va2  s.  c o m

    Dimension origDim, newDim;
    try {
        origDim = ImageFileUtil.getDimension(uiValue);
    } catch (IOException e) {
        _logger.error("Skipping scaling because an error occurred.", e);
        return uiValue;
    }

    if (origDim == null) {
        _logger.warn("Skipping scaling because retrieved dimension for ui value was null.");
        return uiValue;
    }

    VTCropPictureEditorConfig.ImageScaleOption option = _config.getImageScaleOptionForName(_uiValue.getName());
    int newDimWidth = option != null && option.scale != null
            ? Double.valueOf(_config.getCropWidth() * option.scale).intValue()
            : _config.getCropWidth();
    int newDimHeight = option != null && option.scale != null
            ? Double.valueOf(_config.getCropHeight() * option.scale).intValue()
            : _config.getCropHeight();

    newDim = ImageFileUtil.getScaledDimension(origDim, newDimWidth, newDimHeight);

    if (!newDim.equals(origDim)) {
        _logger.debug("Scale to " + newDim.getWidthMetric() + " x " + newDim.getHeightMetric());
        FileItem scaledFileItem = _fileItemFactory.createItem(uiValue.getFieldName(), uiValue.getContentType(),
                uiValue.isFormField(), uiValue.getName());
        try (InputStream is = uiValue.getInputStream(); OutputStream os = scaledFileItem.getOutputStream()) {
            Thumbnailer tn = Thumbnailer.getInstance(is);
            BufferedImage scaledImg = tn.getQualityThumbnail(newDim.getWidthMetric().intValue(),
                    newDim.getHeightMetric().intValue());
            String extension = StringFactory.getExtension(uiValue.getName());
            ImageIO.write(scaledImg, extension, os);
            uiValue.delete();
            uiValue = scaledFileItem;
        } catch (Throwable e) {
            _logger.warn("Skipping scaling due to:", e);
        }
    }

    return uiValue;
}

From source file:com.example.app.support.ui.vtcrop.VTCropPictureEditor.java

@Nullable
private FileItem _getUIValue(@Nullable FileItem uiValue) {
    if (uiValue == null) {
        return null;
    }//ww w .  jav  a2  s . c o  m

    Dimension origDim, newDim;
    try {
        origDim = ImageFileUtil.getDimension(uiValue);
    } catch (IOException e) {
        _logger.error("Skipping scaling because an error occurred.", e);
        return uiValue;
    }

    if (origDim == null) {
        _logger.warn("Skipping scaling because retrieved dimension for ui value was null.");
        return uiValue;
    }

    VTCropPictureEditorConfig.ImageScaleOption option = _config.getImageScaleOptionForName(_uiValue.getName());
    int newDimWidth = option != null && option.scale != null
            ? Double.valueOf(_config.getCropWidth() * option.scale).intValue()
            : _config.getCropWidth();
    int newDimHeight = option != null && option.scale != null
            ? Double.valueOf(_config.getCropHeight() * option.scale).intValue()
            : _config.getCropHeight();

    newDim = ImageFileUtil.getScaledDimension(origDim, newDimWidth, newDimHeight);

    if (!Objects.equals(newDim, origDim)) {
        _logger.debug("Scale to " + newDim.getWidthMetric() + " x " + newDim.getHeightMetric());
        FileItem scaledFileItem = _fileItemFactory.createItem(uiValue.getFieldName(), uiValue.getContentType(),
                uiValue.isFormField(), uiValue.getName());
        try (InputStream is = uiValue.getInputStream(); OutputStream os = scaledFileItem.getOutputStream()) {
            Thumbnailer tn = Thumbnailer.getInstance(is);
            BufferedImage scaledImg = tn.getQualityThumbnail(newDim.getWidthMetric().intValue(),
                    newDim.getHeightMetric().intValue());
            String extension = StringFactory.getExtension(uiValue.getName());
            ImageIO.write(scaledImg, extension, os);
            uiValue.delete();
            uiValue = scaledFileItem;
        } catch (Throwable e) {
            _logger.warn("Skipping scaling due to:", e);
        }
    }

    return uiValue;
}

From source file:com.zlk.fckeditor.Dispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In
 * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and
 * {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * /*from  w ww  . ja  v  a  2  s .c o  m*/
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
UploadResponse doPost(final HttpServletRequest request) {
    logger.debug("Entering Dispatcher#doPost");

    Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request))
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    // check parameters  
    else if (!Command.isValidForPost(context.getCommandStr()))
        uploadResponse = UploadResponse.getInvalidCommandError();
    else if (!ResourceType.isValidType(context.getTypeStr()))
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    else if (!UtilsFile.isValidPath(context.getCurrentFolderStr()))
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    else {

        // call the Connector#fileUpload
        ResourceType type = context.getDefaultResourceType();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            String fileName = FilenameUtils.getName(uplFile.getName());
            logger.debug("Parameter NewFile: {}", fileName);

            // ??
            if (uplFile.getSize() > 1024 * 1024 * 50) {//50M
                // ?
                uploadResponse = new UploadResponse(204);
            } else {

                //??uuid?
                String extension = FilenameUtils.getExtension(fileName);
                fileName = UUID.randomUUID().toString() + "." + extension;
                /*              String path=request.getSession().getServletContext().getRealPath("/")+"userfiles/";
                              fileName = makeFileName(path+"/"+type.getPath(), fileName);*/

                logger.debug("Change FileName to UUID: {} (by zhoulukang)", fileName);

                // check the extension
                if (type.isDeniedExtension(FilenameUtils.getExtension(fileName)))
                    uploadResponse = UploadResponse.getInvalidFileTypeError();
                // Secure image check (can't be done if QuickUpload)
                else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                        && !UtilsFile.isImage(uplFile.getInputStream())) {
                    uploadResponse = UploadResponse.getInvalidFileTypeError();
                } else {
                    String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                    logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                    String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(),
                            sanitizedFileName, uplFile.getInputStream());
                    String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type,
                            context.getCurrentFolderStr(), newFileName);

                    if (sanitizedFileName.equals(newFileName))
                        uploadResponse = UploadResponse.getOK(fileUrl);
                    else {
                        uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                        logger.debug("Parameter NewFile (renamed): {}", newFileName);
                    }
                }
                uplFile.delete();
            }

        } catch (InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}

From source file:com.silverpeas.servlets.upload.AjaxFileUploadServlet.java

/**
 * Do the effective upload of files.//ww w  .j  a  v  a2 s  . c  o  m
 *
 * @param session the HttpSession
 * @param request the multpart request
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private void doFileUpload(HttpSession session, HttpServletRequest request) throws IOException {
    try {
        session.setAttribute(UPLOAD_ERRORS, "");
        session.setAttribute(UPLOAD_FATAL_ERROR, "");
        List<String> paths = new ArrayList<String>();
        session.setAttribute(FILE_UPLOAD_PATHS, paths);
        FileUploadListener listener = new FileUploadListener(request.getContentLength());
        session.setAttribute(FILE_UPLOAD_STATS, listener.getFileUploadStats());
        FileItemFactory factory = new MonitoringFileItemFactory(listener);
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
        startingToSaveUploadedFile(session);
        String errorMessage = "";
        for (FileItem fileItem : items) {
            if (!fileItem.isFormField() && fileItem.getSize() > 0L) {
                try {
                    String filename = fileItem.getName();
                    if (filename.indexOf('/') >= 0) {
                        filename = filename.substring(filename.lastIndexOf('/') + 1);
                    }
                    if (filename.indexOf('\\') >= 0) {
                        filename = filename.substring(filename.lastIndexOf('\\') + 1);
                    }
                    if (!isInWhiteList(filename)) {
                        errorMessage += "The file " + filename + " is not uploaded!";
                        errorMessage += (StringUtil.isDefined(whiteList)
                                ? " Only " + whiteList.replaceAll(" ", ", ")
                                        + " file types can be uploaded<br/>"
                                : " No allowed file format has been defined for upload<br/>");
                        session.setAttribute(UPLOAD_ERRORS, errorMessage);
                    } else {
                        filename = System.currentTimeMillis() + "-" + filename;
                        File targetDirectory = new File(uploadDir, fileItem.getFieldName());
                        targetDirectory.mkdirs();
                        File uploadedFile = new File(targetDirectory, filename);
                        OutputStream out = null;
                        try {
                            out = new FileOutputStream(uploadedFile);
                            IOUtils.copy(fileItem.getInputStream(), out);
                            paths.add(uploadedFile.getParentFile().getName() + '/' + uploadedFile.getName());
                        } finally {
                            IOUtils.closeQuietly(out);
                        }
                    }
                } finally {
                    fileItem.delete();
                }
            }
        }
    } catch (Exception e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.WARNING, e.getMessage());
        session.setAttribute(UPLOAD_FATAL_ERROR,
                "Could not process uploaded file. Please see log for details.");
    } finally {
        endingToSaveUploadedFile(session);
    }
}

From source file:it.lufraproini.cms.servlet.Upload.java

private String action_upload(HttpServletRequest request, Map data)
        throws ErroreGrave, SQLException, IOException, NamingException, NoSuchAlgorithmException {

    FileItem fi = null;
    String sdigest = "";
    String cartella = "";
    String tipo_file = data.get("submit").toString();
    String estensione = "";
    String campi_errati = "";
    Map files = new HashMap();
    files = (HashMap) data.get("files");
    campi_errati = checkfields(data);/*from   w  ww .  j  a  va  2s  . co m*/
    if (!campi_errati.equals("")) {
        throw new ErroreGrave("I seguenti campi contengono valori non ammessi: " + campi_errati);
        //return null;
    }

    if (tipo_file.equals("immagine")) {
        cartella = getServletContext().getInitParameter("system.image_directory");
    } else if (tipo_file.equals("css")) {
        cartella = getServletContext().getInitParameter("system.css_directory");
    } else if (tipo_file.equals("slide")) {
        cartella = getServletContext().getInitParameter("system.slide_directory");
    } else {
        throw new ErroreGrave("i tipi di file che si vogliono inviare al server non sono ancora supportati");
    }

    fi = (FileItem) files.get("file_to_upload");
    String nome = fi.getName();
    if (nome != null) {
        estensione = FilenameUtils.getExtension(FilenameUtils.getName(nome));
    }
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    File temp_file = File.createTempFile("upload_", "_temp",
            new File(getServletContext().getRealPath(cartella)));
    InputStream is = fi.getInputStream();
    OutputStream os = new FileOutputStream(temp_file);
    byte[] buffer = new byte[1024];
    int read;
    while ((read = is.read(buffer)) > 0) {
        //durante la copia, aggreghiamo i byte del file nel digest sha-1
        os.write(buffer, 0, read);
        md.update(buffer, 0, read);
    }
    is.close();
    os.close();

    //covertiamo il digest in una stringa
    byte[] digest = md.digest();
    for (byte b : digest) {
        sdigest += String.valueOf(b);
    }

    if (sdigest.equals("")) {
        throw new ErroreGrave();
    }

    this.estensione = estensione;
    if (estensione.equals("css")) {
        this.nomefile = data.get("nome").toString();
    } else {
        this.nomefile = sdigest;
    }
    //L'immagine sar salvata con il digest + l'estensione del file mentre il css sar salvato con il nome inserito nella form
    File uploaded_file = new File(
            getServletContext().getRealPath(cartella) + File.separatorChar + this.nomefile + "." + estensione);
    if (!uploaded_file.exists()) {
        temp_file.renameTo(uploaded_file);
    } else {
        temp_file.delete();
    }
    return sdigest;
}

From source file:edu.lafayette.metadb.web.controlledvocab.UpdateVocab.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*//*from w ww  .j a v  a 2 s.  c o  m*/
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    String vocabName = null;
    String name = "nothing";
    String status = "Upload failed ";

    try {

        if (ServletFileUpload.isMultipartContent(request)) {
            status = "isMultiPart";
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            InputStream input = null;
            Iterator it = fileItemsList.iterator();
            String result = "";
            String vocabs = null;
            int assigned = -1;

            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                result += "UpdateVocab: Form Field: " + fileItem.isFormField() + " Field name: "
                        + fileItem.getFieldName() + " Name: " + fileItem.getName() + " String: "
                        + fileItem.getString("utf-8") + "\n";
                if (fileItem.isFormField()) {
                    /* The file item contains a simple name-value pair of a form field */
                    if (fileItem.getFieldName().equals("vocab-name"))
                        vocabName = fileItem.getString();
                    else if (fileItem.getFieldName().equals("vocab-terms"))
                        vocabs = fileItem.getString("utf-8");
                    else if (fileItem.getFieldName().equals("assigned-field"))
                        assigned = Integer.parseInt(fileItem.getString());
                } else {
                    if (fileItem.getString() != null && !fileItem.getString().equals("")) {
                        @SuppressWarnings("unused")
                        String content = "nothing";
                        /* The file item contains an uploaded file */

                        /* Create new File object
                        File uploadedFile = new File("test.txt");
                        if(!uploadedFile.exists())
                           uploadedFile.createNewFile();
                        // Write the uploaded file to the system
                        fileItem.write(uploadedFile);
                        */
                        name = fileItem.getName();
                        content = fileItem.getContentType();
                        input = fileItem.getInputStream();
                    }
                }
            }
            //MetaDbHelper.note(result);
            if (vocabName != null) {
                Set<String> vocabList = new TreeSet<String>();
                if (input != null) {
                    Scanner fileSc = new Scanner(input);
                    while (fileSc.hasNextLine()) {
                        String vocabEntry = fileSc.nextLine();
                        vocabList.add(vocabEntry.trim());
                    }

                    HttpSession session = request.getSession(false);
                    if (session != null) {
                        String userName = (String) session.getAttribute("username");
                        SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                "User " + userName + " created vocab " + vocabName);
                    }
                    status = "Vocab name: " + vocabName + ". File name: " + name + "\n";

                } else {
                    //MetaDbHelper.note(vocabs);
                    for (String vocabTerm : vocabs.split("\n"))
                        vocabList.add(vocabTerm);
                }
                if (!vocabList.isEmpty()) {
                    boolean updated = ControlledVocabDAO.addControlledVocab(vocabName, vocabList)
                            || ControlledVocabDAO.updateControlledVocab(vocabName, vocabList);
                    if (updated) {
                        status = "Vocab " + vocabName + " updated successfully ";
                        if (assigned != -1)
                            if (!AdminDescAttributesDAO.setControlledVocab(assigned, vocabName)) {
                                status = "Vocab " + vocabName + " cannot be assigned to " + assigned;
                            }

                    } else
                        status = "Vocab " + vocabName + " cannot be updated/created";
                } else
                    status = "Vocab " + vocabName + " has empty vocabList";
            }
        }
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    MetaDbHelper.note(status);
    out.print(status);
    out.flush();
}

From source file:edu.ucsd.library.xdre.web.CollectionOperationController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String message = "";

    Map<String, String[]> paramsMap = null;
    if (ServletFileUpload.isMultipartContent(request)) {
        paramsMap = new HashMap<String, String[]>();
        paramsMap.putAll(request.getParameterMap());
        FileItemFactory factory = new DiskFileItemFactory();

        //Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        List items = null;/*from   ww  w .  j  a v  a 2s. c om*/
        InputStream in = null;
        ByteArrayOutputStream out = null;
        byte[] buf = new byte[4096];
        List<String> dataItems = new ArrayList<String>();
        List<String> fileNames = new ArrayList<String>();
        try {
            items = upload.parseRequest(request);

            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                out = new ByteArrayOutputStream();
                if (item.isFormField()) {
                    paramsMap.put(item.getFieldName(), new String[] { item.getString() });
                } else {
                    fileNames.add(item.getName());
                    in = item.getInputStream();

                    int bytesRead = -1;
                    while ((bytesRead = in.read(buf)) > 0) {
                        out.write(buf, 0, bytesRead);
                    }
                    dataItems.add(out.toString());
                }
            }
        } catch (FileUploadException e) {
            throw new ServletException(e.getMessage());
        } finally {
            if (in != null) {
                in.close();
                in = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        }

        if (dataItems.size() > 0) {
            String[] a = new String[dataItems.size()];
            paramsMap.put("data", dataItems.toArray(a));
            paramsMap.put("fileName", fileNames.toArray(new String[dataItems.size()]));
        }
    } else
        paramsMap = request.getParameterMap();

    String collectionId = getParameter(paramsMap, "category");
    String activeButton = getParameter(paramsMap, "activeButton");
    boolean dataConvert = getParameter(paramsMap, "dataConvert") != null;
    boolean isIngest = getParameter(paramsMap, "ingest") != null;
    boolean isDevUpload = getParameter(paramsMap, "devUpload") != null;
    boolean isBSJhoveReport = getParameter(paramsMap, "bsJhoveReport") != null;
    boolean isSolrDump = getParameter(paramsMap, "solrDump") != null
            || getParameter(paramsMap, "solrRecordsDump") != null;
    boolean isSerialization = getParameter(paramsMap, "serialize") != null;
    boolean isMarcModsImport = getParameter(paramsMap, "marcModsImport") != null;
    boolean isExcelImport = getParameter(paramsMap, "excelImport") != null;
    boolean isCollectionRelease = getParameter(paramsMap, "collectionRelease") != null;
    boolean isFileUpload = getParameter(paramsMap, "fileUpload") != null;
    String fileStore = getParameter(paramsMap, "fs");
    if (activeButton == null || activeButton.length() == 0)
        activeButton = "validateButton";
    HttpSession session = request.getSession();
    session.setAttribute("category", collectionId);
    session.setAttribute("user", request.getRemoteUser());

    String ds = getParameter(paramsMap, "ts");
    if (ds == null || ds.length() == 0)
        ds = Constants.DEFAULT_TRIPLESTORE;

    if (fileStore == null || (fileStore = fileStore.trim()).length() == 0)
        fileStore = null;

    String forwardTo = "/controlPanel.do?ts=" + ds + (fileStore != null ? "&fs=" + fileStore : "");
    if (dataConvert)
        forwardTo = "/pathMapping.do?ts=" + ds + (fileStore != null ? "&fs=" + fileStore : "");
    else if (isIngest) {
        String unit = getParameter(paramsMap, "unit");
        forwardTo = "/ingest.do?ts=" + ds + (fileStore != null ? "&fs=" + fileStore : "")
                + (unit != null ? "&unit=" + unit : "");
    } else if (isDevUpload)
        forwardTo = "/devUpload.do?" + (fileStore != null ? "&fs=" + fileStore : "");
    else if (isSolrDump)
        forwardTo = "/solrDump.do" + (StringUtils.isBlank(collectionId) ? "" : "#colsTab");
    else if (isSerialization)
        forwardTo = "/serialize.do?" + (fileStore != null ? "&fs=" + fileStore : "");
    else if (isMarcModsImport)
        forwardTo = "/marcModsImport.do?";
    else if (isExcelImport)
        forwardTo = "/excelImport.do?";
    else if (isCollectionRelease)
        forwardTo = "/collectionRelease.do?";
    else if (isFileUpload)
        forwardTo = "/fileUpload.do?";

    String[] emails = null;
    String user = request.getRemoteUser();
    if ((!(getParameter(paramsMap, "solrRecordsDump") != null || isBSJhoveReport || isDevUpload || isFileUpload)
            && getParameter(paramsMap, "rdfImport") == null && getParameter(paramsMap, "externalImport") == null
            && getParameter(paramsMap, "dataConvert") == null)
            && getParameter(paramsMap, "marcModsImport") == null
            && getParameter(paramsMap, "excelImport") == null
            && (collectionId == null || (collectionId = collectionId.trim()).length() == 0)) {
        message = "Please choose a collection ...";
    } else {
        String servletId = getParameter(paramsMap, "progressId");
        boolean vRequest = false;
        try {
            vRequest = RequestOrganizer.setReferenceServlet(session, servletId, Thread.currentThread());
        } catch (Exception e) {
            message = e.getMessage();
        }
        if (!vRequest) {
            if (isSolrDump || isCollectionRelease || isFileUpload)
                session.setAttribute("message", message);
            else {
                forwardTo += "&activeButton=" + activeButton;
                forwardTo += "&message=" + message;
            }

            forwordPage(request, response, response.encodeURL(forwardTo));
            return null;
        }

        session.setAttribute("status", "Processing request ...");
        DAMSClient damsClient = null;
        try {
            //user = getUserName(request);
            //email = getUserEmail(request);
            damsClient = new DAMSClient(Constants.DAMS_STORAGE_URL);
            JSONArray mailArr = (JSONArray) damsClient.getUserInfo(user).get("mail");
            if (mailArr != null && mailArr.size() > 0) {
                emails = new String[mailArr.size()];
                mailArr.toArray(emails);
            }
            message = handleProcesses(paramsMap, request.getSession());
        } catch (Exception e) {
            e.printStackTrace();
            //throw new ServletException(e.getMessage());
            message += "<br />Internal Error: " + e.getMessage();
        } finally {
            if (damsClient != null)
                damsClient.close();
        }
    }
    System.out.println("XDRE Manager execution for " + request.getRemoteUser() + " from IP "
            + request.getRemoteAddr() + ": ");
    System.out.println(message.replace("<br />", "\n"));

    try {
        int count = 0;
        String result = (String) session.getAttribute("result");
        while (result != null && result.length() > 0 && count++ < 10) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            result = (String) session.getAttribute("result");
        }
        RequestOrganizer.clearSession(session);
    } catch (IllegalStateException e) {
        //e.printStackTrace();
    }
    //send email
    try {
        String sender = Constants.MAILSENDER_DAMSSUPPORT;
        if (emails == null && user != null) {
            emails = new String[1];
            emails[0] = user + "@ucsd.edu";
        }
        if (emails == null)
            DAMSClient.sendMail(sender, new String[] { sender },
                    "DAMS Manager Invocation Result - "
                            + Constants.CLUSTER_HOST_NAME.replace("http://", "").replace(".ucsd.edu/", ""),
                    message, "text/html", "smtp.ucsd.edu");
        else
            DAMSClient.sendMail(sender, emails,
                    "DAMS Manager Invocation Result - "
                            + Constants.CLUSTER_HOST_NAME.replace("http://", "").replace(".ucsd.edu/", ""),
                    message, "text/html", "smtp.ucsd.edu");
    } catch (AddressException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }

    if (isSolrDump || isMarcModsImport || isExcelImport || isCollectionRelease || isFileUpload) {
        session.setAttribute("message", message.replace("\n", "<br />"));
        if (collectionId != null && (isMarcModsImport || isExcelImport || isCollectionRelease))
            forwardTo += "category=" + collectionId;
    } else {
        forwardTo += "&activeButton=" + activeButton;
        if (collectionId != null)
            forwardTo += "&category=" + collectionId;

        forwardTo += "&message=" + URLEncoder.encode(message.replace("\n", "<br />"), "UTF-8");
    }
    System.out.println(forwardTo);
    //String forwardToUrl = "/controlPanel.do?category=" + collectionId + "&message=" + message + "&activeButton=" + activeButton;
    forwordPage(request, response, response.encodeURL(forwardTo));
    return null;
}