Example usage for javax.servlet.http HttpServletRequest getRemoteUser

List of usage examples for javax.servlet.http HttpServletRequest getRemoteUser

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRemoteUser.

Prototype

public String getRemoteUser();

Source Link

Document

Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

Usage

From source file:org.lamsfoundation.lams.admin.web.UserAction.java

public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    initServices();/*w  w w  .ja v a2  s.c  o m*/
    if (UserAction.locales == null) {
        UserAction.locales = service.findAll(SupportedLocale.class);
        Collections.sort(UserAction.locales);
    }
    if (UserAction.authenticationMethods == null) {
        UserAction.authenticationMethods = service.findAll(AuthenticationMethod.class);
    }

    DynaActionForm userForm = (DynaActionForm) form;
    Integer orgId = WebUtil.readIntParam(request, "orgId", true);
    Integer userId = WebUtil.readIntParam(request, "userId", true);

    // Get all the css and flash themes themes
    List<Theme> cssThemes = themeService.getAllCSSThemes();
    request.setAttribute("cssThemes", cssThemes);
    List<Theme> flashThemes = themeService.getAllFlashThemes();
    request.setAttribute("flashThemes", flashThemes);

    // Select the default themes by default
    Theme defaultCSSTheme = themeService.getDefaultCSSTheme();
    for (Theme theme : cssThemes) {
        if (theme.getThemeId().equals(defaultCSSTheme.getThemeId())) {
            userForm.set("userCSSTheme", theme.getThemeId());
            break;
        }
    }
    Theme defaultFlashTheme = themeService.getDefaultFlashTheme();
    for (Theme theme : flashThemes) {
        if (theme.getThemeId().equals(defaultFlashTheme.getThemeId())) {
            userForm.set("userFlashTheme", theme.getThemeId());
            break;
        }
    }

    // test requestor's permission
    Organisation org = null;
    Boolean canEdit = service.isUserGlobalGroupAdmin();
    if (orgId != null) {
        org = (Organisation) service.findById(Organisation.class, orgId);
        if (!canEdit) {
            OrganisationType orgType = org.getOrganisationType();
            Integer orgIdOfCourse = orgType.getOrganisationTypeId().equals(OrganisationType.CLASS_TYPE)
                    ? org.getParentOrganisation().getOrganisationId()
                    : orgId;
            User requestor = service.getUserByLogin(request.getRemoteUser());
            if (service.isUserInRole(requestor.getUserId(), orgIdOfCourse, Role.GROUP_ADMIN)
                    || service.isUserInRole(requestor.getUserId(), orgIdOfCourse, Role.GROUP_MANAGER)) {
                Organisation course = (Organisation) service.findById(Organisation.class, orgIdOfCourse);
                canEdit = course.getCourseAdminCanAddNewUsers();
            }
        }
    }

    if (!(canEdit || request.isUserInRole(Role.SYSADMIN))) {
        request.setAttribute("errorName", "UserAction");
        request.setAttribute("errorMessage", messageService.getMessage("error.authorisation"));
        return mapping.findForward("error");
    }

    // editing a user
    if (userId != null && userId != 0) {
        User user = (User) service.findById(User.class, userId);
        UserAction.log.debug("got userid to edit: " + userId);
        BeanUtils.copyProperties(userForm, user);
        userForm.set("password", null);
        SupportedLocale locale = user.getLocale();
        userForm.set("localeId", locale.getLocaleId());

        AuthenticationMethod authenticationMethod = user.getAuthenticationMethod();
        userForm.set("authenticationMethodId", authenticationMethod.getAuthenticationMethodId());
        // set user's organisations to display
        request.setAttribute("userOrgRoles", getUserOrgRoles(user));
        request.setAttribute("globalRoles", getGlobalRoles(user));

        // Check the user css theme is still installed
        Long userSelectedCSSTheme = null;
        if (user.getHtmlTheme() != null) {
            for (Theme theme : cssThemes) {
                if (theme.getThemeId() == user.getHtmlTheme().getThemeId()) {
                    userSelectedCSSTheme = theme.getThemeId();
                    break;
                }
            }
        }
        // if still null, use the default
        if (userSelectedCSSTheme == null) {
            userSelectedCSSTheme = themeService.getDefaultCSSTheme().getThemeId();
        }
        userForm.set("userCSSTheme", userSelectedCSSTheme);

        // Check the user flash theme is still installed
        Long userSelectedFlashTheme = null;
        if (user.getHtmlTheme() != null) {
            for (Theme theme : flashThemes) {
                if (theme.getThemeId() == user.getFlashTheme().getThemeId()) {
                    userSelectedFlashTheme = theme.getThemeId();
                    break;
                }
            }
        }
        // if still null, use the default
        if (userSelectedFlashTheme == null) {
            userSelectedFlashTheme = themeService.getDefaultFlashTheme().getThemeId();
        }
        userForm.set("userFlashTheme", userSelectedFlashTheme);

    } else { // create a user
        try {
            SupportedLocale locale = LanguageUtil.getDefaultLocale();
            userForm.set("localeId", locale.getLocaleId());
        } catch (Exception e) {
            UserAction.log.debug(e);
        }
    }
    userForm.set("orgId", (org == null ? null : org.getOrganisationId()));

    // Get all available time zones
    List<Timezone> availableTimeZones = timezoneService.getDefaultTimezones();
    TreeSet<TimezoneDTO> timezoneDtos = new TreeSet<TimezoneDTO>(new TimezoneDTOComparator());
    for (Timezone availableTimeZone : availableTimeZones) {
        String timezoneId = availableTimeZone.getTimezoneId();
        TimezoneDTO timezoneDto = new TimezoneDTO();
        timezoneDto.setTimeZoneId(timezoneId);
        timezoneDto.setDisplayName(TimeZone.getTimeZone(timezoneId).getDisplayName());
        timezoneDtos.add(timezoneDto);
    }
    request.setAttribute("timezoneDtos", timezoneDtos);

    // for breadcrumb links
    if (org != null) {
        request.setAttribute("orgName", org.getName());
        Organisation parentOrg = org.getParentOrganisation();
        if (parentOrg != null && !parentOrg.equals(service.getRootOrganisation())) {
            request.setAttribute("pOrgId", parentOrg.getOrganisationId());
            request.setAttribute("parentName", parentOrg.getName());
        }
    }

    request.setAttribute("locales", UserAction.locales);
    request.setAttribute("authenticationMethods", UserAction.authenticationMethods);

    return mapping.findForward("user");
}

