Process a PROPPATCH WebDAV request for the specified resource.<p>

Not implemented yet.<p>

@param req the servlet request we are processing
@param resp the servlet response we are creating
353097
protected void doProppatch(HttpServletRequest req, HttpServletResponse resp) {

        // Check if Webdav is read only
        if (m_readOnly) {

            resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_WEBDAV_READ_ONLY_0));
            }

            return;
        }

        // Check if resource is locked
        if (isLocked(req)) {

            resp.setStatus(CmsWebdavStatus.SC_LOCKED);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_LOCKED_1, getRelativePath(req)));
            }

            return;
        }

        resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
    }
28835
protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response) {
        parseRequest(request,
                     response);
        if (profile == null) {
            profile = _profileService.findProfile(request,
                                                  "jbpm");
        }
        Repository repository = profile.getRepository();
        if (!initialized) {
            try {
                initializeDefaultRepo(profile,
                                      repository,
                                      request);
                initialized = true;
            } catch (Exception e) {
                logger.error("Unable to initialize repository: " + e.getMessage());
            }
        }
        JSONObject returnJson = new JSONObject();
        try {
            Iterator<String> keys = requestParams.keySet().iterator();
            while (keys.hasNext()) {
                String key = keys.next();
            }

            String cmd = (String) requestParams.get("cmd");
            if (cmd != null && cmd.equals("open")) {
                OpenCommand command = new OpenCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("mkdir")) {
                MakeDirCommand command = new MakeDirCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("mkfile")) {
                MakeFileCommand command = new MakeFileCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("rm")) {
                RemoveAssetCommand command = new RemoveAssetCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("rename")) {
                RenameCommand command = new RenameCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("paste")) {
                PasteCommand command = new PasteCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("upload")) {
                UploadCommand command = new UploadCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams,
                             listFiles,
                             listFileStreams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("getsvg")) {
                try {
                    Asset asset = profile.getRepository().loadAssetFromPath((String) requestParams.get("current"));
                    if (asset != null && asset.getAssetContent() != null) {
                        outputPlain(response,
                                    false,
                                    (String) asset.getAssetContent(),
                                    "image/svg+xml");
                    } else {
                        outputPlain(response,
                                    true,
                                    "<p><b>Process image not available.</p><p>You can generate the process image in the process editor.</b></p>",
                                    null);
                    }
                } catch (NoSuchFileException e) {
                    logger.warn("Error loading process image: " + e.getMessage());
                    outputPlain(response,
                                true,
                                "<p><b>Could not find process image.</p><p>You can generate the process image in the process editor.</b></p>",
                                null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            putResponse(returnJson,
                        "error",
                        e.getMessage());

            // output the error
            try {
                output(response,
                       false,
                       returnJson);
            } catch (Exception ee) {
                logger.error("",
                             ee);
            }
        }
    }
784621
@RequirePOST
    public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
        checkPermission(ADMINISTER);

        BulkChange bc = new BulkChange(this);
        try {
            JSONObject json = req.getSubmittedForm();

            ExtensionList.lookupSingleton(MasterBuildConfiguration.class).configure(req,json);

            getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
        } finally {
            bc.commit();
        }

        updateComputerList();

        rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl());  // back to the computer page
    }
265263
@SuppressWarnings({"UnusedDeclaration"})
    public void doIndex(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {
        req.getView(this, chooseAction()).forward(req, resp);
    }
894502
def process_request(self, req, resp):
        

        key = req.env['REMOTE_PORT'] + req.env['REMOTE_ADDR']
        val = self.cache.get(key, 0)

        if val == self.count:
            abort(exceptions.TooManyRequests(headers=self._error_headers))
        else:
            self.cache[key] = val + 1
510859
def process_request(self, req, resp):  # pylint: disable=unused-argument
        

        if req.path in (self.revoke_endpoint, self.token_endpoint):
            return

        try:
            token = self._get_token(req)
            self.auth_token(token)
        except (AuthRequired, InvalidAuthSyntax) as exc:
            if not self.optional:
                abort(exc)
        except AuthRejected as exc:
            if not self.optional:
                exc.headers = self._get_invalid_token_headers(exc.detail)
                abort(exc)
1075991
public void doProcess(BasicServlet servlet, HttpServletRequest req, HttpServletResponse res, PrintWriter out) 
        throws ServletException, IOException
    {
        Map<String,Object> propRequest = this.getRequestProperties(req, true);
        String strBaseURL = (String)propRequest.get(DBParams.BASE_URL);
        if (strBaseURL != null)
        {
            if (strBaseURL.endsWith(AJAX))
                strBaseURL = strBaseURL.substring(0, strBaseURL.length() - AJAX.length());
            propRequest.put(DBParams.BASE_URL, strBaseURL);
        }
        String strCodeBase = this.getRealPath(req, DBConstants.BLANK);
        if ((strCodeBase != null) && (strCodeBase.length() > 0))
        {
            if (!strCodeBase.endsWith(System.getProperty("file.separator")))
                strCodeBase = strCodeBase + System.getProperty("file.separator");
            if (strCodeBase != null)
                propRequest.put(Params.CODEBASE, strCodeBase);
        }

        servlet.setContentType(res);
        InputStream in = null;  // Not used for the default.
        if (out == null)
            out = servlet.getOutputStream(res);

        String strTarget = (String)propRequest.get(TARGET);
        if (strTarget == null)
        {   // Application method
            String strCommand = (String)propRequest.get(REMOTE_COMMAND);
            if (CREATE_REMOTE_TASK.equals(strCommand))
            {
            	Map<String, Object> taskProperties = this.getProperties();
                if (taskProperties != null)
                    propRequest.putAll(taskProperties);
                Map<String,Object> properties = this.getNextPropertiesParam(in, PROPERTIES, propRequest);
                if (properties != null)
                    propRequest.putAll(properties);
                RemoteTask remoteTask = this.getNewRemoteTask(null, propRequest);
                String strUniqueID = this.add(new TaskHolder(this, remoteTask));
                out.write(strUniqueID);
            }
        }
        else 
        {
            try {
                BaseHolder baseHolder = this.getSessionFromPath(strTarget);
                if (baseHolder != null)
                	baseHolder.doProcess(in, out, propRequest);
                else
                {
                    if (ProxyConstants.FREE_REMOTE_SESSION.equals(propRequest.get(REMOTE_COMMAND)))
                        Utility.getLogger().info("Session not found, command: " + propRequest.get(REMOTE_COMMAND)); // Common to free main session first.
                    else
                        Utility.getLogger().warning("Session not found, command: " + propRequest.get(REMOTE_COMMAND));
                }
            } catch (RemoteException ex) {
                try {
                    this.setErrorReturn(out, ex);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    }
1371550
@Override
  protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
      throws ServletException, IOException {

    final boolean noCache = null != req && Boolean.valueOf(req.getParameter(noCacheParamName));

    if (noCache || System.currentTimeMillis() - lastRefreshedTime > cacheTimeInMilliseconds) {
      this.populateStatistics(noCache);
    }

    JSONUtils.toJSON(cachedstats, resp.getOutputStream(), true);
  }
313062
protected void doAction(final HttpServletRequest req, final HttpServletResponse resp, String action) {
        // Read the request.
        ApiRequest srequest;
        try {
            srequest = readRequest(req);
            srequest.setType(action);
        } catch (Exception e) {
            writeError(null, resp, e);
            return;
        }

        final CountDownLatch latch = new CountDownLatch(1);
        final ApiRequest finalRequest = srequest;

        // Now execute the request via the apiman engine
        IApiRequestExecutor executor = getEngine().executor(srequest, new IAsyncResultHandler<IEngineResult>() {
            @Override
            public void handle(IAsyncResult<IEngineResult> asyncResult) {
                if (asyncResult.isSuccess()) {
                    IEngineResult engineResult = asyncResult.getResult();
                    if (engineResult.isResponse()) {
                        try {
                            writeResponse(resp, engineResult.getApiResponse());
                            final ServletOutputStream outputStream = resp.getOutputStream();
                            engineResult.bodyHandler(new IAsyncHandler<IApimanBuffer>() {
                                @Override
                                public void handle(IApimanBuffer chunk) {
                                    try {
                                        if (chunk instanceof ByteBuffer) {
                                            byte [] buffer = (byte []) chunk.getNativeBuffer();
                                            outputStream.write(buffer, 0, chunk.length());
                                        } else {
                                            outputStream.write(chunk.getBytes());
                                        }
                                    } catch (IOException e) {
                                        // This will get caught by the API connector, which will abort the
                                        // connection to the back-end API.
                                        throw new RuntimeException(e);
                                    }
                                }
                            });
                            engineResult.endHandler(new IAsyncHandler<Void>() {
                                @Override
                                public void handle(Void result) {
                                    try {
                                        resp.flushBuffer();
                                    } catch (IOException e) {
                                        // This will get caught by the API connector, which will abort the
                                        // connection to the back-end API.
                                        throw new RuntimeException(e);
                                    } finally {
                                        latch.countDown();
                                    }
                                }
                            });
                        } catch (IOException e) {
                            // this would mean we couldn't get the output stream from the response, so we
                            // need to abort the engine result (which will let the back-end connection
                            // close down).
                            engineResult.abort(e);
                            latch.countDown();
                            throw new RuntimeException(e);
                        }
                    } else {
                        writeFailure(finalRequest, resp, engineResult.getPolicyFailure());
                        latch.countDown();
                    }
                } else {
                    writeError(finalRequest, resp, asyncResult.getError());
                    latch.countDown();
                }
            }
        });
        executor.streamHandler(new IAsyncHandler<ISignalWriteStream>() {
            @Override
            public void handle(ISignalWriteStream connectorStream) {
                try {
                    final InputStream is = req.getInputStream();
                    ByteBuffer buffer = new ByteBuffer(2048);
                    int numBytes = buffer.readFrom(is);
                    while (numBytes != -1) {
                        connectorStream.write(buffer);
                        numBytes = buffer.readFrom(is);
                    }
                    connectorStream.end();
                } catch (Throwable e) {
                    connectorStream.abort(e);
                }
            }
        });
        executor.execute();
        try { latch.await(); } catch (InterruptedException e) { }
    }
1242475
@Override
  protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
      throws ServletException, IOException {
    final Map<String, Object> ret = new HashMap<>();

    if (hasParam(req, ACTION_PARAM)) {
      final String action = getParam(req, ACTION_PARAM);
      if (action.equals(STATS_SET_REPORTINGINTERVAL)) {
        handleChangeMetricInterval(req, ret);
      } else if (action.equals(STATS_SET_CLEANINGINTERVAL)) {
        handleChangeCleaningInterval(req, ret);
      } else if (action.equals(STATS_SET_MAXREPORTERPOINTS)) {
        handleChangeEmitterPoints(req, ret);
      } else if (action.equals(STATS_GET_ALLMETRICSNAME)) {
        handleGetAllMMetricsName(req, ret);
      } else if (action.equals(STATS_GET_METRICHISTORY)) {
        handleGetMetricHistory(req, ret);
      } else if (action.equals(STATS_SET_ENABLEMETRICS)) {
        handleChangeManagerStatusRequest(req, ret, true);
      } else if (action.equals(STATS_SET_DISABLEMETRICS)) {
        handleChangeManagerStatusRequest(req, ret, false);
      } else {
        ret.put(RESPONSE_ERROR, "Invalid action");
      }
    }

    JSONUtils.toJSON(ret, resp.getOutputStream(), true);
  }
1032413
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        // TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active)

        if(req.getUserPrincipal()==null) {
            // authentication must have failed
            rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        // the user is now authenticated, so send him back to the target
        String path = req.getContextPath()+req.getOriginalRestOfPath();
        String q = req.getQueryString();
        if(q!=null)
            path += '?'+q;

        rsp.sendRedirect2(path);
    }
537677
protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String path = getRelativePath(req);

        // Check if Webdav is read only
        if (m_readOnly) {

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_WEBDAV_READ_ONLY_0));
            }

            resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN);
            return;
        }

        // Check if resource is locked
        if (isLocked(req)) {

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_LOCKED_1, path));
            }

            resp.setStatus(CmsWebdavStatus.SC_LOCKED);
            return;
        }

        boolean exists = m_session.exists(path);

        // Can't create a collection if a resource already exists at the given path
        if (exists) {

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_EXISTS_1, path));
            }

            // Get allowed methods
            StringBuffer methodsAllowed = determineMethodsAllowed(getRelativePath(req));
            resp.addHeader(HEADER_ALLOW, methodsAllowed.toString());
            resp.setStatus(CmsWebdavStatus.SC_METHOD_NOT_ALLOWED);
            return;
        }

        if (req.getInputStream().available() > 0) {
            try {
                new SAXReader().read(req.getInputStream());

                // TODO: Process this request body (from Apache Tomcat)
                resp.setStatus(CmsWebdavStatus.SC_NOT_IMPLEMENTED);
                return;

            } catch (DocumentException de) {

                // Parse error - assume invalid content
                resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST);

                if (LOG.isDebugEnabled()) {
                    LOG.debug(Messages.get().getBundle().key(Messages.LOG_INVALID_CONTENT_0));
                }

                return;
            }
        }

        // call session to create collection
        try {

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_CREATE_COLLECTION_0));
            }

            m_session.create(path);
        } catch (CmsVfsResourceAlreadyExistsException raeex) {

            // should never happen, because it was checked if the item exists before
            resp.setStatus(CmsWebdavStatus.SC_PRECONDITION_FAILED);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_EXISTS_1, path));
            }

            return;
        } catch (CmsSecurityException sex) {

            resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_NO_PERMISSION_0));
            }

            return;
        } catch (CmsException ex) {

            resp.setStatus(CmsWebdavStatus.SC_INTERNAL_SERVER_ERROR);

            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_REPOSITORY_ERROR_2, "MKCOL", path), ex);
            }

            return;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_CREATE_SUCCESS_0));
        }

        resp.setStatus(CmsWebdavStatus.SC_CREATED);
    }
