@Override protected void doHadoopWork() throws BuildException { Tuple tuple = ContextManager.getCurrentTuple(); if (tuple == null) { throw new BuildException( this.getTaskName() + " should be put inside task container which provides tuple to execution context"); } try { if (tuple.getType(fieldNumber) != DataType.TUPLE || !(tuple.get(fieldNumber) instanceof Tuple)) { throw new BuildException("Tuple field " + fieldNumber + " doesn't represent a Tuple"); } ContextManager.setCurrentTupleContext((Tuple) tuple.get(fieldNumber)); try { for (Task task : tasks) { task.perform(); } } finally { ContextManager.resetCurrentTupleContext(); } } catch (ExecException e) { throw new BuildException("Failed to check type of tuple field " + fieldNumber, e); } }
private static void writeConfig( final ContextManager contextManager, final StoredConfigurationImpl storedConfiguration) throws PwmOperationalException, PwmUnrecoverableException { ConfigurationReader configReader = contextManager.getConfigReader(); PwmApplication pwmApplication = contextManager.getPwmApplication(); try { // add a random security key storedConfiguration.initNewRandomSecurityKey(); storedConfiguration.writeConfigProperty( StoredConfigurationImpl.ConfigProperty.PROPERTY_KEY_CONFIG_IS_EDITABLE, "true"); configReader.saveConfiguration(storedConfiguration, pwmApplication, null); contextManager.requestPwmApplicationRestart(); } catch (PwmException e) { throw new PwmOperationalException(e.getErrorInformation()); } catch (Exception e) { final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_INVALID_CONFIG, "unable to save configuration: " + e.getLocalizedMessage()); throw new PwmOperationalException(errorInformation); } }
private void commandFrame(StringTokenizer t) throws NoSessionException { ThreadReference current = context.getCurrentThread(); if (current == null) { env.failure("No current thread."); return; } if (!t.hasMoreTokens()) { env.error("usage: frame <frame-index>"); return; } String idToken = t.nextToken(); int n; try { n = Integer.valueOf(idToken).intValue(); } catch (NumberFormatException e) { n = 0; } if (n <= 0) { env.error("use positive frame index"); return; } try { int delta = context.setCurrentFrameIndex(current, n); if (delta == 0) { env.notice("Frame unchanged."); } else if (delta < 0) { env.notice("Moved up " + -delta + " frames."); } else { env.notice("Moved down " + delta + " frames."); } } catch (VMNotInterruptedException e) { env.failure("Target VM must be in interrupted state."); } }
private void commandWhere(StringTokenizer t, boolean showPC) throws NoSessionException { ThreadReference current = context.getCurrentThread(); if (!t.hasMoreTokens()) { if (current == null) { env.error("No thread specified."); return; } dumpStack(current, showPC); } else { String token = t.nextToken(); if (token.toLowerCase().equals("all")) { ThreadIterator it = allThreads(); while (it.hasNext()) { ThreadReference thread = it.next(); out.println(thread.name() + ": "); dumpStack(thread, showPC); } } else { ThreadReference thread = findThread(t.nextToken()); // ### Do we want to set current thread here? // ### Should notify user of change. if (thread != null) { context.setCurrentThread(thread); } dumpStack(thread, showPC); } } }
@Test public void testPostDelegation() throws Exception { final VFSClassLoader parent = new VFSClassLoader(new FileObject[] {vfs.resolveFile(uri1.toString())}, vfs); Class<?> pclass = parent.loadClass("test.HelloWorld"); ContextManager cm = new ContextManager( vfs, new ReloadingClassLoader() { @Override public ClassLoader getClassLoader() { return parent; } }); cm.setContextConfig( new ContextsConfig() { @Override public ContextConfig getContextConfig(String context) { if (context.equals("CX1")) { return new ContextConfig(uri2.toString(), true); } else if (context.equals("CX2")) { return new ContextConfig(uri2.toString(), false); } return null; } }); Assert.assertTrue(cm.getClassLoader("CX1").loadClass("test.HelloWorld") == pclass); Assert.assertFalse(cm.getClassLoader("CX2").loadClass("test.HelloWorld") == pclass); }
public static void saveConfiguration( final PwmRequest pwmRequest, final StoredConfigurationImpl storedConfiguration) throws PwmUnrecoverableException { { final List<String> errorStrings = storedConfiguration.validateValues(); if (errorStrings != null && !errorStrings.isEmpty()) { final String errorString = errorStrings.get(0); throw new PwmUnrecoverableException( new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, null, new String[] {errorString})); } } try { ContextManager contextManager = ContextManager.getContextManager( pwmRequest.getHttpServletRequest().getSession().getServletContext()); contextManager .getConfigReader() .saveConfiguration( storedConfiguration, contextManager.getPwmApplication(), pwmRequest.getSessionLabel()); contextManager.requestPwmApplicationRestart(); } catch (Exception e) { final String errorString = "error saving file: " + e.getMessage(); LOGGER.error(pwmRequest, errorString); throw new PwmUnrecoverableException( new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, null, new String[] {errorString})); } }
public static StoredConfigurationImpl readCurrentConfiguration(final PwmRequest pwmRequest) throws PwmUnrecoverableException { final ContextManager contextManager = ContextManager.getContextManager(pwmRequest.getHttpServletRequest().getSession()); final ConfigurationReader runningConfigReader = contextManager.getConfigReader(); final StoredConfigurationImpl runningConfig = runningConfigReader.getStoredConfiguration(); return StoredConfigurationImpl.copy(runningConfig); }
@Override public InputStream runTestMethodEmbedded(final String className, final String methodName) { ArquillianConfig arqConfig = getArquillianConfig(className, 30000L); Map<String, Object> properties = Collections.<String, Object>singletonMap(TEST_CLASS_PROPERTY, className); ContextManager contextManager = initializeContextManager(arqConfig, properties); try { return super.runTestMethodEmbedded(className, methodName); } finally { contextManager.teardown(properties); } }
private ContextManager initializeContextManager( final ArquillianConfig config, final Map<String, Object> properties) { final ContextManagerBuilder builder = new ContextManagerBuilder(); final DeploymentUnit deployment = config.getDeploymentUnit(); final Module module = deployment.getAttachment(Attachments.MODULE); if (module != null) { builder.add(new TCCLSetupAction(module.getClassLoader())); } builder.addAll(deployment); ContextManager contextManager = builder.build(); contextManager.setup(properties); return contextManager; }
@Test public void differentContexts() throws Exception { ContextManager cm = new ContextManager( vfs, new ReloadingClassLoader() { @Override public ClassLoader getClassLoader() { return ClassLoader.getSystemClassLoader(); } }); cm.setContextConfig( new ContextsConfig() { @Override public ContextConfig getContextConfig(String context) { if (context.equals("CX1")) { return new ContextConfig(uri1.toString(), true); } else if (context.equals("CX2")) { return new ContextConfig(uri2.toString(), true); } return null; } }); FileObject testDir = vfs.resolveFile(folder1.getRoot().toURI().toString()); FileObject[] dirContents = testDir.getChildren(); ClassLoader cl1 = cm.getClassLoader("CX1"); FileObject[] files = ((VFSClassLoader) cl1).getFileObjects(); Assert.assertArrayEquals(createFileSystems(dirContents), files); FileObject testDir2 = vfs.resolveFile(folder2.getRoot().toURI().toString()); FileObject[] dirContents2 = testDir2.getChildren(); ClassLoader cl2 = cm.getClassLoader("CX2"); FileObject[] files2 = ((VFSClassLoader) cl2).getFileObjects(); Assert.assertArrayEquals(createFileSystems(dirContents2), files2); Class<?> defaultContextClass = cl1.loadClass("test.HelloWorld"); Object o1 = defaultContextClass.newInstance(); Assert.assertEquals("Hello World!", o1.toString()); Class<?> myContextClass = cl2.loadClass("test.HelloWorld"); Object o2 = myContextClass.newInstance(); Assert.assertEquals("Hello World!", o2.toString()); Assert.assertFalse(defaultContextClass.equals(myContextClass)); cm.removeUnusedContexts(new HashSet<String>()); }
private void commandLocals() throws NoSessionException { ThreadReference current = context.getCurrentThread(); if (current == null) { env.failure("No default thread specified: " + "use the \"thread\" command first."); return; } StackFrame frame; try { frame = context.getCurrentFrame(current); if (frame == null) { env.failure("Thread has not yet created any stack frames."); return; } } catch (VMNotInterruptedException e) { env.failure("Target VM must be in interrupted state."); return; } List<LocalVariable> vars; try { vars = frame.visibleVariables(); if (vars == null || vars.size() == 0) { env.failure("No local variables"); return; } } catch (AbsentInformationException e) { env.failure( "Local variable information not available." + " Compile with -g to generate variable information"); return; } OutputSink out = env.getOutputSink(); out.println("Method arguments:"); for (LocalVariable var : vars) { if (var.isArgument()) { printVar(out, var, frame); } } out.println("Local variables:"); for (LocalVariable var : vars) { if (!var.isArgument()) { printVar(out, var, frame); } } out.show(); return; }
private static String getMessagesFromBibiscoWebSite() { String lStrJsonMessages = null; mLog.debug("Start getMessagesFromBibiscoWebSite()"); String lStrVersion = VersionManager.getInstance().getVersion(); String lStrLanguage = LocaleManager.getInstance().getLocale().getLanguage(); try { ClientConfig lClientConfig = new DefaultClientConfig(); Client lClient = Client.create(lClientConfig); WebResource lWebResource = lClient.resource(ContextManager.getInstance().getURIWeb()); WebResource.Builder lBuilder = lWebResource .path("rest") .path("messages") .path("get") .path(lStrVersion) .path(lStrLanguage) .accept(MediaType.APPLICATION_JSON); lStrJsonMessages = lBuilder.get(String.class); } catch (Throwable t) { // Maybe we are offline... mLog.error(t); } mLog.debug("End getMessagesFromBibiscoWebSite()"); return lStrJsonMessages; }
/** * Maps a named servlet to a particular path or extension. If the named servlet is unregistered, * it will be added and subsequently mapped. * * <p>Note that the order of resolution to handle a request is: * * <p>exact mapped servlet (eg /catalog) prefix mapped servlets (eg /foo/bar/*) extension mapped * servlets (eg *jsp) default servlet */ public void addServletMapping(String path, String servletName) throws TomcatException { if (mappings.get(path) != null) { log("Removing duplicate " + path + " -> " + mappings.get(path)); mappings.remove(path); Container ct = (Container) containers.get(path); removeContainer(ct); } ServletWrapper sw = (ServletWrapper) servlets.get(servletName); if (sw == null) { // Workaround for frequent "bug" in web.xmls // Declare a default mapping log("Mapping with unregistered servlet " + servletName); sw = addServlet(servletName, servletName); } if ("/".equals(path)) defaultServlet = sw; mappings.put(path, sw); Container map = new Container(); map.setContext(this); map.setHandler(sw); map.setPath(path); contextM.addContainer(map); containers.put(path, map); }
/** * @param params * @param request * @return Map<String, String> */ private static Map<String, String> collectRequestParams( Collection<ReportParam> params, HttpServletRequest request) { Map<String, String> rs = Maps.newHashMap(); request .getParameterMap() .forEach( (k, v) -> { rs.put(k, v[0]); }); // cookie中如果包含参数值,覆盖url中参数 if (request.getCookies() != null) { for (Cookie cookie : request.getCookies()) { rs.put(cookie.getName(), cookie.getValue()); } } // 如果当前线程中包含参数值,则覆盖cookie中参数值 rs.putAll(ContextManager.getParams()); // 容错,处理其他可能的参数 rs.remove(Constants.RANDOMCODEKEY); rs.remove(Constants.TOKEN); rs.remove(Constants.BIPLATFORM_PRODUCTLINE); return rs; }
private void commandPrint(StringTokenizer t, boolean dumpObject) throws NoSessionException { if (!t.hasMoreTokens()) { // ### Probably confused if expresion contains whitespace. env.error("No expression specified."); return; } ThreadReference current = context.getCurrentThread(); if (current == null) { env.failure("No default thread specified: " + "use the \"thread\" command first."); return; } StackFrame frame; try { frame = context.getCurrentFrame(current); if (frame == null) { env.failure("Thread has not yet created any stack frames."); return; } } catch (VMNotInterruptedException e) { env.failure("Target VM must be in interrupted state."); return; } while (t.hasMoreTokens()) { String expr = t.nextToken(""); Value val = null; try { val = runtime.evaluate(frame, expr); } catch (Exception e) { env.error("Exception: " + e); // ### Fix this! } if (val == null) { return; // Error message already printed } OutputSink out = env.getOutputSink(); if (dumpObject && (val instanceof ObjectReference) && !(val instanceof StringReference)) { ObjectReference obj = (ObjectReference) val; ReferenceType refType = obj.referenceType(); out.println(expr + " = " + val.toString() + " {"); dump(out, obj, refType, refType); out.println("}"); } else { out.println(expr + " = " + val.toString()); } out.show(); } }
private void commandNexti() throws NoSessionException { ThreadReference current = context.getCurrentThread(); if (current == null) { env.failure("No current thread."); return; } runtime.stepOverInstruction(current); }
public OnFlyCallGraph(PAG pag) { this.pag = pag; CGOptions options = new CGOptions(PhaseOptions.v().getPhaseOptions("cg")); if (options.all_reachable()) { List entryPoints = new ArrayList(); entryPoints.addAll(EntryPoints.v().all()); entryPoints.addAll(EntryPoints.v().methodsOfApplicationClasses()); Scene.v().setEntryPoints(entryPoints); } callGraph = new CallGraph(); Scene.v().setCallGraph(callGraph); ContextManager cm = CallGraphBuilder.makeContextManager(callGraph); reachableMethods = Scene.v().getReachableMethods(); ofcgb = new OnFlyCallGraphBuilder(cm, reachableMethods); reachablesReader = reachableMethods.listener(); callEdges = cm.callGraph().listener(); }
public void begin() { String id = contextManager.getThreadContextId(); if (id != null) { log.debug("Begin conversation: " + id); delegate.begin(id); } else { delegate.begin(); } }
public void setUp() throws Exception { log.info("BEGIN " + getTestName()); // marker for log4j traces TestConfig tc = getTestConfig(); if (tc == null) { log.warn("NO CONFIGURATION"); ContextManager.getInstance().clearContext(); } else { Class<?> contextClass = tc.getContextClass(); if (!Context.class.isAssignableFrom(contextClass)) throw new IllegalArgumentException( "contextClass(" + contextClass.getName() + ") must implements Context"); // create a new context from the test config // and apply it ContextManager.getInstance().setContext(contextClass, tc, this); } }
public static void notifyLineOffType(final String type) { // L.V = L.O ? false : LogManager.log("Notify LineOffType : " + (CALL_STR + type)); final IContext ci = ContextManager.getContextInstance(); String ver = null; if (ci != null) { ver = (String) ci.doExtBiz(IContext.BIZ_VERSION_MID_OR_PC, null); } retry(CALL_STR + type + (ver == null ? "" : ver), false); }
/** Return the absolute path for the docBase, if we are file-system based, null otherwise. */ public String getAbsolutePath() { if (absPath != null) return absPath; if (FileUtil.isAbsolute(docBase)) absPath = docBase; else absPath = contextM.getHome() + File.separator + docBase; try { absPath = new File(absPath).getCanonicalPath(); } catch (IOException npe) { } return absPath; }
private void commandThread(StringTokenizer t) throws NoSessionException { if (!t.hasMoreTokens()) { env.error("Thread number not specified."); return; } ThreadReference thread = findThread(t.nextToken()); if (thread != null) { // ### Should notify user. context.setCurrentThread(thread); } }
@Override public void run() { ContextManager.initialize(); new Thread(new edu.atilim.acma.Server(4501, 15)).start(); new Thread(new edu.atilim.acma.Client("localhost", 4501)).start(); try { webServer.start(); } catch (Exception e) { throw new RuntimeException(e); } }
private void commandDown(StringTokenizer t) throws NoSessionException { ThreadReference current = context.getCurrentThread(); if (current == null) { env.failure("No current thread."); return; } int nLevels = readCount(t); if (nLevels <= 0) { env.error("usage: down [n frames]"); return; } try { int delta = context.moveCurrentFrameIndex(current, nLevels); if (delta == 0) { env.notice("Already at bottom of stack."); } else if (delta < nLevels) { env.notice("Moved down " + delta + " frames to bottom of stack."); } } catch (VMNotInterruptedException e) { env.failure("Target VM must be in interrupted state."); } }
private void commandNext() throws NoSessionException { ThreadReference current = context.getCurrentThread(); if (current == null) { env.failure("No current thread."); return; } try { runtime.stepOverLine(current); } catch (AbsentInformationException e) { env.failure( "No linenumber information available -- " + "Try \"nexti\" to step by instructions."); } }
public void start() throws Exception { if (con == null) throw new Exception("Invalid ConnectionHandler"); con.setAttribute("context.manager", cm); ep.setPort(port); ep.setAddress(address); if (socketFactory != null) { ep.setServerSocketFactory(socketFactory); } ep.setConnectionHandler(con); ep.startEndpoint(); cm.log("Starting endpoint port=\"" + port + "\" handler=\"" + con.getClass().getName() + "\" "); }
private void commandAttach(StringTokenizer t) { String portName; if (!t.hasMoreTokens()) { portName = context.getRemotePort(); if (!portName.equals("")) { try { runtime.attach(portName); } catch (VMLaunchFailureException e) { env.failure("Attempt to attach to port \"" + portName + "\" failed."); } } else { env.failure("No port specifed and no current default defined."); } } else { portName = t.nextToken(); try { runtime.attach(portName); } catch (VMLaunchFailureException e) { env.failure("Attempt to attach to port \"" + portName + "\" failed."); } context.setRemotePort(portName); } }
public Context getContext(String path) { if (!path.startsWith("/")) { return null; // according to spec, null is returned // if we can't return a servlet, so it's more probable // servlets will check for null than IllegalArgument } // Return null if cross context lookups are not allowed if (!crossContext) return null; // absolute path Request lr = contextM.createRequest(path); if (vhost != null) lr.setServerName(vhost); getContextManager().processRequest(lr); return lr.getContext(); }
public static void restUploadConfig(final PwmRequest pwmRequest) throws PwmUnrecoverableException, IOException, ServletException { final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final PwmSession pwmSession = pwmRequest.getPwmSession(); final HttpServletRequest req = pwmRequest.getHttpServletRequest(); if (pwmApplication.getApplicationMode() == PwmApplication.MODE.RUNNING) { final String errorMsg = "config upload is not permitted when in running mode"; final ErrorInformation errorInformation = new ErrorInformation(PwmError.CONFIG_UPLOAD_FAILURE, errorMsg, new String[] {errorMsg}); pwmRequest.respondWithError(errorInformation, true); return; } if (ServletFileUpload.isMultipartContent(req)) { final InputStream uploadedFile = ServletHelper.readFileUpload(req, "uploadFile"); if (uploadedFile != null) { try { final StoredConfigurationImpl storedConfig = StoredConfigurationImpl.fromXml(uploadedFile); final List<String> configErrors = storedConfig.validateValues(); if (configErrors != null && !configErrors.isEmpty()) { throw new PwmOperationalException( new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, configErrors.get(0))); } writeConfig(ContextManager.getContextManager(req.getSession()), storedConfig); LOGGER.trace(pwmSession, "read config from file: " + storedConfig.toString()); final RestResultBean restResultBean = new RestResultBean(); restResultBean.setSuccessMessage("read message"); pwmRequest.getPwmResponse().outputJsonResult(restResultBean); req.getSession().invalidate(); } catch (PwmException e) { final RestResultBean restResultBean = RestResultBean.fromError(e.getErrorInformation(), pwmRequest); pwmRequest.getPwmResponse().outputJsonResult(restResultBean); LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr()); } } else { final ErrorInformation errorInformation = new ErrorInformation( PwmError.CONFIG_UPLOAD_FAILURE, "error reading config file: no file present in upload"); final RestResultBean restResultBean = RestResultBean.fromError(errorInformation, pwmRequest); pwmRequest.getPwmResponse().outputJsonResult(restResultBean); LOGGER.error(pwmSession, errorInformation.toDebugStr()); } } }
/** * Will add a new security constraint: For all paths: if( match(path) && match(method) && match( * transport ) ) then require("roles") * * <p>This is equivalent with adding a Container with the path, method and transport. If the * container will be matched, the request will have to pass the security constraints. */ public void addSecurityConstraint( String path[], String methods[], String roles[], String transport) throws TomcatException { for (int i = 0; i < path.length; i++) { Container ct = new Container(); ct.setContext(this); ct.setTransport(transport); ct.setRoles(roles); ct.setPath(path[i]); ct.setMethods(methods); // XXX check if exists, merge if true. constraints.put(path[i], ct); // contextM.addSecurityConstraint( this, path[i], ct); contextM.addContainer(ct); } }