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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

From source file:it.geosolutions.geofence.gui.server.UploadServlet.java

@SuppressWarnings("unchecked")
@Override/*from   www. jav a2s.  c o  m*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

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

        File uploadedFile = null;
        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(req);

            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    continue;
                }

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                uploadedFile = File.createTempFile(fileName, "");
                // if (uploadedFile.createNewFile()) {
                item.write(uploadedFile);
                resp.setStatus(HttpServletResponse.SC_CREATED);
                resp.flushBuffer();

                // uploadedFile.delete();
                // } else
                // throw new IOException(
                // "The file already exists in repository.");
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

        try {
            String wkt = calculateWKT(uploadedFile);
            resp.getWriter().print(wkt);
        } catch (Exception exc) {
            resp.getWriter().print("Error : " + exc.getMessage());
            logger.error("ERROR ********** " + exc);
        }

        uploadedFile.delete();

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:com.tremolosecurity.proxy.postProcess.PushRequestProcess.java

@Override
public void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpFilterChain chain)
        throws Exception {
    boolean isText;

    HashMap<String, String> uriParams = (HashMap<String, String>) req.getAttribute("TREMOLO_URI_PARAMS");

    StringBuffer proxyToURL = new StringBuffer();

    proxyToURL.append(holder.getProxyURL(uriParams));

    boolean first = true;
    for (NVP p : req.getQueryStringParams()) {
        if (first) {
            proxyToURL.append('?');
            first = false;//  w w w.  ja  v  a  2  s. c om
        } else {
            proxyToURL.append('&');
        }

        proxyToURL.append(p.getName()).append('=').append(URLEncoder.encode(p.getValue(), "UTF-8"));
    }

    HttpEntity entity = null;

    if (req.isMultiPart()) {

        MultipartEntityBuilder mpeb = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (String name : req.getFormParams()) {

            /*if (queryParams.contains(name)) {
               continue;
            }*/

            for (String val : req.getFormParamVals(name)) {
                //ent.addPart(name, new StringBody(val));
                mpeb.addTextBody(name, val);
            }

        }

        HashMap<String, ArrayList<FileItem>> files = req.getFiles();
        for (String name : files.keySet()) {
            for (FileItem fi : files.get(name)) {
                //ent.addPart(name, new InputStreamBody(fi.getInputStream(),fi.getContentType(),fi.getName()));

                mpeb.addBinaryBody(name, fi.get(), ContentType.create(fi.getContentType()), fi.getName());

            }
        }

        entity = mpeb.build();

    } else if (req.isParamsInBody()) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        for (String paramName : req.getFormParams()) {

            for (String val : req.getFormParamVals(paramName)) {

                formparams.add(new BasicNameValuePair(paramName, val));
            }
        }

        entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    } else {

        byte[] msgData = (byte[]) req.getAttribute(ProxySys.MSG_BODY);
        ByteArrayEntity bentity = new ByteArrayEntity(msgData);
        bentity.setContentType(req.getContentType());

        entity = bentity;
    }

    MultipartRequestEntity frm;

    CloseableHttpClient httpclient = this.getHttp(proxyToURL.toString(), req.getServletRequest(),
            holder.getConfig());

    //HttpPost httppost = new HttpPost(proxyToURL.toString());
    HttpEntityEnclosingRequestBase httpMethod = new EntityMethod(req.getMethod(), proxyToURL.toString());//this.getHttpMethod(proxyToURL.toString());

    setHeadersCookies(req, holder, httpMethod, proxyToURL.toString());

    httpMethod.setEntity(entity);

    HttpContext ctx = (HttpContext) req.getSession().getAttribute(ProxySys.HTTP_CTX);
    HttpResponse response = httpclient.execute(httpMethod, ctx);

    postProcess(req, resp, holder, response, proxyToURL.toString(), chain, httpMethod);

}