From source file:org.apache.catalina.valves.ExtendedAccessLogValve.java

/**
 * Get app specific data./*from  w  w  w  .j  a  v a  2  s  . c  o  m*/
 * @param fieldInfo The field to decode
 * @param request Where we will pull the data from.
 * @return The appropriate value
 */
private String getAppSpecific(FieldInfo fieldInfo, Request request) {

    ServletRequest sr = request.getRequest();
    HttpServletRequest hsr = null;
    if (sr instanceof HttpServletRequest)
        hsr = (HttpServletRequest) sr;

    switch (fieldInfo.xType) {
    case FieldInfo.X_PARAMETER:
        return wrap(urlEncode(sr.getParameter(fieldInfo.value)));
    case FieldInfo.X_REQUEST:
        return wrap(sr.getAttribute(fieldInfo.value));
    case FieldInfo.X_SESSION:
        HttpSession session = null;
        if (hsr != null) {
            session = hsr.getSession(false);
            if (session != null)
                return wrap(session.getAttribute(fieldInfo.value));
        }
        break;
    case FieldInfo.X_COOKIE:
        Cookie[] c = hsr.getCookies();
        for (int i = 0; c != null && i < c.length; i++) {
            if (fieldInfo.value.equals(c[i].getName())) {
                return wrap(c[i].getValue());
            }
        }
    case FieldInfo.X_APP:
        return wrap(request.getContext().getServletContext().getAttribute(fieldInfo.value));
    case FieldInfo.X_SERVLET_REQUEST:
        if (fieldInfo.location == FieldInfo.X_LOC_AUTHTYPE) {
            return wrap(hsr.getAuthType());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REMOTEUSER) {
            return wrap(hsr.getRemoteUser());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONID) {
            return wrap(hsr.getRequestedSessionId());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDFROMCOOKIE) {
            return wrap("" + hsr.isRequestedSessionIdFromCookie());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDVALID) {
            return wrap("" + hsr.isRequestedSessionIdValid());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CONTENTLENGTH) {
            return wrap("" + hsr.getContentLength());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CHARACTERENCODING) {
            return wrap(hsr.getCharacterEncoding());
        } else if (fieldInfo.location == FieldInfo.X_LOC_LOCALE) {
            return wrap(hsr.getLocale());
        } else if (fieldInfo.location == FieldInfo.X_LOC_PROTOCOL) {
            return wrap(hsr.getProtocol());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SCHEME) {
            return wrap(hsr.getScheme());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SECURE) {
            return wrap("" + hsr.isSecure());
        }
        break;
    default:
        ;
    }

    return "-";

}

