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

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

Introduction

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

Prototype

String getString();

Source Link

Document

Returns the contents of the file item as a String, using the default character encoding.

Usage

From source file:com.buddycloud.mediaserver.business.dao.MediaDAO.java

protected String getFormFieldContent(List<FileItem> items, String fieldName) {
    String field = null;//from www  . java 2 s.  com

    for (int i = 0; i < items.size(); i++) {
        FileItem item = items.get(i);
        if (fieldName.equals(item.getFieldName().toLowerCase())) {
            field = item.getString();
            items.remove(i);

            break;
        }
    }

    return field;
}

From source file:com.mylop.servlet.TimelineServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from www.  j a v a 2  s .  c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    HttpSession session = request.getSession();
    String userid = (String) session.getAttribute("userid");
    String status = "aaa";
    String urlTimelineImage = "";
    String title = "";
    String subtitle = "";
    String content = "";
    Date date = new Date(Calendar.getInstance().getTimeInMillis());
    TimelineModel tm = new TimelineModel();
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> multiparts = upload.parseRequest(request);
            for (FileItem item : multiparts) {

                if (!item.isFormField()) {
                    String contentType = item.getContentType();
                    String fileName = UPLOAD_DIRECTORY + File.separator + userid + "_"
                            + (tm.getLastIndex() + 1);
                    File file = new File(fileName);
                    item.write(file);
                    urlTimelineImage = "http://mylop.tk:8080/Timeline/" + file.getName();
                } else {
                    String fieldName = item.getFieldName();

                    if (fieldName.equals("title")) {
                        title = item.getString();
                    }
                    if (fieldName.equals("subtitle")) {
                        subtitle = item.getString();
                    }
                    if (fieldName.equals("content")) {
                        content = item.getString();
                    }
                    if (fieldName.equals("date")) {
                        Long dateLong = Long.parseLong(item.getString());
                        date = new Date(dateLong);
                    }

                }
            }

            tm.addTimeline(userid, title, subtitle, date, content, urlTimelineImage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String json = "{\"message\": \"success\"}";
    response.getWriter().write(json);
}

From source file:com.twinsoft.convertigo.engine.servlets.GenericServlet.java