From source file:com.weaforce.system.component.fckeditor.connector.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*from   w w w. j  av a 2  s  .  c  o m*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command"); // "FileUpload"
    String typeStr = request.getParameter("Type"); // Image
    String currentFolderStr = request.getParameter("CurrentFolder"); // "/"
    imageSubPath = request.getParameter("subpath");

    logger.info("Parameter Command in doPost: {}", commandStr);
    logger.info("Parameter Type in doPost: {}", typeStr);
    logger.info("Parameter CurrentFolder in doPost: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (StringUtil.isEmpty(commandStr) && StringUtil.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!FileUtils.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);
        //String userLogin = Security.getCurrentUserName().toLowerCase();
        // typePath=\\data\\file in the weaforce.properties
        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        typePath = typePath + "/" + imageSubPath + "/" + DateUtil.getCurrentYearObliqueMonthStr();
        System.out.println("typePath: " + typePath);
        logger.info("doPost: typePath value is: {}", typePath);
        String typeDirPath = typePath;
        FileUtils.checkAndCreateDir(typeDirPath);
        File typeDir = new File(typeDirPath);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                List<FileItem> items = upload.parseRequest(request);
                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                // String baseName =
                // FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);
                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                else {
                    filename = getFilename(typeDirPath, System.currentTimeMillis(), extension);
                    File pathToSave = new File(currentDir, filename);
                    // String responseUrl = UtilsResponse
                    // .constructResponseUrl(request, resourceType,
                    // currentFolderStr, true,
                    // ConnectorHandler.isFullUrl());
                    String responseUrl = UtilsResponse.constructResponseUrl(resourceType, imageSubPath,
                            currentFolderStr);
                    if (StringUtil.isEmpty(newFilename)) {
                        responseUrl = responseUrl + DateUtil.getCurrentYearObliqueMonthStr() + "/";
                        ur = new UploadResponse(UploadResponse.SC_OK, responseUrl.concat(filename));
                    } else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED, responseUrl.concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (FileUtils.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
            // System.out.println("newFilename2: " + newFilename);
        }

    }
    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:calliope.handler.post.AeseTextImportHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws AeseException {
    try {//w ww .j a  va  2  s  .co  m
        if (ServletFileUpload.isMultipartContent(request)) {
            StringBuilder sb = new StringBuilder();
            // Check that we have a file upload request
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            String log = "";
            sb.append("<html><body>");
            // Parse the request
            List items = upload.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    if (fieldName != null) {
                        sb.append("<p>form field: ");
                        sb.append(fieldName);
                        sb.append("</p>");
                    }
                } else if (item.getName().length() > 0) {
                    String fieldName = item.getFieldName();
                    if (fieldName != null) {
                        sb.append("<p>file field: ");
                        sb.append(fieldName);
                        sb.append("</p>");
                    }
                }
            }
            sb.append("</body></html>");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println(sb.toString());
        }
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:com.boundlessgeo.geoserver.api.controllers.IconController.java

@RequestMapping(value = "/{wsName:.+}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseStatus(value = HttpStatus.CREATED) @ResponseBody JSONArr create(@PathVariable String wsName,
        HttpServletRequest request) throws IOException, FileUploadException {

    WorkspaceInfo ws;/*from w  w  w  . jav a2 s . c o m*/
    Resource styles;

    if (wsName == null) {
        ws = null;
        styles = dataDir().getRoot("styles");
    } else {
        ws = findWorkspace(wsName, catalog());
        styles = dataDir().get(ws, "styles");
    }

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    @SuppressWarnings("unchecked")
    List<FileItem> input = (List<FileItem>) upload.parseRequest(request);

    JSONArr created = new JSONArr();
    for (FileItem file : input) {
        String filename = file.getName();

        // trim filename if required
        if (filename.lastIndexOf('/') != -1) {
            filename = filename.substring(filename.lastIndexOf('/'));
        }
        if (filename.lastIndexOf('\\') != -1) {
            filename = filename.substring(filename.lastIndexOf('\\'));
        }
        String ext = fileExt(filename);
        if (!ICON_FORMATS.containsKey(ext)) {
            String msg = "Icon " + filename + " format " + ext + " unsupported - try:" + ICON_FORMATS.keySet();
            LOG.warning(msg);
            throw new FileUploadException(msg);
        }
        try {
            InputStream data = file.getInputStream();
            Resources.copy(data, styles, filename);

            icon(created.addObject(), ws, styles.get(filename), request);
        } catch (Exception e) {
            throw new FileUploadException("Unable to write " + filename, e);
        }
    }

    return created;
}

From source file:ManageViewerFiles.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w w  .j  av a  2 s  .  co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        //get the viewer files
        //add more files
        //delete some files
        /* TODO output your page here. You may use following sample code. */
        String command = request.getParameter("command");
        String viewerid = request.getParameter("viewerid");
        //System.out.println("Hello World");
        //System.out.println(command);
        //System.out.println(studyid);
        if (command.equalsIgnoreCase("getViewerFiles")) {
            //getting viewer files
            //first get the filenames in the directory.
            //I will get the list of files in this directory and send it

            String studyPath = getServletContext().getRealPath("/viewer/" + viewerid);

            File root = new File(studyPath);
            File[] list = root.listFiles();

            ArrayList<String> fileItemList = new ArrayList<String>();
            if (list == null) {
                System.out.println("List is null");
                return;
            }

            for (File f : list) {
                if (f.isDirectory()) {
                    ArrayList<String> dirItems = getFileItems(f.getAbsolutePath(), f.getName());

                    for (int i = 0; i < dirItems.size(); i++) {
                        fileItemList.add(dirItems.get(i));
                    }

                } else {
                    //System.out.println(f.getName());
                    fileItemList.add(f.getName());
                }
            }

            System.out.println("**** Printing the fileItems now **** ");
            String outputStr = "";
            for (int i = 0; i < fileItemList.size(); i++) {
                outputStr += fileItemList.get(i) + "::::";
            }

            out.println(outputStr);
        } else if (command.equalsIgnoreCase("addViewerFiles")) {
            //add the files
            //get the files and add them

            String studyFolderPath = getServletContext().getRealPath("/viewer/" + viewerid);
            File studyFolder = new File(studyFolderPath);

            //process only if its multipart content
            if (ServletFileUpload.isMultipartContent(request)) {
                try {
                    List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory())
                            .parseRequest(request);
                    int cnt = 0;
                    for (FileItem item : multiparts) {
                        if (!item.isFormField()) {
                            // cnt++;
                            String name = new File(item.getName()).getName();
                            //write the file to disk  
                            if (!studyFolder.exists()) {
                                studyFolder.mkdir();
                                System.out.println("The Folder has been created");
                            }
                            item.write(new File(studyFolder + File.separator + name));
                            System.out.println("File name is :: " + name);
                        }
                    }

                    out.print("Files successfully uploaded");
                } catch (Exception ex) {
                    //System.out.println("File Upload Failed due to " + ex);
                    out.print("File Upload Failed due to " + ex);
                }

            } else {
                // System.out.println("The request did not include files");
                out.println("The request did not include files");
            }

        } else if (command.equalsIgnoreCase("deleteViewerFiles")) {
            //get the array of files and delete thems
            String[] mpk;

            //get the array of file-names
            mpk = request.getParameterValues("fileNames");
            for (int i = 0; i < mpk.length; i++) {
                String filePath = getServletContext().getRealPath("/viewer/" + viewerid + "/" + mpk[i]);

                File f = new File(filePath);
                f.delete();

            }
        }
        //out.println("</html>");
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:com.yeoou.fckeditor.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*from www  . ja v  a2s. c  o m*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                upload.setHeaderEncoding("UTF-8");
                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:gov.ymp.slts.doSWTransaction.java

