org.osgl.util.C Java Examples

The following examples show how to use org.osgl.util.C. 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: 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 #2
Source File: Gh202.java    From java-tool with Apache License 2.0 6 votes vote down vote up
@Test
public void test2() {
    Foo foo = new Foo();
    foo.id = "foo";

    Bar bar = new Bar();
    bar.id = "bar";
    bar.foo = foo;

    Bean bean = new Bean();
    bean.name = "bean";
    bean.map = C.Map("foo", bar);
    bean.bar = bar;

    Bean target = $.deepCopy(bean).filter("bar").to(Bean.class);
    isNull(target.name);
    isNull(target.map);

    Bar tgtBar = target.bar;
    notNull(tgtBar);
    eq("bar", tgtBar.id);

    Foo tgtFoo = tgtBar.foo;
    notNull(tgtFoo);
    eq("foo", tgtFoo.id);
}
 
Example #3
Source File: SecureTicketCodec.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Override
public final T createTicket(H.Session session) {
    String id = session.id();
    Map<String, String> map = new HashMap<>();
    Set<String> keys = this.keys;
    if (keys.isEmpty()) {
        keys = C.newSet(session.keySet());
        keys.remove(H.Session.KEY_EXPIRATION);
        keys.remove(H.Session.KEY_ID);
    }
    for (String key : keys) {
        String val = session.get(key);
        if (null != val) {
            map.put(key, val);
        }
    }
    return serialize(id, map);
}
 
Example #4
Source File: GeneralAnnoInfo.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    C.List<String> keys = C.newList(attributes.keySet()).append(listAttributes.keySet()).sorted();
    S.Buffer sb = S.newBuffer("@").append(type.getClassName()).append("(");
    for (String key: keys) {
        Object v = attributes.get(key);
        if (null == v) {
            v = listAttributes.get(v);
        }
        sb.append(key).append("=").append(v).append(", ");
    }
    if (!keys.isEmpty()) {
        sb.delete(sb.length() - 2, sb.length());
    }
    sb.append(")");
    return sb.toString();
}
 
Example #5
Source File: JSONTraverser.java    From actframework with Apache License 2.0 6 votes vote down vote up
public Object traverse(String path) {
    String[] sa = path.split("[\\.\\[\\]]+");
    if (sa.length == 1) {
        if (obj != null) {
            return obj.get(path);
        } else {
            return array.get(Integer.parseInt(path));
        }
    }
    List<String> list = C.newListOf(sa);
    String first = list.remove(0);
    if ("".equalsIgnoreCase(first)) {
        first = list.remove(0);
    }
    Object o = traverse(first);
    JSONTraverser traverser = new JSONTraverser(o);
    String rest = S.join(list).by(".").get();
    return traverser.traverse(rest);
}
 
Example #6
Source File: EndpointTester.java    From actframework with Apache License 2.0 6 votes vote down vote up
protected Map<String, Object> prepareJsonData(List<$.T2<String, Object>> params) {
    Map<String, Object> map = C.newMap();
    if (null != params) {
        for ($.T2<String, Object> pair : params) {
            String key = pair._1;
            Object val = pair._2;
            if (map.containsKey(key)) {
                List list;
                Object x = map.get(key);
                if (x instanceof List) {
                    list = $.cast(x);
                } else {
                    list = C.newList(x);
                    map.put(key, list);
                }
                list.add(val);
            } else {
                map.put(key, val);
            }
        }
    }
    return map;
}
 
Example #7
Source File: ConfLoader.java    From actframework with Apache License 2.0 6 votes vote down vote up
private Map loadConfFromDir_(File confDir) {
    File[] confFiles = confDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".properties") || name.endsWith(".conf");
        }
    });
    if (null == confFiles) {
        return C.Map();
    } else {
        Map map = new HashMap<>();
        int n = confFiles.length;
        for (int i = 0; i < n; ++i) {
            map.putAll(loadConfFromFile(confFiles[i]));
        }
        return map;
    }
}
 
Example #8
Source File: Zen.java    From actframework with Apache License 2.0 6 votes vote down vote up
private static List<String> loadWords() {
    URL url = Act.getResource("act_zen.txt");
    List<String> words = C.newList(defaultWords());
    if (null != url) {
        try {
            List<String> myWords = IO.readLines(url.openStream());
            if (!myWords.isEmpty()) {
                words = myWords;
            }
        } catch (Exception e) {
            // ignore it
        }
    }
    List<String> retVal = new ArrayList<>(words.size());
    for (String s : words) {
        if (s.contains("\n")) {
            s = s.replaceAll("\n", "\n          ");
        } else if (s.contains("\\n")) {
            s = s.replaceAll("\\\\n", "\n          ");
        }
        retVal.add(s);
    }
    return retVal;
}
 