From source file:org.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java

protected void buildRequestInfo(StringBuilder sb, HttpServletRequest request, HttpServletResponse response,
        boolean showResponse) {
    sb.append("Request class=" + request.getClass().getName());
    sb.append(", RequestedSessionId=").append(request.getRequestedSessionId());

    sb.append(LF).append(IND);/*from ww w.  ja v a  2  s  . c o m*/
    sb.append(", REQUEST_URI=").append(request.getRequestURI());
    sb.append(", SERVLET_PATH=").append(request.getServletPath());
    sb.append(", CharacterEncoding=" + request.getCharacterEncoding());
    sb.append(", ContentLength=").append(request.getContentLength());

    sb.append(LF).append(IND);
    sb.append(", ContentType=").append(request.getContentType());
    sb.append(", Locale=").append(request.getLocale());
    sb.append(", Locales=");
    final Enumeration<?> locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        final Locale locale = (Locale) locales.nextElement();
        if (first) {
            first = false;
        } else {
            sb.append(", ");
        }
        sb.append(locale.toString());
    }
    sb.append(", Scheme=").append(request.getScheme());
    sb.append(", isSecure=").append(request.isSecure());

    sb.append(LF).append(IND);
    sb.append(", SERVER_PROTOCOL=").append(request.getProtocol());
    sb.append(", REMOTE_ADDR=").append(request.getRemoteAddr());
    sb.append(", REMOTE_HOST=").append(request.getRemoteHost());
    sb.append(", SERVER_NAME=").append(request.getServerName());
    sb.append(", SERVER_PORT=").append(request.getServerPort());

    sb.append(LF).append(IND);
    sb.append(", ContextPath=").append(request.getContextPath());
    sb.append(", REQUEST_METHOD=").append(request.getMethod());
    sb.append(", PathInfo=").append(request.getPathInfo());
    sb.append(", RemoteUser=").append(request.getRemoteUser());

    sb.append(LF).append(IND);
    sb.append(", REQUEST_URL=").append(request.getRequestURL());
    sb.append(LF).append(IND);
    sb.append(", QUERY_STRING=").append(request.getQueryString());
    if (showResponse) {
        sb.append(LF).append(IND);
        buildResponseInfo(sb, request, response);
    }

    sb.append(LF);
    buildRequestHeaders(sb, request);
    buildRequestParameters(sb, request);
    buildCookies(sb, request);
    buildRequestAttributes(sb, request);
    buildSessionAttributes(sb, request);
}

