org.osgl.util.S Java Examples

The following examples show how to use org.osgl.util.S. 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: Tags.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Override
public String apply() throws NotAppliedException, $.Break {
    ActContext context = ActContext.Base.currentContext();
    E.illegalStateIf(null == context, "Cannot get full action path reference outside of act context");
    /*
     * try to determine if the template is free or bounded template
     */
    if (context.templatePathIsImplicit()) {
        return context.methodPath();
    } else {
        String path = context.templatePath();
        path = org.osgl.util.S.beforeLast(path, ".");
        if (!isTemplateBounded(path, context.methodPath())) {
            return context.methodPath();
        }
        return path.replace('/', '.');
    }
}
 
Example #2
Source File: RequestHandlerProxy.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Inject
public RequestHandlerProxy(final String actionMethodName, final App app) {
    int pos = actionMethodName.lastIndexOf('.');
    final String ERR = "Invalid controller action: %s";
    E.illegalArgumentIf(pos < 0, ERR, actionMethodName);
    controllerClassName = actionMethodName.substring(0, pos);
    E.illegalArgumentIf(S.isEmpty(controllerClassName), ERR, actionMethodName);
    this.actionMethodName = actionMethodName.substring(pos + 1);
    E.illegalArgumentIf(S.isEmpty(this.actionMethodName), ERR, actionMethodName);
    this.actionPath = actionMethodName;
    if (app.classLoader() != null) {
        cache = app.config().cacheService(CACHE_NAME);
    } else {
        app.jobManager().on(SysEventId.CLASS_LOADER_INITIALIZED, "RequestHandlerProxy[" + actionMethodName + "]:setCache", new Runnable() {
            @Override
            public void run() {
                cache = app.config().cacheService(CACHE_NAME);
            }
        });
    }
    this.app = app;
    this.appInterceptor = app.interceptorManager();
}
 
Example #3
Source File: ResourceChecksumManager.java    From actframework with Apache License 2.0 6 votes vote down vote up
public String checksumOf(String path) {
    E.illegalArgumentIf((path.startsWith("http:") || path.startsWith("//")));
    if (path.startsWith("/")) {
        path = path.substring(1);
    }
    if (path.contains("?")) {
        path = S.beforeFirst(path, "?");
    }
    $.Val<String> bag = checksums.get(path);
    if (null == bag) {
        InputStream is = Act.app().classLoader().getResourceAsStream(path);
        String checksum = null == is ? null : crypto.checksum(is);
        bag = $.val(checksum);
        checksums.put(path, bag);
    }
    return bag.get();
}
 
Example #4
Source File: Config.java    From actframework with Apache License 2.0 6 votes vote down vote up
public Map<String, Object> subSet(String namespace) {
    namespace = Config.canonical(namespace);
    namespace = S.ensure(namespace).endWith(".");
    String prefix2 = "act." + namespace;
    Map<String, Object> subset = new HashMap<>();
    for (String key : raw.keySet()) {
        if (key.startsWith(namespace) || key.startsWith(prefix2)) {
            Object o = raw.get(key);
            if (null == o) {
                continue;
            }
            if (o instanceof String) {
                o = AppConfigKey.helper.evaluate(o.toString(), raw);
            }
            if (key.startsWith("act.")) {
                key = key.substring(4);
            }
            if (subset.containsKey(key)) continue;
            subset.put(key, o);
        }
    }
    return subset;
}
 
Example #5
Source File: RequestImplBase.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Override
public H.Method method() {
    if (null == method) {
        method = _method();
        if (method == H.Method.POST) {
            // check the method overload
            String s = header(H.Header.Names.X_HTTP_METHOD_OVERRIDE);
            if (S.blank(s)) {
                s = paramVal("_method"); // Spring convention
            }
            if (S.notBlank(s)) {
                method = H.Method.valueOfIgnoreCase(s);
            }
        }
    }
    return method;
}
 
