@Override public void put(String name, Scriptable start, Object value) { if (wrapped == null) { super.put(name, this, value); } else { if (properties.has(name, start)) { properties.put(name, properties, value); } else { wrapped.put(name, wrapped, value); } } }
/** * Initialize the JavaScript context using given parent scope. * * @param scPrototype Parent scope object. If it's null, use default scope. */ public final void init(Scriptable scPrototype) throws ChartException { final Context cx = Context.enter(); try { if (scPrototype == null) // NO PROTOTYPE { // scope = cx.initStandardObjects(); scope = new ImporterTopLevel(cx); } else { scope = cx.newObject(scPrototype); scope.setPrototype(scPrototype); // !don't reset the parent scope here. // scope.setParentScope( null ); } // final Scriptable scopePrevious = scope; // !deprecated, remove this later. use script context instead. // registerExistingScriptableObject( this, "chart" ); //$NON-NLS-1$ // scope = scopePrevious; // RESTORE // !deprecated, remove this later, use logger from script context // instead. // ADD LOGGING CAPABILITIES TO JAVASCRIPT ACCESS final Object oConsole = Context.javaToJS(getLogger(), scope); scope.put("logger", scope, oConsole); // $NON-NLS-1$ } catch (RhinoException jsx) { throw convertException(jsx); } finally { Context.exit(); } }
/** * Sets the value of the indexed property, creating it if need be. * * @param index the numeric index for the property * @param start the object whose property is being set * @param value value to set the property to */ public void put(int index, Scriptable start, Object value) { if (start == this) { synchronized (this) { indexedProps.put(new Integer(index), value); } } else { start.put(index, start, value); } }
protected void addToScope(Scriptable scope) { Object value = exportingBundle.lookup(name); StringTokenizer tokenizer = new StringTokenizer(name, "."); // $NON-NLS-1$ while (true) { String token = tokenizer.nextToken(); Object current = scope.get(token, scope); if (!tokenizer.hasMoreTokens()) { if (current == Scriptable.NOT_FOUND) { if (value instanceof NativeObject) { Scriptable wrapped = Context.getCurrentContext().newObject(scope); wrapped.setPrototype((Scriptable) value); value = wrapped; } scope.put(token, scope, value); return; } throw new IllegalStateException( "Resolve error: " + name + " already exists for " + this.toString()); // $NON-NLS-1$//$NON-NLS-2$ } if (current == Scriptable.NOT_FOUND) { current = ScriptableObject.getProperty(scope, token); if (current == Scriptable.NOT_FOUND) current = Context.getCurrentContext().newObject(scope); else if (current instanceof NativeObject) { // we need to wrap this object from the prototype Scriptable wrapped = Context.getCurrentContext().newObject(scope); wrapped.setPrototype((Scriptable) current); current = wrapped; } else throw new IllegalStateException( "Resolve error: " + name + "-" + token + " already exists for " + this.toString()); // $NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ scope.put(token, scope, current); } scope = (Scriptable) current; } }
/** * Registers a new variable to current JavaScript context. If the name already exists, it'll be * overwritten. * * @param sVarName * @throws ChartException */ public final void registerVariable(String sVarName, Object var) throws ChartException { Context.enter(); try { final Object oConsole = Context.javaToJS(var, scope); scope.put(sVarName, scope, oConsole); } finally { Context.exit(); } }
@Override public void setUp() { Context cx = Context.enter(); try { globalScope = cx.initStandardObjects(); cx.setOptimizationLevel(-1); // must use interpreter mode globalScope.put("myObject", globalScope, Context.javaToJS(new MyClass(), globalScope)); } finally { Context.exit(); } }
protected void prepareScenario() throws Throwable { clearHooksAndStepDefinitions(); cx = Context.enter(); scope = new Global(cx); // This gives us access to global functions like load() scope.put("jsLanguage", scope, this); cx.evaluateReader( scope, new InputStreamReader(getClass().getResourceAsStream(JS_DSL)), JS_DSL, 1, null); for (String jsFile : jsFiles) { cx.evaluateReader(scope, new FileReader(jsFile), jsFile, 1, null); } }
private static void putGlobalVariablesIntoScope( @NotNull Scriptable scope, @Nullable Map<String, Object> variables) { if (variables == null) { return; } Set<Map.Entry<String, Object>> entries = variables.entrySet(); for (Map.Entry<String, Object> entry : entries) { String name = entry.getKey(); Object value = entry.getValue(); scope.put(name, scope, value); } }
public static void finishInit( Scriptable scope, FunctionObject constructor, Scriptable prototype) { // Create and make these properties in the prototype visible Context cx = Context.getCurrentContext(); Scriptable jars = cx.newArray(prototype, 0); jars.put(0, jars, cx.newArray(jars, 0)); defineProperty(prototype, "params", cx.newArray(prototype, 0), ScriptableObject.PERMANENT); defineProperty(prototype, "auth", cx.newArray(prototype, 0), ScriptableObject.PERMANENT); defineProperty(prototype, "jars", jars, ScriptableObject.PERMANENT); defineProperty(prototype, "headers", cx.newArray(prototype, 0), ScriptableObject.PERMANENT); }
public String executeFormula( String formula, final Map map, final CamposObjetoNegocioDTO camposObjetoNegocioDTO) { if (formula == null) { return null; } // SE FOR EXECUCAO DE CLASSE, CAI FORA! SERVE PARA CARREGAR COMBOS. if (camposObjetoNegocioDTO.getTipoNegocio() != null && camposObjetoNegocioDTO.getTipoNegocio().equalsIgnoreCase("CLASS")) { return null; } final org.mozilla.javascript.Context cx = org.mozilla.javascript.Context.enter(); final org.mozilla.javascript.Scriptable scope = cx.initStandardObjects(); final String sourceName = this.getClass().getName() + "_Formula"; br.com.centralit.citcorpore.metainfo.util.HashMapUtil.map = map; final String retorno = ""; formula = formula.replaceAll("TEXTSEARCH", "utilStrings.generateNomeBusca"); formula = formula.replaceAll("GETFIELD", "hashMapUtil.getFieldInHash"); formula = "retorno = " + formula; final StringBuilder compl = new StringBuilder(); compl.append("var importNames = JavaImporter();\n"); compl.append("importNames.importPackage(Packages.br.com.citframework.util);\n"); compl.append( "importNames.importPackage(Packages.br.com.centralit.citcorpore.metainfo.util);\n"); formula = compl.toString() + "\n" + formula; scope.put("retorno", scope, retorno); scope.put("utilStrings", scope, new UtilStrings()); scope.put("hashMapUtil", scope, new HashMapUtil()); final Object result = cx.evaluateString(scope, formula, sourceName, 1, null); return Context.toString(result); }
@Function( doc = "Read the certificate object from the keystore.", parameters = @Parameter(name = "name", type = "string", doc = "The certificate's name"), returns = "The certificate object.") public Object getCertificate(String name) throws KeyStoreException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Scriptable ret = Context.getCurrentContext().newObject(global); X509Certificate cer = (X509Certificate) keystore.getCertificate(name); for (PropertyDescriptor pc : BeanUtils.getPropertyDescriptors(X509Certificate.class)) { ret.put(pc.getName(), ret, String.valueOf(pc.getReadMethod().invoke(cer))); } return ret; }
public static Object eval(String source, Map<String, Scriptable> bindings) { Context cx = ContextFactory.getGlobal().enterContext(); try { Scriptable scope = cx.initStandardObjects(); if (bindings != null) { for (String id : bindings.keySet()) { Scriptable object = bindings.get(id); object.setParentScope(scope); scope.put(id, scope, object); } } return cx.evaluateString(scope, source, "source", 1, null); } finally { Context.exit(); } }
/** * Sets the value of the named property, creating it if need be. * * @param name the name of the property * @param start the object whose property is being set * @param value value to set the property to */ public void put(String name, Scriptable start, Object value) { if (start == this) { synchronized (this) { if (isEmpty(name)) { indexedProps.put(name, value); } else { synchronized (context) { int scope = context.getAttributesScope(name); if (scope == -1) { scope = ScriptContext.ENGINE_SCOPE; } context.setAttribute(name, jsToJava(value), scope); } } } } else { start.put(name, start, value); } }
/** * Registers a new scriptable object into current JavaScript context. * * @param clsScriptable The class representing the new scriptable object to be registered * @param sVarName The name of the javascript variable associated with the new scriptable object * that will be added to the scope * @throws ChartException */ public final void registerNewScriptableObject( Class<? extends Scriptable> clsScriptable, String sVarName) throws ChartException { try { ScriptableObject.defineClass(scope, clsScriptable); } catch (Exception ex) { throw convertException(ex); } final Context cx = Context.enter(); Scriptable soNew = null; try { soNew = cx.newObject(scope, clsScriptable.getName(), null); } catch (RuntimeException ex) { throw convertException(ex); } finally { Context.exit(); } scope.put(sVarName, scope, soNew); }
/** * Registers an existing scriptable object into current JavaScript context. * * @param so The existing scriptable object to be registered * @param sVarName The name of the javascript variable associated with the new scriptable object * that will be added to the scope * @throws ChartException */ public final void registerExistingScriptableObject(ScriptableObject so, String sVarName) throws ChartException { try { ScriptableObject.defineClass(scope, so.getClass()); } catch (Exception ex) { throw convertException(ex); } final Context cx = Context.enter(); Scriptable soNew = null; try { soNew = cx.newObject(scope, so.getClassName(), null); } catch (RhinoException ex) { throw convertException(ex); } finally { Context.exit(); } so.setPrototype(soNew.getPrototype()); so.setParentScope(soNew.getParentScope()); scope.put(sVarName, scope, so); }
public String compile(String coffeeScriptSource) throws JavaScriptException { Context context = Context.enter(); try { Scriptable compileScope = context.newObject(globalScope); compileScope.setParentScope(globalScope); compileScope.put("coffeeScriptSource", compileScope, coffeeScriptSource); Object src = context.evaluateString( compileScope, String.format("CoffeeScript.compile(coffeeScriptSource);"), "CoffeeScriptCompiler", 0, null); if (src != null) { return src.toString(); } else { return null; } } finally { Context.exit(); } }
public ModuleLoader() { global.put("require", global, this); }
/** * Este metodo trata do motor do sistema dinamico de gravacao de dados de visoes (montadas * dinamicamente) */ @Override public void save( final UsuarioDTO usuarioDto, final DinamicViewsDTO dinamicViewDto, final Map map, final HttpServletRequest request) throws Exception { final VisaoRelacionadaDao visaoRelacionadaDao = new VisaoRelacionadaDao(); final GrupoVisaoDao grupoVisaoDao = new GrupoVisaoDao(); final GrupoVisaoCamposNegocioDao grupoVisaoCamposNegocioDao = new GrupoVisaoCamposNegocioDao(); final CamposObjetoNegocioDao camposObjetoNegocioDao = new CamposObjetoNegocioDao(); final VinculoVisaoDao vinculoVisaoDao = new VinculoVisaoDao(); final ScriptsVisaoDao scriptsVisaoDao = new ScriptsVisaoDao(); final MatrizVisaoDao matrizVisaoDao = new MatrizVisaoDao(); final VisaoDao visaoDao = this.getDao(); final TransactionControler tc = this.getDao().getTransactionControler(); visaoRelacionadaDao.setTransactionControler(tc); grupoVisaoDao.setTransactionControler(tc); grupoVisaoCamposNegocioDao.setTransactionControler(tc); camposObjetoNegocioDao.setTransactionControler(tc); vinculoVisaoDao.setTransactionControler(tc); scriptsVisaoDao.setTransactionControler(tc); matrizVisaoDao.setTransactionControler(tc); final Integer idVisao = dinamicViewDto.getDinamicViewsIdVisao(); final Collection colScripts = scriptsVisaoDao.findByIdVisao(idVisao); final HashMap mapScritps = new HashMap<>(); if (colScripts != null) { for (final Iterator it = colScripts.iterator(); it.hasNext(); ) { final ScriptsVisaoDTO scriptsVisaoDTO = (ScriptsVisaoDTO) it.next(); mapScritps.put( scriptsVisaoDTO.getTypeExecute() + "#" + scriptsVisaoDTO.getScryptType().trim(), scriptsVisaoDTO.getScript()); } } final Collection colCamposPKPrincipal = new ArrayList<>(); final Collection colCamposTodosPrincipal = new ArrayList<>(); Collection colCamposTodosVinc = null; CamposObjetoNegocioDTO camposObjetoNegocioChaveMatriz = new CamposObjetoNegocioDTO(); this.setInfoSave(idVisao, colCamposPKPrincipal, colCamposTodosPrincipal); final Collection colVisoesRelacionadas = visaoRelacionadaDao.findByIdVisaoPaiAtivos(idVisao); try { tc.start(); if (this.isPKExists(colCamposPKPrincipal, map)) { String strScript = (String) mapScritps.get( ScriptsVisaoDTO.SCRIPT_EXECUTE_SERVER + "#" + ScriptsVisaoDTO.SCRIPT_ONUPDATE.getName()); if (strScript != null && !strScript.trim().equalsIgnoreCase("")) { final ScriptRhinoJSExecute scriptExecute = new ScriptRhinoJSExecute(); final RuntimeScript runtimeScript = new RuntimeScript(); final Context cx = Context.enter(); final Scriptable scope = cx.initStandardObjects(); scope.put("mapFields", scope, map); final String action = "UPDATE"; scope.put("ACTION", scope, action); scope.put("userLogged", scope, usuarioDto); scope.put("transactionControler", scope, tc); scope.put("dinamicViewDto", scope, dinamicViewDto); scope.put("RuntimeScript", scope, runtimeScript); scope.put("language", scope, WebUtil.getLanguage(request)); scriptExecute.processScript( cx, scope, strScript, VisaoServiceEjb.class.getName() + "_" + ScriptsVisaoDTO.SCRIPT_ONUPDATE.getName()); } if (!dinamicViewDto.isAbortFuncaoPrincipal()) { this.updateFromMap(map, colCamposTodosPrincipal, usuarioDto, visaoDao, request); strScript = (String) mapScritps.get( ScriptsVisaoDTO.SCRIPT_EXECUTE_SERVER + "#" + ScriptsVisaoDTO.SCRIPT_AFTERUPDATE.getName()); if (strScript != null && !strScript.trim().equalsIgnoreCase("")) { final ScriptRhinoJSExecute scriptExecute = new ScriptRhinoJSExecute(); final RuntimeScript runtimeScript = new RuntimeScript(); final Context cx = Context.enter(); final Scriptable scope = cx.initStandardObjects(); scope.put("mapFields", scope, map); final String action = "UPDATE"; scope.put("ACTION", scope, action); scope.put("userLogged", scope, usuarioDto); scope.put("transactionControler", scope, tc); scope.put("dinamicViewDto", scope, dinamicViewDto); scope.put("RuntimeScript", scope, runtimeScript); scope.put("language", scope, WebUtil.getLanguage(request)); scriptExecute.processScript( cx, scope, strScript, VisaoServiceEjb.class.getName() + "_" + ScriptsVisaoDTO.SCRIPT_AFTERUPDATE.getName()); } } } else { String strScript = (String) mapScritps.get( ScriptsVisaoDTO.SCRIPT_EXECUTE_SERVER + "#" + ScriptsVisaoDTO.SCRIPT_ONCREATE.getName()); if (strScript != null && !strScript.trim().equalsIgnoreCase("")) { final ScriptRhinoJSExecute scriptExecute = new ScriptRhinoJSExecute(); final RuntimeScript runtimeScript = new RuntimeScript(); final Context cx = Context.enter(); final Scriptable scope = cx.initStandardObjects(); scope.put("mapFields", scope, map); final String action = "CREATE"; scope.put("ACTION", scope, action); scope.put("userLogged", scope, usuarioDto); scope.put("transactionControler", scope, tc); scope.put("dinamicViewDto", scope, dinamicViewDto); scope.put("RuntimeScript", scope, runtimeScript); scope.put("language", scope, WebUtil.getLanguage(request)); scriptExecute.processScript( cx, scope, strScript, VisaoServiceEjb.class.getName() + "_" + ScriptsVisaoDTO.SCRIPT_ONCREATE.getName()); } if (!dinamicViewDto.isAbortFuncaoPrincipal()) { this.createFromMap(map, colCamposTodosPrincipal, usuarioDto, visaoDao, request); strScript = (String) mapScritps.get( ScriptsVisaoDTO.SCRIPT_EXECUTE_SERVER + "#" + ScriptsVisaoDTO.SCRIPT_AFTERCREATE.getName()); if (strScript != null && !strScript.trim().equalsIgnoreCase("")) { final ScriptRhinoJSExecute scriptExecute = new ScriptRhinoJSExecute(); final RuntimeScript runtimeScript = new RuntimeScript(); final Context cx = Context.enter(); final Scriptable scope = cx.initStandardObjects(); scope.put("mapFields", scope, map); final String action = "CREATE"; scope.put("ACTION", scope, action); scope.put("userLogged", scope, usuarioDto); scope.put("transactionControler", scope, tc); scope.put("dinamicViewDto", scope, dinamicViewDto); scope.put("RuntimeScript", scope, runtimeScript); scope.put("language", scope, WebUtil.getLanguage(request)); scriptExecute.processScript( cx, scope, strScript, VisaoServiceEjb.class.getName() + "_" + ScriptsVisaoDTO.SCRIPT_AFTERCREATE.getName()); } } } if (colVisoesRelacionadas != null) { for (final Iterator it = colVisoesRelacionadas.iterator(); it.hasNext(); ) { final VisaoRelacionadaDTO visaoRelacionadaDto = (VisaoRelacionadaDTO) it.next(); final Collection colVinculos = vinculoVisaoDao.findByIdVisaoRelacionada(visaoRelacionadaDto.getIdVisaoRelacionada()); final Object objFromHash = map.get( VisaoRelacionadaDTO.PREFIXO_SISTEMA_TABELA_VINCULADA + visaoRelacionadaDto.getIdVisaoFilha()); VisaoDTO visaoDtoAux = new VisaoDTO(); visaoDtoAux.setIdVisao(visaoRelacionadaDto.getIdVisaoFilha()); visaoDtoAux = (VisaoDTO) visaoDao.restore(visaoDtoAux); MatrizVisaoDTO matrizVisaoDTO = new MatrizVisaoDTO(); boolean ehMatriz = false; if (visaoDtoAux != null) { if (visaoDtoAux.getTipoVisao().equalsIgnoreCase(VisaoDTO.MATRIZ)) { ehMatriz = true; matrizVisaoDTO.setIdVisao(visaoDtoAux.getIdVisao()); final Collection colMatriz = matrizVisaoDao.findByIdVisao(visaoDtoAux.getIdVisao()); if (colMatriz != null && colMatriz.size() > 0) { matrizVisaoDTO = (MatrizVisaoDTO) colMatriz.iterator().next(); camposObjetoNegocioChaveMatriz.setIdCamposObjetoNegocio( matrizVisaoDTO.getIdCamposObjetoNegocio1()); camposObjetoNegocioChaveMatriz.setIdObjetoNegocio( matrizVisaoDTO.getIdObjetoNegocio()); camposObjetoNegocioChaveMatriz = (CamposObjetoNegocioDTO) camposObjetoNegocioDao.restore(camposObjetoNegocioChaveMatriz); } } } if (HashMap.class.isInstance(objFromHash)) { final HashMap mapVinc = (HashMap) objFromHash; if (mapVinc != null) { // Se existir dados recebidos. final Collection colCamposPKVinc = new ArrayList<>(); colCamposTodosVinc = new ArrayList<>(); this.setInfoSave( visaoRelacionadaDto.getIdVisaoFilha(), colCamposPKVinc, colCamposTodosVinc); // Grava os dados de informacoes vinculadas. if (this.isPKExists(colCamposPKVinc, mapVinc)) { this.updateFromMap(mapVinc, colCamposTodosVinc, usuarioDto, visaoDao, request); } else { this.createFromMap(mapVinc, colCamposTodosVinc, usuarioDto, visaoDao, request); } } } else if (Collection.class.isInstance(objFromHash)) { final Collection colVinc = (Collection) objFromHash; if (colVinc != null) { for (final Iterator it2 = colVinc.iterator(); it2.hasNext(); ) { Map mapVinc = (Map) it2.next(); if (mapVinc != null) { // Se existir dados recebidos. final Collection colCamposPKVinc = new ArrayList<>(); colCamposTodosVinc = new ArrayList<>(); this.setInfoSave( visaoRelacionadaDto.getIdVisaoFilha(), colCamposPKVinc, colCamposTodosVinc); // ***** String tipoVinc = ""; if (colVinculos != null && colVinculos.size() > 0) { final VinculoVisaoDTO vinculoVisaoDTO = (VinculoVisaoDTO) ((List) colVinculos).get(0); tipoVinc = vinculoVisaoDTO.getTipoVinculo(); } if (ehMatriz) { if (camposObjetoNegocioChaveMatriz != null) { mapVinc.put(camposObjetoNegocioChaveMatriz.getNomeDB(), mapVinc.get("FLD_0")); } CamposObjetoNegocioDTO camposObjetoNegocioDTO = null; if (colCamposPKVinc != null && colCamposPKVinc.size() > 0) { for (final Iterator itVinc = colCamposPKVinc.iterator(); itVinc.hasNext(); ) { camposObjetoNegocioDTO = (CamposObjetoNegocioDTO) itVinc.next(); if (!camposObjetoNegocioDTO .getNomeDB() .trim() .equalsIgnoreCase(camposObjetoNegocioChaveMatriz.getNomeDB().trim())) { mapVinc.put( camposObjetoNegocioDTO.getNomeDB(), map.get(camposObjetoNegocioDTO.getNomeDB())); } } } if (tipoVinc == null || tipoVinc.equalsIgnoreCase("")) { tipoVinc = VinculoVisaoDTO.VINCULO_1_TO_N; } } if (tipoVinc.equalsIgnoreCase(VinculoVisaoDTO.VINCULO_N_TO_N)) { // Grava os dados de informacoes vinculadas. if (this.isPKExists(colCamposPKVinc, mapVinc)) { this.updateFromMap( mapVinc, colCamposTodosVinc, usuarioDto, visaoDao, request); } else { this.createFromMap( mapVinc, colCamposTodosVinc, usuarioDto, visaoDao, request); } this.processCreateVinc( visaoRelacionadaDto, colVinculos, map, mapVinc, usuarioDto, request); } if (tipoVinc.equalsIgnoreCase(VinculoVisaoDTO.VINCULO_1_TO_N)) { mapVinc = this.createUniqueMap(map, mapVinc); // ****** // Grava os dados de informacoes vinculadas. if (this.isPKExists(colCamposPKVinc, mapVinc)) { this.updateFromMap( mapVinc, colCamposTodosVinc, usuarioDto, visaoDao, request); } else { this.createFromMap( mapVinc, colCamposTodosVinc, usuarioDto, visaoDao, request); } } } } } } } } if (dinamicViewDto.getIdFluxo() != null || dinamicViewDto.getIdTarefa() != null) { new ExecucaoSolicitacaoServiceEjb() .executa( usuarioDto, tc, dinamicViewDto.getIdFluxo(), dinamicViewDto.getIdTarefa(), dinamicViewDto.getAcaoFluxo(), map, colCamposTodosPrincipal, colCamposTodosVinc); } tc.commit(); tc.close(); } catch (final Exception e) { this.rollbackTransaction(tc, e); } }
@Override public synchronized Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { Transaction previousTransaction = Transaction.currentTransaction(); Transaction.startTransaction(); String filename = (String) args[0]; if (filename.startsWith(".")) filename = currentJslibPath + filename; filename = Pattern.compile("\\.\\./[^.]*/").matcher(filename).replaceAll("/"); filename = filename.replace("./", ""); InputStream inStream; ScriptableObject exportObject; String oldJsLibPath = currentJslibPath; try { File jslibFile = jslibFiles.get(filename); if (jslibFile == null && !filename.endsWith(".js")) { filename += ".js"; jslibFile = jslibFiles.get(filename); } if (jslibFile == null) throw ScriptRuntime.constructError("Error", "File not found " + filename); exportObject = exports.get(filename); Long lastTimeStamp = lastTimeStamps.get(filename); if (lastTimeStamp == null || lastTimeStamp < jslibFile.lastModified()) { lastTimeStamps.put(filename, jslibFile.lastModified()); inStream = new FileInputStream(jslibFile); exportObject = new NativeObject(); ScriptRuntime.setObjectProtoAndParent((ScriptableObject) exportObject, global); // setup the module scope ScriptableObject moduleScope = new NativeObject(); moduleScope.setParentScope(global); int lastSlash = filename.lastIndexOf('/'); currentJslibPath = lastSlash == -1 ? "" : filename.substring(0, lastSlash + 1); moduleScope.put("exports", moduleScope, exportObject); // memoize exports.put(filename, exportObject); // evaluate the script try { cx.evaluateString(moduleScope, IOUtils.toString(inStream, "UTF-8"), filename, 1, null); } catch (RuntimeException e) { // revert exports.remove(filename); jslibFiles.put(filename, jslibFile); throw e; } // re-retrieve it in case the library changed it exportObject = (ScriptableObject) moduleScope.get("exports", moduleScope); exports.put(filename, exportObject); if ("jsgi-app.js".equals(filename)) { // handle jackconfig.js, setting up the app if it is there global.put("app", global, exportObject.get("app", exportObject)); } // freeze it // exportObject.sealObject(); } Transaction.currentTransaction().commit(); } catch (IOException e) { throw ScriptRuntime.constructError("Error", e.getMessage()); } finally { currentJslibPath = oldJsLibPath; previousTransaction.enterTransaction(); } return exportObject; }
private void handleAcceptHeader(String hdr, String value, Context cx, Scriptable accept) { String subname; if (hdr.equals("Accept")) { subname = "media"; } else if (hdr.startsWith("Accept-")) { subname = hdr.substring(7).toLowerCase(); } else { // Do nothing return; } Map<Double, List<Scriptable>> objects = new TreeMap<Double, List<Scriptable>>(); String[] values = value.split(","); for (String v : values) { double q = 1.0; double w = 0.0; String[] parts = v.split(";"); Scriptable object = cx.newObject(accept); object.put("valueOf", object, acceptValueOf); object.put("value", object, parts[0].trim()); // Add all attributes for (int i = 1; i < parts.length; ++i) { String[] attr = parts[i].split("=", 2); if (attr.length == 2) { // Parse Q factor if (attr[0].trim().equals("q")) { q = Double.parseDouble(attr[1].trim()); } else { object.put(attr[0].trim(), object, attr[1].trim()); } } } object.put("q", object, "" + q); // Calculate implicit weight if (parts[0].trim().equals("*/*")) { w = 0.0000; } else if (parts[0].trim().endsWith("/*")) { w = 0.0001; } else { w = 0.0002; } // Attributes give extra points w += parts.length * 0.00001; // Add to tree multi-map, inverse order double key = -(q + w); List<Scriptable> l = objects.get(key); if (l == null) { l = new ArrayList<Scriptable>(); objects.put(key, l); } l.add(object); } Scriptable object = cx.newArray(accept, objects.size()); accept.put(subname, accept, object); int i = 0; for (List<Scriptable> l : objects.values()) { for (Scriptable s : l) { object.put(i++, object, s); } } }