From source file:org.eclipse.lyo.samples.sharepoint.adapter.ResourceService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("entered do Post for /resource");
    boolean isFileUpload = ServletFileUpload.isMultipartContent(request);
    String contentType = request.getContentType();

    if (!isFileUpload && !IConstants.CT_RDF_XML.equals(contentType)) {
        throw new ShareServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
    }//w  w  w .java 2 s.c  o  m

    InputStream content = request.getInputStream();

    if (isFileUpload) {
        // being uploaded from a web page
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);

            // find the first (and only) file resource in the post
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    // this is a form field, maybe we can accept a title or descr?
                } else {
                    content = item.getInputStream();
                    contentType = item.getContentType();
                }
            }

        } catch (Exception e) {
            throw new ShareServiceException(e);
        }
    }

    ShareStore store = this.getStore();
    if (ShareStore.rdfFormatFromContentType(contentType) != null) {
        try {
            String resUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            SharepointResource resource = new SharepointResource(resUri);
            List<ShareStatement> statements = store.parse(resUri, content, contentType);
            resource.addStatements(statements);
            String userUri = getUserUri(request.getRemoteUser());

            // if it parsed, then add it to the store.
            store.update(resource, userUri);

            // now get it back, to find 
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (ShareServerException e) {
            throw new ShareServiceException(IConstants.SC_BAD, e);
        }
    } else if (IAmConstants.CT_APP_X_VND_MSPPT.equals(contentType) || isFileUpload) {
        try {

            ByteArrayInputStream bais = isToBais(content);

            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            SharepointResource resource = new SharepointResource(uri);
            resource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
            resource.addRdfType(IAmConstants.RIO_AM_PPT_DECK);
            String id = resource.getIdentifier();
            String deckTitle = "PPT Deck " + id;
            resource.setTitle(deckTitle);
            resource.setDescription("A Power Point Deck");
            String sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());

            store.storeBinaryResource(bais, id);
            bais.reset();

            SlideShow ppt = new SlideShow(bais);
            Dimension pgsize = ppt.getPageSize();

            Slide[] slide = ppt.getSlides();
            for (int i = 0; i < slide.length; i++) {
                String slideTitle = extractTitle(slide[i]);
                String slideUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
                SharepointResource slideResource = new SharepointResource(slideUri);
                slideResource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
                slideResource.addRdfType(IAmConstants.RIO_AM_PPT_SLIDE);
                String slideId = slideResource.getIdentifier();
                slideResource.setTitle(slideTitle);
                sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + slideId;
                slideResource.setSource(sourceUri);
                slideResource.setSourceContentType(IConstants.CT_IMAGE_PNG);
                store.update(slideResource, userUri);

                BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                slide[i].draw(graphics);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                javax.imageio.ImageIO.write(img, "png", out);
                ByteArrayInputStream is = new ByteArrayInputStream(out.toByteArray());
                store.storeBinaryResource(is, slideId);
                out.close();
                is.close();
                try {
                    ShareValue v = new ShareValue(ShareValueType.URI, slideResource.getUri());
                    resource.appendToSeq(IConstants.SHARE_NAMESPACE + "slides", v);
                } catch (UnrecognizedValueTypeException e) {
                    // log this?  don't want to throw away everything, since this should never happen
                }
            }

            store.update(resource, userUri);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (ShareServerException e) {
            throw new ShareServiceException(IConstants.SC_BAD, e);
        }

    } else {
        // must be a binary or unknown format, treat as black box
        // normally a service provider will understand this and parse it appropriately
        // however this server will accept any blank box resource

        try {
            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            SharepointResource resource = new SharepointResource(uri);
            String id = resource.getIdentifier();
            resource.setTitle("Resource " + id);
            resource.setDescription("A binary resource");
            String sourceUri = getBaseUrl() + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());
            store.update(resource, userUri);

            store.storeBinaryResource(content, id);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (ShareServerException e) {
            throw new ShareServiceException(IConstants.SC_BAD, e);
        }
    }
}