470223
private void handlePageRender(final HttpServletRequest req,
      final HttpServletResponse resp, final Session session, final ProjectManager manager) {
    final User user = session.getUser();

    final Page page =
        newPage(req, resp, session, "azkaban/webapp/servlet/velocity/index.vm");

    if (this.lockdownCreateProjects &&
        !UserUtils.hasPermissionforAction(this.userManager, user, Permission.Type.CREATEPROJECTS)) {
      page.add("hideCreateProject", true);
    }

    if (hasParam(req, "all")) {
      final List<Project> projects = manager.getProjects();
      page.add("viewProjects", "all");
      page.add("projects", projects);
    } else if (hasParam(req, "group")) {
      final List<Project> projects = manager.getGroupProjects(user);
      page.add("viewProjects", "group");
      page.add("projects", projects);
    } else {
      final List<Project> projects = manager.getUserProjects(user);
      page.add("viewProjects", "personal");
      page.add("projects", projects);
    }

    page.render();
  }
847319
@Override
	final protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setBufferSize(BUFFER_SIZE);
		postCount.incrementAndGet();
		try {
			reportingDoPost(req, resp);
		} catch (ThreadDeath t) {
			throw t;
		} catch (RuntimeException | ServletException | IOException e) {
			getLogger().log(Level.SEVERE, null, e);
			throw e;
		} catch (SQLException t) {
			getLogger().log(Level.SEVERE, null, t);
			throw new ServletException(t);
		}
	}