Example #9
Source File: RouterAdmin.java    From actframework with Apache License 2.0 6 votes vote down vote up
private List<RouteInfo> routeInfoList(String portName, String q) {
    final Router router = S.blank(portName) ? app.router() : app.router(portName);
    List<RouteInfo> list = router.debug();
    if (S.notBlank(q)) {
        List<RouteInfo> toBeRemoved = new ArrayList<>();
        for (RouteInfo info: list) {
            String handler = S.string(info.handler());
            String path = info.path();
            if (path.contains(q) || handler.contains(q) || path.matches(q) || handler.matches(q)) {
                continue;
            }
            toBeRemoved.add(info);
        }
        list = C.list(list).without(toBeRemoved);
    }
    return list;
}
 
Example #10
Source File: PrimitiveTypeArrayActionParameterBindingTestBase.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrimitiveEmptyArrayJSON() throws Exception {
    // TODO: track FastJson issue #821
    if (this instanceof CharArrayActionParameterBindingTest) {
        // ignore. see https://github.com/alibaba/fastjson/issues/821
        return;
    }
    _verify("[]", pathPrimitive, C.list(), ParamEncoding.JSON, EndPointTestContext.RequestMethod.POST_JSON);
}
 
Example #11
Source File: FuncTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Test
public void RandLongWithTwoInitVals() {
    Func func = new Func.RandomLong();
    func.init(C.list("10", "14"));
    Object o = func.apply();
    notNull(o);
    yes(o instanceof Long);
    long i = (Long) o;
    yes(i >= 10);
    yes(i < 14);
}
 
Example #12
Source File: ContentLinesResolver.java    From actframework with Apache License 2.0 5 votes vote down vote up
private List<String> fallBack(String value) {
    Boolean mercy = attribute(ATTR_MERCY);
    if (null == mercy) {
        mercy = false;
    }
    return mercy ? C.list(value) : C.<String>list();
}
 
Example #13
Source File: EventBus.java    From actframework with Apache License 2.0 5 votes vote down vote up
public static Set<Key> keysOf(Object id, SimpleEventListener eventListener) {
    Set<Key> retSet = new HashSet<>();
    for (List<Class> argTypes : permutationOf(eventListener.argumentTypes())) {
        retSet.add(new Key(id, argTypes));
    }
    if (retSet.isEmpty()) {
        retSet.add(new Key(id, C.<Class>list()));
    }
    return retSet;
}
 
Example #14
Source File: Gh78.java    From java-tool with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Map<String, String> from = C.Map("name", "Tom");
    Map<String, String> to = C.newMap();
    $.map(from).to(to);
    eq(1, to.size());
    eq("Tom", to.get("name"));
}
 
Example #15
Source File: YamlLoader.java    From actframework with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> loadFixture(String fixtureName, DaoLocator daoLocator) {
    boolean isJson = fixtureName.endsWith(".json");
    boolean isYaml = !isJson && (fixtureName.endsWith(".yaml") || fixtureName.endsWith(".yml"));
    E.unsupportedIfNot(isJson || isYaml, "fixture resource file type not supported: " + fixtureName);
    String content = getResourceAsString(fixtureName);
    if (null == content) {
        return C.Map();
    }
    return isJson ? parseJson(content, daoLocator) : parse(content, daoLocator);
}
 
Example #16
Source File: RandomListLoader.java    From java-di with Apache License 2.0 5 votes vote down vote up
@Override
public List<Integer> get() {
    List<Integer> list = C.newList();
    for (int i = 0; i < 10; ++i) {
        list.add(N.randInt(100));
    }
    return list;
}
 
Example #17
Source File: ContentLinesBinder.java    From actframework with Apache License 2.0 5 votes vote down vote up
private List<String> fallBack(String model, ParamValueProvider params) {
    Boolean mercy = attribute(ATTR_MERCY);
    if (null == mercy) {
        mercy = false;
    }
    if (mercy) {
        String val = params.paramVal(model);
        return null == val ? C.<String>list() : C.list(val);
    }
    return C.list();
}
 
Example #18
Source File: UploadFileStorageService.java    From actframework with Apache License 2.0 5 votes vote down vote up
public static UploadFileStorageService create(App app) {
    File tmp = app.tmpDir();
    if (!tmp.exists() && !tmp.mkdirs()) {
        throw E.unexpected("Cannot create tmp dir");
    }
    Map<String, String> conf = C.newMap("storage.fs.home.dir", Files.file(app.tmpDir(), "uploads").getAbsolutePath(),
            "storage.keygen", KeyGenerator.Predefined.BY_DATE.name());
    conf.put(IStorageService.CONF_ID, "__upload");
    conf.put("storage.storeSuffix", "false");
    return new UploadFileStorageService(conf, app.config().uploadInMemoryCacheThreshold());
}
 
Example #19
Source File: SimpleTypeArrayActionParameterBindingTestBase.java    From actframework with Apache License 2.0 5 votes vote down vote up
protected final void _verify(String expected, String urlPath, List data, ParamEncoding paramEncoding, RequestMethod method) throws Exception {
    context
            .expected(expected, e2(), es2())
            .accept(H.Format.JSON)
            .url(processUrl(urlPath))
            .params(paramEncoding.encode(null == data ? "v" : PARAM, null == data ? C.list() : data))
            .method(method)
            .applyTo(this);
}
 
