Java Code Examples for org.springframework.http.MediaType#TEXT_HTML

The following examples show how to use org.springframework.http.MediaType#TEXT_HTML . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AttachmentApiController.java    From onboard with Apache License 2.0 7 votes vote down vote up
private MediaType getContentType(String contentType) {
    if (contentType.equalsIgnoreCase(MediaType.IMAGE_GIF_VALUE)) {
        return MediaType.IMAGE_GIF;
    } else if (contentType.equalsIgnoreCase(MediaType.IMAGE_PNG_VALUE)) {
        return MediaType.IMAGE_PNG;
    } else if (contentType.equalsIgnoreCase(MediaType.IMAGE_JPEG_VALUE)) {
        return MediaType.IMAGE_JPEG;
    } else if (contentType.equalsIgnoreCase(MediaType.TEXT_PLAIN_VALUE)) {
        return MediaType.TEXT_PLAIN;
    } else if (contentType.equalsIgnoreCase(MediaType.TEXT_XML_VALUE)) {
        return MediaType.TEXT_XML;
    } else if (contentType.equalsIgnoreCase(MediaType.TEXT_HTML_VALUE)) {
        return MediaType.TEXT_HTML;
    }
    return MediaType.APPLICATION_OCTET_STREAM;
}
 
Example 2
Source File: ProducesRequestConditionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test // gh-22853
public void matchAndCompare() {
	ContentNegotiationManager manager = new ContentNegotiationManager(
			new HeaderContentNegotiationStrategy(),
			new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));

	ProducesRequestCondition none = new ProducesRequestCondition(new String[0], null, manager);
	ProducesRequestCondition html = new ProducesRequestCondition(new String[] {"text/html"}, null, manager);

	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addHeader("Accept", "*/*");

	ProducesRequestCondition noneMatch = none.getMatchingCondition(request);
	ProducesRequestCondition htmlMatch = html.getMatchingCondition(request);

	assertEquals(1, noneMatch.compareTo(htmlMatch, request));
}
 
Example 3
Source File: AttachmentApi.java    From onboard with Apache License 2.0 6 votes vote down vote up
private MediaType getContentType(String contentType) {
    if (contentType.equalsIgnoreCase(MediaType.IMAGE_GIF_VALUE)) {
        return MediaType.IMAGE_GIF;
    } else if (contentType.equalsIgnoreCase(MediaType.IMAGE_PNG_VALUE)) {
        return MediaType.IMAGE_PNG;
    } else if (contentType.equalsIgnoreCase(MediaType.IMAGE_JPEG_VALUE)) {
        return MediaType.IMAGE_JPEG;
    } else if (contentType.equalsIgnoreCase(MediaType.TEXT_PLAIN_VALUE)) {
        return MediaType.TEXT_PLAIN;
    } else if (contentType.equalsIgnoreCase(MediaType.TEXT_XML_VALUE)) {
        return MediaType.TEXT_XML;
    } else if (contentType.equalsIgnoreCase(MediaType.TEXT_HTML_VALUE)) {
        return MediaType.TEXT_HTML;
    }
    return MediaType.APPLICATION_OCTET_STREAM;
}
 
Example 4
Source File: SpringletsSecurityWebAccessDeniedHandlerImpl.java    From springlets with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
    AccessDeniedException accessDeniedException) throws IOException, ServletException {

  ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy();
  MediaTypeRequestMatcher matcher =
      new MediaTypeRequestMatcher(negotiationStrategy, MediaType.TEXT_HTML);
  matcher.setUseEquals(false);

  if (matcher.matches(request)) {
    DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    redirectStrategy.setContextRelative(false);
    redirectStrategy.sendRedirect(request, response, "/errores/403");
  } else {
    response.sendError(HttpServletResponse.SC_FORBIDDEN);

  }

}
 
Example 5
Source File: SpringletsSecurityWebAuthenticationEntryPoint.java    From springlets with Apache License 2.0 6 votes vote down vote up
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
    AuthenticationException authException) throws IOException, ServletException {

  ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy();
  MediaTypeRequestMatcher matcher =
      new MediaTypeRequestMatcher(negotiationStrategy, MediaType.TEXT_HTML);
  matcher.setUseEquals(false);

  if (matcher.matches(request)) {
    DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    redirectStrategy.setContextRelative(false);
    redirectStrategy.sendRedirect(request, response, LOGIN_FORM_URL);
  } else {
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
  }
}
 
