org.osgl.util.IO Java Examples

The following examples show how to use org.osgl.util.IO. 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: Gh1145.java    From actframework with Apache License 2.0 6 votes vote down vote up
@OnAppStart
public void generateRandomData() {
    // populate data list
    for (int i = 0; i < 10000; ++i) {
        Data data = new Data();
        for (int j = 0; j < 30; ++j) {
            String key = "key" + j;
            data.putValue(key, "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
        }
        list.add(data);
    }

    // try get csv file checksum
    String content = csvContent();
    checksum = IO.checksum(content.getBytes());
}
 
Example #2
Source File: Destroyable.java    From actframework with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to destroy all {@link Destroyable} elements,
 * and close all {@link Closeable} elements in the collection specified
 *
 * @param col   the collection might contains {@link Destroyable} and
 *              {@link Closeable} elements
 * @param scope specify the scope annotation.
 */
public static void tryDestroyAll(Collection<?> col, Class<? extends Annotation> scope) {
    if (null == col) {
        return;
    }
    for (Object o : col) {
        if (inScope(o, scope)) {
            try {
                if (o instanceof Destroyable) {
                    ((Destroyable) o).destroy();
                }
            } catch (Exception e) {
                Act.LOGGER.warn(e, "Error encountered destroying instance of %s", o.getClass().getName());
                // keep destroy next one
            }
            if (o instanceof Closeable) {
                IO.close((Closeable) o);
            }
        }
    }

    //col.clear();
}
 
Example #3
Source File: SimpleMetricStore.java    From actframework with Apache License 2.0 6 votes vote down vote up
void write(SimpleMetricStore store) {
    if (ioError) {
        return;
    }
    ObjectOutputStream oos = null;
    try {
        File file = new File(FILE_NAME);
        oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(store);
    } catch (IOException e) {
        ioError = true;
        throw E.ioException(e);
    } finally {
        IO.close(oos);
    }
}
 
Example #4
Source File: Interaction.java    From actframework with Apache License 2.0 6 votes vote down vote up
private boolean verify() {
    Response resp = null;
    try {
        if (S.notBlank(request.email)) {
            doVerifyEmail(request.email);
        } else {
            resp = TestSession.current().sendRequest(request);
            doVerify(resp);
        }
        return true;
    } catch (Exception e) {
        errorMessage = e.getMessage();
        if (null == errorMessage) {
            errorMessage = e.getClass().getName();
        }
        cause = causeOf(e);
        return false;
    } finally {
        IO.close(resp);
    }
}
 
Example #5
Source File: AppScanner.java    From actframework with Apache License 2.0 6 votes vote down vote up
private ProjectLayout probeLayoutPropertiesFile(File appBase) {
    File f = new File(appBase, ProjectLayout.PROJ_LAYOUT_FILE);
    if (f.exists() && f.canRead()) {
        Properties p = new Properties();
        InputStream is = IO.is(f);
        try {
            p.load(is);
        } catch (IOException e) {
            throw E.ioException(e);
        } finally {
            IO.close(is);
        }
        return ProjectLayout.util.build(p);
    } else {
        return null;
    }
}
 
Example #6
Source File: ScenarioManager.java    From actframework with Apache License 2.0 6 votes vote down vote up
private void loadFromScenarioDir(File scenariosDir) {
    File[] ymlFiles = scenariosDir.listFiles();
    if (null == ymlFiles) {
        return;
    }
    for (File file : ymlFiles) {
        if (file.isDirectory()) {
            loadFromScenarioDir(file);
        } else {
            String fileName = file.getName();
            if (fileName.endsWith(".yml") || fileName.endsWith(".yaml")) {
                String content = IO.read(file).toString();
                if (S.blank(content)) {
                    warn("Empty yaml file found: " + file.getPath());
                    continue;
                }
                try {
                    parseOne(content, file.getAbsolutePath());
                } catch (RuntimeException e) {
                    error(e, "Error parsing scenario file: %s", file.getName());
                    throw e;
                }
            }
        }
    }
}
 
Example #7
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 #8
Source File: ConfLoader.java    From actframework with Apache License 2.0 6 votes vote down vote up
private Map loadConfFromFile(File conf) {
    if (isTraceEnabled()) {
        trace("loading app conf from file: %s", conf);
    }
    if (!conf.canRead()) {
        logger.warn("Cannot read conf file[%s]", conf.getAbsolutePath());
        return new HashMap<>();
    }
    InputStream is = IO.inputStream(conf);
    Properties p = new Properties();
    try {
        p.load(is);
        return p;
    } catch (Exception e) {
        logger.warn(e, "Error loading %s", confFileName());
    } finally {
        IO.close(is);
    }
    return new HashMap<>();
}
 
Example #9
Source File: Book.java    From act-doc with Apache License 2.0 6 votes vote down vote up
public void process() {
    List<String> lines = new ArrayList<>();
    for (String chapter : processor.chapters()) {
        File src = new File(base, chapter);
        List<String> fileLines = IO.readLines(src);
        C.List<String> processedFileLines = C.newList();
        for (String line : fileLines) {
            if ("[返回目录](index.md)".equals(line.trim())) {
                continue;
            }
            line = processor.processTag(line);
            processedFileLines.add(line);
        }
        if (!lines.isEmpty()) {
            processedFileLines.add("\\newpage");
        }
        lines.addAll(processedFileLines);
    }
    File target = new File(processor.workspace(), "act_doc-" + lang + ".md");
    IO.write(S.join(lines).by("\n").get()).to(target);
}
 
Example #10
Source File: BootstrapClassLoaderTestRunner.java    From actframework with Apache License 2.0 5 votes vote down vote up
private static void packageJarInto(File from, File to, String selector) {
    try {
        String cmd = S.fmt("jar cf %s %s", to.getAbsolutePath(), selector);
        Process p = Runtime.getRuntime().exec(cmd.split("[\\s]+"), null, from);
        p.waitFor();
        String out = IO.readContentAsString(p.getInputStream());
        String err = IO.readContentAsString(p.getErrorStream());
    } catch (Exception e) {
        throw E.unexpected(e);
    }
}
 
Example #11
Source File: TestServerBootstrapClassLoader.java    From actframework with Apache License 2.0 5 votes vote down vote up
protected byte[] tryLoadResource(String name) {
    if (!name.startsWith("act.")) return null;
    String fn = ClassNames.classNameToClassFileName(name, true);
    URL url = findResource(fn.substring(1));
    if (null == url) return null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IO.copy(url.openStream(), baos);
        return baos.toByteArray();
    } catch (IOException e) {
        throw E.ioException(e);
    }
}
 