Example #20
Source File: FsChangeDetector.java    From actframework with Apache License 2.0 5 votes vote down vote up
private Set<String> prependContext(C.Set<String> paths) {
    return C.set(paths.map(new $.F1<String, String>() {
        @Override
        public String apply(String s) throws NotAppliedException, $.Break {
            return context + s;
        }
    }));
}
 
Example #21
Source File: Gh1117.java    From actframework with Apache License 2.0 5 votes vote down vote up
/**
 * Note the issue only occur when executing CLI command and it has to be manually verified.
 */
@GetAction
@PropertySpec("-bar")
@Command("gh1117")
public Iterable<Foo> test() {
    return C.list(new Foo());
}
 
Example #22
Source File: RythmTemplateException.java    From actframework with Apache License 2.0 5 votes vote down vote up
RythmSourceInfo(org.rythmengine.exception.RythmException e, boolean javaSource) {
    fileName = e.getTemplateName();
    if (javaSource) {
        lineNumber = e.javaLineNumber;
        String jsrc = e.javaSource;
        lines = null != jsrc ? C.listOf(jsrc.split("[\n]")) : C.<String>list();
    } else {
        lineNumber = e.templateLineNumber;
        lines = C.listOf(e.templateSource.split("[\n]"));
    }
}
 
Example #23
Source File: FuncTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Test
public void randIntWithTwoInitVals() {
    Func func = new Func.RandomInt();
    func.init(C.list("10", "14"));
    Object o = func.apply();
    notNull(o);
    yes(o instanceof Integer);
    int i = (Integer) o;
    yes(i >= 10);
    yes(i < 14);
}
 
Example #24
Source File: AppByteCodeScannerBase.java    From actframework with Apache License 2.0 5 votes vote down vote up
protected final void addDependencyClass(String className) {
    Set<String> set = dependencyClasses.get(getClass());
    if (null == set) {
        set = C.newSet();
        dependencyClasses.put(getClass(), set);
    }
    set.add(className);
}
 
Example #25
Source File: EventBus.java    From actframework with Apache License 2.0 5 votes vote down vote up
private <T extends EventObject> void callOn(final T event, List<? extends ActEventListener> listeners, boolean async) {
    if (null == listeners) {
        return;
    }
    JobManager jobManager = null;
    if (async) {
        jobManager = app().jobManager();
    }
    Set<ActEventListener> toBeRemoved = C.newSet();
    try {
        for (final ActEventListener l : listeners) {
            if (!async) {
                boolean result = callOn(event, l);
                if (result && once) {
                    toBeRemoved.add(l);
                }
            } else {
                jobManager.now(new Runnable() {
                    @Override
                    public void run() {
                        callOn(event, l);
                    }
                }, event instanceof SysEvent);
            }
        }
    } catch (ConcurrentModificationException e) {
        String eventName;
        if (event instanceof SysEvent) {
            eventName = event.toString();
        } else {
            eventName = event.getClass().getName();
        }
        throw E.unexpected("Concurrent modification issue encountered on handling event: " + eventName);
    }
    if (once && !toBeRemoved.isEmpty()) {
        listeners.removeAll(toBeRemoved);
    }
}
 
Example #26
Source File: Gh149.java    From java-tool with Apache License 2.0 5 votes vote down vote up
@Test
public void testToMap() {
    Map<String, Object> src = new HashMap<>();
    src.put("a", 1);
    Map tgt = $.map(src).map(C.<String, String>Map("a", "b")).to(Map.class);
    eq(1, tgt.get("b"));
}
 
Example #27
Source File: ContentSuffixSensor.java    From actframework with Apache License 2.0 5 votes vote down vote up
private static List<String> prepareUrlList() {
    final int size = 100;
    List<String> suffixes = C.listOf(".json,/json,.xml,/xml,.csv,/csv".split(","));
    if (null == generated) {
        generated = new ArrayList<String>(size);
        for (int i = 0; i < size; ++i) {
            String url = S.random(30 + N.randInt(40));
            if (i % 2 == 0) {
                url += $.random(suffixes);
            }
            generated.add(url);
        }
    }
    return generated;
}
 
Example #28
Source File: CommandLineParserTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Test
public void argumentsDeclaredBeforeOptions() {
    p = p("myCommand -o x arg1 -b -n 1 arg2");
    eq('x', p.getChar("-o", null, 'y'));
    yes(p.getBoolean("-b", null));
    same(1, p.getInt("-n", null, 2));
    ceq(C.listOf("arg1 arg2".split(" ")), p.arguments());
}
 
Example #29
Source File: LoadResourceTest.java    From actframework with Apache License 2.0 4 votes vote down vote up
@Test
public void testLoadLines() {
    eq(C.listOf("line1", "line2"), testBed.lines);
}
 
Example #30
Source File: SecureTicketCodec.java    From actframework with Apache License 2.0 4 votes vote down vote up
public Base(Collection<String> keys) {
    this.keys = C.set($.requireNotNull(keys));
}