Example 6
Source File: ContentNegotiatingViewResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void nestedViewResolverIsNotSpringBean() throws Exception {
	StaticWebApplicationContext webAppContext = new StaticWebApplicationContext();
	webAppContext.setServletContext(new MockServletContext());
	webAppContext.refresh();

	InternalResourceViewResolver nestedResolver = new InternalResourceViewResolver();
	nestedResolver.setApplicationContext(webAppContext);
	nestedResolver.setViewClass(InternalResourceView.class);
	viewResolver.setViewResolvers(new ArrayList<ViewResolver>(Arrays.asList(nestedResolver)));

	FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(MediaType.TEXT_HTML);
	viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy));

	viewResolver.afterPropertiesSet();

	String viewName = "view";
	Locale locale = Locale.ENGLISH;

	View result = viewResolver.resolveViewName(viewName, locale);
	assertNotNull("Invalid view", result);
}
 
Example 7
Source File: ContentNegotiatingViewResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void nestedViewResolverIsNotSpringBean() throws Exception {
	StaticWebApplicationContext webAppContext = new StaticWebApplicationContext();
	webAppContext.setServletContext(new MockServletContext());
	webAppContext.refresh();

	InternalResourceViewResolver nestedResolver = new InternalResourceViewResolver();
	nestedResolver.setApplicationContext(webAppContext);
	nestedResolver.setViewClass(InternalResourceView.class);
	viewResolver.setViewResolvers(new ArrayList<>(Arrays.asList(nestedResolver)));

	FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(MediaType.TEXT_HTML);
	viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy));

	viewResolver.afterPropertiesSet();

	String viewName = "view";
	Locale locale = Locale.ENGLISH;

	View result = viewResolver.resolveViewName(viewName, locale);
	assertNotNull("Invalid view", result);
}
 
Example 8
Source File: RecipientsReportServiceImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private DownloadRecipientReport getDownloadReportData(ComAdmin admin, String filename, String reportContent) throws UnsupportedEncodingException {
    DownloadRecipientReport recipientReport = new DownloadRecipientReport();
    if (StringUtils.isBlank(reportContent)) {
        reportContent = I18nString.getLocaleString("recipient.reports.notAvailable", admin.getLocale());
        recipientReport.setMediaType(MediaType.TEXT_PLAIN);
        recipientReport.setFilename(FilenameUtils.removeExtension(filename) + RecipientReportUtils.TXT_EXTENSION);
    } else {
        recipientReport.setFilename(RecipientReportUtils.resolveFileName(filename, reportContent));
        MediaType mediaType = MediaType.parseMediaType(mimeTypeService.getMimetypeForFile(filename.toLowerCase()));
        recipientReport.setMediaType(mediaType);
        if (MediaType.TEXT_HTML == mediaType) {
            reportContent = reportContent.replace("\r\n", "\n").replace("\n", "<br />\n");
        }
    }
    
    recipientReport.setContent(reportContent.getBytes("UTF-8"));
    return recipientReport;
}
 
Example 9
Source File: RecipientsReportController.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@GetMapping("/{reportId:\\d+}/view.action")
public String view(ComAdmin admin, @PathVariable int reportId, Model model) {
    String reportContent = recipientsReportService.getImportReportContent(admin.getCompanyID(), reportId);

    if (StringUtils.isBlank(reportContent)) {
        reportContent = I18nString.getLocaleString("recipient.reports.notAvailable", admin.getLocale());
    }
    
    if (RecipientReportUtils.resolveMediaType(reportContent) != MediaType.TEXT_HTML) {
        reportContent = reportContent.replace("\r\n", "\n").replace("\n", "<br />\n");
    }

    model.addAttribute("reportId", reportId);
    // Escape all text, even html, so it can be viewed in an iframe as docsource
    model.addAttribute("reportContentEscaped", StringEscapeUtils.escapeHtml4(reportContent));
    
    writeUserActivityLog(admin, "Import/Export logs view", "Report ID: " + reportId);

    return "recipient_report_view";
}
 