private String processRequest(HttpServletRequest request, HttpServletResponse response) {
    String command = request.getParameter("command");
    String idS = request.getParameter("id");
    int id = Integer.parseInt(idS);
    String prodIDS = request.getParameter("prodid");
    int prodID = Integer.parseInt(prodIDS);
    String transIDS = request.getParameter("transid");
    int transID = Integer.parseInt(transIDS);
    //System.out.println("doSWTransaction - Got Here 1" +"- command: " + command + ", Timestamp: " + Utils.genDateID());

    String outLine = "";
    String nextScript = request.getParameter("nextscript");
    OutputStream toClient;/*from   w  ww  . jav  a  2  s. c om*/
    HttpSession session = request.getSession();
    boolean success = false;
    String userIDs = (String) session.getAttribute("user.id");
    userIDs = ((userIDs != null) ? userIDs : "0");
    long userID = Long.parseLong(userIDs);

    command = (command != null && command.compareTo(" ") > 0) ? command : "new";
    nextScript = (nextScript != null && nextScript.compareTo(" ") > 0) ? nextScript : "swBrowse.jsp";

    DbConn myConn = null;
    try {

        Context initCtx = new InitialContext();
        String ProductionStatus = (String) initCtx.lookup("java:comp/env/ProductionStatus");
        //String csiSchema = (String) initCtx.lookup("java:comp/env/csi-schema-path");
        String acronym = (String) initCtx.lookup("java:comp/env/SystemAcronym");
        myConn = new DbConn();
        String csiSchema = myConn.getSchemaPath();
        SWProduct sw = new SWProduct(prodID, myConn);
        SWTransactions trn = null;
        if (command.equals("new") || command.equals("update")) {
            //if (command.equals("update")) {
            //System.out.println("doSWTransaction - Got Here 2");
            // process transaction
            if (command.equals("new")) {
                trn = new SWTransactions();
                trn.setProductID(prodID);
            } else {
                trn = new SWTransactions(prodID, transID, myConn);
            }

            String tag = request.getParameter("tag");
            trn.setTag(((tag != null) ? tag : null));
            String serialnumber = request.getParameter("serialnumber");
            trn.setSerialNumber(((serialnumber != null) ? serialnumber : null));
            String purchaseorder = request.getParameter("purchaseorder");
            trn.setPurchaseOrder(((purchaseorder != null) ? purchaseorder : null));
            String dateverified = request.getParameter("dateverified");
            trn.setDateVerified(((dateverified != null) ? Utils.toDate(dateverified) : null));
            String datereceived = request.getParameter("datereceived");
            trn.setDateReceived(((datereceived != null) ? Utils.toDate(datereceived) : null));
            String dateexpires = request.getParameter("dateexpires");
            trn.setDateExpires(((dateexpires != null) ? Utils.toDate(dateexpires) : null));
            String location = request.getParameter("location");
            trn.setLocation(((location != null) ? location : null));
            String licensetype = request.getParameter("licensetype");
            trn.setLicenseType(((licensetype != null) ? licensetype : null));
            String licensecountS = request.getParameter("licensecount");
            if (licensecountS != null && licensecountS.compareTo("       ") > 0) {
                int licensecount = Integer.parseInt(licensecountS);
                trn.setLicenseCount(licensecount);
            }
            String transactiontype = request.getParameter("transactiontype");
            trn.setTransactionType(((transactiontype != null) ? transactiontype : null));
            String relatedtransactionS = request.getParameter("relatedtransaction");
            if (relatedtransactionS != null && relatedtransactionS.compareTo("       ") > 0) {
                int relatedtransaction = Integer.parseInt(relatedtransactionS);
                trn.setRelatedTransaction(relatedtransaction);
            }
            String documentation = request.getParameter("documentation");
            trn.setDocumentation(((documentation != null) ? documentation : null));
            trn.save(myConn);
            transID = trn.getID();
            //System.out.println("doSWTransaction - Got Here 2.5");
            String comments = request.getParameter("comments");
            // process comments
            if (comments != null && comments.compareTo("                            ") > 0) {
                Comments comm = new Comments(prodID, transID, userID, comments, myConn);
            }
            //System.out.println("doSWTransaction - Got Here 3");
            //Process attachments
            String attachCountS = request.getParameter("attachcount");
            int attachCount = Integer.parseInt(attachCountS);
            for (int i = 1; i <= attachCount; i++) {
                Object fileObject = request.getAttribute("attachment" + i);
                if (fileObject != null && !(fileObject instanceof FileUploadException)) {
                    String aTypeS = request.getParameter("attachmenttype" + i);
                    int aType = Integer.parseInt(aTypeS);
                    String aDesc = request.getParameter("attachmentdesc" + i);
                    FileItem fileItem = (FileItem) fileObject;
                    String fileName = fileItem.getName();
                    aDesc = ((aDesc != null && aDesc.compareTo("                                ") > 0) ? aDesc
                            : fileName);
                    fileName = trimFilePath(fileName);
                    InputStream inStream = fileItem.getInputStream();
                    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                    int myByte = inStream.read();
                    while (myByte >= 0) {
                        outStream.write(myByte);
                        myByte = inStream.read();
                    }
                    Attachment at = new Attachment(prodID, transID, fileName, aType, aDesc, myConn);
                    at.setImage(myConn, outStream);
                }
            }
            //System.out.println("doSWTransaction - Got Here 4");

            success = true;
            outLine = "";
            ALog.logActivity(userID, "slts", 2, "Transaction updated.");

        } else if (command.equals("drop")) {

            //success = true;
            //outLine = "Transaction " + temp + " Removed";
            //ALog.logActivity(userID, "slts", 3, outLine);
        } else if (command.equals("test")) {
            outLine = "test";
        }

    }

    catch (IllegalArgumentException e) {
        outLine = outLine + "IllegalArgumentException caught: " + e.getMessage();
        ALog.logError(userID, "slts", 0, "doSWTransaction error: '" + outLine + "'");
        //log(outLine);
    }

    catch (NullPointerException e) {
        outLine = outLine + "NullPointerException caught: " + e.getMessage();
        ALog.logError(userID, "slts", 0, "doSWTransaction error: '" + outLine + "'");
        //log(outLine);
    }

    //catch (IOException e) {
    //    outLine = outLine + "IOException caught: " + e.getMessage();
    //    ALog.logError(userID, "slts", 0, "doSWTransaction error: '" + outLine + "'");
    //    //log(outLine);
    //}

    //catch (MessagingException e) {
    //    outLine = outLine + "Messaging Exception caught: " + e.getMessage();
    //    ALog.logError(userID, "slts", 0, "doSWTransaction error: '" + outLine + "'");
    //    //log(outLine);
    //}
    catch (Exception e) {
        outLine = outLine + "Exception caught: " + e.getMessage();
        ALog.logError(userID, "slts", 0, "doSWTransaction error: '" + outLine + "'");
        //log(outLine);
    } finally {
        try {
            generateResponse(outLine, command, nextScript, success, response);
        } catch (Exception i) {
        }

        myConn.release();
        //log("Test log message\n");
    }

    return outLine;

}