Example #12
Source File: MailerEnhancerTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
protected synchronized Class<?> loadClass(final String name,
                                          final boolean resolve) throws ClassNotFoundException {
    if (!name.startsWith("testapp.")) {
        return super.loadClass(name, resolve);
    }

    // gets an input stream to read the bytecode of the class
    String cn = name.replace('.', '/');
    String resource = cn + ".class";
    InputStream is = getResourceAsStream(resource);
    byte[] b;

    // adapts the class on the fly
    try {
        ClassReader cr = new ClassReader(is);
        ClassWriter cw = new ClassWriter(0);
        MailerEnhancer enhancer = new MailerEnhancer(cw, MailerEnhancerTest.this);
        cr.accept(enhancer, 0);
        b = cw.toByteArray();
        OutputStream os1 = new FileOutputStream("/tmp/" + S.afterLast(cn, "/") + ".class");
        IO.write(b, os1);
        cr = new ClassReader(b);
        cw = new ClassWriter(0);
        OutputStream os2 = new FileOutputStream("/tmp/" + S.afterLast(cn, "/") + ".java");
        ClassVisitor tv = new TraceClassVisitor(cw, new PrintWriter(os2));
        cr.accept(tv, 0);
    } catch (Exception e) {
        throw new ClassNotFoundException(name, e);
    }

    // returns the adapted class
    return defineClass(name, b, 0, b.length);
}
 
Example #13
Source File: ControllerEnhancerTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
protected synchronized Class<?> loadClass(final String name,
                                          final boolean resolve) throws ClassNotFoundException {
    if (!name.startsWith("testapp.")) {
        return super.loadClass(name, resolve);
    }

    // gets an input stream to read the bytecode of the class
    String cn = name.replace('.', '/');
    String resource = cn + ".class";
    InputStream is = getResourceAsStream(resource);
    byte[] b;

    // adapts the class on the fly
    try {
        ClassReader cr = new ClassReader(is);
        ClassWriter cw = new ClassWriter(0);
        ControllerEnhancer enhancer = new ControllerEnhancer(cw, ControllerEnhancerTest.this);
        cr.accept(enhancer, 0);
        b = cw.toByteArray();
        OutputStream os1 = new FileOutputStream("/tmp/" + S.afterLast(cn, "/") + ".class");
        IO.write(b, os1);
        cr = new ClassReader(b);
        cw = new ClassWriter(0);
        OutputStream os2 = new FileOutputStream("/tmp/" + S.afterLast(cn, "/") + ".java");
        ClassVisitor tv = new TraceClassVisitor(cw, new PrintWriter(os2));
        cr.accept(tv, 0);
    } catch (Exception e) {
        throw new ClassNotFoundException(name, e);
    }

    // returns the adapted class
    return defineClass(name, b, 0, b.length);
}
 