From source file:edu.wisc.my.redirect.TabSelectingUrlRedirectController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    final String serverName = request.getServerName();
    final PortalUrl portalUrl = this.portalUrlProvider.getPortalUrl(serverName);

    //If strict param matching only run if the request parameter keyset matches the mapped parameter keyset
    final Set<?> requestParameterKeys = request.getParameterMap().keySet();
    if (this.strictParameterMatching && !requestParameterKeys.equals(this.parameterMappings.keySet())) {
        if (this.logger.isInfoEnabled()) {
            this.logger.info("Sending not found error, requested parameter key set " + requestParameterKeys
                    + " does not match mapped parameter key set " + this.parameterMappings.keySet());
        }/*from w ww. j  a  va  2s. c  o m*/

        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    //Map static parameters
    for (final Map.Entry<String, List<String>> parameterMappingEntry : this.staticParameters.entrySet()) {
        final String name = parameterMappingEntry.getKey();
        final List<String> values = parameterMappingEntry.getValue();

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Adding static parameter '" + name + "' with values: " + values);
        }

        portalUrl.setParameter(name, values.toArray(new String[values.size()]));
    }

    //Map request parameters
    for (final Map.Entry<String, Set<String>> parameterMappingEntry : this.parameterMappings.entrySet()) {
        final String name = parameterMappingEntry.getKey();
        final String[] values = request.getParameterValues(name);

        if (values != null) {
            for (final String mappedName : parameterMappingEntry.getValue()) {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Mapping parameter '" + name + "' to portal parameter '" + mappedName
                            + "' with values: " + Arrays.asList(values));
                }

                portalUrl.setParameter(mappedName, values);
            }
        } else if (this.logger.isDebugEnabled()) {
            this.logger.debug(
                    "Skipping mapped parameter '" + name + "' since it was not specified on the original URL");
        }
    }

    //Set public based on if remoteUser is set
    final String remoteUser = request.getRemoteUser();
    final boolean isAuthenticated = StringUtils.isNotBlank(remoteUser);
    portalUrl.setPublic(!isAuthenticated);

    if (isAuthenticated) {
        portalUrl.setTabIndex(this.privateTabIndex);
    } else {
        portalUrl.setTabIndex(this.publicTabIndex);
    }

    portalUrl.setType(RequestType.ACTION);

    final String redirectUrl = portalUrl.toString();
    if (this.logger.isInfoEnabled()) {
        this.logger.info("Redirecting to: " + redirectUrl);
    }

    return new ModelAndView(new RedirectView(redirectUrl, false));
}

From source file:org.ambraproject.wombat.controller.SearchController.java

/**
 * Set defaults and performs search for subject area landing page
 *
 * @param request HTTP request for browsing subject areas
 * @param model   model that will be passed to the template
 * @param site    site the request originates from
 * @param params  HTTP request params/*from w  ww.ja  v a 2  s.  co m*/
 * @param subject the subject area to be search; return all articles if no subject area is provided
 * @throws IOException
 */