1039446
private void doMacLockRequestWorkaround( final ITransaction transaction, final WebdavRequest req, final WebdavResponse resp )
        throws LockFailedException, IOException
    {
        LockedObject lo;
        final int depth = getDepth( req );
        int lockDuration = getTimeout( transaction, req );
        if ( lockDuration < 0 || lockDuration > MAX_TIMEOUT )
        {
            lockDuration = DEFAULT_TIMEOUT;
        }

        boolean lockSuccess = false;
        lockSuccess = _resourceLocks.exclusiveLock( transaction, _path, _lockOwner, depth, lockDuration );

        if ( lockSuccess )
        {
            // Locks successfully placed - return information about
            lo = _resourceLocks.getLockedObjectByPath( transaction, _path );
            if ( lo != null )
            {
                generateXMLReport( transaction, resp, lo );
            }
            else
            {
                resp.sendError( SC_INTERNAL_SERVER_ERROR );
            }
        }
        else
        {
            // Locking was not successful
            sendLockFailError( transaction, req, resp );
        }
    }
602419
@SuppressWarnings({"UnusedDeclaration"})
    protected void doApi(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {
        try {
            log.log(Level.INFO, "Initiating Artifactory Release Staging using API");
            // Enforce release permissions
            project.checkPermission(ArtifactoryPlugin.RELEASE);
            // In case a staging user plugin is configured, the init() method invoke it:
            init();
            // Read the values provided by the staging user plugin and assign them to data members in this class.
            // Those values can be overriden by URL arguments sent with the API:
            readStagingPluginValues();
            // Read values from the request and override the staging plugin values:
            overrideStagingPluginParams(req);
            // Schedule the release build:
            Queue.WaitingItem item = Jenkins.getInstance().getQueue().schedule(
                project, 0,
                new Action[]{this, new CauseAction(new Cause.UserIdCause())}
            );
            if (item == null) {
                log.log(Level.SEVERE, "Failed to schedule a release build following a Release API invocation");
                resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR);
            } else {
                String url = req.getContextPath() + '/' + item.getUrl();
                JSONObject json = new JSONObject();
                json.element("queueItem", item.getId());
                json.element("releaseVersion", getReleaseVersion());
                json.element("nextVersion", getNextVersion());
                json.element("releaseBranch", getReleaseBranch());
                // Must use getOutputStream as sendRedirect uses getOutputStream (and closes it)
                resp.getOutputStream().print(json.toString());
                resp.sendRedirect(201, url);
            }
        } catch (Exception e) {
            log.log(Level.SEVERE, "Artifactory Release Staging API invocation failed: " + e.getMessage(), e);
            resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR);
            ErrorResponse errorResponse = new ErrorResponse(StaplerResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            resp.getWriter().write(mapper.writeValueAsString(errorResponse));
        }
    }