Example 10
Source File: ContentNegotiatingViewResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void nestedViewResolverIsNotSpringBean() throws Exception {
	StaticWebApplicationContext webAppContext = new StaticWebApplicationContext();
	webAppContext.setServletContext(new MockServletContext());
	webAppContext.refresh();

	InternalResourceViewResolver nestedResolver = new InternalResourceViewResolver();
	nestedResolver.setApplicationContext(webAppContext);
	nestedResolver.setViewClass(InternalResourceView.class);
	viewResolver.setViewResolvers(new ArrayList<>(Arrays.asList(nestedResolver)));

	FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(MediaType.TEXT_HTML);
	viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy));

	viewResolver.afterPropertiesSet();

	String viewName = "view";
	Locale locale = Locale.ENGLISH;

	View result = viewResolver.resolveViewName(viewName, locale);
	assertNotNull("Invalid view", result);
}
 
Example 11
Source File: RecipientReportUtils.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public static MediaType resolveMediaType(String reportContent) {
    if (StringUtils.startsWith(reportContent, HTML_TAG) || StringUtils.startsWith(reportContent, DOCTYPE_HTML_TAG)) {
        return MediaType.TEXT_HTML;
    } else {
        return MediaType.TEXT_PLAIN;
    }
}
 
Example 12
Source File: RecipientReportUtils.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String resolveFileName(String filename, String reportContent) {
    String fileNameWithoutExtension = FilenameUtils.removeExtension(filename);
    if (StringUtils.isNotEmpty(fileNameWithoutExtension)) {
        //resolve content type and create proper file name if file name doesn't have extension
        MediaType contentType = resolveMediaType(reportContent);
        
        return fileNameWithoutExtension + (MediaType.TEXT_HTML == contentType ? HTML_EXTENSION : TXT_EXTENSION);
    }
    return filename;
}
 
Example 13
Source File: EncoderHttpMessageWriterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void useHttpOutputMessageMediaType() {

	MediaType outputMessageMediaType = MediaType.TEXT_HTML;
	this.response.getHeaders().setContentType(outputMessageMediaType);

	HttpMessageWriter<String> writer = getWriter(TEXT_PLAIN_UTF_8, TEXT_HTML);
	writer.write(Mono.just("body"), forClass(String.class), TEXT_PLAIN, this.response, NO_HINTS);

	assertEquals(outputMessageMediaType, this.response.getHeaders().getContentType());
	assertEquals(outputMessageMediaType, this.mediaTypeCaptor.getValue());
}
 
Example 14
Source File: OAuth2SecurityConfigUtils.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static void forLogin(
        final ServerHttpSecurity http,
        final AMType amType,
        final ApplicationContext ctx) {

    ReactiveClientRegistrationRepository clientRegistrationRepository =
            ctx.getBean(ReactiveClientRegistrationRepository.class);

    ReactiveOAuth2AuthorizedClientService authorizedClientService =
            new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);
    ServerOAuth2AuthorizedClientRepository authorizedClientRepository =
            new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService);

    OAuth2AuthorizationRequestRedirectWebFilter authRequestRedirectFilter =
            new OAuth2AuthorizationRequestRedirectWebFilter(clientRegistrationRepository);

    AuthenticationWebFilter authenticationFilter =
            new OAuth2LoginAuthenticationWebFilter(authenticationManager(amType), authorizedClientRepository);
    authenticationFilter.setRequiresAuthenticationMatcher(
            new PathPatternParserServerWebExchangeMatcher("/login/oauth2/code/{registrationId}"));
    authenticationFilter.setServerAuthenticationConverter(
            new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(clientRegistrationRepository));
    authenticationFilter.setAuthenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler());
    authenticationFilter.setAuthenticationFailureHandler((exchange, ex) -> Mono.error(ex));
    authenticationFilter.setSecurityContextRepository(new WebSessionServerSecurityContextRepository());

    MediaTypeServerWebExchangeMatcher htmlMatcher = new MediaTypeServerWebExchangeMatcher(MediaType.TEXT_HTML);
    htmlMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
    ServerAuthenticationEntryPoint entrypoint =
            new RedirectServerAuthenticationEntryPoint("/oauth2/authorization/" + amType.name());
    http.exceptionHandling().authenticationEntryPoint(new DelegateEntry(htmlMatcher, entrypoint).getEntryPoint());

    http.addFilterAt(authRequestRedirectFilter, SecurityWebFiltersOrder.HTTP_BASIC);
    http.addFilterAt(authenticationFilter, SecurityWebFiltersOrder.AUTHENTICATION);
}
 