Example #6
Source File: JobAnnotationProcessor.java    From actframework with Apache License 2.0 6 votes vote down vote up
private String evaluateExpression(String expression, Class<? extends Annotation> annoClass) {
    String prefix = annoClass.getSimpleName();
    if (S.eq(FixedDelay.class.getName(), prefix)) {
        prefix = "fixed-delay";
    } else {
        prefix = prefix.toLowerCase();
    }
    String ret = expression.trim();
    if (ret.startsWith(prefix)) {
        ret = (String) app().config().get(expression);
        if (S.blank(ret)) {
            throw E.invalidConfiguration("Expression configuration not found: %s", expression);
        }
    }
    return ret;
}
 
Example #7
Source File: Help.java    From actframework with Apache License 2.0 6 votes vote down vote up
private void list(String label, Collection<CliCmdInfo> commands, CliContext context, String q, String fmt) {
    List<String> lines = new ArrayList<>();
    lines.add(label.toUpperCase());
    q = S.string(q).trim();
    boolean hasFilter = S.notEmpty(q);
    List<CliCmdInfo> toBeDisplayed = new ArrayList<>();
    for (CliCmdInfo info : commands) {
        String cmd = info.name;
        if (hasFilter && !(cmd.toLowerCase().contains(q) || cmd.matches(q))) {
            continue;
        }
        if (null == fmt) {
            toBeDisplayed.add(info);
        } else {
            lines.add(S.fmt(fmt, info.nameAndShortcut(), info.help));
        }
    }
    context.println(Ansi.ansi().render(S.join("\n", lines)).toString());

    if (null == fmt) {
        // display table list
        context.println(CliView.TABLE.render(toBeDisplayed, metaInfo, context));
    }
}
 
Example #8
Source File: StringConcatBenchmark.java    From java-tool with Apache License 2.0 5 votes vote down vote up
@Test
public void concat6a() {
    String s = S.concat(s1, s2, s3, s4, s5, s6);
    for (int i = 0; i < 1000; ++i) {
        s = S.concat(s1, s2, s3, s4, s5, s6);
    }
    Assert.assertSame(i123456, s.length());
}
 
Example #9
Source File: HarmonyParamAnnotationTraitBase.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public String compatibilityErrorMessage(ParamAnnoInfoTrait otherParamAnnotation) {
    if ($.eq(otherParamAnnotation.getClass(), getClass())) {
        return S.fmt("Duplicated annotation found: %s", getClass());
    }
    return null;
}
 
Example #10
Source File: AppDescriptor.java    From actframework with Apache License 2.0 5 votes vote down vote up
private static String ensureAppName(String appName, String packageName, Version version) {
    if (S.blank(appName)) {
        if (!version.isUnknown()) {
            appName = version.getArtifactId();
        }
        if (S.blank(appName)) {
            appName = AppNameInferer.fromPackageName(packageName);
        }
    }
    return appName;
}
 
Example #11
Source File: FuncTestBase.java    From java-tool with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    rs1 = S.random();
    rs2 = S.random();
    rs3 = S.random();
    rs4 = S.random();
    rs5 = S.random();
}
 
Example #12
Source File: EndpointTester.java    From actframework with Apache License 2.0 5 votes vote down vote up
public ReqBuilder param(String key, Object val) {
    E.illegalArgumentIf(S.blank(key));
    if (method == H.Method.GET) {
        sb.append(paramAttached ? "&" : "?");
        paramAttached = true;
        sb.append(key).append("=").append(Codec.encodeUrl(S.string(val)));
    } else {
        postParams.add($.T2(key, val));
    }
    return this;
}
 
Example #13
Source File: ActContext.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public String templatePath() {
    String path = templatePath;
    String context = templateContext;
    if (S.notBlank(path)) {
        return path.startsWith("/") || S.blank(context) ? path : S.pathConcat(context, '/', path);
    } else {
        if (S.blank(context)) {
            return methodPath().replace('.', '/');
        } else {
            return S.pathConcat(context, '/', S.afterLast(methodPath(), "."));
        }
    }
}
 
Example #14
Source File: HeaderTokenSessionMapper.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public void write(String session, String flash, H.Response response) {
    if (null != session && hasSessionPayloadPrefix) {
        session = S.concat(sessionPayloadPrefix, session);
    }
    if (null != session) {
        response.header(sessionHeader, session);
    }
    if (null != flash) {
        response.header(flashHeader, flash);
    }
}
 
