org.osgl.http.H Java Examples

The following examples show how to use org.osgl.http.H. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ActionContext.java    From actframework with Apache License 2.0 6 votes vote down vote up
public ActionContext applyContentSecurityPolicy() {
    RequestHandler handler = handler();
    if (null != handler) {
        boolean disableCSP = handler.disableContentSecurityPolicy();
        if (disableCSP) {
            return this;
        }
        String csp = handler.contentSecurityPolicy();
        if (S.notBlank(csp)) {
            H.Response resp = resp();
            resp.addHeaderIfNotAdded(CONTENT_SECURITY_POLICY, csp);
        }
    }
    applyGlobalCspSetting();
    return this;
}
 
Example #2
Source File: DefaultSessionCodec.java    From actframework with Apache License 2.0 6 votes vote down vote up
private String dissolveIntoCookieContent(H.KV<?> kv, boolean isSession) {
    S.Buffer sb = S.buffer();
    int i = 0;
    for (Map.Entry<String, String> entry : kv.entrySet()) {
        if (i > 0) {
            sb.append("\u0000");
        }
        String k = entry.getKey();
        String v = entry.getValue();
        sb.append(k);
        sb.append("\u0001");
        sb.append(v);
        i++;
    }
    String data = sb.toString();
    if (isSession) {
        String sign = crypto.sign(data);
        data = S.concat(sign, "-", data);
        if (encryptSession) {
            data = crypto.encrypt(data);
        }
    }
    data = Codec.encodeUrl(data, Charsets.UTF_8);
    return data;
}
 
Example #3
Source File: JobContext.java    From actframework with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize current thread's JobContext using specified copy
 * @param origin the original job context
 */
static void loadFromOrigin(JobContext origin) {
    if (origin.bag_.isEmpty()) {
        return;
    }
    ActContext<?> actContext = ActContext.Base.currentContext();
    if (null != actContext) {
        Locale locale = (Locale) origin.bag_.get("locale");
        if (null != locale) {
            actContext.locale(locale);
        }
        H.Session session = (H.Session) origin.bag_.get("session");
        if (null != session) {
            actContext.attribute("__session", session);
        }
    }
}
 
Example #4
Source File: JsonWebTokenSessionCodec.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Override
public String encodeSession(H.Session session) {
    if (null == session) {
        return null;
    }
    boolean sessionChanged = session.changed();
    if (!sessionChanged && (session.empty() || !sessionWillExpire)) {
        // Nothing changed and no cookie-expire or empty, consequently send nothing back.
        return null;
    }
    session.id(); // ensure session ID is generated
    if (sessionWillExpire && !session.contains(KEY_EXPIRATION)) {
        // session get cleared before
        session.put(KEY_EXPIRATION, $.ms() + ttlInMillis);
    }
    return populateToken(jwt.newToken(), session).toString(jwt);
}
 
Example #5
Source File: JsonWebTokenSessionCodec.java    From actframework with Apache License 2.0 6 votes vote down vote up
private void resolveFromJwtToken(H.KV<?> state, String tokenString, boolean isSession) {
    JWT.Token token = jwt.deserialize(tokenString);
    if (null == token) {
        return;
    }
    for (Map.Entry<String, Object> entry : token.payloads().entrySet()) {
        String key = entry.getKey();
        Object val = entry.getValue();
        if (isSession && JWT.ID.equals(key)) {
            state.put(H.Session.KEY_ID, val);
        } else if (ISSUER.key().equals(key)) {
            // ignore
        } else if (EXPIRES_AT.key().equals(key)) {
            Number number = (Number) val;
            long exp = number.longValue() * 1000;
            state.put(H.Session.KEY_EXPIRATION, exp);
        } else {
            state.put(key, val);
        }
    }
}
 
Example #6
Source File: SecureTicketHandler.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(ActionContext context) {
    Object ticket = secureTicketCodec.createTicket(context.session());
    H.Format accept = context.accept();
    H.Response resp = context.prepareRespForResultEvaluation();
    resp.contentType(accept.contentType());
    String content;
    if (H.Format.JSON.isSameTypeWith(accept)) {
        Map<String, Object> map = C.Map("ticket", ticket);
        content = JSON.toJSONString(map);
    } else if (H.Format.XML.isSameTypeWith(accept)) {
        content = S.concat("<?xml version=\"1.0\" ?><ticket>", ticket.toString(), "</ticket>");
    } else {
        content = ticket.toString();
    }
    resp.writeContent(content);
}
 
Example #7
Source File: CustomBinderTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Test
public void normalCaseWithPojoBind() throws IOException {
    Address address = new Address(Country.ZH, SiChuan);
    url("/bind/custom/pojo")
            .post("address.country", address.country, "address.state", address.state)
            .accept(H.Format.JSON);
    String s = resp().body().string();
    eq(JSON.toJSONString(address), s);
}
 