Example 15
Source File: ViewResolutionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testContentNegotiation() throws Exception {

	Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
	marshaller.setClassesToBeBound(Person.class);

	List<View> viewList = new ArrayList<View>();
	viewList.add(new MappingJackson2JsonView());
	viewList.add(new MarshallingView(marshaller));

	ContentNegotiationManager manager = new ContentNegotiationManager(
			new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));

	ContentNegotiatingViewResolver cnViewResolver = new ContentNegotiatingViewResolver();
	cnViewResolver.setDefaultViews(viewList);
	cnViewResolver.setContentNegotiationManager(manager);
	cnViewResolver.afterPropertiesSet();

	MockMvc mockMvc =
		standaloneSetup(new PersonController())
			.setViewResolvers(cnViewResolver, new InternalResourceViewResolver())
			.build();

	mockMvc.perform(get("/person/Corea"))
		.andExpect(status().isOk())
		.andExpect(model().size(1))
		.andExpect(model().attributeExists("person"))
		.andExpect(forwardedUrl("person/show"));

	mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
		.andExpect(status().isOk())
		.andExpect(content().contentType(MediaType.APPLICATION_JSON))
		.andExpect(jsonPath("$.person.name").value("Corea"));

	mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
		.andExpect(status().isOk())
		.andExpect(content().contentType(MediaType.APPLICATION_XML))
		.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
 
Example 16
Source File: MetricsResponse.java    From timely with Apache License 2.0 5 votes vote down vote up
public TextWebSocketFrame toWebSocketResponse(String acceptHeader) throws Exception {
    MediaType negotiatedType = MediaType.TEXT_HTML;
    if (null != acceptHeader) {
        List<MediaType> requestedTypes = MediaType.parseMediaTypes(acceptHeader);
        MediaType.sortBySpecificityAndQuality(requestedTypes);
        LOG.trace("Acceptable response types: {}", MediaType.toString(requestedTypes));
        for (MediaType t : requestedTypes) {
            if (t.includes(MediaType.TEXT_HTML)) {
                negotiatedType = MediaType.TEXT_HTML;
                LOG.trace("{} allows HTML", t.toString());
                break;
            }
            if (t.includes(MediaType.APPLICATION_JSON)) {
                negotiatedType = MediaType.APPLICATION_JSON;
                LOG.trace("{} allows JSON", t.toString());
                break;
            }
        }
    }
    String result = null;
    if (negotiatedType.equals(MediaType.APPLICATION_JSON)) {
        result = this.generateJson(JsonUtil.getObjectMapper());
    } else {
        result = this.generateHtml().toString();
    }
    return new TextWebSocketFrame(result);
}
 
Example 17
Source File: MetricsResponse.java    From timely with Apache License 2.0 5 votes vote down vote up
public FullHttpResponse toHttpResponse(String acceptHeader) throws Exception {
    MediaType negotiatedType = MediaType.TEXT_HTML;
    if (null != acceptHeader) {
        List<MediaType> requestedTypes = MediaType.parseMediaTypes(acceptHeader);
        MediaType.sortBySpecificityAndQuality(requestedTypes);
        LOG.trace("Acceptable response types: {}", MediaType.toString(requestedTypes));
        for (MediaType t : requestedTypes) {
            if (t.includes(MediaType.TEXT_HTML)) {
                negotiatedType = MediaType.TEXT_HTML;
                LOG.trace("{} allows HTML", t.toString());
                break;
            }
            if (t.includes(MediaType.APPLICATION_JSON)) {
                negotiatedType = MediaType.APPLICATION_JSON;
                LOG.trace("{} allows JSON", t.toString());
                break;
            }
        }
    }
    byte[] buf = null;
    Object responseType = Constants.HTML_TYPE;
    if (negotiatedType.equals(MediaType.APPLICATION_JSON)) {
        buf = this.generateJson(JsonUtil.getObjectMapper()).getBytes(StandardCharsets.UTF_8);
        responseType = Constants.JSON_TYPE;
    } else {
        buf = this.generateHtml().toString().getBytes(StandardCharsets.UTF_8);
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer(buf));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, responseType);
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
 