private void subjectAreaSearch(HttpServletRequest request, Model model, Site site,
        MultiValueMap<String, String> params, String subject) throws IOException {

    TaxonomyGraph taxonomyGraph = modelSubjectHierarchy(model, site, subject);

    String subjectName;
    if (Strings.isNullOrEmpty(subject)) {
        params.add("subject", "");
        subjectName = "All Subject Areas";
    } else {
        subject = subject.replace("_", " ");
        params.add("subject", subject);
        subjectName = taxonomyGraph.getName(subject);
    }
    model.addAttribute("subjectName", subjectName);

    // set defaults for subject area landing page
    if (isNullOrEmpty(params.get("resultsPerPage"))) {
        params.add("resultsPerPage", BROWSE_RESULTS_PER_PAGE);
    }

    if (isNullOrEmpty(params.get("sortOrder"))) {
        params.add("sortOrder", "DATE_NEWEST_FIRST");
    }

    if (isNullOrEmpty(params.get("filterJournals"))) {
        params.add("filterJournals", site.getJournalKey());
    }

    CommonParams commonParams = modelCommonParams(request, model, site, params, false);
    ArticleSearchQuery.Builder query = ArticleSearchQuery.builder().setQuery("").setSimple(false);
    commonParams.fill(query);

    ArticleSearchQuery queryObj = query.build();
    Map<String, ?> searchResults = solrSearchApi.search(queryObj, site);

    model.addAttribute("articles", SolrArticleAdapter.unpackSolrQuery(searchResults));
    model.addAttribute("searchResults", solrSearchApi.addArticleLinks(searchResults, request, site, siteSet));
    model.addAttribute("page", commonParams.getSingleParam(params, "page", "1"));
    model.addAttribute("journalKey", site.getKey());
    model.addAttribute("isBrowse", true);

    String authId = request.getRemoteUser();
    boolean subscribed = false;
    if (authId != null) {
        String subjectParam = Strings.isNullOrEmpty(subject) ? "" : subjectName;
        subscribed = alertService.isUserSubscribed(authId, site.getJournalKey(), subjectParam);
    }
    model.addAttribute("subscribed", subscribed);
}

From source file:org.nema.medical.mint.server.controller.JobsController.java

@RequestMapping(method = RequestMethod.POST, value = "/jobs/updatestudy")
public void updateStudy(HttpServletRequest req, HttpServletResponse res) throws IOException {

    String jobID = UUID.randomUUID().toString();
    File jobFolder = new File(jobTemp, jobID);
    jobFolder.mkdirs();/*from  w  ww  . j a  v a2  s .  com*/

    // the list of files uploaded
    List<File> files = new ArrayList<File>();

    // the set of form parameters
    Map<String, String> params = new HashMap<String, String>();

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "expected multipart form data");
        return;
    }

    try {
        handleUpload(req, jobFolder, files, params);
    } catch (FileUploadException e) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "unable to parse multipart form data");
        return;
    }

    if (files.size() < 1) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "at least one file (containing metadata) is required.");
        return;
    }

    if (!params.containsKey(HttpMessagePart.STUDY_UUID.toString())) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing parameter " + HttpMessagePart.STUDY_UUID);
        return;
    }

    final String studyUUID = params.get(HttpMessagePart.STUDY_UUID.toString());

    final Utils.StudyStatus studyStatus = Utils.validateStudyStatus(studiesRoot, studyUUID, res, studyDAO);
    if (studyStatus != Utils.StudyStatus.OK) {
        return;
    }

    if (!params.containsKey(HttpMessagePart.OLD_VERSION.toString())) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing parameter " + HttpMessagePart.OLD_VERSION);
        return;
    }

    final String oldVersionString = params.get(HttpMessagePart.OLD_VERSION.toString());
    final int oldVersion = StringUtils.isBlank(oldVersionString) ? -1 : Integer.parseInt(oldVersionString);

    JobInfo jobInfo = new JobInfo();
    jobInfo.setId(jobID);
    jobInfo.setStudyID(studyUUID);
    jobInfo.setStatus(JobStatus.IN_PROGRESS);
    jobInfo.setStatusDescription("0% complete");
    String jobURI = req.getContextPath() + "/jobs/status/" + jobInfo.getId();
    jobInfoDAO.saveOrUpdateJobInfo(jobInfo);

    File studyFolder = new File(studiesRoot, studyUUID);

    final StudyUpdateProcessor processor = new StudyUpdateProcessor(jobFolder, studyFolder, availableTypes,
            oldVersion, req.getRemoteUser(), req.getRemoteHost(), jobInfoDAO, studyDAO, updateDAO);
    executor.execute(processor); // process immediately in the background

    res.setStatus(HttpServletResponse.SC_SEE_OTHER);
    res.setHeader("Location", jobURI);

}

From source file:org.openecomp.sdcrests.action.rest.services.ActionsImpl.java