Example #8
Source File: CookieSessionMapper.java    From actframework with Apache License 2.0 5 votes vote down vote up
private H.Cookie createCookie(String name, String value) {
    H.Cookie cookie = new H.Cookie(name, value);
    cookie.path("/");
    cookie.domain(cookieDomain);
    cookie.httpOnly(true);
    cookie.secure(sessionSecure);
    if (sessionWillExpire && persistentSession) {
        cookie.maxAge(ttl);
    }
    return cookie;
}
 
Example #9
Source File: C1.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Action(value = "/doIt", methods = {H.Method.POST, H.Method.GET})
public static void doIt(@Param("acc_id") String id, ActionContext ctx, @Bind(EmailBinder.class) String email,  boolean b) {
    int i = 0, j = 1;
    if (b) {
        ok();
    }
    renderStatic("", i, j, b, id, email);
}
 
Example #10
Source File: RouterTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
private void _regExtTests(String pattern) {
    router.addMapping(GET, "/int/" + pattern, controller);
    H.Request req = Mockito.mock(H.Request.class);
    when(ctx.req()).thenReturn(req);

    when(req.path()).thenReturn("/int/33");
    RequestHandler handler = router.getInvoker(GET, "/int/33", ctx);
    same(controller, handler);

    verify(ctx).urlPathParam("n", "33");
}
 
Example #11
Source File: CSRFProtector.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public String generateToken(H.Session session, App app) {
    String id = session.id();
    String username = session.get(app.config().sessionKeyUsername());
    String payload = S.concat(id, username);
    String sign = app.sign(payload);
    return S.concat(payload, "-", sign);
}
 
Example #12
Source File: DefaultSessionCodec.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public H.Session decodeSession(String encodedSession, H.Request request) {
    H.Session session = new H.Session();
    boolean newSession = true;
    if (S.notBlank(encodedSession)) {
        resolveFromCookieContent(session, encodedSession, true);
        newSession = false;
    }
    session = processExpiration(session, $.ms(), newSession, sessionWillExpire, ttlInMillis, pingPath, request);
    return session;
}
 
Example #13
Source File: RequestBodyParser.java    From actframework with Apache License 2.0 5 votes vote down vote up
public static RequestBodyParser get(H.Request req) {
    H.Format contentType = req.contentType();
    RequestBodyParser parser = parsers.get(contentType);
    if (null == parser) {
        parser = TextParser.INSTANCE;
    }
    return parser;
}
 
Example #14
Source File: CaptchaService.java    From actframework with Apache License 2.0 5 votes vote down vote up
@GetAction()
@NonBlock
@JsonView
public CaptchaSession randomSession(H.Response resp) {
    resp.addHeader(CACHE_CONTROL, "no-store");
    return pluginManager.randomGenerator().generate();
}
 
Example #15
Source File: StaticFileGetterTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Test
public void invokePathHandlerOnNonExistingResource() {
    when(ctx.accept()).thenReturn(H.Format.HTML);
    ctx.param(ParamNames.PATH, "/some/where/non_exists.txt");
    pathHandler.handle(ctx);
    eq(resp.status, 404);
}
 
Example #16
Source File: ActionContextTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Before
public void prepare() throws Exception {
    setup();
    H.Request req = mock(H.Request.class);
    when(req.method()).thenReturn(H.Method.GET);
    when(req.paramNames()).thenReturn(C.list("foo", "bar"));
    when(req.paramVal("foo")).thenReturn("FOO");
    when(req.paramVal("bar")).thenReturn("BAR");
    when(req.paramVals("foo")).thenReturn(new String[]{"FOO", "foo"});
    when(req.paramVals("bar")).thenReturn(new String[]{"BAR", "bar"});

    ActResponse resp = mock(ActResponse.class);
    ctx = ActionContext.create(mockApp, req, resp);
    ctx.router(mock(Router.class));
}
 
Example #17
Source File: ActionContext.java    From actframework with Apache License 2.0 5 votes vote down vote up
public ActionContext applyContentType() {
    ActResponse resp = resp();
    H.Format lastContentType = resp.lastContentType();
    if (null != lastContentType && !lastContentType.isSameTypeWith(UNKNOWN)) {
        resp.commitContentType();
        return this;
    }
    H.Request req = req();
    H.Format fmt = req.accept();
    if (fmt.isSameTypeWith(UNKNOWN)) {
        fmt = req.contentType();
    }
    applyContentType(fmt);
    return this;
}
 
Example #18
Source File: ActionContext.java    From actframework with Apache License 2.0 5 votes vote down vote up
private Map<String, String[]> bodyParams() {
    if (null == bodyParams) {
        Map<String, String[]> map = new HashMap<>();
        H.Method method = request.method();
        if (H.Method.POST == method || H.Method.PUT == method || H.Method.PATCH == method || H.Method.DELETE == method) {
            RequestBodyParser parser = RequestBodyParser.get(request);
            map = parser.parse(this);
        }
        bodyParams = map;
        router.markRequireBodyParsing(handler);
    }
    return bodyParams;
}
 