Example #14
Source File: MetricEnhancerTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
protected synchronized Class<?> loadClass(final String name,
                                          final boolean resolve) throws ClassNotFoundException {
    if (!name.equals("testapp.metric.TestBed")) {
        return super.loadClass(name, resolve);
    }

    // gets an input stream to read the bytecode of the class
    String cn = name.replace('.', '/');
    String resource = cn + ".class";
    InputStream is = getResourceAsStream(resource);
    byte[] b;

    // adapts the class on the fly
    try {
        ClassReader cr = new ClassReader(is);
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        MetricEnhancer enhancer = new MetricEnhancer(repo, cw);
        cr.accept(enhancer, ClassReader.EXPAND_FRAMES);
        b = cw.toByteArray();
        OutputStream os1 = new FileOutputStream("/tmp/" + S.afterLast(cn, "/") + ".class");
        IO.write(b, os1);
        cr = new ClassReader(b);
        cw = new ClassWriter(0);
        OutputStream os2 = new FileOutputStream("/tmp/" + S.afterLast(cn, "/") + ".java");
        ClassVisitor tv = new TraceClassVisitor(cw, new PrintWriter(os2));
        cr.accept(tv, 0);
    } catch (Exception e) {
        throw new ClassNotFoundException(name, e);
    }

    // returns the adapted class
    return defineClass(name, b, 0, b.length);
}
 
Example #15
Source File: DataObjectEnhancerTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
protected synchronized Class<?> loadClass(final String name,
                                          final boolean resolve) throws ClassNotFoundException {
    if (!name.startsWith("testapp.")) {
        return super.loadClass(name, resolve);
    }

    // gets an input stream to read the bytecode of the class
    String cn = name.replace('.', '/');
    String resource = cn + ".class";
    InputStream is = getResourceAsStream(resource);
    byte[] b;

    // adapts the class on the fly
    try {
        ClassReader cr = new ClassReader(is);
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        DataObjectEnhancer enhancer = new DataObjectEnhancer(cw);
        cr.accept(enhancer, 0);
        b = cw.toByteArray();
        //CheckClassAdapter.verify(new ClassReader(cw.toByteArray()), true, new PrintWriter(System.out));
        OutputStream os1 = new FileOutputStream("/tmp/" + S.afterLast(cn, "/") + ".class");
        IO.write(b, os1);
        cr = new ClassReader(b);
        cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        OutputStream os2 = new FileOutputStream("/tmp/" + S.afterLast(cn, "/") + ".java");
        ClassVisitor tv = new TraceClassVisitor(cw, new PrintWriter(os2));
        cr.accept(tv, 0);
    } catch (Exception e) {
        throw new ClassNotFoundException(name, e);
    }

    // returns the adapted class
    return defineClass(name, b, 0, b.length);
}
 
Example #16
Source File: YamlLoader.java    From actframework with Apache License 2.0 5 votes vote down vote up
protected String getResourceAsString(String name) {
    File file = getFile(name);
    if (null != file) {
        return IO.readContentAsString(file);
    }
    // unit testing! that's why we are here
    URL url = loadResource(name);
    return null == url ? null : IO.readContentAsString(url);
}
 
Example #17
Source File: CliSession.java    From actframework with Apache License 2.0 5 votes vote down vote up
public void stop() {
    exit = true;
    if (null != runningThread) {
        runningThread.interrupt();
    }
    console = null;
    IO.close(socket);
}
 
Example #18
Source File: UploadFileStorageService.java    From actframework with Apache License 2.0 5 votes vote down vote up
private OutputStream createFileOutputStream() {
    File dir = file.getParentFile();
    if (!dir.exists() && !dir.mkdirs()) {
        throw E.ioException("Cannot create dir: " + dir.getAbsolutePath());
    }
    return IO.buffered(IO.outputStream(file));
}
 
Example #19
Source File: XmlDocumentToJsonArray.java    From java-tool with Apache License 2.0 5 votes vote down vote up
private static void foo() {
    String s = "<root>\n\t<foo>\n\t\t<name>x</name>\n<id>1</id></foo><foo><name>y</name><id>2</id></foo></root>";
    Document document = XML.read(s);
    StringWriter w = new StringWriter();
    IO.write(document).pretty().to(w);
    System.out.println(s);
    //System.out.println(w.toString());
    //System.out.println($.convert(document).hint(XML.HINT_PRETTY).toString());
    JSONObject json = $.convert(document).to(JSONObject.class);
    System.out.println(JSON.toJSONString(json, true));
    Document doc2 = $.convert(json).to(Document.class);
    System.out.println($.convert(doc2).hint(XML.HINT_PRETTY).toString());
}
 
Example #20
Source File: MiscsTestBed.java    From actframework with Apache License 2.0 5 votes vote down vote up
@PostAction("readMulti")
public Object testMultiFileRead(
        @ReadContent(mercy = true) String file1,
        File file2,
        SObject file3
) {
    String c1 = file1;
    String c2 = IO.readContentAsString(file2);
    String c3 = IO.readContentAsString(file3.asInputStream());
    return render(c1, c2, c3);
}
 