public Response updateArtifactInternal(String actionInvariantUuId, String artifactUuId, String artifactName,
        String artifactLabel, String artifactCategory, String artifactDescription, String artifactProtection,
        String checksum, Attachment artifactToUpdate, HttpServletRequest servletRequest) {
    byte[] payload = null;
    Map<String, String> errorMap = validateRequestHeaders(servletRequest);
    //Content-Type Header Validation
    String contentType = servletRequest.getContentType();
    if (StringUtils.isEmpty(contentType)) {
        errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID);
    }//from   www . j  a  v a2 s  .  co  m

    if (artifactToUpdate != null) {
        InputStream artifactInputStream = null;
        try {
            artifactInputStream = artifactToUpdate.getDataHandler().getInputStream();
        } catch (IOException e) {
            throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR);
        }

        payload = FileUtils.toByteArray(artifactInputStream);
        //Validate Artifact size
        if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) {
            throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, ACTION_ARTIFACT_TOO_BIG_ERROR);
        }

        //Validate Checksum
        if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) {
            errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR);
        }
    }

    if (artifactProtection != null && (artifactProtection.isEmpty()
            || (!artifactProtection.equals(ActionArtifactProtection.readOnly.name())
                    && !artifactProtection.equals(ActionArtifactProtection.readWrite.name())))) {
        errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE, ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE);
    }

    ActionArtifact updateArtifact = new ActionArtifact();
    if (errorMap.isEmpty()) {
        String user = servletRequest.getRemoteUser();
        ActionArtifact update = new ActionArtifact();
        update.setArtifactUuId(artifactUuId);
        update.setArtifactName(artifactName);
        update.setArtifactLabel(artifactLabel);
        update.setArtifactDescription(artifactDescription);
        update.setArtifact(payload);
        update.setArtifactCategory(artifactCategory);
        update.setArtifactProtection(artifactProtection);
        actionManager.updateArtifact(update, actionInvariantUuId, user);
    } else {
        checkAndThrowError(errorMap);
    }
    return Response.ok().build();
    //return Response.status(Response.Status.OK).entity("Artifact successfully updated").build();
}

From source file:org.apache.ranger.rest.ServiceREST.java

@POST
@Path("/policies/apply")
@Produces({ "application/json", "application/xml" })
public RangerPolicy applyPolicy(RangerPolicy policy, @Context HttpServletRequest request) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceREST.applyPolicy(" + policy + ")");
    }/*  w w w . ja  v a 2s  .c  om*/

    RangerPolicy ret = null;

    if (policy != null && StringUtils.isNotBlank(policy.getService())) {
        try {
            // Check if applied policy contains any conditions
            if (ServiceRESTUtil.containsRangerCondition(policy)) {
                LOG.error("Applied policy contains condition(s); not supported:" + policy);
                throw new Exception("Applied policy contains condition(s); not supported:" + policy);
            }

            String user = request.getRemoteUser();
            RangerPolicy existingPolicy = getExactMatchPolicyForResource(policy.getService(),
                    policy.getResources(), StringUtils.isNotBlank(user) ? user : "admin");

            if (existingPolicy == null) {
                ret = createPolicy(policy, null);
            } else {
                ServiceRESTUtil.processApplyPolicy(existingPolicy, policy);

                ret = updatePolicy(existingPolicy);
            }
        } catch (WebApplicationException excp) {
            throw excp;
        } catch (Exception exception) {
            LOG.error("Failed to apply policy:", exception);
            throw restErrorUtil.createRESTException(exception.getMessage());
        }
    } else {
        throw restErrorUtil.createRESTException("Non-existing service specified:");
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== ServiceREST.applyPolicy(" + policy + ") : " + ret);
    }

    return ret;
}

From source file:io.hops.hopsworks.api.jobs.JobService.java

