use of org.atmosphere.runtime.AtmosphereRequest in project atmosphere by Atmosphere.
the class CorsInterceptor method inspect.
@Override
public Action inspect(AtmosphereResource r) {
if (Utils.webSocketMessage(r))
return Action.CONTINUE;
if (!enableAccessControl)
return Action.CONTINUE;
AtmosphereRequest req = r.getRequest();
AtmosphereResponse res = r.getResponse();
if (req.getHeader("Origin") != null && res.getHeader("Access-Control-Allow-Origin") == null) {
res.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
res.addHeader("Access-Control-Expose-Headers", EXPOSE_HEADERS);
res.setHeader("Access-Control-Allow-Credentials", "true");
}
if ("OPTIONS".equals(req.getMethod())) {
res.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST");
res.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, AuthToken, X-Atmosphere-Framework, X-Requested-With, " + EXPOSE_HEADERS + ", X-Atmosphere-Transport, X-Atmosphere-TrackMessageSize, X-atmo-protocol");
res.setHeader("Access-Control-Max-Age", "-1");
return Action.SKIP_ATMOSPHEREHANDLER;
}
return Action.CONTINUE;
}
use of org.atmosphere.runtime.AtmosphereRequest in project atmosphere by Atmosphere.
the class JSONPAtmosphereInterceptor method inspect.
@Override
public Action inspect(AtmosphereResource r) {
if (Utils.webSocketMessage(r))
return Action.CONTINUE;
final AtmosphereRequest request = r.getRequest();
final AtmosphereResponse response = r.getResponse();
// Shield from Broken server
String uri = request.getRequestURI() == null ? "" : request.getRequestURI();
if (r.transport().equals(AtmosphereResource.TRANSPORT.JSONP) || uri.indexOf("jsonp") != -1) {
super.inspect(r);
if (uri.indexOf("jsonp") != -1) {
startChunk = "(\"";
endChunk = "\");\r\n\r\n";
}
AsyncIOWriter writer = response.getAsyncIOWriter();
if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) {
AtmosphereInterceptorWriter.class.cast(writer).interceptor(new AsyncIOInterceptorAdapter() {
String callbackName() {
String callback = request.getParameter(HeaderConfig.JSONP_CALLBACK_NAME);
if (callback == null) {
// Look for extension
String jsonp = (String) config.properties().get(HeaderConfig.JSONP_CALLBACK_NAME);
if (jsonp != null) {
callback = request.getParameter(jsonp);
}
}
return callback;
}
@Override
public void prePayload(AtmosphereResponse response, byte[] data, int offset, int length) {
String callbackName = callbackName();
response.write(callbackName + startChunk);
}
@Override
public byte[] transformPayload(AtmosphereResponse response, byte[] responseDraft, byte[] data) throws IOException {
String charEncoding = response.getCharacterEncoding() == null ? "UTF-8" : response.getCharacterEncoding();
return escapeForJavaScript(new String(responseDraft, charEncoding)).getBytes(charEncoding);
}
@Override
public void postPayload(AtmosphereResponse response, byte[] data, int offset, int length) {
response.write(endChunk, true);
}
});
} else {
logger.warn("Unable to apply {}. Your AsyncIOWriter must implement {}", getClass().getName(), AtmosphereInterceptorWriter.class.getName());
}
}
return Action.CONTINUE;
}
use of org.atmosphere.runtime.AtmosphereRequest in project atmosphere by Atmosphere.
the class JavaScriptProtocol method inspect.
@Override
public Action inspect(final AtmosphereResource ar) {
if (Utils.webSocketMessage(ar))
return Action.CONTINUE;
final AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(ar);
final AtmosphereRequest request = r.getRequest(false);
final AtmosphereResponse response = r.getResponse(false);
String uuid = request.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID);
String handshakeUUID = request.getHeader(HeaderConfig.X_ATMO_PROTOCOL);
if (uuid != null && uuid.equals("0") && handshakeUUID != null) {
if (enforceAtmosphereVersion) {
String javascriptVersion = request.getHeader(HeaderConfig.X_ATMOSPHERE_FRAMEWORK);
int version = 0;
if (javascriptVersion != null) {
version = parseVersion(javascriptVersion.split("-")[0]);
}
if (version < 221) {
logger.error("Invalid Atmosphere Version {}", javascriptVersion);
response.setStatus(501);
response.addHeader(X_ATMOSPHERE_ERROR, "Atmosphere Protocol version not supported.");
try {
response.flushBuffer();
} catch (IOException e) {
}
return Action.CANCELLED;
}
}
request.header(HeaderConfig.X_ATMO_PROTOCOL, null);
// Extract heartbeat data
int heartbeatInterval = 0;
String heartbeatData = "";
for (final AtmosphereInterceptor interceptor : framework.interceptors()) {
if (HeartbeatInterceptor.class.isAssignableFrom(interceptor.getClass())) {
final HeartbeatInterceptor heartbeatInterceptor = HeartbeatInterceptor.class.cast(interceptor);
heartbeatInterval = heartbeatInterceptor.clientHeartbeatFrequencyInSeconds() * 1000;
heartbeatData = new String(heartbeatInterceptor.getPaddingBytes());
break;
}
}
String message;
if (enforceAtmosphereVersion) {
// UUID since 1.0.10
message = new StringBuilder(r.uuid()).append(wsDelimiter).append(heartbeatInterval).append(wsDelimiter).append(heartbeatData).append(wsDelimiter).toString();
} else {
// UUID since 1.0.10
message = r.uuid();
}
// https://github.com/Atmosphere/atmosphere/issues/993
final AtomicReference<String> protocolMessage = new AtomicReference<String>(message);
if (r.getBroadcaster().getBroadcasterConfig().hasFilters()) {
for (BroadcastFilter bf : r.getBroadcaster().getBroadcasterConfig().filters()) {
if (TrackMessageSizeFilter.class.isAssignableFrom(bf.getClass())) {
protocolMessage.set((String) f.filter(r.getBroadcaster().getID(), r, protocolMessage.get(), protocolMessage.get()).message());
break;
}
}
}
if (!Utils.resumableTransport(r.transport())) {
OnSuspend a = new OnSuspend() {
@Override
public void onSuspend(AtmosphereResourceEvent event) {
response.write(protocolMessage.get());
try {
response.flushBuffer();
} catch (IOException e) {
logger.trace("", e);
}
r.removeEventListener(this);
}
};
// Pass the information to Servlet Based Framework
request.setAttribute(CALLBACK_JAVASCRIPT_PROTOCOL, a);
r.addEventListener(a);
} else {
response.write(protocolMessage.get());
}
// We don't need to reconnect here
if (r.transport() == AtmosphereResource.TRANSPORT.WEBSOCKET || r.transport() == AtmosphereResource.TRANSPORT.STREAMING || r.transport() == AtmosphereResource.TRANSPORT.SSE) {
return Action.CONTINUE;
} else {
return Action.CANCELLED;
}
}
return Action.CONTINUE;
}
use of org.atmosphere.runtime.AtmosphereRequest in project atmosphere by Atmosphere.
the class OnDisconnectInterceptor method inspect.
@Override
public Action inspect(final AtmosphereResource r) {
if (Utils.webSocketMessage(r))
return Action.CONTINUE;
AtmosphereRequest request = AtmosphereResourceImpl.class.cast(r).getRequest(false);
String uuid = r.uuid();
if (closeMessage(request)) {
AtmosphereResource ss = config.resourcesFactory().find(uuid);
if (ss == null) {
logger.debug("No Suspended Connection found for {}. Using the AtmosphereResource associated with the close message", uuid);
ss = r;
}
if (ss == null) {
logger.debug("Was unable to execute onDisconnect on {}", r.uuid());
return Action.CONTINUE;
}
logger.debug("AtmosphereResource {} disconnected", uuid);
// Block websocket closing detection
AtmosphereResourceEventImpl.class.cast(ss.getAtmosphereResourceEvent()).isClosedByClient(true);
p.completeLifecycle(ss, false);
return Action.CANCELLED;
}
return Action.CONTINUE;
}
use of org.atmosphere.runtime.AtmosphereRequest in project atmosphere by Atmosphere.
the class SimpleRestInterceptor method inspect.
@Override
public Action inspect(final AtmosphereResource r) {
if (AtmosphereResource.TRANSPORT.WEBSOCKET != r.transport() && AtmosphereResource.TRANSPORT.SSE != r.transport() && AtmosphereResource.TRANSPORT.POLLING != r.transport()) {
LOG.debug("Skipping for non websocket request");
return Action.CONTINUE;
}
if (AtmosphereResource.TRANSPORT.POLLING == r.transport()) {
final String saruuid = (String) r.getRequest().getAttribute(ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID);
final AtmosphereResponse suspendedResponse = suspendedResponses.get(saruuid);
LOG.debug("Attaching a proxy writer to suspended response");
r.getResponse().asyncIOWriter(new AtmosphereInterceptorWriter() {
@Override
public AsyncIOWriter write(AtmosphereResponse r, String data) throws IOException {
suspendedResponse.write(data);
suspendedResponse.flushBuffer();
return this;
}
@Override
public AsyncIOWriter write(AtmosphereResponse r, byte[] data) throws IOException {
suspendedResponse.write(data);
suspendedResponse.flushBuffer();
return this;
}
@Override
public AsyncIOWriter write(AtmosphereResponse r, byte[] data, int offset, int length) throws IOException {
suspendedResponse.write(data, offset, length);
suspendedResponse.flushBuffer();
return this;
}
@Override
public void close(AtmosphereResponse response) throws IOException {
}
});
// REVISIT we need to keep this response's asyncwriter alive so that data can be written to the
// suspended response, but investigate if there is a better alternative.
r.getResponse().destroyable(false);
return Action.CONTINUE;
}
r.addEventListener(new AtmosphereResourceEventListenerAdapter() {
@Override
public void onSuspend(AtmosphereResourceEvent event) {
final String srid = (String) event.getResource().getRequest().getAttribute(ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID);
LOG.debug("Registrering suspended resource: {}", srid);
suspendedResponses.put(srid, event.getResource().getResponse());
AsyncIOWriter writer = event.getResource().getResponse().getAsyncIOWriter();
if (writer == null) {
writer = new AtmosphereInterceptorWriter();
r.getResponse().asyncIOWriter(writer);
}
if (writer instanceof AtmosphereInterceptorWriter) {
((AtmosphereInterceptorWriter) writer).interceptor(interceptor);
}
}
@Override
public void onDisconnect(AtmosphereResourceEvent event) {
super.onDisconnect(event);
final String srid = (String) event.getResource().getRequest().getAttribute(ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID);
LOG.debug("Unregistrering suspended resource: {}", srid);
suspendedResponses.remove(srid);
}
});
AtmosphereRequest request = r.getRequest();
if (request.getAttribute(REQUEST_DISPATCHED) == null) {
try {
//REVISIT use a more efficient approach for the detached mode (i.e.,avoid reading the message into a string)
// read the message entity and dispatch a service call
String body = IOUtils.readEntirelyAsString(r).toString();
LOG.debug("Request message: '{}'", body);
if (body.length() == 0) {
//TODO we might want to move this heartbeat scheduling after the handshake phase (if that is added)
if ((AtmosphereResource.TRANSPORT.WEBSOCKET == r.transport() || AtmosphereResource.TRANSPORT.SSE == r.transport()) && request.getAttribute(HEARTBEAT_SCHEDULED) == null) {
r.suspend();
scheduleHeartbeat(r);
request.setAttribute(HEARTBEAT_SCHEDULED, "true");
return Action.SUSPEND;
}
return Action.CANCELLED;
}
AtmosphereRequest ar = createAtmosphereRequest(request, body);
if (ar == null) {
return Action.CANCELLED;
}
AtmosphereResponse response = r.getResponse();
ar.localAttributes().put(REQUEST_DISPATCHED, "true");
request.removeAttribute(FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE);
response.request(ar);
attachWriter(r);
Action action = r.getAtmosphereConfig().framework().doCometSupport(ar, response);
if (action.type() == Action.TYPE.SUSPEND) {
ar.destroyable(false);
response.destroyable(false);
}
return Action.CANCELLED;
} catch (IOException | ServletException e) {
LOG.error("Failed to process", e);
}
}
return Action.CONTINUE;
}
Aggregations