Search in sources :

Example 71 with ScriptException

use of org.jaggeryjs.scriptengine.exceptions.ScriptException in project jaggery by wso2.

the class RegistryHostObject method jsFunction_search.

public static Scriptable jsFunction_search(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException {
    String functionName = "search";
    int argsCount = args.length;
    if (argsCount != 1) {
        HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
    }
    if (!(args[0] instanceof NativeObject)) {
        HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "json", args[0], false);
    }
    NativeObject options = (NativeObject) args[0];
    CustomSearchParameterBean parameters = new CustomSearchParameterBean();
    String path = null;
    List<String[]> values = new ArrayList<String[]>();
    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    String val;
    for (Object idObj : options.getIds()) {
        String id = (String) idObj;
        Object value = options.get(id, options);
        if (value == null || value instanceof Undefined) {
            continue;
        }
        if ("path".equals(id)) {
            path = (String) value;
            continue;
        }
        if ("createdBefore".equals(id) || "createdAfter".equals(id) || "updatedBefore".equals(id) || "updatedAfter".equals(id)) {
            long t;
            if (value instanceof Number) {
                t = ((Number) value).longValue();
            } else {
                t = Long.parseLong(HostObjectUtil.serializeObject(value));
            }
            val = new String(dateFormat.format(new Date(t)).getBytes());
        } else {
            val = HostObjectUtil.serializeObject(value);
        }
        values.add(new String[] { id, val });
    }
    parameters.setParameterValues(values.toArray(new String[0][0]));
    RegistryHostObject registryHostObject = (RegistryHostObject) thisObj;
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        UserRegistry userRegistry = RegistryHostObjectContext.getRegistryService().getRegistry(registryHostObject.registry.getUserName(), tenantId);
        Registry configRegistry = RegistryHostObjectContext.getRegistryService().getConfigSystemRegistry(tenantId);
        AdvancedSearchResultsBean resultsBean = registryHostObject.search(configRegistry, userRegistry, parameters);
        if (resultsBean.getResourceDataList() == null) {
            ScriptableObject error = (ScriptableObject) cx.newObject(thisObj);
            error.put("error", error, true);
            error.put("description", error, resultsBean.getErrorMessage());
            return error;
        }
        List<ScriptableObject> results = new ArrayList<ScriptableObject>();
        for (ResourceData resourceData : resultsBean.getResourceDataList()) {
            String resourcePath = resourceData.getResourcePath();
            if (path != null && !resourcePath.startsWith(path)) {
                continue;
            }
            ScriptableObject result = (ScriptableObject) cx.newObject(thisObj);
            result.put("author", result, resourceData.getAuthorUserName());
            result.put("rating", result, resourceData.getAverageRating());
            result.put("created", result, resourceData.getCreatedOn().getTime().getTime());
            result.put("description", result, resourceData.getDescription());
            result.put("name", result, resourceData.getName());
            result.put("path", result, resourceData.getResourcePath());
            List<ScriptableObject> tags = new ArrayList<ScriptableObject>();
            if (resourceData.getTagCounts() != null) {
                for (TagCount tagCount : resourceData.getTagCounts()) {
                    ScriptableObject tag = (ScriptableObject) cx.newObject(thisObj);
                    tag.put("name", tag, tagCount.getKey());
                    tag.put("count", tag, tagCount.getValue());
                    tags.add(tag);
                }
            }
            result.put("tags", result, cx.newArray(thisObj, tags.toArray()));
            results.add(result);
        }
        return cx.newArray(thisObj, results.toArray());
    } catch (RegistryException e) {
        throw new ScriptException(e);
    } catch (CarbonException e) {
        throw new ScriptException(e);
    }
}
Also used : CustomSearchParameterBean(org.wso2.carbon.registry.search.beans.CustomSearchParameterBean) ResourceData(org.wso2.carbon.registry.common.ResourceData) CarbonException(org.wso2.carbon.CarbonException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) RegistryException(org.wso2.carbon.registry.api.RegistryException) AdvancedSearchResultsBean(org.wso2.carbon.registry.search.beans.AdvancedSearchResultsBean) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) TagCount(org.wso2.carbon.registry.common.TagCount) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat)

Example 72 with ScriptException

use of org.jaggeryjs.scriptengine.exceptions.ScriptException in project jaggery by wso2.

the class FileHostObject method jsFunction_unZip.

/**
     * To unzip a zip file
     *
     * @param cx      Context
     * @param thisObj FileHostObject to be unzipped
     * @param args    Path to unzip the zip file
     * @param funObj  Function Object
     * @throws ScriptException
     */