Example 18
Source File: BasicAuthSecurityConfiguration.java    From spring-cloud-dashboard with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	final RequestMatcher textHtmlMatcher = new MediaTypeRequestMatcher(
			contentNegotiationStrategy,
			MediaType.TEXT_HTML);

	final String loginPage = dashboard("/#/login");

	final BasicAuthenticationEntryPoint basicAuthenticationEntryPoint = new BasicAuthenticationEntryPoint();
	basicAuthenticationEntryPoint.setRealmName(securityProperties.getBasic().getRealm());
	basicAuthenticationEntryPoint.afterPropertiesSet();

	http
		.csrf()
		.disable()
		.authorizeRequests()
		.antMatchers("/")
		.authenticated()
		.antMatchers(
				dashboard("/**"),
				"/authenticate",
				"/security/info",
				"/features",
				"/assets/**").permitAll()
	.and()
		.formLogin().loginPage(loginPage)
		.loginProcessingUrl(dashboard("/login"))
		.defaultSuccessUrl(dashboard("/")).permitAll()
	.and()
		.logout().logoutUrl(dashboard("/logout"))
			.logoutSuccessUrl(dashboard("/logout-success.html"))
		.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()).permitAll()
	.and().httpBasic()
		.and().exceptionHandling()
		.defaultAuthenticationEntryPointFor(
				new LoginUrlAuthenticationEntryPoint(loginPage),
				textHtmlMatcher)
		.defaultAuthenticationEntryPointFor(basicAuthenticationEntryPoint,
				AnyRequestMatcher.INSTANCE)
	.and()
		.authorizeRequests()
		.anyRequest().authenticated();

	final SessionRepositoryFilter<ExpiringSession> sessionRepositoryFilter = new SessionRepositoryFilter<ExpiringSession>(
			sessionRepository());
	sessionRepositoryFilter
			.setHttpSessionStrategy(new HeaderHttpSessionStrategy());

	http.addFilterBefore(sessionRepositoryFilter,
			ChannelProcessingFilter.class).csrf().disable();
	http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
}
 
Example 19
Source File: ViewResolutionTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void testContentNegotiation() throws Exception {
	Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
	marshaller.setClassesToBeBound(Person.class);

	List<View> viewList = new ArrayList<>();
	viewList.add(new MappingJackson2JsonView());
	viewList.add(new MarshallingView(marshaller));

	ContentNegotiationManager manager = new ContentNegotiationManager(
			new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));

	ContentNegotiatingViewResolver cnViewResolver = new ContentNegotiatingViewResolver();
	cnViewResolver.setDefaultViews(viewList);
	cnViewResolver.setContentNegotiationManager(manager);
	cnViewResolver.afterPropertiesSet();

	MockMvc mockMvc =
		standaloneSetup(new PersonController())
			.setViewResolvers(cnViewResolver, new InternalResourceViewResolver())
			.build();

	mockMvc.perform(get("/person/Corea"))
		.andExpect(status().isOk())
		.andExpect(model().size(1))
		.andExpect(model().attributeExists("person"))
		.andExpect(forwardedUrl("person/show"));

	mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
		.andExpect(status().isOk())
		.andExpect(content().contentType(MediaType.APPLICATION_JSON))
		.andExpect(jsonPath("$.person.name").value("Corea"));

	mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
		.andExpect(status().isOk())
		.andExpect(content().contentType(MediaType.APPLICATION_XML))
		.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
 
Example 20
Source File: Entity.java    From sinavi-jfw with Apache License 2.0 2 votes vote down vote up
/**
 * ContentTypeがtext/htmlのヘッダとリクエストデータを設定します。
 * @param entity リクエストデータ
 * @param <T> リクエストデータの型
 * @return このユーティリティを返します。
 */
public static <T> Entity<T> html(final T entity) {
    return new Entity<T>(entity, MediaType.TEXT_HTML);
}