repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/model/InternalApiMessage.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/model/InternalApiMessage.java | package com.baeldung.jersey.jackson.model;
import java.time.LocalDate;
import java.util.List;
import com.baeldung.jersey.jackson.annotation.InternalApi;
@InternalApi
public class InternalApiMessage {
public String text;
public LocalDate date;
public String debugInfo;
public List<String> metadata;
public InternalApiMessage(String text, LocalDate date, String debugInfo, List<String> metadata) {
this.text = text;
this.date = date;
this.debugInfo = debugInfo;
this.metadata = metadata;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/annotation/InternalApi.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/annotation/InternalApi.java | package com.baeldung.jersey.jackson.annotation;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface InternalApi {} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/annotation/PublicApi.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/annotation/PublicApi.java | package com.baeldung.jersey.jackson.annotation;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface PublicApi {} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/mapper/ConditionalObjectMapperResolver.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/mapper/ConditionalObjectMapperResolver.java | package com.baeldung.jersey.jackson.mapper;
import com.baeldung.jersey.jackson.annotation.InternalApi;
import com.baeldung.jersey.jackson.annotation.PublicApi;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import jakarta.ws.rs.ext.ContextResolver;
import jakarta.ws.rs.ext.Provider;
@Provider
public class ConditionalObjectMapperResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper publicApiMapper;
private final ObjectMapper internalApiMapper;
private final ObjectMapper defaultMapper;
public ConditionalObjectMapperResolver() {
publicApiMapper = JsonMapper.builder()
.findAndAddModules()
.build();
publicApiMapper.enable(SerializationFeature.INDENT_OUTPUT);
publicApiMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
publicApiMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
publicApiMapper.disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS);
internalApiMapper = JsonMapper.builder()
.findAndAddModules()
.build();
internalApiMapper.enable(SerializationFeature.INDENT_OUTPUT);
internalApiMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
internalApiMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
internalApiMapper.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID);
defaultMapper = JsonMapper.builder()
.findAndAddModules()
.build();
defaultMapper.enable(SerializationFeature.INDENT_OUTPUT);
defaultMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
@Override
public ObjectMapper getContext(Class<?> type) {
if (isPublicApiModel(type)) return publicApiMapper;
else if (isInternalApiModel(type)) return internalApiMapper;
return defaultMapper;
}
private boolean isPublicApiModel(Class<?> type) {
return type.getPackage().getName().contains("public.api") ||
type.isAnnotationPresent(PublicApi.class);
}
private boolean isInternalApiModel(Class<?> type) {
return type.getPackage().getName().contains("internal.api") ||
type.isAnnotationPresent(InternalApi.class);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/mapper/ObjectMapperContextResolver.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/mapper/ObjectMapperContextResolver.java | package com.baeldung.jersey.jackson.mapper;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import jakarta.ws.rs.ext.ContextResolver;
import jakarta.ws.rs.ext.Provider;
@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
mapper = JsonMapper.builder()
.findAndAddModules()
.build();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/timeout/server/TimeoutAppConfig.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/timeout/server/TimeoutAppConfig.java | package com.baeldung.jersey.timeout.server;
import org.glassfish.jersey.server.ResourceConfig;
public class TimeoutAppConfig extends ResourceConfig {
public TimeoutAppConfig() {
packages(JerseyTimeoutServerApp.class.getPackage()
.getName());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/timeout/server/JerseyTimeoutServerApp.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/timeout/server/JerseyTimeoutServerApp.java | package com.baeldung.jersey.timeout.server;
import java.io.IOException;
import java.net.URI;
import org.glassfish.grizzly.http.server.HttpServer;
import com.baeldung.jersey.server.EmbeddedJerseyServer;
public class JerseyTimeoutServerApp {
public static final URI BASE_URI = URI.create("http://localhost:8082");
public static void main(String... args) throws IOException {
start();
}
public static HttpServer start() throws IOException {
return EmbeddedJerseyServer.start(BASE_URI, new TimeoutAppConfig());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/timeout/server/TimeoutResource.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/timeout/server/TimeoutResource.java | package com.baeldung.jersey.timeout.server;
import java.util.concurrent.TimeUnit;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
@Path("/timeout")
public class TimeoutResource {
public static final long STALL = TimeUnit.SECONDS.toMillis(2l);
@GET
public String get() throws InterruptedException {
Thread.sleep(STALL);
return "processed";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/timeout/client/JerseyTimeoutClient.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/timeout/client/JerseyTimeoutClient.java | package com.baeldung.jersey.timeout.client;
import java.util.concurrent.TimeUnit;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import com.baeldung.jersey.timeout.server.TimeoutResource;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Invocation.Builder;
public class JerseyTimeoutClient {
private static final long TIMEOUT = TimeoutResource.STALL / 2;
private final String endpoint;
public JerseyTimeoutClient(String endpoint) {
this.endpoint = endpoint;
}
private String get(Client client) {
return get(client, null);
}
private String get(Client client, Long requestTimeout) {
Builder request = client.target(endpoint)
.request();
if (requestTimeout != null) {
request.property(ClientProperties.CONNECT_TIMEOUT, requestTimeout);
request.property(ClientProperties.READ_TIMEOUT, requestTimeout);
}
return request.get(String.class);
}
public String viaClientBuilder() {
ClientBuilder builder = ClientBuilder.newBuilder()
.connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(TIMEOUT, TimeUnit.MILLISECONDS);
return get(builder.build());
}
public String viaClientConfig() {
ClientConfig config = new ClientConfig();
config.property(ClientProperties.CONNECT_TIMEOUT, TIMEOUT);
config.property(ClientProperties.READ_TIMEOUT, TIMEOUT);
return get(ClientBuilder.newClient(config));
}
public String viaClientProperty() {
Client client = ClientBuilder.newClient();
client.property(ClientProperties.CONNECT_TIMEOUT, TIMEOUT);
client.property(ClientProperties.READ_TIMEOUT, TIMEOUT);
return get(client);
}
public String viaRequestProperty() {
return get(ClientBuilder.newClient(), TIMEOUT);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/test/java/com/baeldung/user/check/UserCheckServletLiveTest.java | web-modules/jakarta-servlets-2/src/test/java/com/baeldung/user/check/UserCheckServletLiveTest.java | package com.baeldung.user.check;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class UserCheckServletLiveTest {
private static final String BASE_URL = "http://localhost:8080/jakarta-servlets-2/user-check";
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
private CloseableHttpClient buildClient() {
return HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
}
@Test
public void whenCorrectCredentials_thenLoginSucceeds() throws Exception {
try (CloseableHttpClient client = buildClient()) {
HttpPost post = new HttpPost(BASE_URL + "/login");
List<BasicNameValuePair> form = new ArrayList<>();
form.add(new BasicNameValuePair("name", "admin"));
form.add(new BasicNameValuePair("password", "password"));
post.setEntity(new UrlEncodedFormEntity(form));
try (CloseableHttpResponse response = client.execute(post)) {
String body = EntityUtils.toString(response.getEntity());
assertTrue(response.getStatusLine()
.getStatusCode() == 200);
assertTrue(body.contains("login success"));
}
}
}
@Test
public void whenIncorrectCredentials_thenLoginFails() throws Exception {
try (CloseableHttpClient client = buildClient()) {
HttpPost post = new HttpPost(BASE_URL + "/login");
List<BasicNameValuePair> form = new ArrayList<>();
form.add(new BasicNameValuePair("name", "admin"));
form.add(new BasicNameValuePair("password", "invalid"));
post.setEntity(new UrlEncodedFormEntity(form));
try (CloseableHttpResponse response = client.execute(post)) {
String body = EntityUtils.toString(response.getEntity());
assertTrue(response.getStatusLine()
.getStatusCode() == 401);
assertTrue(body.contains("invalid login"));
}
}
}
@Test
public void whenNotLoggedIn_thenRedirectedToLoginPage() throws Exception {
try (CloseableHttpClient client = buildClient()) {
HttpGet get = new HttpGet(BASE_URL + "/home");
try (CloseableHttpResponse response = client.execute(get)) {
String body = EntityUtils.toString(response.getEntity());
assertTrue(response.getStatusLine()
.getStatusCode() == 401);
assertTrue(body.contains("redirected to login"));
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/test/java/com/baeldung/jsonresponse/EmployeeServletIntegrationTest.java | web-modules/jakarta-servlets-2/src/test/java/com/baeldung/jsonresponse/EmployeeServletIntegrationTest.java | package com.baeldung.jsonresponse;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import com.google.gson.Gson;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@RunWith(MockitoJUnitRunner.class)
public class EmployeeServletIntegrationTest {
@Mock
HttpServletRequest httpServletRequest;
@Mock
HttpServletResponse httpServletResponse;
Employee employee;
@Test
public void whenPostRequestToEmployeeServlet_thenEmployeeReturnedAsJson() throws Exception {
//Given
int id = 1;
String name = "Karan Khanna";
String department = "IT";
long salary = 5000;
employee = new Employee(id, name, department, salary);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
when(httpServletResponse.getWriter()).thenReturn(pw);
EmployeeServlet employeeServlet = new EmployeeServlet();
employeeServlet.doGet(httpServletRequest, httpServletResponse);
String employeeJsonString = sw.getBuffer().toString().trim();
Employee fetchedEmployee = new Gson().fromJson(employeeJsonString, Employee.class);
assertEquals(fetchedEmployee, employee);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/test/java/com/baeldung/context/ContextServletUnitTest.java | web-modules/jakarta-servlets-2/src/test/java/com/baeldung/context/ContextServletUnitTest.java | package com.baeldung.context;
import org.apache.http.HttpStatus;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
class ContextServletUnitTest extends BaseServletTest {
private static final List<String> CONTEXT_LABELS = List.of(ContextServlet.LABEL_FROM_HTTP_SERVLET, ContextServlet.LABEL_FROM_SERVLET_CONFIG,
ContextServlet.LABEL_FROM_HTTP_SERVLET_REQUEST, ContextServlet.LABEL_FROM_HTTP_SESSION);
@Override
protected void configure(ServletContextHandler ctx) {
ctx.addServlet(ContextServlet.class, ContextServlet.PATH);
}
@Test
void givenContextServlet_whenGetRequest_thenResponseContainsSameContextInstance() throws Exception {
ContentResponse response = httpClient.GET(URI.create(baseUri() + ContextServlet.PATH));
assertEquals(HttpStatus.SC_OK, response.getStatus());
String body = response.getContentAsString();
assertContextLinesIn(body);
List<String> tokens = parseServletContextTokens(body);
assertAllEqual(tokens);
}
private static void assertContextLinesIn(String body) {
for (String label : CONTEXT_LABELS) {
assertTrue(body.contains(label));
}
}
private static List<String> parseServletContextTokens(String body) {
List<String> targetLines = body.lines()
.filter(line -> CONTEXT_LABELS.stream()
.anyMatch(line::startsWith))
.collect(Collectors.toList());
assertEquals(CONTEXT_LABELS.size(), targetLines.size());
return targetLines.stream()
.map(line -> {
int indexOf = line.indexOf(':');
assertTrue(indexOf >= 0);
return line.substring(indexOf + 1)
.trim();
})
.collect(Collectors.toList());
}
private static void assertAllEqual(List<String> tokens) {
Set<String> distinct = Set.copyOf(tokens);
assertEquals(1, distinct.size());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/test/java/com/baeldung/context/BaseServletTest.java | web-modules/jakarta-servlets-2/src/test/java/com/baeldung/context/BaseServletTest.java | package com.baeldung.context;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.jupiter.api.*;
import java.net.InetSocketAddress;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public abstract class BaseServletTest {
protected HttpClient httpClient;
protected Server server;
protected int port() {
return 0; // (random) available port
}
protected String host() {
return "localhost";
}
protected String contextPath() {
return "/";
}
@BeforeAll
void startup() throws Exception {
httpClient = new HttpClient();
httpClient.start();
ServletContextHandler context = prepareContextHandler();
server = new Server(new InetSocketAddress(host(), port()));
server.setHandler(context);
server.start();
}
private ServletContextHandler prepareContextHandler() {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath(contextPath());
configure(context);
return context;
}
protected abstract void configure(ServletContextHandler context);
@AfterAll
void shutdown() throws Exception {
if (server != null) {
server.stop();
}
if (httpClient != null) {
httpClient.stop();
}
}
protected String baseUri() {
String uri = server.getURI()
.toString();
return uri.endsWith("/") ? uri.substring(0, uri.length() - 1) : uri;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/UpdateServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/UpdateServlet.java | package com.baeldung;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
@WebServlet("/update")
public class UpdateServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.setAttribute("userName", request.getParameter("userName"));
session.setAttribute("age", request.getParameter("age"));
request.setAttribute("sessionData", session);
}
request.getRequestDispatcher("/WEB-INF/jsp/update.jsp").forward(request, response);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/MyHttpServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/MyHttpServlet.java | package com.baeldung;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(name = "MyHttpServlet", urlPatterns = "/servlet-mapping")
public class MyHttpServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
writer.println(request.getParameter("function"));
if ("getContextPath".equals(request.getParameter("function"))) {
writer.println(request.getContextPath());
} else if ("getLocalAddr".equals(request.getParameter("function"))) {
writer.println(request.getLocalAddr());
} else if ("getLocalName".equals(request.getParameter("function"))) {
writer.println(request.getLocalName());
} else if ("getLocalPort".equals(request.getParameter("function"))) {
writer.println(request.getLocalPort());
} else if ("getMethod".equals(request.getParameter("function"))) {
writer.println(request.getMethod());
} else if ("getParameterNames".equals(request.getParameter("function"))) {
writer.println(request.getParameterNames());
} else if ("getPathInfo".equals(request.getParameter("function"))) {
writer.println(request.getPathInfo());
} else if ("getProtocol".equals(request.getParameter("function"))) {
writer.println(request.getProtocol());
} else if ("getQueryString".equals(request.getParameter("function"))) {
writer.println(request.getQueryString());
} else if ("getRequestedSessionId".equals(request.getParameter("function"))) {
writer.println(request.getRequestedSessionId());
} else if ("getRequestURI".equals(request.getParameter("function"))) {
writer.println(request.getRequestURI());
} else if ("getRequestURL".equals(request.getParameter("function"))) {
writer.println(request.getRequestURL());
} else if ("getScheme".equals(request.getParameter("function"))) {
writer.println(request.getScheme());
} else if ("getServerName".equals(request.getParameter("function"))) {
writer.println(request.getServerName());
} else if ("getServerPort".equals(request.getParameter("function"))) {
writer.println(request.getServerPort());
} else if ("getServletPath".equals(request.getParameter("function"))) {
writer.println(request.getServletPath());
} else {
writer.println("INVALID FUNCTION");
}
writer.flush();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/UserServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/UserServlet.java | package com.baeldung;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(name = "UserServlet", urlPatterns = "/userServlet", initParams={
@WebInitParam(name="name", value="Not provided"),
@WebInitParam(name="email", value="Not provided")})
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
forwardRequest(request, response, "/WEB-INF/jsp/result.jsp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("name", getRequestParameter(request, "name"));
request.setAttribute("email", getRequestParameter(request, "email"));
request.setAttribute("province", getContextParameter("province"));
request.setAttribute("country", getContextParameter("country"));
}
protected String getRequestParameter(HttpServletRequest request, String name) {
String param = request.getParameter(name);
return !param.isEmpty() ? param : getInitParameter(name);
}
protected String getContextParameter(String name) {
return getServletContext().getInitParameter(name);
}
protected void forwardRequest(HttpServletRequest request, HttpServletResponse response, String path)
throws ServletException, IOException {
request.getRequestDispatcher(path).forward(request, response);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/mvc/StudentServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/mvc/StudentServlet.java | package com.baeldung.mvc;
import java.io.IOException;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(name = "StudentServlet", urlPatterns = "/student-record")
public class StudentServlet extends HttpServlet {
private final StudentService studentService = new StudentService();
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String studentID = request.getParameter("id");
if (studentID != null) {
int id = Integer.parseInt(studentID);
studentService.getStudent(id)
.ifPresent(s -> request.setAttribute("studentRecord", s));
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/student-record.jsp");
dispatcher.forward(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/mvc/Student.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/mvc/Student.java | package com.baeldung.mvc;
public class Student {
private int id;
private String firstName;
private String lastName;
public Student(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/mvc/StudentService.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/mvc/StudentService.java | package com.baeldung.mvc;
import java.util.Optional;
public class StudentService {
public Optional<Student> getStudent(int id) {
switch (id) {
case 1:
return Optional.of(new Student(1, "John", "Doe"));
case 2:
return Optional.of(new Student(2, "Jane", "Goodall"));
case 3:
return Optional.of(new Student(3, "Max", "Born"));
default:
return Optional.empty();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/user/check/UserCheckLogoutServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/user/check/UserCheckLogoutServlet.java | package com.baeldung.user.check;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
@WebServlet("/user-check/logout")
public class UserCheckLogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
request.setAttribute("loggedOut", true);
response.sendRedirect("./");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/user/check/UserCheckServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/user/check/UserCheckServlet.java | package com.baeldung.user.check;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
@WebServlet(name = "home", urlPatterns = { "/user-check/", "/user-check", "/user-check/home" })
public class UserCheckServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("user") == null) {
throw new IllegalStateException("user not logged in");
}
User user = (User) session.getAttribute("user");
request.setAttribute("user", user);
UserCheckFilter.forward(request, response, "/home.jsp");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/user/check/UserCheckFilter.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/user/check/UserCheckFilter.java | package com.baeldung.user.check;
import java.io.IOException;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebFilter("/user-check/*")
public class UserCheckFilter implements Filter {
public static void forward(HttpServletRequest request, HttpServletResponse response, String page) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/user.check" + page)
.forward(request, response);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
if (!(req instanceof HttpServletRequest)) {
throw new ServletException("Can only process HttpServletRequest");
}
if (!(res instanceof HttpServletResponse)) {
throw new ServletException("Can only process HttpServletResponse");
}
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
request.setAttribute("origin", request.getRequestURI());
if (!request.getRequestURI()
.contains("login") && request.getSession(false) == null) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
forward(request, response, "/login.jsp");
// we return here so the original servlet is not processed
return;
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg) throws ServletException {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/user/check/User.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/user/check/User.java | package com.baeldung.user.check;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* @since 6 de fev de 2022
* @author ulisses
*/
public class User implements Serializable {
private static final long serialVersionUID = 1L;
protected static final HashMap<String, User> DB = new HashMap<>();
static {
DB.put("admin", new User("admin", "password"));
DB.put("user", new User("user", "pass"));
}
private String name;
private String password;
private List<Date> logins = new ArrayList<Date>();
public User(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Date> getLogins() {
return logins;
}
public void setLogins(List<Date> logins) {
this.logins = logins;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/user/check/UserCheckLoginServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/user/check/UserCheckLoginServlet.java | package com.baeldung.user.check;
import java.io.IOException;
import java.util.Date;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
@WebServlet("/user-check/login")
public class UserCheckLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getSession(false) != null) {
response.sendRedirect(request.getContextPath() + "/user-check/home");
return;
}
String referer = (String) request.getAttribute("origin");
request.setAttribute("origin", referer);
UserCheckFilter.forward(request, response, "/login.jsp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String key = request.getParameter("name");
String pass = request.getParameter("password");
User user = User.DB.get(key);
if (user == null || !user.getPassword()
.equals(pass)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
request.setAttribute("origin", request.getParameter("origin"));
request.setAttribute("error", "invalid login");
UserCheckFilter.forward(request, response, "/login.jsp");
return;
}
user.getLogins()
.add(new Date());
HttpSession session = request.getSession();
session.setAttribute("user", user);
String origin = request.getParameter("origin");
if (origin == null || origin.contains("login"))
origin = "./";
response.sendRedirect(origin);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/error/RandomErrorServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/error/RandomErrorServlet.java | package com.baeldung.error;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/randomError")
public class RandomErrorServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, final HttpServletResponse resp) {
throw new IllegalStateException("Random error");
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/error/ErrorHandlerServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/error/ErrorHandlerServlet.java | package com.baeldung.error;
import static jakarta.servlet.RequestDispatcher.ERROR_EXCEPTION;
import static jakarta.servlet.RequestDispatcher.ERROR_EXCEPTION_TYPE;
import static jakarta.servlet.RequestDispatcher.ERROR_MESSAGE;
import static jakarta.servlet.RequestDispatcher.ERROR_STATUS_CODE;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/errorHandler")
public class ErrorHandlerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html; charset=utf-8");
try (PrintWriter writer = resp.getWriter()) {
writer.write("<html><head><title>Error description</title></head><body>");
writer.write("<h2>Error description</h2>");
writer.write("<ul>");
Arrays.asList(ERROR_STATUS_CODE, ERROR_EXCEPTION_TYPE, ERROR_MESSAGE)
.forEach(e ->
writer.write("<li>" + e + ":" + req.getAttribute(e) + " </li>")
);
writer.write("</ul>");
writer.write("</html></body>");
}
Exception exception = (Exception) req.getAttribute(ERROR_EXCEPTION);
if (IllegalArgumentException.class.isInstance(exception)) {
getServletContext().log("Error on an application argument", exception);
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/upload/UploadServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/upload/UploadServlet.java | package com.baeldung.upload;
import static com.baeldung.upload.Constants.MAX_FILE_SIZE;
import static com.baeldung.upload.Constants.MAX_REQUEST_SIZE;
import static com.baeldung.upload.Constants.UPLOAD_DIRECTORY;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import org.apache.commons.fileupload2.core.DiskFileItemFactory;
import org.apache.commons.fileupload2.core.FileItem;
import org.apache.commons.fileupload2.jakarta.servlet6.JakartaServletFileUpload;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(
name = "UploadServlet",
urlPatterns = {"/uploadFile"}
)
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (JakartaServletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory factory = DiskFileItemFactory.builder().get();
JakartaServletFileUpload upload = new JakartaServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
item.write(Path.of(uploadPath, fileName));
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/upload/MultipartServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/upload/MultipartServlet.java | package com.baeldung.upload;
import static com.baeldung.upload.Constants.UPLOAD_DIRECTORY;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
@WebServlet(
name = "MultiPartServlet",
urlPatterns = {"/multiPartServlet"}
)
@MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)
public class MultipartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename"))
return content.substring(content.indexOf("=") + 2, content.length() - 1);
}
return Constants.DEFAULT_FILENAME;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists())
uploadDir.mkdir();
try {
String fileName = "";
for (Part part : request.getParts()) {
fileName = getFileName(part);
part.write(uploadPath + File.separator + fileName);
}
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
} catch (FileNotFoundException fne) {
request.setAttribute("message", "There was an error: " + fne.getMessage());
}
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/upload/UploadWelcomeServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/upload/UploadWelcomeServlet.java | package com.baeldung.upload;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(name = "UploadWelcomeServlet", urlPatterns = "/uploadwelcome")
public class UploadWelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/upload.jsp").forward(request, response);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/upload/Constants.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/upload/Constants.java | package com.baeldung.upload;
public class Constants {
public static final String UPLOAD_DIRECTORY = "upload";
public static final String DEFAULT_FILENAME = "default.file";
public static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
public static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/jsonresponse/Employee.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/jsonresponse/Employee.java | package com.baeldung.jsonresponse;
public class Employee {
private int id;
private String name;
private String department;
private long salary;
public Employee(int id, String name, String department, long salary) {
super();
this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
return true;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/jsonresponse/EmployeeServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/jsonresponse/EmployeeServlet.java | package com.baeldung.jsonresponse;
import java.io.IOException;
import java.io.PrintWriter;
import com.google.gson.Gson;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(name = "EmployeeServlet", urlPatterns = "/employeeServlet")
public class EmployeeServlet extends HttpServlet {
private Gson gson = new Gson();
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Employee employee = new Employee(1, "Karan", "IT", 5000);
String employeeJsonString = this.gson.toJson(employee);
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(employeeJsonString);
out.flush();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/download/DownloadServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/download/DownloadServlet.java | package com.baeldung.download;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
private final int ARBITARY_SIZE = 1048;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
resp.setHeader("Content-disposition", "attachment; filename=sample.txt");
try (InputStream in = req.getServletContext().getResourceAsStream("/WEB-INF/sample.txt");
OutputStream out = resp.getOutputStream()) {
byte[] buffer = new byte[ARBITARY_SIZE];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, numBytesRead);
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets-2/src/main/java/com/baeldung/context/ContextServlet.java | web-modules/jakarta-servlets-2/src/main/java/com/baeldung/context/ContextServlet.java | package com.baeldung.context;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(ContextServlet.PATH)
public class ContextServlet extends HttpServlet {
protected static final String PATH = "/context";
protected static final String LABEL_FROM_HTTP_SERVLET = "1) From HttpServlet: ";
protected static final String LABEL_FROM_SERVLET_CONFIG = "2) From ServletConfig: ";
protected static final String LABEL_FROM_HTTP_SERVLET_REQUEST = "3) From HttpServletRequest: ";
protected static final String LABEL_FROM_HTTP_SESSION = "4) From HttpSession: ";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
resp.setContentType("text/plain");
// 1. Direct Access From the Servlet
ServletContext contextFromServlet = this.getServletContext();
resp.getWriter()
.println(LABEL_FROM_HTTP_SERVLET + contextFromServlet);
resp.getWriter()
.println();
// 2. Accessing Through the ServletConfig
ServletConfig config = this.getServletConfig();
ServletContext contextFromConfig = config.getServletContext();
resp.getWriter()
.println(LABEL_FROM_SERVLET_CONFIG + contextFromConfig);
resp.getWriter()
.println();
// 3. Getting the Context From the HttpServletRequest (Servlet 3.0+)
ServletContext contextFromRequest = req.getServletContext();
resp.getWriter()
.println(LABEL_FROM_HTTP_SERVLET_REQUEST + contextFromRequest);
resp.getWriter()
.println();
// 4. Retrieving Through the Session Object
ServletContext contextFromSession = req.getSession()
.getServletContext();
resp.getWriter()
.println(LABEL_FROM_HTTP_SESSION + contextFromSession);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/test/java/com/baeldung/AppHttpUnitTest.java | web-modules/ratpack/src/test/java/com/baeldung/AppHttpUnitTest.java | package com.baeldung;
import com.baeldung.model.Employee;
import org.junit.Test;
import ratpack.exec.Promise;
import ratpack.func.Action;
import ratpack.handling.Chain;
import ratpack.handling.Handler;
import ratpack.registry.Registry;
import ratpack.test.embed.EmbeddedApp;
import ratpack.test.exec.ExecHarness;
import static org.junit.Assert.assertEquals;
public class AppHttpUnitTest {
@Test
public void givenAnyUri_GetEmployeeFromSameRegistry() throws Exception {
Handler allHandler = ctx -> {
Long id = Long.valueOf(ctx.getPathTokens()
.get("id"));
Employee employee = new Employee(id, "Mr", "NY");
ctx.next(Registry.single(Employee.class, employee));
};
Handler empNameHandler = ctx -> {
Employee employee = ctx.get(Employee.class);
ctx.getResponse()
.send("Name of employee with ID " + employee.getId() + " is " + employee.getName());
};
Handler empTitleHandler = ctx -> {
Employee employee = ctx.get(Employee.class);
ctx.getResponse()
.send("Title of employee with ID " + employee.getId() + " is " + employee.getTitle());
};
Action<Chain> chainAction = chain -> chain.prefix("employee/:id", empChain -> {
empChain.all(allHandler)
.get("name", empNameHandler)
.get("title", empTitleHandler);
});
EmbeddedApp.fromHandlers(chainAction)
.test(testHttpClient -> {
assertEquals("Name of employee with ID 1 is NY", testHttpClient.get("employee/1/name")
.getBody()
.getText());
assertEquals("Title of employee with ID 1 is Mr", testHttpClient.get("employee/1/title")
.getBody()
.getText());
});
}
@Test
public void givenSyncDataSource_GetDataFromPromise() throws Exception {
String value = ExecHarness.yieldSingle(execution -> Promise.sync(() -> "Foo"))
.getValueOrThrow();
assertEquals("Foo", value);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/test/java/com/baeldung/ApplicationIntegrationTest.java | web-modules/ratpack/src/test/java/com/baeldung/ApplicationIntegrationTest.java | package com.baeldung;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import com.baeldung.model.Employee;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ratpack.test.MainClassApplicationUnderTest;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
@RunWith(JUnit4.class)
public class ApplicationIntegrationTest {
MainClassApplicationUnderTest appUnderTest = new MainClassApplicationUnderTest(Application.class);
@Test
public void givenDefaultUrl_getStaticText() {
assertEquals("Welcome to baeldung ratpack!!!", appUnderTest.getHttpClient().getText("/"));
}
@Test
public void givenDynamicUrl_getDynamicText() {
assertEquals("Hello dummybot!!!", appUnderTest.getHttpClient().getText("/dummybot"));
}
@Test
public void givenUrl_getListOfEmployee() throws JsonProcessingException {
List<Employee> employees = new ArrayList<Employee>();
ObjectMapper mapper = new ObjectMapper();
employees.add(new Employee(1L, "Mr", "John Doe"));
employees.add(new Employee(2L, "Mr", "White Snow"));
assertEquals(mapper.writeValueAsString(employees), appUnderTest.getHttpClient().getText("/data/employees"));
}
@Test
public void givenStaticUrl_getDynamicText() {
assertEquals(21, appUnderTest.getHttpClient().getText("/randomString").length());
}
@After
public void shutdown() {
appUnderTest.close();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/test/java/com/baeldung/ratpack/NonCompliantPublisher.java | web-modules/ratpack/src/test/java/com/baeldung/ratpack/NonCompliantPublisher.java | package com.baeldung.ratpack;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NonCompliantPublisher implements Publisher<Integer> {
private static final Logger log = LoggerFactory.getLogger(NonCompliantPublisher.class);
@Override
public void subscribe(Subscriber<? super Integer> subscriber) {
log.info("subscribe");
subscriber.onSubscribe(new NonCompliantSubscription(subscriber));
}
private class NonCompliantSubscription implements Subscription {
private Subscriber<? super Integer> subscriber;
private int recurseLevel = 0;
public NonCompliantSubscription(Subscriber<? super Integer> subscriber) {
this.subscriber = subscriber;
}
@Override
public void request(long n) {
log.info("request: n={}", n);
if ( recurseLevel > 0 ) {
return;
}
recurseLevel++;
for (int i = 0 ; i < (n + 5) ; i ++ ) {
subscriber.onNext(i);
}
subscriber.onComplete();
}
@Override
public void cancel() {
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/test/java/com/baeldung/ratpack/RatpackStreamsUnitTest.java | web-modules/ratpack/src/test/java/com/baeldung/ratpack/RatpackStreamsUnitTest.java | package com.baeldung.ratpack;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ratpack.exec.ExecResult;
import ratpack.func.Action;
import ratpack.stream.StreamEvent;
import ratpack.stream.Streams;
import ratpack.stream.TransformablePublisher;
import ratpack.test.exec.ExecHarness;
public class RatpackStreamsUnitTest {
private static Logger log = LoggerFactory.getLogger(RatpackStreamsUnitTest.class);
@Test
public void whenPublish_thenSuccess() {
Publisher<String> pub = Streams.publish(Arrays.asList("hello", "hello again"));
LoggingSubscriber<String> sub = new LoggingSubscriber<String>();
pub.subscribe(sub);
sub.block();
}
@Test
public void whenYield_thenSuccess() {
Publisher<String> pub = Streams.yield((t) -> {
return t.getRequestNum() < 5 ? "hello" : null;
});
LoggingSubscriber<String> sub = new LoggingSubscriber<String>();
pub.subscribe(sub);
sub.block();
assertEquals(5, sub.getReceived());
}
@Test
public void whenPeriodic_thenSuccess() {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Publisher<String> pub = Streams.periodically(executor, Duration.ofSeconds(1), (t) -> {
return t < 5 ? String.format("hello %d",t): null;
});
LoggingSubscriber<String> sub = new LoggingSubscriber<String>();
pub.subscribe(sub);
sub.block();
assertEquals(5, sub.getReceived());
}
@Test
public void whenMap_thenSuccess() throws Exception {
TransformablePublisher<String> pub = Streams.yield( t -> {
return t.getRequestNum() < 5 ? t.getRequestNum() : null;
})
.map(v -> String.format("item %d", v));
ExecResult<List<String>> result = ExecHarness.yieldSingle((c) -> pub.toList() );
assertTrue("should succeed", result.isSuccess());
assertEquals("should have 5 items",5,result.getValue().size());
}
@Test
public void whenNonCompliantPublisherWithBuffer_thenSuccess() throws Exception {
TransformablePublisher<Integer> pub = Streams.transformable(new NonCompliantPublisher())
.wiretap(new LoggingAction("before buffer"))
.buffer()
.wiretap(new LoggingAction("after buffer"))
.take(1);
LoggingSubscriber<Integer> sub = new LoggingSubscriber<>();
pub.subscribe(sub);
sub.block();
}
@Test
public void whenNonCompliantPublisherWithoutBuffer_thenSuccess() throws Exception {
TransformablePublisher<Integer> pub = Streams.transformable(new NonCompliantPublisher())
.wiretap(new LoggingAction(""))
.take(1);
LoggingSubscriber<Integer> sub = new LoggingSubscriber<>();
pub.subscribe(sub);
sub.block();
}
@Test
public void whenCompliantPublisherWithoutBatch_thenSuccess() throws Exception {
TransformablePublisher<Integer> pub = Streams.transformable(new CompliantPublisher(10))
.wiretap(new LoggingAction(""));
LoggingSubscriber<Integer> sub = new LoggingSubscriber<>();
pub.subscribe(sub);
sub.block();
}
@Test
public void whenCompliantPublisherWithBatch_thenSuccess() throws Exception {
TransformablePublisher<Integer> pub = Streams.transformable(new CompliantPublisher(10))
.wiretap(new LoggingAction("before batch"))
.batch(5, Action.noop())
.wiretap(new LoggingAction("after batch"));
LoggingSubscriber<Integer> sub = new LoggingSubscriber<>();
pub.subscribe(sub);
sub.block();
}
private static class LoggingAction implements Action<StreamEvent<Integer>>{
private final String label;
public LoggingAction(String label) {
this.label = label;
}
@Override
public void execute(StreamEvent<Integer> e) throws Exception {
log.info("{}: event={}", label,e);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/test/java/com/baeldung/ratpack/LoggingSubscriber.java | web-modules/ratpack/src/test/java/com/baeldung/ratpack/LoggingSubscriber.java | package com.baeldung.ratpack;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggingSubscriber<T> implements Subscriber<T> {
private static final Logger log = LoggerFactory.getLogger(LoggingSubscriber.class);
private Subscription subscription;
private long requested;
private long received;
private CountDownLatch finished = new CountDownLatch(1);
@Override
public void onComplete() {
log.info("onComplete: sub={}", subscription.hashCode());
finished.countDown();
}
@Override
public void onError(Throwable t) {
log.error("Error: sub={}, message={}", subscription.hashCode(), t.getMessage(),t);
finished.countDown();
}
@Override
public void onNext(T value) {
log.info("onNext: sub={}, value={}", subscription.hashCode(), value);
this.received++;
this.requested++;
subscription.request(1);
}
@Override
public void onSubscribe(Subscription sub) {
log.info("onSubscribe: sub={}", sub.hashCode());
this.subscription = sub;
this.received = 0;
this.requested = 1;
sub.request(1);
}
public long getRequested() {
return requested;
}
public long getReceived() {
return received;
}
public void block() {
try {
finished.await(10, TimeUnit.SECONDS);
}
catch(InterruptedException iex) {
throw new RuntimeException(iex);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/test/java/com/baeldung/ratpack/CompliantPublisher.java | web-modules/ratpack/src/test/java/com/baeldung/ratpack/CompliantPublisher.java | package com.baeldung.ratpack;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Non-thread safe !!!
class CompliantPublisher implements Publisher<Integer> {
String name;
private static final Logger log = LoggerFactory.getLogger(CompliantPublisher.class);
private long available;
public CompliantPublisher(long available) {
this.available = available;
}
@Override
public void subscribe(Subscriber<? super Integer> subscriber) {
log.info("subscribe");
subscriber.onSubscribe(new CompliantSubscription(subscriber));
}
private class CompliantSubscription implements Subscription {
private Subscriber<? super Integer> subscriber;
private int recurseLevel;
private long requested;
private boolean cancelled;
public CompliantSubscription(Subscriber<? super Integer> subscriber) {
this.subscriber = subscriber;
}
@Override
public void request(long n) {
log.info("request: requested={}, available={}", n, available);
requested += n;
if ( recurseLevel > 0 ) {
return;
}
recurseLevel++;
for (int i = 0 ; i < (requested) && !cancelled && available > 0 ; i++, available-- ) {
subscriber.onNext(i);
}
subscriber.onComplete();
}
@Override
public void cancel() {
cancelled = true;
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java | web-modules/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java | package com.baeldung.hystrix;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import ratpack.test.MainClassApplicationUnderTest;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
/**
* @author aiet
*/
public class RatpackHystrixAppFallbackLiveTest {
static MainClassApplicationUnderTest appUnderTest;
@BeforeClass
public static void setup() {
System.setProperty("ratpack.hystrix.timeout", "10");
appUnderTest = new MainClassApplicationUnderTest(RatpackHystrixApp.class);
}
@Test
public void whenFetchReactive_thenGotFallbackProfile() {
assertThat(appUnderTest
.getHttpClient()
.getText("rx"), containsString("reactive fallback profile"));
}
@Test
public void whenFetchAsync_thenGotFallbackProfile() {
assertThat(appUnderTest
.getHttpClient()
.getText("async"), containsString("async fallback profile"));
}
@Test
public void whenFetchSync_thenGotFallbackProfile() {
assertThat(appUnderTest
.getHttpClient()
.getText("sync"), containsString("sync fallback profile"));
}
@AfterClass
public static void clean() {
appUnderTest.close();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java | web-modules/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java | package com.baeldung.hystrix;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import ratpack.test.MainClassApplicationUnderTest;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
/**
* @author aiet
*/
public class RatpackHystrixAppLiveTest {
static MainClassApplicationUnderTest appUnderTest;
@BeforeClass
public static void setup() {
System.setProperty("ratpack.hystrix.timeout", "5000");
appUnderTest = new MainClassApplicationUnderTest(RatpackHystrixApp.class);
}
@Test
public void whenFetchReactive_thenGotEugenProfile() {
assertThat(appUnderTest
.getHttpClient()
.getText("rx"), containsString("www.baeldung.com"));
}
@Test
public void whenFetchAsync_thenGotEugenProfile() {
assertThat(appUnderTest
.getHttpClient()
.getText("async"), containsString("www.baeldung.com"));
}
@Test
public void whenFetchSync_thenGotEugenProfile() {
assertThat(appUnderTest
.getHttpClient()
.getText("sync"), containsString("www.baeldung.com"));
}
@AfterClass
public static void clean() {
appUnderTest.close();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/test/java/com/baeldung/spring/EmbedRatpackAppIntegrationTest.java | web-modules/ratpack/src/test/java/com/baeldung/spring/EmbedRatpackAppIntegrationTest.java | package com.baeldung.spring;
import org.junit.Test;
import ratpack.test.MainClassApplicationUnderTest;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
/**
* @author aiet
*/
public class EmbedRatpackAppIntegrationTest {
MainClassApplicationUnderTest appUnderTest = new MainClassApplicationUnderTest(EmbedRatpackApp.class);
@Test
public void whenSayHello_thenGotWelcomeMessage() {
assertEquals("hello baeldung!", appUnderTest
.getHttpClient()
.getText("/hello"));
}
@Test
public void whenRequestList_thenGotArticles() throws IOException {
assertEquals(3, appUnderTest
.getHttpClient()
.getText("/list")
.split(",").length);
}
@Test
public void whenRequestStaticResource_thenGotStaticContent() {
assertThat(appUnderTest
.getHttpClient()
.getText("/"), containsString("page is static"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/Application.java | web-modules/ratpack/src/main/java/com/baeldung/Application.java | package com.baeldung;
import com.baeldung.filter.RequestValidatorFilter;
import com.baeldung.handler.EmployeeHandler;
import com.baeldung.handler.RedirectHandler;
import com.baeldung.model.Employee;
import com.baeldung.repository.EmployeeRepository;
import com.baeldung.repository.EmployeeRepositoryImpl;
import com.zaxxer.hikari.HikariConfig;
import io.netty.buffer.PooledByteBufAllocator;
import ratpack.exec.internal.DefaultExecController;
import ratpack.func.Action;
import ratpack.func.Function;
import ratpack.guice.BindingsSpec;
import ratpack.guice.Guice;
import ratpack.handling.Chain;
import ratpack.hikari.HikariModule;
import ratpack.http.client.HttpClient;
import ratpack.jackson.Jackson;
import ratpack.registry.Registry;
import ratpack.server.RatpackServer;
import ratpack.server.RatpackServerSpec;
import ratpack.server.ServerConfig;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
public class Application {
public static void main(String[] args) throws Exception {
final Action<HikariConfig> hikariConfigAction = hikariConfig -> {
hikariConfig.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource");
hikariConfig.addDataSourceProperty("URL", "jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'classpath:/DDL.sql'");
};
final Action<BindingsSpec> bindingsSpecAction = bindings -> bindings.module(HikariModule.class, hikariConfigAction);
final HttpClient httpClient = HttpClient.of(httpClientSpec -> {
httpClientSpec.poolSize(10)
.connectTimeout(Duration.of(60, ChronoUnit.SECONDS))
.maxContentLength(ServerConfig.DEFAULT_MAX_CONTENT_LENGTH)
.responseMaxChunkSize(16384)
.readTimeout(Duration.of(60, ChronoUnit.SECONDS))
.byteBufAllocator(PooledByteBufAllocator.DEFAULT).execController(new DefaultExecController(2));
});
final Function<Registry, Registry> registryFunction = Guice.registry(bindingsSpecAction);
final Action<Chain> chainAction = chain -> chain.all(new RequestValidatorFilter())
.get(ctx -> ctx.render("Welcome to baeldung ratpack!!!"))
.get("data/employees", ctx -> ctx.render(Jackson.json(createEmpList())))
.get(":name", ctx -> ctx.render("Hello " + ctx.getPathTokens()
.get("name") + "!!!"))
.post(":amount", ctx -> ctx.render(" Amount $" + ctx.getPathTokens()
.get("amount") + " added successfully !!!"));
final Action<Chain> routerChainAction = routerChain -> {
routerChain.path("redirect", new RedirectHandler())
.prefix("employee", empChain -> {
empChain.get(":id", new EmployeeHandler());
});
};
final Action<RatpackServerSpec> ratpackServerSpecAction = serverSpec -> serverSpec.registry(registryFunction)
.registryOf(registrySpec -> {
registrySpec.add(EmployeeRepository.class, new EmployeeRepositoryImpl());
registrySpec.add(HttpClient.class, httpClient);
})
.handlers(chain -> chain.insert(routerChainAction)
.insert(chainAction));
RatpackServer.start(ratpackServerSpecAction);
}
private static List<Employee> createEmpList() {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1L, "Mr", "John Doe"));
employees.add(new Employee(2L, "Mr", "White Snow"));
return employees;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/filter/RequestValidatorFilter.java | web-modules/ratpack/src/main/java/com/baeldung/filter/RequestValidatorFilter.java | package com.baeldung.filter;
import ratpack.handling.Context;
import ratpack.handling.Handler;
import ratpack.http.MutableHeaders;
public class RequestValidatorFilter implements Handler {
@Override
public void handle(Context ctx) throws Exception {
MutableHeaders headers = ctx.getResponse().getHeaders();
headers.set("Access-Control-Allow-Origin", "*");
ctx.next();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/guice/Application.java | web-modules/ratpack/src/main/java/com/baeldung/guice/Application.java | package com.baeldung.guice;
import com.baeldung.guice.config.DependencyModule;
import com.baeldung.guice.service.DataPumpService;
import com.baeldung.guice.service.ServiceFactory;
import com.baeldung.guice.service.impl.DataPumpServiceImpl;
import ratpack.guice.Guice;
import ratpack.server.RatpackServer;
public class Application {
public static void main(String[] args) throws Exception {
RatpackServer
.start(server -> server.registry(Guice.registry(bindings -> bindings.module(DependencyModule.class)))
.handlers(chain -> chain.get("randomString", ctx -> {
DataPumpService dataPumpService = ctx.get(DataPumpService.class);
ctx.render(dataPumpService.generate());
}).get("factory", ctx -> ctx.render(ServiceFactory.getInstance().generate()))));
// RatpackServer.start(server -> server
// .registry(Guice
// .registry(bindings -> bindings.bindInstance(DataPumpService.class, new DataPumpServiceImpl())))
// .handlers(chain -> chain.get("randomString", ctx -> {
// DataPumpService dataPumpService = ctx.get(DataPumpService.class);
// ctx.render(dataPumpService.generate());
// }).get("factory", ctx -> ctx.render(ServiceFactory.getInstance().generate()))));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/guice/service/ServiceFactory.java | web-modules/ratpack/src/main/java/com/baeldung/guice/service/ServiceFactory.java | package com.baeldung.guice.service;
import com.baeldung.guice.service.impl.DataPumpServiceImpl;
public class ServiceFactory {
private static DataPumpService instance;
public static void setInstance(DataPumpService dataPumpService) {
instance = dataPumpService;
}
public static DataPumpService getInstance() {
if (instance == null) {
return new DataPumpServiceImpl();
}
return instance;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/guice/service/DataPumpService.java | web-modules/ratpack/src/main/java/com/baeldung/guice/service/DataPumpService.java | package com.baeldung.guice.service;
public interface DataPumpService {
String generate();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/guice/service/impl/DataPumpServiceImpl.java | web-modules/ratpack/src/main/java/com/baeldung/guice/service/impl/DataPumpServiceImpl.java | package com.baeldung.guice.service.impl;
import java.util.UUID;
import com.baeldung.guice.service.DataPumpService;
public class DataPumpServiceImpl implements DataPumpService {
@Override
public String generate() {
return UUID.randomUUID().toString();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/guice/config/DependencyModule.java | web-modules/ratpack/src/main/java/com/baeldung/guice/config/DependencyModule.java | package com.baeldung.guice.config;
import com.baeldung.guice.service.DataPumpService;
import com.baeldung.guice.service.impl.DataPumpServiceImpl;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
public class DependencyModule extends AbstractModule {
@Override
protected void configure() {
bind(DataPumpService.class).to(DataPumpServiceImpl.class)
.in(Scopes.SINGLETON);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/model/Movie.java | web-modules/ratpack/src/main/java/com/baeldung/model/Movie.java | package com.baeldung.model;
/**
*
*POJO class for Movie object
*/
public class Movie {
private String name;
private String year;
private String director;
private Double rating;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public Double getRating() {
return rating;
}
public void setRating(Double rating) {
this.rating = rating;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/model/Employee.java | web-modules/ratpack/src/main/java/com/baeldung/model/Employee.java | package com.baeldung.model;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 3077867088762010705L;
private Long id;
private String title;
private String name;
public Employee(Long id, String title, String name) {
super();
this.id = id;
this.title = title;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/model/Quote.java | web-modules/ratpack/src/main/java/com/baeldung/model/Quote.java | package com.baeldung.model;
import java.time.Instant;
public class Quote {
private Instant ts;
private String symbol;
private double value;
public Quote() {}
public Quote(Instant ts, String symbol, double value) {
this.ts = ts;
this.symbol = symbol;
this.value = value;
}
/**
* @return the ts
*/
public Instant getTs() {
return ts;
}
/**
* @param ts the ts to set
*/
public void setTs(Instant ts) {
this.ts = ts;
}
/**
* @return the symbol
*/
public String getSymbol() {
return symbol;
}
/**
* @param symbol the symbol to set
*/
public void setSymbol(String symbol) {
this.symbol = symbol;
}
/**
* @return the value
*/
public double getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(double value) {
this.value = value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((symbol == null) ? 0 : symbol.hashCode());
result = prime * result + ((ts == null) ? 0 : ts.hashCode());
long temp;
temp = Double.doubleToLongBits(value);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Quote other = (Quote) obj;
if (symbol == null) {
if (other.symbol != null)
return false;
} else if (!symbol.equals(other.symbol))
return false;
if (ts == null) {
if (other.ts != null)
return false;
} else if (!ts.equals(other.ts))
return false;
if (Double.doubleToLongBits(value) != Double.doubleToLongBits(other.value))
return false;
return true;
}
@Override
public String toString() {
return "Quote [ts=" + ts + ", symbol=" + symbol + ", value=" + value + "]";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/rxjava/RatpackErrorHandlingApp.java | web-modules/ratpack/src/main/java/com/baeldung/rxjava/RatpackErrorHandlingApp.java | package com.baeldung.rxjava;
import ratpack.error.ServerErrorHandler;
import ratpack.rx.RxRatpack;
import ratpack.server.RatpackServer;
import rx.Observable;
public class RatpackErrorHandlingApp {
/**
* Try hitting http://localhost:5050/error to see the error handler in action
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
RxRatpack.initialize();
RatpackServer.start(def -> def.registryOf(regSpec -> regSpec.add(ServerErrorHandler.class, (ctx, throwable) -> {
ctx.render("Error caught by handler : " + throwable.getMessage());
}))
.handlers(chain -> chain.get("error", ctx -> {
Observable.<String> error(new Exception("Error from observable"))
.subscribe(s -> {
});
})));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/rxjava/RatpackPromiseApp.java | web-modules/ratpack/src/main/java/com/baeldung/rxjava/RatpackPromiseApp.java | package com.baeldung.rxjava;
import com.baeldung.model.Movie;
import com.baeldung.rxjava.service.MovieObservableService;
import com.baeldung.rxjava.service.impl.MovieObservableServiceImpl;
import ratpack.handling.Handler;
import ratpack.jackson.Jackson;
import ratpack.rx.RxRatpack;
import ratpack.server.RatpackServer;
import rx.Observable;
public class RatpackPromiseApp {
/**
* Try hitting http://localhost:5050/movies or http://localhost:5050/movie to see the application in action.
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
RxRatpack.initialize();
Handler movieHandler = (ctx) -> {
MovieObservableService movieSvc = ctx.get(MovieObservableService.class);
Observable<Movie> movieObs = movieSvc.getMovie();
RxRatpack.promiseSingle(movieObs)
.then(movie -> ctx.render(Jackson.json(movie)));
};
Handler moviesHandler = (ctx) -> {
MovieObservableService movieSvc = ctx.get(MovieObservableService.class);
Observable<Movie> movieObs = movieSvc.getMovies();
RxRatpack.promise(movieObs)
.then(movie -> ctx.render(Jackson.json(movie)));
};
RatpackServer.start(def -> def.registryOf(rSpec -> rSpec.add(MovieObservableService.class, new MovieObservableServiceImpl()))
.handlers(chain -> chain.get("movie", movieHandler)
.get("movies", moviesHandler)));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/rxjava/RatpackObserveApp.java | web-modules/ratpack/src/main/java/com/baeldung/rxjava/RatpackObserveApp.java | package com.baeldung.rxjava;
import java.util.List;
import com.baeldung.model.Movie;
import com.baeldung.rxjava.service.MoviePromiseService;
import com.baeldung.rxjava.service.impl.MoviePromiseServiceImpl;
import ratpack.exec.Promise;
import ratpack.handling.Handler;
import ratpack.jackson.Jackson;
import ratpack.rx.RxRatpack;
import ratpack.server.RatpackServer;
public class RatpackObserveApp {
/**
* Try hitting http://localhost:5050/movies or http://localhost:5050/movie to see the application in action.
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
RxRatpack.initialize();
Handler moviePromiseHandler = ctx -> {
MoviePromiseService promiseSvc = ctx.get(MoviePromiseService.class);
Promise<Movie> moviePromise = promiseSvc.getMovie();
RxRatpack.observe(moviePromise)
.subscribe(movie -> ctx.render(Jackson.json(movie)));
};
Handler moviesPromiseHandler = ctx -> {
MoviePromiseService promiseSvc = ctx.get(MoviePromiseService.class);
Promise<List<Movie>> moviePromises = promiseSvc.getMovies();
RxRatpack.observeEach(moviePromises)
.toList()
.subscribe(movie -> ctx.render(Jackson.json(movie)));
};
RatpackServer.start(def -> def.registryOf(regSpec -> regSpec.add(MoviePromiseService.class, new MoviePromiseServiceImpl()))
.handlers(chain -> chain.get("movie", moviePromiseHandler)
.get("movies", moviesPromiseHandler)));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/rxjava/RatpackParallelismApp.java | web-modules/ratpack/src/main/java/com/baeldung/rxjava/RatpackParallelismApp.java | package com.baeldung.rxjava;
import com.baeldung.model.Movie;
import com.baeldung.rxjava.service.MovieObservableService;
import com.baeldung.rxjava.service.impl.MovieObservableServiceImpl;
import ratpack.jackson.Jackson;
import ratpack.rx.RxRatpack;
import ratpack.server.RatpackServer;
import rx.Observable;
public class RatpackParallelismApp {
/**
* Try hitting http://localhost:5050/movies to see the application in action.
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
RxRatpack.initialize();
RatpackServer.start(def -> def.registryOf(regSpec -> regSpec.add(MovieObservableService.class, new MovieObservableServiceImpl()))
.handlers(chain -> chain.get("movies", ctx -> {
MovieObservableService movieSvc = ctx.get(MovieObservableService.class);
Observable<Movie> movieObs = movieSvc.getMovies();
Observable<String> upperCasedNames = movieObs.compose(RxRatpack::forkEach)
.map(movie -> movie.getName()
.toUpperCase())
.serialize();
RxRatpack.promise(upperCasedNames)
.then(movie -> {
ctx.render(Jackson.json(movie));
});
})));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/rxjava/service/QuotesService.java | web-modules/ratpack/src/main/java/com/baeldung/rxjava/service/QuotesService.java | package com.baeldung.rxjava.service;
import java.time.Duration;
import java.time.Instant;
import java.util.Random;
import java.util.concurrent.ScheduledExecutorService;
import org.reactivestreams.Publisher;
import com.baeldung.model.Quote;
import ratpack.stream.Streams;
public class QuotesService {
private final ScheduledExecutorService executorService;
private static Random rnd = new Random();
private static String[] symbols = new String[] {
"MSFT",
"ORCL",
"GOOG",
"AAPL",
"CSCO"
};
public QuotesService(ScheduledExecutorService executorService) {
this.executorService = executorService;
}
public Publisher<Quote> newTicker() {
return Streams.periodically(executorService, Duration.ofSeconds(2), (t) -> {
return randomQuote();
});
}
private static Quote randomQuote() {
return new Quote (
Instant.now(),
symbols[rnd.nextInt(symbols.length)],
Math.round(rnd.nextDouble()*100)
);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/rxjava/service/MovieObservableService.java | web-modules/ratpack/src/main/java/com/baeldung/rxjava/service/MovieObservableService.java | package com.baeldung.rxjava.service;
import com.baeldung.model.Movie;
import rx.Observable;
public interface MovieObservableService {
Observable<Movie> getMovies();
Observable<Movie> getMovie();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/rxjava/service/MoviePromiseService.java | web-modules/ratpack/src/main/java/com/baeldung/rxjava/service/MoviePromiseService.java | package com.baeldung.rxjava.service;
import java.util.List;
import com.baeldung.model.Movie;
import ratpack.exec.Promise;
public interface MoviePromiseService {
Promise<List<Movie>> getMovies();
Promise<Movie> getMovie();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/rxjava/service/impl/MoviePromiseServiceImpl.java | web-modules/ratpack/src/main/java/com/baeldung/rxjava/service/impl/MoviePromiseServiceImpl.java | package com.baeldung.rxjava.service.impl;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.model.Movie;
import com.baeldung.rxjava.service.MoviePromiseService;
import ratpack.exec.Promise;
public class MoviePromiseServiceImpl implements MoviePromiseService {
@Override
public Promise<Movie> getMovie() {
Movie movie = new Movie();
movie.setName("The Godfather");
movie.setYear("1972");
movie.setDirector("Coppola");
movie.setRating(9.2);
return Promise.value(movie);
}
@Override
public Promise<List<Movie>> getMovies() {
Movie movie = new Movie();
movie.setName("The Godfather");
movie.setYear("1972");
movie.setDirector("Coppola");
movie.setRating(9.2);
Movie movie2 = new Movie();
movie2.setName("The Godfather Part 2");
movie2.setYear("1974");
movie2.setDirector("Coppola");
movie2.setRating(9.0);
List<Movie> movies = new ArrayList<>();
movies.add(movie);
movies.add(movie2);
return Promise.value(movies);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/rxjava/service/impl/MovieObservableServiceImpl.java | web-modules/ratpack/src/main/java/com/baeldung/rxjava/service/impl/MovieObservableServiceImpl.java | package com.baeldung.rxjava.service.impl;
import com.baeldung.model.Movie;
import com.baeldung.rxjava.service.MovieObservableService;
import rx.Observable;
public class MovieObservableServiceImpl implements MovieObservableService {
@Override
public Observable<Movie> getMovie() {
Movie movie = new Movie();
movie.setName("The Godfather");
movie.setYear("1972");
movie.setDirector("Coppola");
movie.setRating(9.2);
return Observable.just(movie);
}
@Override
public Observable<Movie> getMovies() {
Movie movie = new Movie();
movie.setName("The Godfather");
movie.setYear("1972");
movie.setDirector("Coppola");
movie.setRating(9.2);
Movie movie2 = new Movie();
movie2.setName("The Godfather Part 2");
movie2.setYear("1974");
movie2.setDirector("Coppola");
movie2.setRating(9.0);
return Observable.just(movie, movie2);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java | web-modules/ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java | package com.baeldung.hystrix;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import java.net.URI;
import java.util.Collections;
/**
* @author aiet
*/
public class HystrixSyncHttpCommand extends HystrixCommand<String> {
private URI uri;
private RequestConfig requestConfig;
HystrixSyncHttpCommand(URI uri, int timeoutMillis) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-sync"))
.andCommandPropertiesDefaults(HystrixCommandProperties
.Setter()
.withExecutionTimeoutInMilliseconds(timeoutMillis)));
requestConfig = RequestConfig
.custom()
.setSocketTimeout(timeoutMillis)
.setConnectTimeout(timeoutMillis)
.setConnectionRequestTimeout(timeoutMillis)
.build();
this.uri = uri;
}
@Override
protected String run() throws Exception {
HttpGet request = new HttpGet(uri);
return EntityUtils.toString(HttpClientBuilder
.create()
.setDefaultRequestConfig(requestConfig)
.setDefaultHeaders(Collections.singleton(new BasicHeader("User-Agent", "Baeldung Blocking HttpClient")))
.build()
.execute(request)
.getEntity());
}
@Override
protected String getFallback() {
return "eugenp's sync fallback profile";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java | web-modules/ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java | package com.baeldung.hystrix;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import java.net.URI;
import java.util.Collections;
/**
* @author aiet
*/
public class HystrixAsyncHttpCommand extends HystrixCommand<String> {
private URI uri;
private RequestConfig requestConfig;
HystrixAsyncHttpCommand(URI uri, int timeoutMillis) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-async"))
.andCommandPropertiesDefaults(HystrixCommandProperties
.Setter()
.withExecutionTimeoutInMilliseconds(timeoutMillis)));
requestConfig = RequestConfig
.custom()
.setSocketTimeout(timeoutMillis)
.setConnectTimeout(timeoutMillis)
.setConnectionRequestTimeout(timeoutMillis)
.build();
this.uri = uri;
}
@Override
protected String run() throws Exception {
return EntityUtils.toString(HttpClientBuilder
.create()
.setDefaultRequestConfig(requestConfig)
.setDefaultHeaders(Collections.singleton(new BasicHeader("User-Agent", "Baeldung Blocking HttpClient")))
.build()
.execute(new HttpGet(uri))
.getEntity());
}
@Override
protected String getFallback() {
return "eugenp's async fallback profile";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java | web-modules/ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java | package com.baeldung.hystrix;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixObservableCommand;
import ratpack.http.client.HttpClient;
import ratpack.rx.RxRatpack;
import rx.Observable;
import java.net.URI;
/**
* @author aiet
*/
public class HystrixReactiveHttpCommand extends HystrixObservableCommand<String> {
private HttpClient httpClient;
private URI uri;
HystrixReactiveHttpCommand(HttpClient httpClient, URI uri, int timeoutMillis) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-reactive"))
.andCommandPropertiesDefaults(HystrixCommandProperties
.Setter()
.withExecutionTimeoutInMilliseconds(timeoutMillis)));
this.httpClient = httpClient;
this.uri = uri;
}
@Override
protected Observable<String> construct() {
return RxRatpack.observe(httpClient
.get(uri, requestSpec -> requestSpec.headers(mutableHeaders -> mutableHeaders.add("User-Agent", "Baeldung HttpClient")))
.map(receivedResponse -> receivedResponse
.getBody()
.getText()));
}
@Override
protected Observable<String> resumeWithFallback() {
return Observable.just("eugenp's reactive fallback profile");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java | web-modules/ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java | package com.baeldung.hystrix;
import ratpack.guice.Guice;
import ratpack.http.client.HttpClient;
import ratpack.hystrix.HystrixMetricsEventStreamHandler;
import ratpack.hystrix.HystrixModule;
import ratpack.server.RatpackServer;
import java.net.URI;
public class RatpackHystrixApp {
public static void main(String[] args) throws Exception {
final int timeout = Integer.valueOf(System.getProperty("ratpack.hystrix.timeout"));
final URI eugenGithubProfileUri = new URI("https://api.github.com/users/eugenp");
RatpackServer.start(server -> server
.registry(Guice.registry(bindingsSpec -> bindingsSpec.module(new HystrixModule().sse())))
.handlers(chain -> chain
.get("rx", ctx -> new HystrixReactiveHttpCommand(ctx.get(HttpClient.class), eugenGithubProfileUri, timeout)
.toObservable()
.subscribe(ctx::render))
.get("async", ctx -> ctx.render(new HystrixAsyncHttpCommand(eugenGithubProfileUri, timeout)
.queue()
.get()))
.get("sync", ctx -> ctx.render(new HystrixSyncHttpCommand(eugenGithubProfileUri, timeout).execute()))
.get("hystrix", new HystrixMetricsEventStreamHandler())));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/repository/EmployeeRepositoryImpl.java | web-modules/ratpack/src/main/java/com/baeldung/repository/EmployeeRepositoryImpl.java | package com.baeldung.repository;
import com.baeldung.model.Employee;
import ratpack.exec.Promise;
import java.util.HashMap;
import java.util.Map;
public class EmployeeRepositoryImpl implements EmployeeRepository {
private static final Map<Long, Employee> EMPLOYEE_MAP = new HashMap<>();
public EmployeeRepositoryImpl() {
EMPLOYEE_MAP.put(1L, new Employee(1L, "Ms", "Jane Doe"));
EMPLOYEE_MAP.put(2L, new Employee(2L, "Mr", "NY"));
}
@Override
public Promise<Employee> findEmployeeById(Long id) throws Exception {
return Promise.async(downstream -> {
Thread.sleep(500);
downstream.success(EMPLOYEE_MAP.get(id));
});
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/repository/EmployeeRepository.java | web-modules/ratpack/src/main/java/com/baeldung/repository/EmployeeRepository.java | package com.baeldung.repository;
import com.baeldung.model.Employee;
import ratpack.exec.Promise;
public interface EmployeeRepository {
Promise<Employee> findEmployeeById(Long id) throws Exception;
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/spring/EmbedRatpackStreamsApp.java | web-modules/ratpack/src/main/java/com/baeldung/spring/EmbedRatpackStreamsApp.java | package com.baeldung.spring;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.baeldung.model.Quote;
import com.baeldung.rxjava.service.QuotesService;
import groovy.util.logging.Slf4j;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import ratpack.func.Action;
import ratpack.handling.Chain;
import ratpack.http.ResponseChunks;
import ratpack.http.Status;
import ratpack.server.ServerConfig;
import ratpack.spring.config.EnableRatpack;
import ratpack.sse.ServerSentEvents;
import ratpack.stream.Streams;
import ratpack.stream.TransformablePublisher;
import ratpack.websocket.WebSockets;
import rx.subscriptions.Subscriptions;
/**
* @author psevestre
*/
@SpringBootApplication
@EnableRatpack
public class EmbedRatpackStreamsApp {
private static final Logger log = LoggerFactory.getLogger(EmbedRatpackStreamsApp.class);
@Autowired
private QuotesService quotesService;
private AtomicLong idSeq = new AtomicLong(0);
@Bean
public ScheduledExecutorService executorService() {
return Executors.newScheduledThreadPool(1);
}
@Bean
public QuotesService quotesService(ScheduledExecutorService executor) {
return new QuotesService(executor);
}
@Bean
public Action<Chain> quotes() {
ServerSentEvents sse = ServerSentEvents.serverSentEvents(quotesService.newTicker(), (evt) -> {
evt
.id(Long.toString(idSeq.incrementAndGet()))
.event("quote")
.data( q -> q.toString());
});
return chain -> chain.get("quotes", ctx -> ctx.render(sse));
}
@Bean
public Action<Chain> quotesWS() {
Publisher<String> pub = Streams.transformable(quotesService.newTicker())
.map(Quote::toString);
return chain -> chain.get("quotes-ws", ctx -> WebSockets.websocketBroadcast(ctx, pub));
}
@Bean
public Action<Chain> uploadFile() {
return chain -> chain.post("upload", ctx -> {
TransformablePublisher<? extends ByteBuf> pub = ctx.getRequest().getBodyStream();
pub.subscribe(new Subscriber<ByteBuf>() {
private Subscription sub;
@Override
public void onSubscribe(Subscription sub) {
this.sub = sub;
sub.request(1);
}
@Override
public void onNext(ByteBuf t) {
try {
int len = t.readableBytes();
log.info("Got {} bytes", len);
// Do something useful with data
// Request next chunk
sub.request(1);
}
finally {
// DO NOT FORGET to RELEASE !
t.release();
}
}
@Override
public void onError(Throwable t) {
ctx.getResponse().status(500);
}
@Override
public void onComplete() {
ctx.getResponse().status(202);
}
});
});
}
@Bean
public Action<Chain> download() {
return chain -> chain.get("download", ctx -> {
ctx.getResponse().sendStream(new RandomBytesPublisher(1024,512));
});
}
@Bean
public Action<Chain> downloadChunks() {
return chain -> chain.get("downloadChunks", ctx -> {
ctx.render(ResponseChunks.bufferChunks("application/octetstream",
new RandomBytesPublisher(1024,512)));
});
}
@Bean
public ServerConfig ratpackServerConfig() {
return ServerConfig
.builder()
.findBaseDir("public")
.build();
}
public static void main(String[] args) {
SpringApplication.run(EmbedRatpackStreamsApp.class, args);
}
public static class RandomBytesPublisher implements Publisher<ByteBuf> {
private int bufCount;
private int bufSize;
private Random rnd = new Random();
RandomBytesPublisher(int bufCount, int bufSize) {
this.bufCount = bufCount;
this.bufSize = bufSize;
}
@Override
public void subscribe(Subscriber<? super ByteBuf> s) {
s.onSubscribe(new Subscription() {
private boolean cancelled = false;
private boolean recurse;
private long requested = 0;
@Override
public void request(long n) {
if ( bufCount == 0 ) {
s.onComplete();
return;
}
requested += n;
if ( recurse ) {
return;
}
recurse = true;
try {
while ( requested-- > 0 && !cancelled && bufCount-- > 0 ) {
byte[] data = new byte[bufSize];
rnd.nextBytes(data);
ByteBuf buf = Unpooled.wrappedBuffer(data);
s.onNext(buf);
}
}
finally {
recurse = false;
}
}
@Override
public void cancel() {
cancelled = true;
}
});
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/spring/Config.java | web-modules/ratpack/src/main/java/com/baeldung/spring/Config.java | package com.baeldung.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
/**
* @author aiet
*/
@Configuration
public class Config {
@Bean
public Content content() {
return () -> "hello baeldung!";
}
@Bean
public ArticleList articles() {
return () -> Arrays.asList("Introduction to Ratpack", "Ratpack Google Guice Integration", "Ratpack Spring Boot Integration");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/spring/EmbedSpringBootApp.java | web-modules/ratpack/src/main/java/com/baeldung/spring/EmbedSpringBootApp.java | package com.baeldung.spring;
import ratpack.server.RatpackServer;
import static ratpack.spring.Spring.spring;
public class EmbedSpringBootApp {
public static void main(String[] args) throws Exception {
RatpackServer.start(server -> server
.registry(spring(Config.class))
.handlers(chain -> chain.get(ctx -> ctx.render(ctx
.get(Content.class)
.body()))));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/spring/EmbedRatpackApp.java | web-modules/ratpack/src/main/java/com/baeldung/spring/EmbedRatpackApp.java | package com.baeldung.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import ratpack.func.Action;
import ratpack.handling.Chain;
import ratpack.server.ServerConfig;
import ratpack.spring.config.EnableRatpack;
/**
* @author aiet
*/
@SpringBootApplication
@EnableRatpack
public class EmbedRatpackApp {
@Autowired private Content content;
@Autowired private ArticleList list;
@Bean
public Action<Chain> hello() {
return chain -> chain.get("hello", ctx -> ctx.render(content.body()));
}
@Bean
public Action<Chain> list() {
return chain -> chain.get("list", ctx -> ctx.render(list
.articles()
.toString()));
}
@Bean
public ServerConfig ratpackServerConfig() {
return ServerConfig
.builder()
.findBaseDir("public")
.build();
}
public static void main(String[] args) {
SpringApplication.run(EmbedRatpackApp.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/spring/Content.java | web-modules/ratpack/src/main/java/com/baeldung/spring/Content.java | package com.baeldung.spring;
/**
* @author aiet
*/
public interface Content {
String body();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/spring/ArticleList.java | web-modules/ratpack/src/main/java/com/baeldung/spring/ArticleList.java | package com.baeldung.spring;
import java.util.List;
/**
* @author aiet
*/
public interface ArticleList {
List<String> articles();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/handler/EmployeeHandler.java | web-modules/ratpack/src/main/java/com/baeldung/handler/EmployeeHandler.java | package com.baeldung.handler;
import com.baeldung.repository.EmployeeRepository;
import com.baeldung.model.Employee;
import ratpack.exec.Promise;
import ratpack.handling.Context;
import ratpack.handling.Handler;
public class EmployeeHandler implements Handler {
@Override
public void handle(Context ctx) throws Exception {
EmployeeRepository repository = ctx.get(EmployeeRepository.class);
Long id = Long.valueOf(ctx.getPathTokens()
.get("id"));
Promise<Employee> employeePromise = repository.findEmployeeById(id);
employeePromise.map(employee -> employee.getName())
.then(name -> ctx.getResponse()
.send(name));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/handler/RedirectHandler.java | web-modules/ratpack/src/main/java/com/baeldung/handler/RedirectHandler.java | package com.baeldung.handler;
import ratpack.exec.Promise;
import ratpack.handling.Context;
import ratpack.handling.Handler;
import ratpack.http.client.HttpClient;
import ratpack.http.client.ReceivedResponse;
import java.net.URI;
public class RedirectHandler implements Handler {
@Override
public void handle(Context ctx) throws Exception {
HttpClient client = ctx.get(HttpClient.class);
URI uri = URI.create("http://localhost:5050/employee/1");
Promise<ReceivedResponse> responsePromise = client.get(uri);
responsePromise.map(response -> response.getBody()
.getText()
.toUpperCase())
.then(responseText -> ctx.getResponse()
.send(responseText));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ratpack/src/main/java/com/baeldung/handler/FooHandler.java | web-modules/ratpack/src/main/java/com/baeldung/handler/FooHandler.java | package com.baeldung.handler;
import ratpack.handling.Context;
import ratpack.handling.Handler;
public class FooHandler implements Handler {
@Override
public void handle(Context ctx) throws Exception {
ctx.getResponse()
.send("Hello Foo!");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ninja/src/test/java/controllers/ApiControllerMockUnitTest.java | web-modules/ninja/src/test/java/controllers/ApiControllerMockUnitTest.java | package controllers;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import ninja.NinjaTest;
import ninja.Result;
import services.UserService;
public class ApiControllerMockUnitTest extends NinjaTest {
private UserService userService;
private ApplicationController applicationController;
@Before
public void setupTest() {
userService = this.ninjaTestServer.getInjector().getInstance(UserService.class);
applicationController = new ApplicationController();
applicationController.userService = userService;
}
@Test
public void testThatGetUserJson() {
Result result = applicationController.userJson();
System.out.println(result.getRenderable());
assertEquals(userService.getUserMap().toString(), result.getRenderable().toString());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterUnitTest.java | web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterUnitTest.java | package controllers;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import org.doctester.testbrowser.Request;
import org.doctester.testbrowser.Response;
import org.junit.Test;
import ninja.NinjaDocTester;
public class ApiControllerDocTesterUnitTest extends NinjaDocTester {
String URL_INDEX = "/";
String URL_HELLO = "/hello";
@Test
public void testGetIndex() {
Response response = makeRequest(Request.GET().url(testServerUrl().path(URL_INDEX)));
assertThat(response.payload, containsString("Hello, welcome to Ninja Framework!"));
}
@Test
public void testGetHello() {
Response response = makeRequest(Request.GET().url(testServerUrl().path(URL_HELLO)));
assertThat(response.payload, containsString("Bonjour, bienvenue dans Ninja Framework!"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ninja/src/main/java/services/UserService.java | web-modules/ninja/src/main/java/services/UserService.java | package services;
import java.util.HashMap;
public interface UserService {
HashMap<String, String> getUserMap();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ninja/src/main/java/services/UserServiceImpl.java | web-modules/ninja/src/main/java/services/UserServiceImpl.java | package services;
import java.util.HashMap;
public class UserServiceImpl implements UserService {
@Override
public HashMap<String, String> getUserMap() {
HashMap<String, String> userMap = new HashMap<>();
userMap.put("name", "Norman Lewis");
userMap.put("email", "norman@email.com");
return userMap;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ninja/src/main/java/controllers/ApplicationController.java | web-modules/ninja/src/main/java/controllers/ApplicationController.java | package controllers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.persist.Transactional;
import models.User;
import ninja.Context;
import ninja.Result;
import ninja.Results;
import ninja.i18n.Lang;
import ninja.i18n.Messages;
import ninja.jpa.UnitOfWork;
import ninja.session.FlashScope;
import ninja.validation.JSR303Validation;
import ninja.validation.Validation;
import services.UserService;
@Singleton
public class ApplicationController {
@Inject
Lang lang;
@Inject
Messages msg;
private static Log logger = LogFactory.getLog(ApplicationController.class);
@Inject
Provider<EntityManager> entityManagerProvider;
@Inject
UserService userService;
public Result index() {
return Results.html();
}
public Result userJson() {
HashMap<String, String> userMap = userService.getUserMap();
logger.info(userMap);
return Results.json().render(userMap);
}
public Result helloWorld(Context context) {
Optional<String> language = Optional.of("fr");
String helloMsg = msg.get("helloMsg", language).get();
return Results.text().render(helloMsg);
}
public Result showFlashMsg(FlashScope flashScope) {
flashScope.success("Success message");
flashScope.error("Error message");
return Results.redirect("/home");
}
public Result home() {
return Results.html();
}
public Result createUser() {
return Results.html();
}
@UnitOfWork
public Result fetchUsers() {
EntityManager entityManager = entityManagerProvider.get();
Query q = entityManager.createQuery("SELECT x FROM User x");
List<User> users = (List<User>) q.getResultList();
return Results.json().render(users);
}
@Transactional
public Result insertUser(FlashScope flashScope, @JSR303Validation User user, Validation validation) {
logger.info("Inserting User : " +user);
if (validation.getViolations().size() > 0) {
flashScope.error("Validation Error: User can't be created");
} else {
EntityManager entityManager = entityManagerProvider.get();
entityManager.persist(user);
entityManager.flush();
flashScope.success("User '" + user + "' is created successfully");
}
return Results.redirect("/home");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ninja/src/main/java/models/User.java | web-modules/ninja/src/main/java/models/User.java | package models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Long id;
@NotNull
public String firstName;
public String email;
public String toString() {
return firstName + " : " + email;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ninja/src/main/java/conf/Routes.java | web-modules/ninja/src/main/java/conf/Routes.java | package conf;
import ninja.AssetsController;
import ninja.Router;
import ninja.application.ApplicationRoutes;
import controllers.ApplicationController;
public class Routes implements ApplicationRoutes {
@Override
public void init(Router router) {
router.GET().route("/index").with(ApplicationController::index);
router.GET().route("/home").with(ApplicationController::home);
router.GET().route("/hello").with(ApplicationController::helloWorld);
router.GET().route("/userJson").with(ApplicationController::userJson);
router.GET().route("/createUser").with(ApplicationController::createUser);
router.GET().route("/flash").with(ApplicationController::showFlashMsg);
router.GET().route("/users").with(ApplicationController::fetchUsers);
router.POST().route("/users").with(ApplicationController::insertUser);
//Assets
router.GET().route("/assets/webjars/{fileName: .*}").with(AssetsController::serveWebJars);
router.GET().route("/assets/{fileName: .*}").with(AssetsController::serveStatic);
//Index
router.GET().route("/.*").with(ApplicationController::index);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ninja/src/main/java/conf/Filters.java | web-modules/ninja/src/main/java/conf/Filters.java | package conf;
import java.util.List;
import ninja.Filter;
public class Filters implements ninja.application.ApplicationFilters {
@Override
public void addFilters(List<Class<? extends Filter>> filters) {
// Add your application - wide filters here
// filters.add(MyFilter.class);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/ninja/src/main/java/conf/Module.java | web-modules/ninja/src/main/java/conf/Module.java | package conf;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import services.UserService;
import services.UserServiceImpl;
@Singleton
public class Module extends AbstractModule {
protected void configure() {
bind(UserService.class).to(UserServiceImpl.class);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/java-takes/src/test/java/com/baeldung/takes/TakesAppIntegrationTest.java | web-modules/java-takes/src/test/java/com/baeldung/takes/TakesAppIntegrationTest.java | package com.baeldung.takes;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.takes.http.FtRemote;
public class TakesAppIntegrationTest {
@Test
public void givenTake_whenRunRemoteServer_thenRespond() throws Exception {
new FtRemote(new TakesContact()).exec(
new FtRemote.Script() {
@Override
public void exec(final URI home) throws IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(new HttpGet(home));
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
assertEquals(200, statusCode);
assertEquals("Contact us at https://www.baeldung.com", result);
}
});
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/java-takes/src/test/java/com/baeldung/takes/TakesContactUnitTest.java | web-modules/java-takes/src/test/java/com/baeldung/takes/TakesContactUnitTest.java | package com.baeldung.takes;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.takes.rq.RqFake;
import org.takes.rs.RsPrint;
public class TakesContactUnitTest {
@Test
public void givenTake_whenInvokeActMethod_thenRespond() throws Exception {
final String resp = new RsPrint(new TakesContact().act(new RqFake())).printBody();
assertEquals("Contact us at https://www.baeldung.com", resp);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/java-takes/src/main/java/com/baeldung/takes/TakesApp.java | web-modules/java-takes/src/main/java/com/baeldung/takes/TakesApp.java | package com.baeldung.takes;
import java.io.IOException;
import java.sql.SQLException;
import org.takes.Response;
import org.takes.facets.fallback.Fallback;
import org.takes.facets.fallback.FbChain;
import org.takes.facets.fallback.FbStatus;
import org.takes.facets.fallback.RqFallback;
import org.takes.facets.fallback.TkFallback;
import org.takes.facets.fork.FkRegex;
import org.takes.facets.fork.TkFork;
import org.takes.http.Exit;
import org.takes.http.FtBasic;
import org.takes.misc.Opt;
import org.takes.rs.RsText;
public final class TakesApp {
public static void main(final String... args) throws IOException, SQLException {
new FtBasic(
new TkFallback(
new TkFork(
new FkRegex("/", new TakesHelloWorld()),
new FkRegex("/index", new TakesIndex()),
new FkRegex("/contact", new TakesContact())
),
new FbChain(
new FbStatus(404, new RsText("Page Not Found")),
new FbStatus(405, new RsText("Method Not Allowed")),
new Fallback() {
@Override
public Opt<Response> route(final RqFallback req) {
return new Opt.Single<Response>(new RsText(req.throwable().getMessage()));
}
})
), 6060
).start(Exit.NEVER);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/java-takes/src/main/java/com/baeldung/takes/TakesContact.java | web-modules/java-takes/src/main/java/com/baeldung/takes/TakesContact.java | package com.baeldung.takes;
import java.io.IOException;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.rs.RsWithBody;
import org.takes.rs.RsWithStatus;
import org.takes.rs.RsWithType;
public final class TakesContact implements Take {
@Override
public Response act(Request req) throws IOException {
return new RsWithStatus(
new RsWithType(
new RsWithBody("Contact us at https://www.baeldung.com"),
"text/html"), 200);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/java-takes/src/main/java/com/baeldung/takes/TakesIndex.java | web-modules/java-takes/src/main/java/com/baeldung/takes/TakesIndex.java | package com.baeldung.takes;
import java.io.IOException;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.rq.form.RqFormSmart;
import org.takes.rs.RsHtml;
import org.takes.rs.RsVelocity;
public final class TakesIndex implements Take {
@Override
public Response act(final Request req) throws IOException {
RqFormSmart form = new RqFormSmart(req);
String username = form.single("username");
return new RsHtml(
new RsVelocity(this.getClass().getResource("/templates/index.vm"),
new RsVelocity.Pair("username", username))
);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/java-takes/src/main/java/com/baeldung/takes/TakesHelloWorld.java | web-modules/java-takes/src/main/java/com/baeldung/takes/TakesHelloWorld.java | package com.baeldung.takes;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.rs.RsText;
public class TakesHelloWorld implements Take {
@Override
public Response act(final Request request) {
return new RsText("Hello, world!");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/services/QaModule.java | web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/services/QaModule.java | package com.baeldung.tapestry.services;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.commons.MappedConfiguration;
import org.apache.tapestry5.ioc.ServiceBinder;
/**
* This module is automatically included as part of the Tapestry IoC Registry if <em>tapestry.execution-mode</em>
* includes <code>qa</code> ("quality assurance").
*/
public class QaModule
{
public static void bind(ServiceBinder binder)
{
// Bind any services needed by the QA team to produce their reports
// binder.bind(MyServiceMonitorInterface.class, MyServiceMonitorImpl.class);
}
public static void contributeApplicationDefaults(
MappedConfiguration<String, Object> configuration)
{
// The factory default is true but during the early stages of an application
// overriding to false is a good idea. In addition, this is often overridden
// on the command line as -Dtapestry.production-mode=false
configuration.add(SymbolConstants.PRODUCTION_MODE, false);
// The application version number is incorprated into URLs for some
// assets. Web browsers will cache assets because of the far future expires
// header. If existing assets are changed, the version number should also
// change, to force the browser to download new versions.
configuration.add(SymbolConstants.APPLICATION_VERSION, "0.0.1-SNAPSHOT-QA");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/services/AppModule.java | web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/services/AppModule.java | package com.baeldung.tapestry.services;
import java.io.IOException;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.commons.MappedConfiguration;
import org.apache.tapestry5.commons.OrderedConfiguration;
import org.apache.tapestry5.http.services.Request;
import org.apache.tapestry5.http.services.RequestFilter;
import org.apache.tapestry5.http.services.RequestHandler;
import org.apache.tapestry5.http.services.Response;
import org.apache.tapestry5.ioc.ServiceBinder;
import org.apache.tapestry5.ioc.annotations.Contribute;
import org.apache.tapestry5.ioc.annotations.Local;
import org.apache.tapestry5.ioc.services.ApplicationDefaults;
import org.apache.tapestry5.ioc.services.SymbolProvider;
import org.slf4j.Logger;
/**
* This module is automatically included as part of the Tapestry IoC Registry, it's a good place to
* configure and extend Tapestry, or to place your own service definitions.
*/
public class AppModule {
public static void bind(ServiceBinder binder) {
// binder.bind(MyServiceInterface.class, MyServiceImpl.class);
// Make bind() calls on the binder object to define most IoC services.
// Use service builder methods (example below) when the implementation
// is provided inline, or requires more initialization than simply
// invoking the constructor.
}
public static void contributeFactoryDefaults(
MappedConfiguration<String, Object> configuration) {
// The values defined here (as factory default overrides) are themselves
// overridden with application defaults by DevelopmentModule and QaModule.
// The application version is primarily useful as it appears in
// any exception reports (HTML or textual).
configuration.override(SymbolConstants.APPLICATION_VERSION, "0.0.1-SNAPSHOT");
// This is something that should be removed when going to production, but is useful
// in the early stages of development.
configuration.override(SymbolConstants.PRODUCTION_MODE, false);
}
public static void contributeApplicationDefaults(
MappedConfiguration<String, Object> configuration) {
// Contributions to ApplicationDefaults will override any contributions to
// FactoryDefaults (with the same key). Here we're restricting the supported
// locales to just "en" (English). As you add localised message catalogs and other assets,
// you can extend this list of locales (it's a comma separated series of locale names;
// the first locale name is the default when there's no reasonable match).
configuration.add(SymbolConstants.SUPPORTED_LOCALES, "en");
// You should change the passphrase immediately; the HMAC passphrase is used to secure
// the hidden field data stored in forms to encrypt and digitally sign client-side data.
configuration.add(SymbolConstants.HMAC_PASSPHRASE, "change this immediately");
}
/**
* Use annotation or method naming convention: <code>contributeApplicationDefaults</code>
*/
@Contribute(SymbolProvider.class)
@ApplicationDefaults
public static void setupEnvironment(MappedConfiguration<String, Object> configuration) {
// Support for jQuery is new in Tapestry 5.4 and will become the only supported
// option in 5.5.
configuration.add(SymbolConstants.JAVASCRIPT_INFRASTRUCTURE_PROVIDER, "jquery");
configuration.add(SymbolConstants.BOOTSTRAP_ROOT, "context:mybootstrap");
}
/**
* This is a service definition, the service will be named "TimingFilter". The interface,
* RequestFilter, is used within the RequestHandler service pipeline, which is built from the
* RequestHandler service configuration. Tapestry IoC is responsible for passing in an
* appropriate Logger instance. Requests for static resources are handled at a higher level, so
* this filter will only be invoked for Tapestry related requests.
*
*
* Service builder methods are useful when the implementation is inline as an inner class
* (as here) or require some other kind of special initialization. In most cases,
* use the static bind() method instead.
*
*
* If this method was named "build", then the service id would be taken from the
* service interface and would be "RequestFilter". Since Tapestry already defines
* a service named "RequestFilter" we use an explicit service id that we can reference
* inside the contribution method.
*/
public RequestFilter buildTimingFilter(final Logger log) {
return new RequestFilter() {
public boolean service(Request request, Response response, RequestHandler handler)
throws IOException {
long startTime = System.currentTimeMillis();
try {
// The responsibility of a filter is to invoke the corresponding method
// in the handler. When you chain multiple filters together, each filter
// received a handler that is a bridge to the next filter.
return handler.service(request, response);
} finally {
long elapsed = System.currentTimeMillis() - startTime;
log.info("Request time: {} ms", elapsed);
}
}
};
}
/**
* This is a contribution to the RequestHandler service configuration. This is how we extend
* Tapestry using the timing filter. A common use for this kind of filter is transaction
* management or security. The @Local annotation selects the desired service by type, but only
* from the same module. Without @Local, there would be an error due to the other service(s)
* that implement RequestFilter (defined in other modules).
*/
@Contribute(RequestHandler.class)
public void addTimingFilter(OrderedConfiguration<RequestFilter> configuration, @Local RequestFilter filter) {
// Each contribution to an ordered configuration has a name, When necessary, you may
// set constraints to precisely control the invocation order of the contributed filter
// within the pipeline.
configuration.add("Timing", filter);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/services/DevelopmentModule.java | web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/services/DevelopmentModule.java | package com.baeldung.tapestry.services;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.commons.MappedConfiguration;
/**
* This module is automatically included as part of the Tapestry IoC Registry if <em>tapestry.execution-mode</em>
* includes <code>development</code>.
*/
public class DevelopmentModule {
public static void contributeApplicationDefaults(
MappedConfiguration<String, Object> configuration) {
// The factory default is true but during the early stages of an application
// overriding to false is a good idea. In addition, this is often overridden
// on the command line as -Dtapestry.production-mode=false
configuration.add(SymbolConstants.PRODUCTION_MODE, false);
// The application version number is incorprated into URLs for some
// assets. Web browsers will cache assets because of the far future expires
// header. If existing assets are changed, the version number should also
// change, to force the browser to download new versions.
configuration.add(SymbolConstants.APPLICATION_VERSION, "0.0.1-SNAPSHOT-DEV");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/pages/Error404.java | web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/pages/Error404.java | package com.baeldung.tapestry.pages;
public class Error404 {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/pages/Login.java | web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/pages/Login.java | package com.baeldung.tapestry.pages;
import org.apache.tapestry5.alerts.AlertManager;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.slf4j.Logger;
public class Login {
@Inject
private Logger logger;
@Inject
private AlertManager alertManager;
@InjectComponent
private Form login;
@Property
private String email;
@Property
private String password;
void onValidateFromLogin() {
if(email == null || password == null) {
alertManager.error("Email/Password is null");
login.recordError("Validation failed");
}
}
Object onSuccessFromLogin() {
alertManager.success("Welcome! Login Successful");
return Home.class;
}
void onFailureFromLogin() {
alertManager.error("Please try again with correct credentials");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/pages/Home.java | web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/pages/Home.java | package com.baeldung.tapestry.pages;
import java.util.Date;
import org.apache.tapestry5.Block;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.ajax.AjaxResponseRenderer;
import org.slf4j.Logger;
public class Home {
@Property
private String appName = "apache-tapestry";
public Date getCurrentTime() {
return new Date();
}
@Inject
private Logger logger;
@Inject
private AjaxResponseRenderer ajaxResponseRenderer;
@Inject
private Block ajaxBlock;
@Log
void onCallAjax() {
logger.info("Ajax call");
ajaxResponseRenderer.addRender("ajaxZone", ajaxBlock);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/pages/Index.java | web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/pages/Index.java | package com.baeldung.tapestry.pages;
import org.apache.tapestry5.Block;
import org.apache.tapestry5.EventContext;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.HttpError;
import org.apache.tapestry5.services.ajax.AjaxResponseRenderer;
import org.slf4j.Logger;
import java.util.Date;
/**
* Start page of application apache-tapestry.
*/
public class Index {
@Inject
private Logger logger;
@Inject
private AjaxResponseRenderer ajaxResponseRenderer;
@Property
@Inject
@Symbol(SymbolConstants.TAPESTRY_VERSION)
private String tapestryVersion;
@Inject
private Block block;
// Handle call with an unwanted context
Object onActivate(EventContext eventContext) {
return eventContext.getCount() > 0 ?
new HttpError(404, "Resource not found") :
null;
}
@Log
void onComplete() {
logger.info("Complete call on Index page");
}
@Log
void onAjax() {
logger.info("Ajax call on Index page");
ajaxResponseRenderer.addRender("middlezone", block);
}
public Date getCurrentTime() {
return new Date();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/components/Layout.java | web-modules/apache-tapestry/src/main/java/com/baeldung/tapestry/components/Layout.java | package com.baeldung.tapestry.components;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
/**
* Layout component for pages of application.
*/
public class Layout {
@Property
@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
private String title;
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.