@SuppressFBWarnings({ "PATH_TRAVERSAL_IN", "PATH_TRAVERSAL_IN", "PATH_TRAVERSAL_IN" })
public static boolean jsFunction_unZip(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException, IOException {
    String functionName = "unZip";
    int argsCount = args.length;
    if (argsCount != 1) {
        HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
    }
    FileHostObject fho = (FileHostObject) thisObj;
    ZipInputStream zin = null;
    BufferedOutputStream out = null;
    if (fho.file.isExist()) {
        JaggeryContext context = (JaggeryContext) RhinoEngine.getContextProperty(EngineConstants.JAGGERY_CONTEXT);
        Object obj = context.getProperty(JAVASCRIPT_FILE_MANAGER);
        if (obj instanceof JavaScriptFileManager) {
            fho.manager = (JavaScriptFileManager) obj;
        } else {
            fho.manager = new JavaScriptFileManagerImpl();
        }
        File zipfile = new File(fho.manager.getFile(fho.file.getPath()).getAbsolutePath());
        File outdir = new File(fho.manager.getDirectoryPath(args[0].toString()));
        if (outdir.getParentFile().exists() || outdir.getParentFile().mkdirs()) {
            if (outdir.exists() || outdir.mkdir()) {
                try {
                    zin = new ZipInputStream(new FileInputStream(zipfile));
                    ZipEntry entry;
                    String name, dir;
                    byte[] buffer = new byte[1024];
                    while ((entry = zin.getNextEntry()) != null) {
                        name = entry.getName();
                        if (entry.isDirectory()) {
                            mkdirs(outdir, name);
                            continue;
                        }
                        int hasParentDirs = name.lastIndexOf(File.separatorChar);
                        dir = (hasParentDirs == -1) ? null : name.substring(0, hasParentDirs);
                        if (dir != null) {
                            mkdirs(outdir, dir);
                        }
                        try {
                            out = new BufferedOutputStream(new FileOutputStream(new File(outdir, name)));
                            int count;
                            while ((count = zin.read(buffer)) != -1) {
                                out.write(buffer, 0, count);
                            }
                        } catch (Exception ex) {
                            log.error("Unable to perform unZip operation for file : " + fho.file.getName(), ex);
                            return false;
                        } finally {
                            if (out != null) {
                                try {
                                    out.close();
                                } catch (IOException er) {
                                    log.error("Unable to close the output stream " + er);
                                }
                            }
                        }
                    }
                    return true;
                } catch (IOException ex) {
                    log.error("Cannot unzip the file " + ex);
                    throw new IOException(ex);
                } finally {
                    if (zin != null) {
                        try {
                            zin.close();
                        } catch (IOException er) {
                            log.error("Unable to close the zip input stream " + er);
                        }
                    }
                }
            } else {
                log.error("Unable to create directories to handle file : " + fho.file.getName());
            }
        } else {
            log.error("Unable to create directories to handle file : " + fho.file.getName());
        }
    } else {
        log.error("Zip file not exists");
    }
    return false;
}
Also used : ZipEntry(java.util.zip.ZipEntry) JaggeryContext(org.jaggeryjs.scriptengine.engine.JaggeryContext) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) ZipInputStream(java.util.zip.ZipInputStream) StreamHostObject(org.jaggeryjs.hostobjects.stream.StreamHostObject) ScriptableObject(org.mozilla.javascript.ScriptableObject) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 73 with ScriptException

use of org.jaggeryjs.scriptengine.exceptions.ScriptException in project jaggery by wso2.

the class JavaScriptFileImpl method read.

@Override
public String read(long count) throws ScriptException {
    if (!opened) {
        log.warn("You need to open the file for reading");
        return null;
    }
    if (!readable) {
        log.warn("File has not opened in a readable mode.");
        return null;
    }
    try {
        byte[] arr = new byte[(int) min(count, file.length())];
        file.readFully(arr);
        return new String(arr, "UTF-8");
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new ScriptException(e);
    }
}
Also used : ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException)

Example 74 with ScriptException

use of org.jaggeryjs.scriptengine.exceptions.ScriptException in project jaggery by wso2.

the class JavaScriptFileImpl method readAll.

@Override
public String readAll() throws ScriptException {
    if (!opened) {
        log.warn("You need to open the file for reading");
        return null;
    }
    if (!readable) {
        log.warn("File has not opened in a readable mode.");
        return null;
    }
    try {
        long pointer = file.getFilePointer();
        file.seek(0);
        String data = read(file.length());
        file.seek(pointer);
        return data;
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new ScriptException(e);
    }
}
Also used : ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException)

Example 75 with ScriptException

use of org.jaggeryjs.scriptengine.exceptions.ScriptException in project jaggery by wso2.

the class JavaScriptFileManagerImpl method getFile.

@SuppressFBWarnings("PATH_TRAVERSAL_IN")
@Override
public File getFile(String uri) throws ScriptException {
    File file;
    if (uri.startsWith("file://")) {
        try {
            file = FileUtils.toFile(new URL(uri));
        } catch (MalformedURLException e) {
            log.error(e.getMessage(), e);
            throw new ScriptException(e);
        }
    } else {
        String oldPath = uri;
        uri = FilenameUtils.normalizeNoEndSeparator(uri);
        if (uri == null) {
            String msg = "Invalid file URI : " + oldPath;
            log.error(msg);
            throw new ScriptException(msg);
        }
        file = new File(uri);
    }
    return file;
}
Also used : ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) MalformedURLException(java.net.MalformedURLException) File(java.io.File) URL(java.net.URL) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Aggregations

ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)83 IOException (java.io.IOException)15 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)13 ScriptableObject (org.mozilla.javascript.ScriptableObject)12 RegistryException (org.wso2.carbon.registry.api.RegistryException)11 ScriptReader (org.jaggeryjs.jaggery.core.ScriptReader)9 URL (java.net.URL)8 JaggeryContext (org.jaggeryjs.scriptengine.engine.JaggeryContext)8 MalformedURLException (java.net.MalformedURLException)7 ServletContext (javax.servlet.ServletContext)6 ScriptCachingContext (org.jaggeryjs.scriptengine.cache.ScriptCachingContext)6 RhinoEngine (org.jaggeryjs.scriptengine.engine.RhinoEngine)5 Context (org.mozilla.javascript.Context)5 File (java.io.File)4 StringReader (java.io.StringReader)4 Callable (java.util.concurrent.Callable)4 ExecutorService (java.util.concurrent.ExecutorService)4 FileItem (org.apache.commons.fileupload.FileItem)4 FileHostObject (org.jaggeryjs.hostobjects.file.FileHostObject)4 StreamHostObject (org.jaggeryjs.hostobjects.stream.StreamHostObject)4