From source file:importer.handler.post.TextImportHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn)
        throws ImporterException {
    try {//from  w  w  w  .  jav a  2  s  .  c om
        if (ServletFileUpload.isMultipartContent(request)) {
            StringBuilder sb = new StringBuilder();
            // Check that we have a file upload request
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            String log = "";
            sb.append("<html><body>");
            // Parse the request
            List items = upload.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    if (fieldName != null) {
                        sb.append("<p>form field: ");
                        sb.append(fieldName);
                        sb.append("</p>");
                    }
                } else if (item.getName().length() > 0) {
                    String fieldName = item.getFieldName();
                    if (fieldName != null) {
                        sb.append("<p>file field: ");
                        sb.append(fieldName);
                        sb.append("</p>");
                    }
                }
            }
            sb.append("</body></html>");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println(sb.toString());
        }
    } catch (Exception e) {
        throw new ImporterException(e);
    }
}

From source file:com.example.app.support.service.FileSaver.java

/**
 *   Set the file on {@link E} and saves it.  Returns the persisted instance of {@link E}
 *   @param value the instance of {@link E} to set the file on and save
 *   @param file the Image to save/*from  w  w w .j  a v  a 2  s.c  o m*/
 *   @return the updated and persisted value
 */
public E save(@Nonnull E value, @Nullable FileItem file) {
    if (file == null) {
        value = _setFile.apply(value, null);
    } else {
        value = _saveValue.apply(value);
        FileEntity currFile = _getFile.apply(value);
        if (currFile == null)
            currFile = new FileEntity();
        String fileName = StringFactory.getBasename(file.getName());
        String ct = file.getContentType();
        if (ct == null || "application/octet-stream".equals(ct))
            ct = MimeTypeUtility.getInstance().getContentType(fileName);
        currFile.setContentType(ct);
        final DirectoryEntity directory = _getDirectory.apply(value, file);
        if (directory != null) {
            currFile.setName(_getFileName.apply(value, file));

            FileSystemDAO.StoreRequest request = new FileSystemDAO.StoreRequest(directory, currFile,
                    new FileItemByteSource(file));
            request.setCreateMode(FileSystemEntityCreateMode.overwrite);

            currFile = _fileSystemDAO.store(request);
        } else {
            _logger.error("Unable to save File.");
            currFile = _getFile.apply(value);
        }

        value = _setFile.apply(value, currFile);
    }
    value = _saveValue.apply(value);
    return value;
}