Example #15
Source File: CSRFProtector.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verifyToken(String token, H.Session session, App app) {
    String tokenInSession = session.get(app.config().csrfCookieName());
    if (S.eq(token, tokenInSession)) {
        return true;
    }
    AppCrypto crypto = Act.crypto();
    return S.eq(crypto.decrypt(token), crypto.decrypt(tokenInSession));
}
 
Example #16
Source File: MetricInfoTree.java    From actframework with Apache License 2.0 5 votes vote down vote up
public String getParentPath() {
    String path = info.getName();
    if (path.contains(Metric.PATH_SEPARATOR)) {
        return S.beforeLast(path, Metric.PATH_SEPARATOR);
    }
    return "";
}
 
Example #17
Source File: Interaction.java    From actframework with Apache License 2.0 5 votes vote down vote up
private void verifyBody(Response rs) throws Exception {
    if (null != response && S.notBlank(response.checksum)) {
        TestSession.current().verifyDownloadChecksum(rs, response.checksum);
        if (S.notBlank(response.downloadFilename)) {
            TestSession.current().verifyDownloadFilename(rs, response.downloadFilename);
        }
    } else if (null != response && S.notBlank(response.downloadFilename)) {
        TestSession.current().verifyDownloadFilename(rs, response.downloadFilename);
    } else {
        String bodyString = S.string(rs.body().string()).trim();
        TestSession.current().verifyBody(bodyString, response);
    }
}
 
Example #18
Source File: DataPropertyRepository.java    From actframework with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the complete property list of a class
 * @param c the class
 * @return the property list of the class
 */
public synchronized List<S.Pair> propertyListOf(Class<?> c) {
    String cn = c.getName();
    List<S.Pair> ls = repo.get(cn);
    if (ls != null) {
        return ls;
    }
    Set<Class<?>> circularReferenceDetector = new HashSet<>();
    ls = propertyListOf(c, circularReferenceDetector, null);
    repo.put(c.getName(), ls);
    return ls;
}
 
Example #19
Source File: JobTrigger.java    From actframework with Apache License 2.0 5 votes vote down vote up
static JobTrigger of(AppConfig config, Every anno) {
    String duration = anno.value();
    if (duration.startsWith("every.")) {
        duration = (String) config.get(duration);
    } else if (duration.startsWith("${") && duration.endsWith("}")) {
        duration = duration.substring(2, duration.length() - 1);
        duration = (String) config.get(duration);
    }
    if (S.blank(duration)) {
        throw E.invalidConfiguration("Cannot find configuration for duration: %s", anno.value());
    }
    return every(duration, anno.startImmediately());
}
 
Example #20
Source File: JobTrigger.java    From actframework with Apache License 2.0 5 votes vote down vote up
static JobTrigger of(AppConfig config, FixedDelay anno) {
    String delay = anno.value();
    if (delay.startsWith("delay.")) {
        delay = (String) config.get(delay);
    } else if (delay.startsWith("${") && delay.endsWith("}")) {
        delay = delay.substring(2, delay.length() - 1);
        delay = (String) config.get(delay);
    }
    if (S.blank(delay)) {
        throw E.invalidConfiguration("Cannot find configuration for delay: %s", anno.value());
    }
    return fixedDelay(delay, anno.startImmediately());
}
 
Example #21
Source File: StringConcatBenchmark.java    From java-tool with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void prepare() {
    s1 = S.random();
    s2 = S.random();
    s3 = S.random();
    s4 = S.random();
    s5 = S.random();
    s6 = S.random();
    s12 = s1 + s2;
    i12 = s12.length();
    s123 = s12 + s3;
    i123 = s123.length();
    s123456 = s123 + s4 + s5 + s6;
    i123456 = s123456.length();
}
 
Example #22
Source File: NoisyWordsFilter.java    From actframework with Apache License 2.0 5 votes vote down vote up
private static Set<String> noiseWords() {
    Set<String> retVal = new HashSet<>(NOISE_WORDS);

    String userDefined = System.getProperty(PROP_NOISE_WORDS);
    if (null != userDefined) {
        retVal.addAll(C.listOf(userDefined.split(S.COMMON_SEP)).map(S.F.TO_LOWERCASE));
    }

    return retVal;
}
 