Example #19
Source File: WebSocketConnectionManager.java    From actframework with Apache License 2.0 5 votes vote down vote up
/**
 * Add tag to any websocket connection linked to the session specified
 * @param session the session used to find websocket connections
 * @param tag the tag to subscribe
 */
public void subscribe(H.Session session, final String tag) {
    sessionRegistry().accept(session.id(), new $.Visitor<WebSocketConnection>() {
        @Override
        public void visit(WebSocketConnection connection) throws $.Break {
            byTag.register(tag, connection);
        }
    });
}
 
Example #20
Source File: GeneralAnnoInfoTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Test
public void annotationProxyTest() {
    Action action =  actionInfo.toAnnotation();
    eq(action.value(), new String[]{"/foo"});
    eq(action.methods(), new H.Method[]{H.Method.GET, H.Method.POST});

    NotNull notNull = notNullInfo.toAnnotation();
    eq(notNull.message(), "{javax.validation.constraints.NotNull.message}");
}
 
Example #21
Source File: Endpoint.java    From actframework with Apache License 2.0 5 votes vote down vote up
Endpoint(int port, H.Method httpMethod, String path, Set<String> urlPathVarNames, RequestHandler handler) {
    AppConfig conf = Act.appConfig();
    this.httpMethod = $.requireNotNull(httpMethod);
    String urlContext = conf.urlContext();
    this.path = null == urlContext || path.startsWith("/~/") ? $.requireNotNull(path) : S.concat(urlContext, $.requireNotNull(path));
    this.handler = handler.toString();
    this.port = port;
    this.urlPathVarNames = urlPathVarNames;
    this.sampleDataProviderManager = Act.app().sampleDataProviderManager();
    explore(handler);
}
 
Example #22
Source File: Router.java    From actframework with Apache License 2.0 5 votes vote down vote up
public String reverseRoute(String action, Map<String, Object> args) {
    String fullAction = inferFullActionPath(action);
    for (H.Method m : supportedHttpMethods()) {
        String url = reverseRoute(fullAction, m, args);
        if (null != url) {
            return ensureUrlContext(url);
        }
    }
    return null;
}
 
Example #23
Source File: RedirectDir.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(ActionContext context) {
    H.Response resp = context.prepareRespForResultEvaluation();
    if (context.isAjax()) {
        resp.status(H.Status.FOUND_AJAX);
    } else {
        resp.status(H.Status.MOVED_PERMANENTLY);
    }
    String path = context.__pathParamVal();
    resp.header(H.Header.Names.LOCATION, url + path);
}
 
Example #24
Source File: RouterBenchmark.java    From actframework with Apache License 2.0 5 votes vote down vote up
void osgl(H.Method method, String url, Object... args) {
    H.Request req = new MockRequest(config, method, url);
    ctx = ActionContext.create(app, req, new MockResponse());
    if (args.length > 0) {
        url = S.fmt(url, args);
    }
    RequestHandler handler = router.getInvoker(method, url, ctx);
    if (AlwaysBadRequest.INSTANCE == handler || AlwaysNotFound.INSTANCE == handler) {
        throw NotFound.get();
    }
}
 
Example #25
Source File: ActErrorResult.java    From actframework with Apache License 2.0 5 votes vote down vote up
public static ErrorResult of(H.Status status, int errorCode) {
    E.illegalArgumentIf(!status.isClientError() && !status.isServerError());
    if (Act.isDev()) {
        return new ActErrorResult(status, errorCode);
    } else {
        return ErrorResult.of(status, errorCode);
    }
}
 
Example #26
Source File: ActErrorResult.java    From actframework with Apache License 2.0 5 votes vote down vote up
public static ErrorResult of(H.Status status, int errorCode, String message, Object... args) {
    E.illegalArgumentIf(!status.isClientError() && !status.isServerError());
    if (Act.isDev()) {
        return new ActErrorResult(status, errorCode, message, args);
    } else {
        return ErrorResult.of(status, errorCode, message, args);
    }
}
 
Example #27
Source File: FileGetter.java    From actframework with Apache License 2.0 5 votes vote down vote up
public static H.Format contentType(String path) {
    H.Format retVal = null;
    if (path.contains(".")) {
        FastStr s = FastStr.unsafeOf(path).afterLast('.');
        retVal = H.Format.of(s.toString());
    }
    return null == retVal ? H.Format.BINARY : retVal;
}
 
Example #28
Source File: RequestImplBase.java    From actframework with Apache License 2.0 4 votes vote down vote up
private H.Method _method() {
    return H.Method.valueOfIgnoreCase(methodName());
}
 
Example #29
Source File: WebSocketContext.java    From actframework with Apache License 2.0 4 votes vote down vote up
@Override
public WebSocketContext accept(H.Format fmt) {
    throw E.unsupport();
}
 
Example #30
Source File: RenderCSV.java    From actframework with Apache License 2.0 4 votes vote down vote up
private RenderCSV() {
    super(H.Format.CSV);
}