public Object processRequest(HttpServletRequest request) throws Exception {
    HttpServletRequestTwsWrapper twsRequest = request instanceof HttpServletRequestTwsWrapper
            ? (HttpServletRequestTwsWrapper) request
            : null;/*from w  w  w  . j  a v a 2 s .c o  m*/
    File temporaryFile = null;

    try {
        // Check multipart request
        if (ServletFileUpload.isMultipartContent(request)) {
            Engine.logContext.debug("(ServletRequester.initContext) Multipart resquest");

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

            // Set factory constraints
            factory.setSizeThreshold(1000);

            temporaryFile = File.createTempFile("c8o-multipart-files", ".tmp");
            int cptFile = 0;
            temporaryFile.delete();
            temporaryFile.mkdirs();
            factory.setRepository(temporaryFile);
            Engine.logContext.debug("(ServletRequester.initContext) Temporary folder for upload is : "
                    + temporaryFile.getAbsolutePath());

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

            // Set overall request size constraint
            upload.setSizeMax(
                    EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_REQUEST_SIZE));
            upload.setFileSizeMax(
                    EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_FILE_SIZE));

            // Parse the request
            List<FileItem> items = GenericUtils.cast(upload.parseRequest(request));

            for (FileItem fileItem : items) {
                String parameterName = fileItem.getFieldName();
                String parameterValue;
                if (fileItem.isFormField()) {
                    parameterValue = fileItem.getString();
                    Engine.logContext.trace("(ServletRequester.initContext) Value for field '" + parameterName
                            + "' : " + parameterValue);
                } else {
                    String name = fileItem.getName().replaceFirst("^.*(?:\\\\|/)(.*?)$", "$1");
                    if (name.length() > 0) {
                        File wDir = new File(temporaryFile, "" + (++cptFile));
                        wDir.mkdirs();
                        File wFile = new File(wDir, name);
                        fileItem.write(wFile);
                        fileItem.delete();
                        parameterValue = wFile.getAbsolutePath();
                        Engine.logContext
                                .debug("(ServletRequester.initContext) Temporary uploaded file for field '"
                                        + parameterName + "' : " + parameterValue);
                    } else {
                        Engine.logContext
                                .debug("(ServletRequester.initContext) No temporary uploaded file for field '"
                                        + parameterName + "', empty name");
                        parameterValue = "";
                    }
                }

                if (twsRequest != null) {
                    twsRequest.addParameter(parameterName, parameterValue);
                }
            }
        }

        Requester requester = getRequester();
        request.setAttribute("convertigo.requester", requester);

        Object result = requester.processRequest(request);

        request.setAttribute("convertigo.cookies", requester.context.getCookieStrings());

        String trSessionId = requester.context.getSequenceTransactionSessionId();
        if (trSessionId != null) {
            request.setAttribute("sequence.transaction.sessionid", trSessionId);
        }

        if (requester.context.requireEndOfContext) {
            // request.setAttribute("convertigo.requireEndOfContext",
            // requester);
            request.setAttribute("convertigo.requireEndOfContext", Boolean.TRUE);
        }

        if (request.getAttribute("convertigo.contentType") == null) { // if
            // contentType
            // set by
            // webclipper
            // servlet
            // (#320)
            request.setAttribute("convertigo.contentType", requester.context.contentType);
        }

        request.setAttribute("convertigo.cacheControl", requester.context.cacheControl);
        request.setAttribute("convertigo.context.contextID", requester.context.contextID);
        request.setAttribute("convertigo.isErrorDocument", new Boolean(requester.context.isErrorDocument));
        request.setAttribute("convertigo.context.removalRequired",
                new Boolean(requester.context.removalRequired()));
        if (requester.context.requestedObject != null) { // #397 : charset HTTP
            // header missing
            request.setAttribute("convertigo.charset", requester.context.requestedObject.getEncodingCharSet());
        } else { // #3803
            Engine.logEngine.warn(
                    "(GenericServlet) requestedObject is null. Set encoding to UTF-8 for processRequest.");
            request.setAttribute("convertigo.charset", "UTF-8");
        }

        return result;
    } finally {
        if (temporaryFile != null) {
            try {
                Engine.logEngine.debug(
                        "(GenericServlet) Removing the temporary file : " + temporaryFile.getAbsolutePath());
                FileUtils.deleteDirectory(temporaryFile);
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.bmth.MyServlet.UploadServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    HttpSession session = request.getSession();
    Account account = (Account) session.getAttribute("account");
    Register re = new Register();
    User user = re.getUserById(account.getUserId());
    // process only if it is multipart content
    String status = "aaa";
    String category = "other";
    if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {/*from ww  w .j  a  va  2s. c  om*/
            // Parse the request
            List<FileItem> multiparts = upload.parseRequest(request);
            ImageDAO img = new ImageDAO();
            String imgId = user.getUserId() + "" + (img.getAllImageUserId(user.getUserId()).size() + 1);
            int imageId = Integer.parseInt(imgId);
            Image image = new Image();
            image.setImgId(imageId);
            image.setUserId(user.getUserId());
            image.setPoint(0f);
            image.setImgDate(Calendar.getInstance().getTimeInMillis());

            for (FileItem item : multiparts) {

                if (!item.isFormField()) {
                    String contentType = item.getContentType();
                    String[] ext = contentType.split("/");

                    String fileName = UPLOAD_DIRECTORY + File.separator + user.getUserId() + "_" + imgId;
                    File file = new File(fileName);
                    item.write(file);
                    image.setImgUrl("http://localhost:8080/Image/" + file.getName());
                } else {
                    String fieldName = item.getFieldName();
                    if (fieldName.equals("status")) {
                        image.setImgDescribe(item.getString());
                    }
                    if (fieldName.equals("optionsRadios")) {
                        image.setTheme(theme(item.getString()));
                    }
                }
            }

            img.AddImage(image);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String json = "{\"message\": \"success\"}";
    response.getWriter().write(json);
}

From source file:de.betterform.agent.web.servlet.HttpRequestHandler.java

/**
 * Parses a HTTP request. Returns an array containing maps for upload
 * controls, other controls, repeat indices, and trigger. The individual
 * maps may be null in case no corresponding parameters appear in the
 * request.// w w w  .j  ava2 s. co m
 *
 * @param request a HTTP request.
 * @return an array of maps containing the parsed request parameters.
 * @throws FileUploadException          if an error occurred during file upload.
 * @throws UnsupportedEncodingException if an error occurred during
 *                                      parameter value decoding.
 */
protected Map[] parseRequest(HttpServletRequest request)
        throws FileUploadException, UnsupportedEncodingException {
    Map[] parameters = new Map[4];

    if (FileUpload.isMultipartContent(new ServletRequestContext(request))) {
        UploadListener uploadListener = new UploadListener(request, this.sessionKey);
        DiskFileItemFactory factory = new MonitoredDiskFileItemFactory(uploadListener);
        factory.setRepository(new File(this.uploadRoot));
        ServletFileUpload upload = new ServletFileUpload(factory);

        String encoding = request.getCharacterEncoding();
        if (encoding == null) {
            encoding = "UTF-8";
        }

        Iterator iterator = upload.parseRequest(request).iterator();
        FileItem item;
        while (iterator.hasNext()) {
            item = (FileItem) iterator.next();
            if (LOGGER.isDebugEnabled()) {
                if (item.isFormField()) {
                    LOGGER.debug(
                            "request param: " + item.getFieldName() + " - value='" + item.getString() + "'");
                } else {
                    LOGGER.debug("file in request: " + item.getName());
                }

            }
            parseMultiPartParameter(item, encoding, parameters);
        }
    } else {
        Enumeration enumeration = request.getParameterNames();
        String name;
        String[] values;
        while (enumeration.hasMoreElements()) {
            name = (String) enumeration.nextElement();
            values = request.getParameterValues(name);

            parseURLEncodedParameter(name, values, parameters);
        }
    }

    return parameters;
}

From source file:Game_DataS.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww  w .j  av  a 2s  .  c  o 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,
        ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
    String datetime = null, field = null, visitors = null, hteamname = null, fteamname = null;
    Integer Ivisitors = null;

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = null;
    try {
        out = response.getWriter();
        //First do the Proccesing of data . Data received from URL-POST method..

        // // Check that we have a file upload request
        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);

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

        //Parse the request to get file items.
        List<FileItem> fields = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator<FileItem> it = fields.iterator();
        //loop

        while (it.hasNext()) {
            FileItem fileItem = it.next();
            boolean isFormField = fileItem.isFormField();

            //Form Field
            if (isFormField) {
                String tmp = fileItem.getFieldName();

                if (tmp.equals("datetime")) {
                    datetime = fileItem.getString();
                } else if (tmp.equals("field")) {
                    field = fileItem.getString();
                } else if (tmp.equals("visitors")) {
                    visitors = fileItem.getString();
                    //cast to Integer
                    Ivisitors = Integer.parseInt(visitors);
                } else if (tmp.equals("hteamname")) {
                    hteamname = fileItem.getString();
                } else if (tmp.equals("fteamname")) {
                    fteamname = fileItem.getString();
                }
            } //extracted all STATIC INFO, now go to txt;s
            else {
                //Call Method that parses txt and do the inserts
                TXT_FILES_PROCESS(fileItem.getString(), fileItem.getFieldName(), out, hteamname, fteamname,
                        datetime, field, Ivisitors);
            }
        }

        //-------------------------------------
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>EuroLeague Page</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<div><h1>Successfull Registry in DataBase !!</h1>");
        out.println("<br></br>");
        out.println("<br>");
        out.println("<form name=\"myForm\" action=\"http://localhost:8080/Test_Project\">");
        out.println("Home Page for further action  --->  <input type=\"submit\" value=\"Home Page!\">");
        out.println("</form>");
        out.println("</div>");
        out.println("</body>");
        out.println("</html>");
    } catch (FileUploadException FUE) {
        System.out.println("debugg " + FUE.getLocalizedMessage());
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title> EuroLeague Page</title>");
        out.println("</head>");
        out.println("<body style = \"background-color: #720;\">");
        out.println(
                "<div><h1> Sorry...Something went wrong with the TXT uploading.Please go to home page and try again uploading a valid txt !!</h1>");
        out.println("<br> </br>");
        out.println("<br>");
        out.println("<form name=\"myForm\" action=\"http://localhost:8080/Test_Project\">");
        out.println("Press here -> <input  type = \"submit\" value = \"Home Page!\">");
        out.println("</form>");
        out.println("</div>");
        out.println("</body>");
        out.println("</html>");
    } catch (IOException IOE) {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title> EuroLeague Page</title>");
        out.println("</head>");
        out.println("<body style = \"background-color: #720;\">");
        out.println(
                "<div><h1> Sorry...Something went wrong.Maybe a network error.Please go to home page !!</h1>");
        out.println("<br> </br>");
        out.println("<br>");
        out.println("<form name=\"myForm\" action=\"http://localhost:8080/Test_Project\">");
        out.println("Press here -> <input  type = \"submit\" value = \"Home Page!\">");
        out.println("</form>");
        out.println("</div>");
        out.println("</body>");
        out.println("</html>");
    }
}

From source file:edu.cudenver.bios.filesvc.resource.UploadResource.java

/**
 * Handle POST requests for file upload/*ww w  .  j  a v a  2s  .  c  o m*/
 * @param entity entity body information (multi-part form encoded)
 */
@Post
public void upload(Representation entity) {
    if (entity != null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {

            // The Apache FileUpload project parses HTTP requests which
            // conform to RFC 1867, "Form-based File Upload in HTML". That
            // is, if an HTTP request is submitted using the POST method,
            // and with a content type of "multipart/form-data", then
            // FileUpload can parse that request, and get all uploaded files
            // as FileItem.

            // 1/ Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1000240);

            // 2 Create a new file upload handler based on the Restlet
            // FileUpload extension that will parse Restlet requests and
            // generates FileItems.
            RestletFileUpload upload = new RestletFileUpload(factory);
            List<FileItem> items;
            try {
                // 3. Request is parsed by the handler which generates a
                // list of FileItems
                items = upload.parseRequest(getRequest());

                // Process only the uploaded item called "fileToUpload" and
                // save it on disk
                boolean found = false;
                FileItem fi = null;
                for (final Iterator<FileItem> it = items.iterator(); it.hasNext() && !found;) {
                    fi = (FileItem) it.next();
                    if (fi.getFieldName().equals(FORM_TAG_FILE)) {
                        found = true;
                        break;
                    }
                }
                // Once handled, the content of the uploaded file is sent
                // back to the client.
                Representation rep = null;
                if (found) {
                    // Create a new representation based on disk file.
                    // The content is arbitrarily sent as plain text.
                    rep = new StringRepresentation(fi.getString(), MediaType.TEXT_HTML);
                    getResponse().setEntity(rep);
                    getResponse().setStatus(Status.SUCCESS_OK);
                } else {
                    rep = new StringRepresentation("No file data found", MediaType.TEXT_HTML);
                    getResponse().setEntity(rep);
                    getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                }
            } catch (Exception e) {
                // The message of all thrown exception is sent back to
                // client as simple plain text
                getResponse().setEntity(
                        new StringRepresentation("Upload failed: " + e.getMessage(), MediaType.TEXT_HTML));
                getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            }
        }
    } else {
        // POST request with no entity.
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    }
}

From source file:com.vectorcast.plugins.vectorcastexecution.job.NewMultiJob.java

/**
 * Create multi-job top-level and sub-projects, updating if required.
 * @param update true to do an update rather than create only
 * @throws IOException exception/*  ww  w  .j a  v a 2 s . c o  m*/
 * @throws ServletException exception
 * @throws hudson.model.Descriptor.FormException exception
 * @throws InvalidProjectFileException exception
 */
@Override
protected void doCreate(boolean update)
        throws IOException, ServletException, Descriptor.FormException, InvalidProjectFileException {
    // Read the manage project file
    FileItem fileItem = getRequest().getFileItem("manageProject");
    if (fileItem == null) {
        return;
    }

    manageFile = fileItem.getString();
    manageProject = new ManageProject(manageFile);
    manageProject.parse();

    getTopProject().setDescription("Top-level multi job to run the manage project: " + getManageProjectName());
    String tmpLabel = getNodeLabel();
    if (tmpLabel == null || tmpLabel.isEmpty()) {
        tmpLabel = "master";
    }
    Label label = new LabelAtom(tmpLabel);
    getTopProject().setAssignedLabel(label);

    // Build actions...
    addSetup(getTopProject());
    // Add multi-job phases
    // Building...
    List<PhaseJobsConfig> phaseJobs = new ArrayList<>();

    projectsAdded = new ArrayList<>();
    projectsNeeded = new ArrayList<>();
    projectsExisting = new ArrayList<>();

    projectsAdded.add(getTopProject().getName());

    String baseName = getBaseName();
    if (getJobName() != null && !getJobName().isEmpty()) {
        baseName = getJobName();
    }
    for (MultiJobDetail detail : manageProject.getJobs()) {
        String name = baseName + "_" + detail.getProjectName();
        projectsNeeded.add(name);
        PhaseJobsConfig phase = null;
        try {
            // Orginal (pre MultiJob 1.30 and possibly earlier), use these
            // parameters
            Constructor ctor = PhaseJobsConfig.class.getConstructor(/*name*/String.class,
                    /*jobproperties*/String.class, /*currParams*/boolean.class, /*configs*/List.class,
                    /*killPhaseOnJobResultCondition*/PhaseJobsConfig.KillPhaseOnJobResultCondition.class,
                    /*disablejob*/boolean.class, /*enableretrystrategy*/boolean.class,
                    /*parsingrulespath*/String.class, /*retries*/int.class, /*enablecondition*/boolean.class,
                    /*abort*/boolean.class, /*condition*/String.class,
                    /*buildonly if scm changes*/boolean.class, /*applycond if no scm changes*/boolean.class);

            phase = (PhaseJobsConfig) ctor.newInstance(name, /*jobproperties*/"", /*currParams*/true,
                    /*configs*/null, PhaseJobsConfig.KillPhaseOnJobResultCondition.NEVER, /*disablejob*/false,
                    /*enableretrystrategy*/false, /*parsingrulespath*/null, /*retries*/0,
                    /*enablecondition*/false, /*abort*/false, /*condition*/"",
                    /*buildonly if scm changes*/false, /*applycond if no scm changes*/false);
        } catch (NoSuchMethodException ex) {
            try {
                // By MultiJob 1.30 there is a new parameter
                Constructor ctor = PhaseJobsConfig.class.getConstructor(/*jobAlias*/String.class,
                        /*name*/String.class, /*jobproperties*/String.class, /*currParams*/boolean.class,
                        /*configs*/List.class,
                        /*killPhaseOnJobResultCondition*/PhaseJobsConfig.KillPhaseOnJobResultCondition.class,
                        /*disablejob*/boolean.class, /*enableretrystrategy*/boolean.class,
                        /*parsingrulespath*/String.class, /*retries*/int.class,
                        /*enablecondition*/boolean.class, /*abort*/boolean.class, /*condition*/String.class,
                        /*buildonly if scm changes*/boolean.class,
                        /*applycond if no scm changes*/boolean.class);
                phase = (PhaseJobsConfig) ctor.newInstance(name, /*jobAlias*/"", /*jobproperties*/"",
                        /*currParams*/true, /*configs*/null,
                        PhaseJobsConfig.KillPhaseOnJobResultCondition.NEVER, /*disablejob*/false,
                        /*enableretrystrategy*/false, /*parsingrulespath*/null, /*retries*/0,
                        /*enablecondition*/false, /*abort*/false, /*condition*/"",
                        /*buildonly if scm changes*/false, /*applycond if no scm changes*/false);
            } catch (NoSuchMethodException ex1) {
                Logger.getLogger(NewMultiJob.class.getName()).log(Level.SEVERE, null, ex1);
            } catch (SecurityException ex1) {
                Logger.getLogger(NewMultiJob.class.getName()).log(Level.SEVERE, null, ex1);
            } catch (InstantiationException ex1) {
                Logger.getLogger(NewMultiJob.class.getName()).log(Level.SEVERE, null, ex1);
            } catch (IllegalAccessException ex1) {
                Logger.getLogger(NewMultiJob.class.getName()).log(Level.SEVERE, null, ex1);
            } catch (IllegalArgumentException ex1) {
                Logger.getLogger(NewMultiJob.class.getName()).log(Level.SEVERE, null, ex1);
            } catch (InvocationTargetException ex1) {
                Logger.getLogger(NewMultiJob.class.getName()).log(Level.SEVERE, null, ex1);
            }
        } catch (SecurityException ex) {
            Logger.getLogger(NewMultiJob.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(NewMultiJob.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(NewMultiJob.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(NewMultiJob.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvocationTargetException ex) {
            Logger.getLogger(NewMultiJob.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (phaseJobs != null) {
            phaseJobs.add(phase);
        }
    }
    MultiJobBuilder multiJobBuilder = new MultiJobBuilder("Build, Execute and Report", phaseJobs,
            MultiJobBuilder.ContinuationCondition.COMPLETED);
    getTopProject().getBuildersList().add(multiJobBuilder);

    // Copy artifacts per building project
    for (MultiJobDetail detail : manageProject.getJobs()) {
        String name = baseName + "_" + detail.getProjectName();
        String tarFile = "";
        if (isUsingSCM()) {
            tarFile = ", " + getBaseName() + "_" + detail.getProjectName() + "_build.tar";
        }
        CopyArtifact copyArtifact = new CopyArtifact(name);
        copyArtifact.setOptional(true);
        copyArtifact.setFilter(
                "**/*_rebuild*," + "execution/*.html, " + "management/*.html, " + "xml_data/**" + tarFile);
        copyArtifact.setFingerprintArtifacts(false);
        BuildSelector bs = new WorkspaceSelector();
        copyArtifact.setSelector(bs);
        getTopProject().getBuildersList().add(copyArtifact);
    }
    addMultiJobBuildCommand();

    // Post-build actions if doing reporting
    if (getOptionUseReporting()) {
        addArchiveArtifacts(getTopProject());
        addXunit(getTopProject());
        addVCCoverage(getTopProject());
        addGroovyScriptMultiJob();
    }

    getTopProject().save();

    for (MultiJobDetail detail : manageProject.getJobs()) {
        String name = baseName + "_" + detail.getProjectName();
        createProjectPair(name, detail, update);
    }
}

From source file:Controlador.Contr_Evento.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w w  w .j  a v a 2 s. c o 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 {
    /*Se detalla el contenido que tendra el servlet*/
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    /*Se crea una variable para la sesion*/
    HttpSession session = request.getSession(true);

    boolean b;
    try {
        /*Se declaran las variables necesarias*/
        Cls_Evento eve = new Cls_Evento();
        Cls_Mensajeria sms = new Cls_Mensajeria();
        String Codigo = "", Mensaje = "", Nombre = "", Tipo = "", Imagen = "", url, Peti;
        String urlsalidaimg;
        urlsalidaimg = "/media/santiago/Santiago/IMGTE/";
        //urlsalidaimg = "I:\\IMGTE\\";
        String urlimgservidor = this.getServletContext().getRealPath("/Libs/Customs/images/Evento");

        /*FileItemFactory es una interfaz para crear FileItem*/
        FileItemFactory file_factory = new DiskFileItemFactory();

        /*ServletFileUpload esta clase convierte los input file a FileItem*/
        ServletFileUpload servlet_up = new ServletFileUpload(file_factory);
        /*sacando los FileItem del ServletFileUpload en una lista */

        List items = servlet_up.parseRequest(request);
        Iterator it = items.iterator();

        /*Se evalua cada una de las posibles peticiones y los posibles campos que envien*/
        while (it.hasNext()) {
            FileItem item = (FileItem) it.next();
            if (item.isFormField()) {
                //Plain request parameters will come here. 

                String name = item.getFieldName();
                if (name.equals("Creador")) {
                    /*Se guarda el campo en la clase*/
                    eve.setCreador(item.getString());
                } else if (name.equals("Nombre")) {
                    /*Se guarda el campo en la clase*/
                    eve.setNombre(item.getString());
                } else if (name.equals("Codigo")) {
                    /*Se guarda el campo en la clase*/
                    eve.setCodigo(item.getString());
                } else if (name.equals("Rango")) {
                    /*Se guarda el campo en la clase*/
                    eve.setRango(item.getString());
                } else if (name.equals("Rangomaximo")) {
                    /*Se guarda el campo en la clase*/
                    eve.setRangoMaximo(item.getString());
                } else if (name.equals("Fecha")) {
                    /*Se guarda el campo en la clase*/
                    eve.setFecha(item.getString());
                } else if (name.equals("Descripcion")) {
                    /*Se guarda el campo en la clase*/
                    eve.setDescipcion(item.getString());
                } else if (name.equals("Ciudad")) {
                    /*Se guarda el campo en la clase*/
                    eve.setCiudad(item.getString());
                } else if (name.equals("Direccion")) {
                    /*Se guarda el campo en la clase*/
                    eve.setDireccion(item.getString());
                } else if (name.equals("Motivo")) {
                    /*Se guarda el campo en la clase*/
                    eve.setMotivo(item.getString());
                } else if (name.equals("Latitud")) {
                    /*Se guarda el campo en la clase*/
                    eve.setLatitud(item.getString());
                } else if (name.equals("Longitud")) {
                    /*Se guarda el campo en la clase*/
                    eve.setLongitud(item.getString());
                } else if (name.equals("RegistrarEvento")) {
                    /*Se convierte la fecha a date*/
                    if (eve.ConvertirFecha(eve.getFecha())) {
                        /*Se evalua si la fecha tiene dos dias mas a la fecha de hoy*/
                        if (eve.ValidarDosDiasFecha(eve.getFechaDate())) {
                            /*Se evalua si se mando una iamgen*/
                            if (!eve.getImagen().equals("")) {
                                /*Si se envia una imagen obtiene la imagen para eliminarla luego*/
                                File img = new File(eve.getImagen());
                                /*Se ejecuta el metodo de registrar evento, en la clase modelo
                                 con los datos que se encuentran en la clase*/
                                String rangoprecios = eve.getRango() + "-" + eve.getRangoMaximo();
                                b = eve.setRegistrarEvento(eve.getTypeimg(), eve.getNombre(),
                                        eve.getFechaDate(), eve.getDescipcion(), rangoprecios, eve.getCreador(),
                                        eve.getCiudad(), eve.getDireccion(), eve.getLatitud(),
                                        eve.getLongitud());
                                if (b) {
                                    File imagedb = new File(
                                            urlimgservidor + "/" + eve.getCodigo() + eve.getTypeimg());
                                    img.renameTo(imagedb);
                                    /*Se guarda un mensaje mediante las sesiones
                                     y se redirecciona*/
                                    session.setAttribute("Mensaje",
                                            "Se registro el evento satisfactoriamente.");
                                    session.setAttribute("TipoMensaje", "Dio");
                                    response.sendRedirect(
                                            "View/RClasificacionEvento.jsp?CodigoEvento=" + eve.getCodigo());
                                } else {
                                    img.delete();
                                    /*Se guarda un mensaje mediante las sesiones
                                     y se redirecciona*/
                                    session.setAttribute("Mensaje", eve.getMensaje());
                                    session.setAttribute("TipoMensaje", "NODio");
                                    response.sendRedirect("View/RegistrarEvento.jsp");
                                }
                            } else {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje",
                                        "Seleccione una imagen para registrar el evento");
                                session.setAttribute("TipoMensaje", "NODio");
                                response.sendRedirect("View/RegistrarEvento.jsp");
                            }

                        } else {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "No se puede registrar un evento que inicie antes de dos das");
                            session.setAttribute("TipoMensaje", "NODio");
                            response.sendRedirect("View/RegistrarEvento.jsp");
                        }
                    } else {
                        /*Se guarda un mensaje mediante las sesiones
                         y se redirecciona*/
                        session.setAttribute("Mensaje",
                                "Ocurri un problema inesperado con la fecha del evento. Estamos trabajando para solucionar este problema.");
                        session.setAttribute("TipoMensaje", "NODio");
                        response.sendRedirect("View/RegistrarEvento.jsp");
                    }

                } else if (name.equals("DesactivarEvento")) {
                    if (eve.validar_Cancelar_Evento_Un_Dia(eve.getCodigo())) {
                        /*Se ejecuta el metodo de desaprobar evento, en la clase modelo
                         con los datos que se encuentran en la clase*/
                        if (eve.setDesaprobarEvento(eve.getCodigo(), eve.getMotivo())) {
                            String[] Datos = eve.BuscarEventoParaMensaje(eve.getCodigo());
                            if (sms.EnviarMensajeCambioEstadoEvento(Datos, "Desaprobado", eve.getMotivo())) {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje", "Se cancel el evento satisfactoriamente.");
                                session.setAttribute("TipoMensaje", "Dio");
                            } else {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje",
                                        "Se cancel el evento, pero no se logr enviar la notificacin al correo electrnico de la empresa.");
                                session.setAttribute("TipoMensaje", "NODio");
                            }
                        } else {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "Ocurri un error al cancelar el evento. Estamos trabajando para solucionar este problema.");
                            session.setAttribute("TipoMensaje", "NODio");
                        }
                    } else {
                        session.setAttribute("Mensaje",
                                "No se puede cancelar un evento antes de un da de su inicio. Lo lamentamos.");
                        session.setAttribute("TipoMensaje", "NODio");
                    }
                    response.sendRedirect("View/CEventoPendiente.jsp");
                } else if (name.equals("DesactivarEventoAdmin")) {
                    if (eve.validar_Cancelar_Evento_Un_Dia(eve.getCodigo())) {
                        /*Se ejecuta el metodo de desaprobar evento, en la clase modelo
                         con los datos que se encuentran en la clase(administradir)*/
                        if (eve.setDesaprobarEvento(eve.getCodigo(), eve.getMotivo())) {
                            String[] Datos = eve.BuscarEventoParaMensaje(eve.getCodigo());
                            if (sms.EnviarMensajeCambioEstadoEvento(Datos, "Desaprobado", eve.getMotivo())) {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje", "Se desaprob el evento satisfactoriamente.");
                                session.setAttribute("TipoMensaje", "Dio");
                            } else {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje",
                                        "Se desaprob el evento, pero no se logr enviar la notificacin al correo electrnico de la empresa.");
                                session.setAttribute("TipoMensaje", "NODio");
                            }
                        } else {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "Ocurri un error al desaprobar el evento. Estamos trabajando para solucionar este problema.");
                            session.setAttribute("TipoMensaje", "NODio");
                        }
                    } else {
                        session.setAttribute("Mensaje",
                                "No se puede cancelar un evento antes de un da de su inicio. Lo lamentamos.");
                        session.setAttribute("TipoMensaje", "NODio");
                    }
                    response.sendRedirect("View/ConsultaTodosEventos.jsp");
                } else if (name.equals("DesactivarEventoEmpresa")) {
                    if (eve.validar_Cancelar_Evento_Un_Dia(eve.getCodigo())) {
                        /*Se ejecuta el metodo de desaprobar evento, en la clase modelo
                         con los datos que se encuentran en la clase(Empresa)*/
                        if (eve.setCancelarEvento(eve.getCodigo(), eve.getMotivo())) {
                            session.setAttribute("Mensaje", "Se cancel el evento satisfactoriamente.");
                            session.setAttribute("TipoMensaje", "Dio");
                        } else {
                            session.setAttribute("Mensaje",
                                    "Ocurri un error al cancelar el evento. Estamos trabajando para solucionar este problema.");
                            session.setAttribute("TipoMensaje", "NODio");
                        }

                    } else {
                        session.setAttribute("Mensaje",
                                "No se puede cancelar un evento antes de un da de su inicio. Lo lamentamos.");
                        session.setAttribute("TipoMensaje", "NODio");
                    }
                    response.sendRedirect("View/MisEventos.jsp");
                }

            } else {
                if (!item.getName().equals("")) {
                    //uploaded files will come here.
                    FileItem file = item;
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();

                    if (sizeInBytes > 1000000) {
                        /*Se muestra un mensaje en caso de pesar mas de 3 MB*/
                        session.setAttribute("Mensaje", "El tamao lmite de la imagen es: 1 MB");
                        session.setAttribute("TipoMensaje", "NODio");
                        /*Se redirecciona*/
                        response.sendRedirect("View/ConsultaSeleccion.jsp");
                    } else {
                        if (contentType.indexOf("jpeg") > 0 || contentType.indexOf("png") > 0) {
                            if (contentType.indexOf("jpeg") > 0) {
                                contentType = ".jpg";
                            } else {
                                contentType = ".png";
                            }
                            /*Se crea la imagne*/
                            File archivo_server = new File(urlimgservidor + "/" + item.getName());
                            /*Se guardael url de la imagen en la clase*/
                            eve.setImagen(urlimgservidor + "/" + item.getName());
                            eve.setTypeimg(contentType);
                            /*Se guarda la imagen*/
                            item.write(archivo_server);
                        } else {
                            session.setAttribute("Mensaje", "Solo se pueden registrar imagenes JPG o PNG");
                            session.setAttribute("TipoMensaje", "NODio");
                        }
                    }
                } else {
                    /**
                     * Se guardael url de la imagen en la clase
                     */
                    eve.setImagen("");
                }
            }
        }

        response.sendRedirect("View/index.jsp");
    } catch (FileUploadException ex) {
        System.out.print(ex.getMessage().toString());

    } catch (Exception ex) {
        Logger.getLogger(Contr_Seleccion.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.nartex.RichFileManager.java

@Override
public JSONObject add() {
    JSONObject fileInfo = new JSONObject();
    Iterator<FileItem> it = this.files.iterator();
    String mode = "";
    String currentPath = "";
    boolean error = false;
    long size = 0;
    if (!it.hasNext()) {
        fileInfo = this.uploadError(lang("INVALID_FILE_UPLOAD"));
    } else {//  ww  w .j  a v a2  s.  c  om
        String allowed[] = { ".", "-" };
        String fileName = "";
        FileItem targetItem = null;
        try {
            while (it.hasNext()) {
                FileItem item = it.next();
                if (item.isFormField()) {
                    if (item.getFieldName().equals("mode")) {
                        mode = item.getString();
                        // v1.0.6 renamed mode add to upload
                        if (!mode.equals("upload") && !mode.equals("add") && !mode.equals("replace")) {
                            //this.error(lang("INVALID_FILE_UPLOAD"));
                        }
                    } else if (item.getFieldName().equals("currentpath")) {
                        currentPath = item.getString();
                    } else if (item.getFieldName().equals("newfilepath")) {
                        currentPath = item.getString();
                    }
                } else if (item.getFieldName().equals("files")) { // replace
                    //replace= true;
                    size = item.getSize();
                    targetItem = item;
                    // v1.0.6 renamed mode add to upload
                    if (mode.equals("add") || mode.equals("upload")) {
                        fileName = item.getName();
                        // set fileName
                    }
                } else if (item.getFieldName().equals("newfile")) {
                    fileName = item.getName();
                    // strip possible directory (IE)
                    int pos = fileName.lastIndexOf(File.separator);
                    if (pos > 0) {
                        fileName = fileName.substring(pos + 1);
                    }
                    size = item.getSize();
                    targetItem = item;
                }
            }
            if (!error) {
                if (mode.equals("replace")) {
                    String tmp[] = currentPath.split("/");
                    fileName = tmp[tmp.length - 1];
                    int pos = fileName.lastIndexOf(File.separator);
                    if (pos > 0)
                        fileName = fileName.substring(pos + 1);
                    if (fileName != null) {
                        currentPath = currentPath.replace(fileName, "");
                        currentPath = currentPath.replace("//", "/");
                    }
                } else {
                    if (!isImage(fileName) && (config.getProperty("upload-imagesonly") != null
                            && config.getProperty("upload-imagesonly").equals("true")
                            || this.params.get("type") != null && this.params.get("type").equals("Image"))) {
                        fileInfo = this.uploadError(lang("UPLOAD_IMAGES_ONLY"));
                        error = true;
                    }
                    LinkedHashMap<String, String> strList = new LinkedHashMap<String, String>();
                    strList.put("fileName", fileName);
                    fileName = cleanString(strList, allowed).get("fileName");
                }
                long maxSize = 0;
                if (config.getProperty("upload-size") != null) {
                    maxSize = Integer.parseInt(config.getProperty("upload-size"));
                    if (maxSize != 0 && size > (maxSize * 1024 * 1024)) {
                        fileInfo = this.uploadError(sprintf(lang("UPLOAD_FILES_SMALLER_THAN"), maxSize + "Mb"));
                        error = true;
                    }
                }
                if (!error) {
                    currentPath = cleanPreview(currentPath.replaceFirst("^/", ""));// relative
                    Path path = currentPath.equals("") ? this.documentRoot
                            : this.documentRoot.resolve(currentPath);
                    if (config.getProperty("upload-overwrite").toLowerCase().equals("false")) {
                        fileName = this.checkFilename(path.toString(), fileName, 0);
                    }
                    if (mode.equals("replace")) {
                        File saveTo = path.resolve(fileName).toFile();
                        targetItem.write(saveTo);
                        log.info("saved " + saveTo);
                    } else {
                        fileName = fileName.replace("//", "/").replaceFirst("^/", "");// relative
                        File saveTo = path.resolve(fileName).toFile();
                        targetItem.write(saveTo);
                        log.info("saved " + saveTo);
                    }
                    fileInfo.put("Path", getPreviewFolder() + currentPath);
                    fileInfo.put("Name", fileName);
                    fileInfo.put("Error", "");
                    fileInfo.put("Code", 0);
                }
            }
        } catch (Exception e) {
            fileInfo = this.uploadError(lang("INVALID_FILE_UPLOAD"));
        }
    }
    return fileInfo;
}