Example #23
Source File: LangTest.java    From java-tool with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertExtension() {
    TypeConverterRegistry.INSTANCE
            .register(new MyConverter())
            .register(new StringToMyFrom());
    String id = S.random();
    eq(new MyTo(id), $.convert(new MyFrom(id)).to(MyTo.class));
    eq("abc", $.convert("abc").to(MyTo.class).toString());
}
 
Example #24
Source File: JsonWebTokenSessionCodec.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public H.Flash decodeFlash(String encodedFlash) {
    H.Flash flash = new H.Flash();
    if (S.notBlank(encodedFlash)) {
        resolveFromJwtToken(flash, encodedFlash, false);
        flash.discard(); // prevent cookie content from been output to response again
    }
    return flash;
}
 
Example #25
Source File: ConfigurationValueLoader.java    From java-di with Apache License 2.0 5 votes vote down vote up
private T cast(Object val, BeanSpec spec) {
    Class<?> type = spec.rawType();
    if (type.isInstance(val)) {
        return (T) val;
    }
    if ($.isSimpleType(type)) {
        StringValueResolver svr = StringValueResolver.predefined(type);
        if (null != svr) {
            return (T) svr.resolve(S.string(val));
        }
    }
    throw new InjectException("Cannot cast value type[%s] to required type[%]", val.getClass(), type);
}
 
Example #26
Source File: JobMethodMetaInfo.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    S.Buffer sb = S.newBuffer();
    sb.append(_invokeType())
            .append(_return())
            .append(fullName());
    return sb.toString();
}
 
Example #27
Source File: ConfigKeyHelper.java    From actframework with Apache License 2.0 5 votes vote down vote up
public String evaluate(String s, Map<String, ?> map) {
    int n = 0, n0 = 0, len = s.length();
    S.Buffer sb = S.newBuffer();
    while (n > -1 && n < len) {
        n = s.indexOf("${", n);
        if (n < 0) {
            if (n0 == 0) {
                return s;
            }
            sb.append(s.substring(n0, len));
            break;
        }
        sb.append(s.substring(n0, n));
        // now search for "}"
        n += 2;
        n0 = n;
        n = s.indexOf("}", n0 + 1);
        if (n < 0) {
            logger.warn("Invalid expression found in the configuration value: %s", s);
            return s;
        }
        String expression = s.substring(n0, n);
        if (S.notBlank(expression)) {
            // in case getting from Env variable
            Object o = map.get(expression);
            if (null == o) {
                o = getConfiguration(expression, null, map);
            }
            if (null != o) {
                sb.append(o);
            } else {
                logger.warn("Cannot find expression value for: %s", expression);
            }
        }
        n += 1;
        n0 = n;
    }
    return sb.toString();
}
 
Example #28
Source File: ErrorTemplatePathResolver.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public String resolve(int code, H.Format fmt) {
    String suffix;
    if (JSON == fmt || HTML == fmt || XML == fmt) {
        suffix = fmt.name();
    } else {
        suffix = TXT.name();
    }
    return Act.isProd() || "json".equals(suffix) ? S.fmt("/error/e%s.%s", code, suffix) : S.fmt("/error/dev/e%s.%s", code, suffix);
}
 
Example #29
Source File: ScenarioManager.java    From actframework with Apache License 2.0 5 votes vote down vote up
private void configure() {
    App app = Act.app();
    if (null == app) {
        return;
    }
    AppConfig<?> config = app.config();
    urlContext = config.get("test.urlContext");
    issueUrlTemplate = config.get("test.issueUrlTemplate");
    if (S.notBlank(issueUrlTemplate)) {
        issueUrlIcon = inferIssueUrlIcon(issueUrlTemplate);
    }
    requestTemplateManager = new RequestTemplateManager();
    requestTemplateManager.load();
}
 
Example #30
Source File: Exists.java    From actframework with Apache License 2.0 5 votes vote down vote up
private boolean exists(Object value) {
    if (null == value) {
        return false;
    }
    if (value instanceof String) {
        return S.notEmpty((String) value);
    }
    return true;
}