Example #21
Source File: UploadFileStorageService.java    From actframework with Apache License 2.0 5 votes vote down vote up
private ISObject _store(FileItemStream fileItemStream) throws IOException {
    String filename = fileItemStream.getName();
    String key = newKey(filename);
    File tmpFile = getFile(key);
    InputStream input = fileItemStream.openStream();
    ThresholdingByteArrayOutputStream output = new ThresholdingByteArrayOutputStream(inMemoryCacheThreshold, tmpFile);
    IO.copy(input, output);

    ISObject retVal;
    if (output.exceedThreshold) {
        retVal = getFull(key);
    } else {
        int size = output.written;
        if (0 == size) {
            return null;
        }
        byte[] buf = output.buf();
        retVal = SObject.of(key, buf, size);
    }

    if (S.notBlank(filename)) {
        retVal.setFilename(filename);
    }
    String contentType = fileItemStream.getContentType();
    if (null != contentType) {
        retVal.setContentType(contentType);
    }
    return retVal;
}
 
Example #22
Source File: IdGenerator.java    From actframework with Apache License 2.0 5 votes vote down vote up
public FileBasedStartCounter(String path) {
    File file = new File(path);
    if (file.exists()) {
        String s = IO.readContentAsString(file);
        long seq = Long.parseLong(s);
        seq = seq + 1;
        IO.write(S.str(seq), file);
        id = (seq);
    } else {
        id = 0;
        IO.write(Long.toString(id), file);
    }
}
 
Example #23
Source File: Destroyable.java    From actframework with Apache License 2.0 5 votes vote down vote up
public static void tryDestroy(Object o, Class<? extends Annotation> scope) {
    if (null == o) {
        return;
    }
    if (!inScope(o, scope)) {
        return;
    }
    if (o instanceof Destroyable) {
        ((Destroyable) o).destroy();
    }
    if (o instanceof Closeable) {
        IO.close((Closeable) o);
    }
}
 
Example #24
Source File: TopLevelDomainList.java    From actframework with Apache License 2.0 5 votes vote down vote up
private void downloadTld() throws Exception {
    OkHttpClient http = new OkHttpClient.Builder().build();
    Request req = new Request.Builder().url("http://data.iana.org/TLD/tlds-alpha-by-domain.txt").get().build();
    Response resp = http.newCall(req).execute();
    List<String> newList = IO.read(resp.body().charStream()).toLines();
    resp.close();
    list = newList;
    filter();
}
 
Example #25
Source File: Destroyable.java    From actframework with Apache License 2.0 5 votes vote down vote up
public static void destroyAll(Collection<? extends Destroyable> col, Class<? extends Annotation> scope) {
    for (Destroyable e : col) {
        if (inScope(e, scope)) {
            e.destroy();
            if (e instanceof Closeable) {
                IO.close((Closeable) e);
            }
        }
    }
}
 
Example #26
Source File: UndertowNetwork.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
protected void close() {
    if (null == channels) {
        // not booted yet
        return;
    }
    for (AcceptingChannel<? extends StreamConnection> channel : channels) {
        IO.close(channel);
    }
    channels.clear();
    worker.shutdownNow();
}
 
Example #27
Source File: ZXingResult.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
protected void applyMessage(H.Request request, H.Response response) {
    String msg = this.getMessage();
    this.applyBeforeCommitHandler(request, response);
    if(S.notBlank(msg)) {
        renderCode(response);
    } else {
        IO.close(response.outputStream());
    }

    this.applyAfterCommitHandler(request, response);
}
 
Example #28
Source File: ContentStringBinder.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public String resolve(String bean, String model, ParamValueProvider params) {
    try {
        ISObject sobj = SObjectBinder.INSTANCE.resolve(null, model, params);
        return null == sobj ? fallBack(model, params) : IO.readContentAsString(sobj.asInputStream());
    } catch (Exception e) {
        return fallBack(model, params);
    }
}
 
Example #29
Source File: ContentLinesResolver.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> resolve(String value) {
    try {
        ISObject sobj = SObjectResolver.INSTANCE.resolve(value);
        return null == sobj ? fallBack(value) : IO.readLines(sobj.asInputStream());
    } catch (Exception e) {
        return fallBack(value);
    }
}
 
Example #30
Source File: ContentStringResolver.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public String resolve(String value) {
    try {
        ISObject sobj = SObjectResolver.INSTANCE.resolve(value);
        return null == sobj ? fallBack(value) : IO.readContentAsString(sobj.asInputStream());
    } catch (Exception e) {
        return fallBack(value);
    }
}