992412
private String validateAndSaveReport(final HttpServletRequest req,
      final HttpServletResponse resp, final Session session) throws ServletException,
      IOException {

    final ProjectManager projectManager = this.server.getProjectManager();
    final User user = session.getUser();

    final Page page =
        newPage(req, resp, session,
            "azkaban/viewer/reportal/reportaleditpage.vm");
    preparePage(page, session);
    page.add("ReportalHelper", ReportalHelper.class);

    final boolean isEdit = hasParam(req, "id");
    if (isEdit) {
      page.add("projectId", getIntParam(req, "id"));
    }

    Project project = null;
    final Reportal report = new Reportal();

    report.title = getParam(req, "title");
    report.description = getParam(req, "description");
    page.add("title", report.title);
    page.add("description", report.description);

    report.schedule = hasParam(req, "schedule");
    report.scheduleHour = getParam(req, "schedule-hour");
    report.scheduleMinute = getParam(req, "schedule-minute");
    report.scheduleAmPm = getParam(req, "schedule-am_pm");
    report.scheduleTimeZone = getParam(req, "schedule-timezone");
    report.scheduleDate = getParam(req, "schedule-date");
    report.scheduleRepeat = hasParam(req, "schedule-repeat");
    report.scheduleIntervalQuantity =
        getParam(req, "schedule-interval-quantity");
    report.scheduleInterval = getParam(req, "schedule-interval");
    report.renderResultsAsHtml = hasParam(req, "render-results-as-html");

    final boolean isEndSchedule = hasParam(req, "end-schedule-date");
    if (isEndSchedule) {
      report.endSchedule = getParam(req, "end-schedule-date");
    }

    page.add("schedule", report.schedule);
    page.add("scheduleHour", report.scheduleHour);
    page.add("scheduleMinute", report.scheduleMinute);
    page.add("scheduleAmPm", report.scheduleAmPm);
    page.add("scheduleTimeZone", report.scheduleTimeZone);
    page.add("scheduleDate", report.scheduleDate);
    page.add("scheduleRepeat", report.scheduleRepeat);
    page.add("scheduleIntervalQuantity", report.scheduleIntervalQuantity);
    page.add("scheduleInterval", report.scheduleInterval);
    page.add("renderResultsAsHtml", report.renderResultsAsHtml);
    page.add("endSchedule", report.endSchedule);
    page.add("max_allowed_schedule_dates", this.max_allowed_schedule_dates);
    page.add("default_schedule_dates", this.default_schedule_dates);

    report.accessViewer = getParam(req, "access-viewer");
    report.accessExecutor = getParam(req, "access-executor");
    report.accessOwner = getParam(req, "access-owner");
    page.add("accessViewer", report.accessViewer);
    page.add("accessExecutor", report.accessExecutor);

    // Adding report creator as explicit owner, if not present already
    if (report.accessOwner == null || report.accessOwner.isEmpty()) {
      report.accessOwner = user.getUserId();
    } else {
      final String[] splittedOwners = report.accessOwner.toLowerCase()
          .split(Reportal.ACCESS_LIST_SPLIT_REGEX);
      if (!Arrays.asList(splittedOwners).contains(user.getUserId())) {
        report.accessOwner = String.format("%s,%s", user.getUserId(),
            StringUtils.join(splittedOwners, ','));
      } else {
        report.accessOwner = StringUtils.join(splittedOwners, ',');
      }
    }

    page.add("accessOwner", report.accessOwner);

    report.notifications = getParam(req, "notifications");
    report.failureNotifications = getParam(req, "failure-notifications");
    page.add("notifications", report.notifications);
    page.add("failureNotifications", report.failureNotifications);

    final int numQueries = getIntParam(req, "queryNumber");
    page.add("queryNumber", numQueries);
    final List<Query> queryList = new ArrayList<>(numQueries);
    page.add("queries", queryList);
    report.queries = queryList;

    final List<String> errors = new ArrayList<>();
    for (int i = 0; i < numQueries; i++) {
      final Query query = new Query();

      query.title = getParam(req, "query" + i + "title");
      query.type = getParam(req, "query" + i + "type");
      query.script = getParam(req, "query" + i + "script");

      // Type check
      final ReportalType type = ReportalType.getTypeByName(query.type);
      if (type == null) {
        errors.add("Type " + query.type + " is invalid.");
      }

      if (!type.checkPermission(user) && report.schedule) {
        errors.add("You do not have permission to schedule Type " + query.type + ".");
      }

      queryList.add(query);
    }

    final int variables = getIntParam(req, "variableNumber");
    page.add("variableNumber", variables);
    final List<Variable> variableList = new ArrayList<>(variables);
    page.add("variables", variableList);
    report.variables = variableList;

    String proxyUser = null;

    for (int i = 0; i < variables; i++) {
      final Variable variable =
          new Variable(getParam(req, "variable" + i + "title"), getParam(req,
              "variable" + i + "name"));

      if (variable.title.isEmpty() || variable.name.isEmpty()) {
        errors.add("Variable title and name cannot be empty.");
      }

      if (variable.title.equals("reportal.config.reportal.execution.user")) {
        proxyUser = variable.name;
      }

      // Validate if the session user (who interact with UI) is part of specified user.to.proxy
      // user. If not, reportal can not be saved and warn users.
      if (variable.title.equals("reportal.config.user.to.proxy")) {
        final String userToProxy = variable.name;
        final UserManager userManager = getApplication().getUserManager();
        if (!userManager.validateProxyUser(userToProxy, user)) {
          errors.add("User " + user.getUserId() + " has no permission to add " + userToProxy
              + " as proxy user.");
        }
      }

      variableList.add(variable);
    }

    // Make sure title isn't empty
    if (report.title.isEmpty()) {
      errors.add("Title must not be empty.");
    }

    // Make sure description isn't empty
    if (report.description.isEmpty()) {
      errors.add("Description must not be empty.");
    }

    // Verify schedule and repeat
    if (report.schedule) {
      // Verify schedule time
      if (!NumberUtils.isDigits(report.scheduleHour)
          || !NumberUtils.isDigits(report.scheduleMinute)) {
        errors.add("Schedule time is invalid.");
      }

      // Verify schedule date is not empty
      if (report.scheduleDate.isEmpty()) {
        errors.add("Schedule date must not be empty.");
      }

      if (report.scheduleRepeat) {
        // Verify repeat interval
        if (!NumberUtils.isDigits(report.scheduleIntervalQuantity)) {
          errors.add("Repeat interval quantity is invalid.");
        }
      }
    }

    // Empty query check
    if (numQueries <= 0) {
      errors.add("There needs to have at least one query.");
    }

    // Validate access users
    final UserManager userManager = getApplication().getUserManager();
    final String[] accessLists =
        new String[]{report.accessViewer, report.accessExecutor,
            report.accessOwner};
    for (String accessList : accessLists) {
      if (accessList == null) {
        continue;
      }

      accessList = accessList.trim();
      if (!accessList.isEmpty()) {
        final String[] users = accessList.split(Reportal.ACCESS_LIST_SPLIT_REGEX);
        for (final String accessUser : users) {
          if (!userManager.validateUser(accessUser)) {
            errors.add("User " + accessUser + " in access list is invalid.");
          }
        }
      }
    }

    // Validate proxy user
    if (proxyUser != null) {
      if (!userManager.validateProxyUser(proxyUser, user)) {
        errors.add("User " + user.getUserId() + " has no permission to add " + proxyUser
            + " as proxy user.");
      }
      proxyUser = null;
    }

    // Validate email addresses
    final Set<String> emails =
        ReportalHelper.parseUniqueEmails(report.notifications + ","
            + report.failureNotifications, Reportal.ACCESS_LIST_SPLIT_REGEX);
    for (final String email : emails) {
      if (!ReportalHelper.isValidEmailAddress(email)) {
        errors.add("Invalid email address: " + email);
        continue;
      }

      final String domain = ReportalHelper.getEmailDomain(email);
      if (this.allowedEmailDomains != null && !this.allowedEmailDomains.contains(domain)) {
        errors.add("Email address '" + email + "' has an invalid domain '"
            + domain + "'. " + "Valid domains are: " + this.allowedEmailDomains);
      }
    }

    if (errors.size() > 0) {
      page.add("errorMsgs", errors);
      page.render();
      return null;
    }

    // Attempt to get a project object
    if (isEdit) {
      // Editing mode, load project
      final int projectId = getIntParam(req, "id");
      project = projectManager.getProject(projectId);
      report.loadImmutableFromProject(project);
    } else {
      // Creation mode, create project
      try {
        project =
            ReportalHelper.createReportalProject(this.server, report.title,
                report.description, user);
        report.reportalUser = user.getUserId();
        report.ownerEmail = user.getEmail();
      } catch (final Exception e) {
        e.printStackTrace();
        errors.add("Error while creating report. " + e.getMessage());
        page.add("errorMsgs", errors);
        page.render();
        return null;
      }

      // Project already exists
      if (project == null) {
        errors.add("A Report with the same name already exists.");
        page.add("errorMsgs", errors);
        page.render();
        return null;
      }
    }

    if (project == null) {
      errors.add("Internal Error: Report not found");
      page.add("errorMsgs", errors);
      page.render();
      return null;
    }

    report.project = project;
    page.add("projectId", project.getId());

    try {
      report.createZipAndUpload(projectManager, user, this.reportalStorageUser);
    } catch (final Exception e) {
      e.printStackTrace();
      errors.add("Error while creating Azkaban jobs. " + e.getMessage());
      page.add("errorMsgs", errors);
      page.render();
      if (!isEdit) {
        try {
          projectManager.removeProject(project, user);
        } catch (final ProjectManagerException e1) {
          e1.printStackTrace();
        }
      }
      return null;
    }

    // Prepare flow
    final Flow flow = project.getFlows().get(0);
    project.getMetadata().put("flowName", flow.getId());

    // Set Reportal mailer
    flow.setMailCreator(ReportalMailCreator.REPORTAL_MAIL_CREATOR);

    // Create/Save schedule
    final ScheduleManager scheduleManager = this.server.getScheduleManager();
    try {
      report.updateSchedules(report, scheduleManager, user, flow);
    } catch (final ScheduleManagerException e) {
      e.printStackTrace();
      errors.add(e.getMessage());
      page.add("errorMsgs", errors);
      page.render();
      return null;
    }

    report.saveToProject(project);

    try {
      ReportalHelper.updateProjectNotifications(project, projectManager);
      projectManager.updateProjectSetting(project);
      projectManager
          .updateProjectDescription(project, report.description, user);
      updateProjectPermissions(project, projectManager, report, user);
      projectManager.updateFlow(project, flow);
    } catch (final ProjectManagerException e) {
      e.printStackTrace();
      errors.add("Error while updating report. " + e.getMessage());
      page.add("errorMsgs", errors);
      page.render();
      if (!isEdit) {
        try {
          projectManager.removeProject(project, user);
        } catch (final ProjectManagerException e1) {
          e1.printStackTrace();
        }
      }
      return null;
    }

    return Integer.toString(project.getId());
  }