/**
 * Get the job ui for the specified job.
 * This act as a proxy to get the job ui from yarn
 * <p>/*from w ww  .ja v  a 2  s. c o  m*/
 * @param appId
 * @param param
 * @param sc
 * @param req
 * @return
 */
@GET
@Path("/{appId}/prox/{path: .+}")
@Produces(MediaType.WILDCARD)
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
public Response getProxy(@PathParam("appId") final String appId, @PathParam("path") final String param,
        @Context SecurityContext sc, @Context HttpServletRequest req) {

    Response response = checkAccessRight(appId);
    if (response != null) {
        return response;
    }
    try {
        String trackingUrl;
        if (param.matches("http([a-zA-Z,:,/,.,0-9,-])+:([0-9])+(.)+")) {
            trackingUrl = param;
        } else {
            trackingUrl = "http://" + param;
        }
        trackingUrl = trackingUrl.replace("@hwqm", "?");
        if (!hasAppAccessRight(trackingUrl)) {
            LOGGER.log(Level.SEVERE, "A user is trying to access an app outside their project!");
            return Response.status(Response.Status.FORBIDDEN).build();
        }
        org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(trackingUrl, false);

        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);

        final HttpMethod method = new GetMethod(uri.getEscapedURI());
        Enumeration<String> names = req.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = req.getHeader(name);
            if (PASS_THROUGH_HEADERS.contains(name)) {
                //yarn does not send back the js if encoding is not accepted
                //but we don't want to accept encoding for the html because we
                //need to be able to parse it
                if (!name.toLowerCase().equals("accept-encoding") || trackingUrl.contains(".js")) {
                    method.setRequestHeader(name, value);
                }
            }
        }
        String user = req.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(method);
        Response.ResponseBuilder responseBuilder = noCacheResponse
                .getNoCacheResponseBuilder(Response.Status.OK);
        for (Header header : method.getResponseHeaders()) {
            responseBuilder.header(header.getName(), header.getValue());
        }
        //method.getPath().contains("/allexecutors") is needed to replace the links under Executors tab
        //which are in a json response object
        if (method.getResponseHeader("Content-Type") == null
                || method.getResponseHeader("Content-Type").getValue().contains("html")
                || method.getPath().contains("/allexecutors")) {
            final String source = "http://" + method.getURI().getHost() + ":" + method.getURI().getPort();
            if (method.getResponseHeader("Content-Length") == null) {
                responseBuilder.entity(new StreamingOutput() {
                    @Override
                    public void write(OutputStream out) throws IOException, WebApplicationException {
                        Writer writer = new BufferedWriter(new OutputStreamWriter(out));
                        InputStream stream = method.getResponseBodyAsStream();
                        Reader in = new InputStreamReader(stream, "UTF-8");
                        char[] buffer = new char[4 * 1024];
                        String remaining = "";
                        int n;
                        while ((n = in.read(buffer)) != -1) {
                            StringBuilder strb = new StringBuilder();
                            strb.append(buffer, 0, n);
                            String s = remaining + strb.toString();
                            remaining = s.substring(s.lastIndexOf(">") + 1, s.length());
                            s = hopify(s.substring(0, s.lastIndexOf(">") + 1), param, appId, source);
                            writer.write(s);
                        }
                        writer.flush();
                    }
                });
            } else {
                String s = hopify(method.getResponseBodyAsString(), param, appId, source);
                responseBuilder.entity(s);
                responseBuilder.header("Content-Length", s.length());
            }

        } else {
            responseBuilder.entity(new StreamingOutput() {
                @Override
                public void write(OutputStream out) throws IOException, WebApplicationException {
                    InputStream stream = method.getResponseBodyAsStream();
                    org.apache.hadoop.io.IOUtils.copyBytes(stream, out, 4096, true);
                    out.flush();
                }
            });
        }
        return responseBuilder.build();
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "exception while geting job ui " + e.getLocalizedMessage(), e);
        return noCacheResponse.getNoCacheResponseBuilder(Response.Status.NOT_FOUND).build();
    }

}