/** * Start server * * @param string[] args */ public static function main(array $args) { $stor = new TestingStorage(); $stor->add(new TestingCollection('/', $stor)); $stor->add(new TestingCollection('/.trash', $stor)); $stor->add(new TestingElement('/.trash/do-not-remove.txt', $stor)); $stor->add(new TestingCollection('/htdocs', $stor)); $stor->add(new TestingElement('/htdocs/file with whitespaces.html', $stor)); $stor->add(new TestingElement('/htdocs/index.html', $stor, "<html/>\n")); $stor->add(new TestingCollection('/outer', $stor)); $stor->add(new TestingCollection('/outer/inner', $stor)); $stor->add(new TestingElement('/outer/inner/index.html', $stor)); $auth = newinstance('lang.Object', array(), '{ public function authenticate($user, $password) { return ("testtest" == $user.$password); } }'); $protocol = newinstance('peer.ftp.server.FtpProtocol', array($stor, $auth), '{ public function onShutdown($socket, $params) { $this->answer($socket, 200, "Shutting down"); $this->server->terminate= TRUE; } }'); isset($args[0]) && $protocol->setTrace(Logger::getInstance()->getCategory()->withAppender(new FileAppender($args[0]))); $s = new Server('127.0.0.1', 0); try { $s->setProtocol($protocol); $s->init(); Console::writeLinef('+ Service %s:%d', $s->socket->host, $s->socket->port); $s->service(); Console::writeLine('+ Done'); } catch (Throwable $e) { Console::writeLine('- ', $e->getMessage()); } }
public function getPageResults() { Console::writeLine('fetching'); $this->fetch(); file_put_contents(Yii::app()->basePath . '/reports/pagehtml.html', $this->pageHtml); CVarDumper::dump($this->response, 10, false); die('Debug Point'); }
/** * Main * * @param string[] args * @return int */ public static function main(array $args) { Console::writeLinef('XP %s { PHP %s & ZE %s } @ %s', xp::version(), phpversion(), zend_version(), php_uname()); Console::writeLine('Copyright (c) 2001-2013 the XP group'); foreach (ClassLoader::getLoaders() as $delegate) { Console::writeLine($delegate->toString()); } return 1; }
/** * Display some information * * Annotate this method w/ @test to retrieve debug information. */ public function classLoaderInformation() { with($p = Package::forName('net.xp_framework.unittest.reflection.classes')); Console::writeLine('Object : ', XPClass::forName('lang.Object')->getClassLoader()); Console::writeLine('This : ', $this->getClass()->getClassLoader()); Console::writeLine('ClassOne : ', $p->loadClass('ClassOne')->getClassLoader()); Console::writeLine('ClassTwo : ', $p->loadClass('ClassTwo')->getClassLoader()); Console::writeLine('ClassThree : ', $p->loadClass('ClassThree')->getClassLoader()); Console::writeLine('ClassFour : ', $p->loadClass('ClassFour')->getClassLoader()); Console::writeLine('ClassFive : ', $p->loadClass('ClassFive')->getClassLoader()); }
public function visit($Object) { if (is('org.dia.DiaObject', $Object)) { Console::writeLine("DiaObject: " . $Object->getName()); } if (is('org.dia.DiaComposite', $Object)) { $name = $Object->getName(); if (isset($name)) { Console::writeLine("DiaComposite: {$name}"); } } }
/** * Start server * * @param string[] args */ public static function main(array $args) { $s = new Server('127.0.0.1', 0); try { $s->setProtocol(XPClass::forName($args[0])->newInstance()); $s->init(); Console::writeLinef('+ Service %s:%d', $s->socket->host, $s->socket->port); $s->service(); Console::writeLine('+ Done'); } catch (Throwable $e) { Console::writeLine('- ', $e->getMessage()); } }
/** * Entry point method. Gets passed the following arguments from "xpws -i": * <ol> * <li>The web root - defaults to $CWD</li> * <li>The configuration directory - defaults to "etc"</li> * <li>The server profile - default to "dev"</li> * <li>The server address - default to "localhost:8080"</li> * </ol> * * @param string[] args */ public static function main(array $args) { $webroot = isset($args[0]) ? realpath($args[0]) : getcwd(); $configd = isset($args[1]) ? $args[1] : 'etc'; $profile = isset($args[2]) ? $args[2] : 'dev'; $address = isset($args[3]) ? $args[3] : 'localhost:8080'; Console::writeLine('xpws-', $profile, ' @ ', $address, ', ', $webroot, ' {'); // Dump configured applications $conf = new xp·scriptlet·WebConfiguration(new Properties($configd . DIRECTORY_SEPARATOR . 'web.ini')); foreach ($conf->mappedApplications($profile) as $url => $app) { Console::writeLine(' Route<', $url, '*> => ', xp::stringOf($app, ' ')); } Console::writeLine('}'); }
/** * * @param array classnames List of fully qualified class names * @param int recurse default 0 * @param bool depend default FALSE * @return &org.dia.DiaDiagram */ public function marshal($classnames, $recurse = 0, $depend = FALSE) { // create new DiaDiagram $Dia = new DiaDiagram(); // check classnames? foreach ($classnames as $classname) { try { $Class = XPClass::forName($Classname); } catch (Exception $e) { Console::writeLine("CLASS NOT FOUND: {$classname}!"); } } return TestMarshaller::recurse($Dia, $classnames, $recurse, $depend); }
/** * Start server * * @param string[] args */ public static function main(array $args) { // Add shutdown message handler EascMessageFactory::setHandler(61, newinstance('remote.server.message.EascMessage', array(), '{ public function getType() { return 61; } public function handle($protocol, $data) { Logger::getInstance()->getCategory()->debug("Shutting down"); $protocol->server->terminate= TRUE; } }')->getClass()); $s = new Server('127.0.0.1', 0); try { $protocol = new EascProtocol(newinstance('remote.server.deploy.scan.DeploymentScanner', array(), '{ private $changed= TRUE; public function scanDeployments() { $changed= $this->changed; $this->changed= FALSE; return $changed; } public function getDeployments() { $res= "net/xp_framework/unittest/remote/deploy/beans.test.CalculatorBean.xar"; with ($d= new Deployment($res)); { $d->setClassLoader(new ArchiveClassLoader(new Archive(ClassLoader::getDefault()->getResourceAsStream($res)))); $d->setImplementation("beans.test.CalculatorBeanImpl"); $d->setInterface("beans.test.Calculator"); $d->setDirectoryName("xp/test/Calculator"); return array($d); } } }')); $protocol->initialize(); $s->setProtocol($protocol); $s->init(); Console::writeLinef('+ Service %s:%d', $s->socket->host, $s->socket->port); $s->service(); Console::writeLine('+ Done'); } catch (Throwable $e) { Console::writeLine('- ', $e->getMessage()); } }
/** * Interactive database setup. * WILL OUTPUT VIA CONSOLE! * * @param boolean $overwrite Overwrite existing config * @return string */ public function setup($overwrite = false) { /** * Output console usage */ if (!$this->console) { throw new \RuntimeException('You can only use this action from a console!'); } $this->console->writeLine("ZF2 Phinx Module - Interactive Setup", self::GREEN); /** * Check for existing config */ $zfConfig = $this->config['phinx-module']['zf2-config']; $phinxConfig = $this->config['phinx-module']['phinx-config']; if (!$overwrite && (file_exists($zfConfig) || file_exists($phinxConfig))) { if (file_exists($zfConfig) && !file_exists($phinxConfig)) { $this->sync(); $this->console->writeLine("ZF2 Config found but Phinx config missing => Config Synced."); } else { $this->console->writeLine("Existing config file(s) found, unable to continue!", self::LIGHT_RED); $this->console->writeLine("Use the --overwrite flag to replace existing config.", self::LIGHT_RED); } return; } /** * Ask questions */ $loop = true; while ($loop) { $this->console->writeLine("MySQL Database connection details:"); $host = Prompt\Line::prompt("Hostname? [localhost] ", true) ?: 'localhost'; $port = Prompt\Line::prompt("Port? [3306] ", true) ?: 3306; $user = Prompt\Line::prompt("Username? "); $pass = Prompt\Line::prompt("Password? "); $dbname = Prompt\Line::prompt("Database name? "); $loop = !Prompt\Confirm::prompt("Save these details? [y/n]"); } /** * Build config */ $config = new Config(array('db' => array('dsn' => "mysql:host={$host};dbname={$dbname}", 'username' => $user, 'password' => $pass, 'port' => $port))); $writer = new PhpArray(); $writer->toFile($zfConfig, $config); $this->console->writeLine(); $this->console->writeLine("ZF2 Config file written: {$zfConfig}"); /** * Write Phinx config */ $migrations = $this->config['phinx-module']['migrations']; $this->writePhinxConfig('mysql', $host, $user, $pass, $dbname, $port, $migrations); $this->console->writeLine("Phinx Config file written: {$phinxConfig}"); }
/** * Extract a ".ar" file into a given target directory * * @param string base * @param string ar * @param io.Folder target * @throws lang.IllegalStateException in case the target is not found * @throws lang.FormatException in case the .ar-file is not parseable */ protected function extract($base, $ar, Folder $target) { // Open a HTTP connection $url = new URL($base . $ar . '.ar'); $r = create(new HttpConnection($url))->get(); if (HttpConstants::STATUS_OK != $r->getStatusCode()) { throw new IllegalStateException(sprintf('Unexpected response %d:%s for %s', $r->getStatusCode(), $r->getMessage(), $url->getURL())); } $in = new BufferedInputStream($r->getInputStream()); do { // Seach for first section header, --[LENGTH]:[FILENAME]-- and parse it do { $line = $this->readLine($in); if (!$in->available()) { throw new FormatException('Cannot locate section header'); } } while (2 !== sscanf($line, '--%d:%[^:]--', $length, $filename)); // Calculate target file $file = new File($target, $filename); $folder = new Folder($file->getPath()); $folder->exists() || $folder->create(); Console::writef(' >> [%-10s] %s (%.2f kB) [%s]%s', $ar, $filename, $length / 1024, str_repeat('.', self::PROGRESS_INDICATOR_WIDTH), str_repeat("", self::PROGRESS_INDICATOR_WIDTH + 1)); // Transfer length bytes into file $c = 0; $out = $file->getOutputStream(); $size = 0; while ($size < $length) { $chunk = $in->read(min(0x1000, $length - $size)); $size += strlen($chunk); $out->write($chunk); // Update progress $d = ceil($size / $length * self::PROGRESS_INDICATOR_WIDTH); if ($d == $c) { continue; } Console::write(str_repeat('#', $d - $c)); $c = $d; } $out->close(); Console::writeLine(); } while ($in->available() > 0); $in->close(); }
/** * Main * * @param string[] args */ public static function main(array $args) { $way = array_shift($args); // Read sourcecode from STDIN if no further argument is given if (0 === sizeof($args)) { $src = file_get_contents('php://stdin'); } else { $src = $args[0]; } $src = trim($src, ' ;') . ';'; // Extract uses() and load classes if (0 === strncmp($src, 'uses', 4)) { $p = strpos($src, ');'); $uses = substr($src, 5, $p - 5); // "uses(" $src = substr($src, $p + 2); // ");" foreach (explode(',', $uses) as $class) { uses(trim($class, '" ')); } } // Allow missing return strstr($src, 'return ') || strstr($src, 'return;') || ($src = 'return ' . $src); // Rewrite argc, argv $argv = array(xp::nameOf(__CLASS__)) + $args; $argc = sizeof($argv); // Perform $return = eval($src); switch ($way) { case '-w': Console::writeLine($return); break; case '-d': var_dump($return); break; } }
/** * Perform this action * * @param string[] args */ public function perform(array $args) { $installation = new Installation(); $installation->setBase(new Folder(isset($args[0]) ? $args[0] : dirname(Runtime::getInstance()->bootstrapScript()) . '/..')); $force = in_array('-f', $args); with($version = $installation->getVersion()); Console::writeLine('===> Local version ', $version, ' @ ', $installation->getBase()); if (strstr($version, '-dev')) { Console::writeLine('*** Cannot update development checkouts'); return 2; } // Query releases website for newer versions $c = new HttpConnection(self::UPGRADE_URL); $r = $c->get(new RequestData($version)); switch ($r->getStatusCode()) { case HttpConstants::STATUS_OK: case HttpConstants::STATUS_NOT_EXTENDED: Console::writeLine('*** ', $this->readLine($r->getInputStream())); return 2; case HttpConstants::STATUS_SEE_OTHER: $upgrade = $r->getHeader('X-Upgrade-To'); $base = $r->getHeader('Location'); Console::writeLine('---> Upgrading to ', $upgrade, ' (', $base, ')'); $target = new Folder($installation->getBase(), $upgrade); $target->exists() || $target->create(); // Verify dependencies $this->extract($base, 'depend', $target); with($p = new Properties($target->getURI() . 'depend.ini')); $verify = 1; $rtversion = phpversion(); $extensions = array_flip(array_map('strtolower', get_loaded_extensions())); foreach ($p->readSection('php') as $op => $compare) { if (!version_compare(phpversion(), $compare, $op)) { $verify &= $this->error('PHP version ' . $op . ' ' . $compare . ' required, have ' . $rtversion); } } foreach ($p->readSection('ext.required') as $ext => $usage) { if (!isset($extensions[$ext])) { $verify &= $this->error('PHP Extension ' . $ext . ' required for ' . $usage); } } foreach ($p->readSection('ext.conflict') as $ext => $usage) { if (isset($extensions[$ext])) { $verify &= $this->error('PHP Extension ' . $ext . ' conflicts (' . $usage . ')'); } } foreach ($p->readSection('ext.optional') as $ext => $usage) { if (!isset($extensions[$ext])) { $verify &= $this->error('PHP Extension ' . $ext . ' not found, needed for ' . $usage . ' (ignoring)'); } } foreach ($p->readSection('ini') as $setting => $match) { $value = ini_get($setting); if (!preg_match($match, $value)) { $verify &= $this->error('PHP .ini setting ' . $setting . ' needs to match ' . $match . ' (but is ' . $value . ')'); } } // Remove depend.ini, finally check if we should continue create(new File($p->getFilename()))->unlink(); if (!$verify) { if (!$force) { return 3; } Console::writeLine('!!! Ignoring errors because -f was passed'); } // Download base, tools, libraries and meta information $this->extract($base, 'base', $target); $this->extract($base, 'tools', $target); $this->extract($base, 'lib', $target); $this->extract($base, 'meta-inf', $target); // Verify it works by running the XP Framework core unittests $tests = array('net.xp_framework.unittest.core.**'); Console::writeLine('---> Running tests with [USE_XP=', $upgrade, ']:'); $rt = Runtime::getInstance(); set_include_path(implode(PATH_SEPARATOR, array(rtrim($target->getURI(), DIRECTORY_SEPARATOR), '', $target->getURI() . 'lib' . DIRECTORY_SEPARATOR . 'xp-net.xp_framework-' . $upgrade . '.xar'))); with($p = $rt->newInstance($rt->startupOptions(), 'class', 'xp.unittest.Runner', $tests)); $p->in->close(); while (!$p->out->eof()) { Console::writeLine($p->out->readLine()); } while (!$p->err->eof()) { Console::writeLine($p->err->readLine()); } $exit = $p->close(); // Nonzero exit means failure if (0 !== $exit) { Console::writeLine('*** Test run failed, please consult above error messsages'); Console::writeLine($p->getCommandLine()); return 2; } Console::writeLine('===> Done, installed @ ', $target); return 0; default: throw new IllegalStateException('Unexpected response ' . xp::stringOf($r)); } }
/** * Main method * * @param string[] args */ public static function main($args) { $sorted = ArrayList::newInstance($args)->sorted(); Console::writeLine('create(new ArrayList(array(', implode(', ', $args), ')))->sorted()= ', $sorted); }
/** * Main runner method * * @param string[] args */ public static function main(array $args) { if (!$args) { self::usage(); } // Parse arguments $output = '-'; for ($i = 0, $s = sizeof($args); $i < $s; $i++) { if ('-O' == $args[$i]) { $output = $args[++$i]; } else { if ('-?' == $args[$i] || '--help' == $args[$i]) { self::usage(); } else { $package = $args[$i]; break; } } } // Load generator class try { $class = Package::forName('xp.codegen')->getPackage($package)->loadClass('Generator'); } catch (ElementNotFoundException $e) { Console::$err->writeLine('*** No generator named "' . $package . '"'); exit(2); } $params = new ParamString(array_slice($args, $i + 1)); if ($params->exists('help', '?')) { Console::$err->writeLine(self::textOf($class->getComment())); exit(1); } // Instantiate generator $generator = $class->newInstance($params); $generator->storage = new FileSystemStorage(System::tempDir()); // Output if ('-' === $output) { $generator->output = new ConsoleOutput(Console::$err); } else { if (strstr($output, '.xar')) { $generator->output = new ArchiveOutput($output); } else { $generator->output = new FileSystemOutput($output); } } $generator->output->addObserver(newinstance('util.Observer', array(), '{ public function update($obs, $arg= NULL) { Console::writeLine(" >> ", $arg); } }')); Console::writeLine('===> Starting ', $generator); // Compile target chain $empty = new ArrayList(); $targets = create('new util.collections.HashTable<lang.reflect.Method, util.collections.HashTable<string, lang.Generic>>()'); foreach ($class->getMethods() as $method) { if (!$method->hasAnnotation('target')) { continue; } $target = create('new util.collections.HashTable<string, lang.Generic>()'); // Fetch dependencies if ($method->hasAnnotation('target', 'depends')) { $depends = create('new util.collections.Vector<lang.reflect.Method>()'); foreach ((array) $method->getAnnotation('target', 'depends') as $dependency) { $depends[] = $class->getMethod($dependency); } $target['depends'] = $depends; } // Fetch input if ($method->hasAnnotation('target', 'input')) { $arguments = create('new util.collections.Vector<lang.reflect.Method>()'); foreach ((array) $method->getAnnotation('target', 'input') as $input) { $arguments[] = $class->getMethod($input); } $target['arguments'] = $arguments; } $targets->put($method, $target); } // Invoke try { foreach ($targets->keys() as $method) { self::invoke($generator, $method, $targets); } } catch (TargetInvocationException $e) { Console::$err->writeLine('*** ', $e->getCause()); exit(3); } $generator->output->commit(); Console::writeLine('===> Done'); }
/** * Main * * @param string[] args */ public static function main(array $args) { if (sizeof($args) < 1 || '' == $args[0]) { Console::$err->writeLine('*** No class or package name given'); return 2; } // Check whether a file, class or a package directory or name is given $cl = ClassLoader::getDefault(); if (strstr($args[0], xp::CLASS_FILE_EXT)) { $class = self::findClassBy(new File($args[0])); } else { if ($cl->providesClass($args[0])) { $class = XPClass::forName($args[0], $cl); } else { if (strcspn($args[0], '\\/') < strlen($args[0])) { $package = self::findPackageBy(new Folder($args[0])); } else { $package = $args[0]; } $provided = FALSE; foreach (ClassLoader::getLoaders() as $loader) { if (!$loader->providesPackage($package)) { continue; } Console::writeLine('@', $loader); $provided = TRUE; } if ($provided) { self::printPackage(Package::forName($package)); return 0; } // Not found Console::$err->writeLine('*** Failed to locate either a class or a package named "', $args[0], '", tried all of {'); foreach (ClassLoader::getLoaders() as $loader) { Console::$err->writeLine(' ', $loader); } Console::$err->writeLine('}'); return 1; } } Console::writeLine('@', $class->getClassLoader()); if ($class->isInterface()) { self::printInterface($class); } else { if ($class->isEnum()) { self::printEnum($class); } else { self::printClass($class); } } return 0; }
/** * Return XML representation of DiaComposite * * @return xml.Node */ public function getNode() { $node = parent::getNode(); if (isset($this->type)) { $node->setAttribute('type', $this->type); } elseif (!is('org.dia.DiaRole', $this)) { // DiaRole has no type... Console::writeLine("Composite 'type' is not set!"); } return $node; }
$Dia->saveTo($file, FALSE); } else { // else: update diagram Console::writeLine('Diagram file found: updating classes...'); // initialize objects try { // Visitor checks if the given classes exist $Visitor = new UpdateVisitor($classes, TRUE, TRUE); } catch (Exception $e) { $e->printStackTrace(); exit(-1); } Console::writeLine('Parsing XML diagram file...'); try { $Dia = DiaUnmarshaller::unmarshal($file); } catch (Exception $e) { $e->printStackTrace(); exit(-1); } // do the updates Console::writeLine('Running visitor...'); $Dia->accept($Visitor); Console::writeLine('Finalize visitor...'); $Visitor->finalize(); // write changes back to file if the visitor has changed something if ($Visitor->changedClasses()) { Console::writeLine('Writing changes back to diagram file...'); $Dia->saveTo($file, FALSE); } } }
public static function writeTitle($title, $color = null) { Console::writeLine("---------------------------", $color); Console::writeLine($title, $color); Console::writeLine("---------------------------", $color); }
/** * Accepts a Visitor object * * @param lang.Visitor Visitor */ public function accept($Visitor) { $Visitor->visit($this); $children = $this->getChildren(); foreach (array_keys($children) as $key) { if (!is_object($children[$key])) { Console::writeLine("NON-object: {$key}=" . xp::typeOf($children[$key])); if (is_array($children[$key])) { Console::writeLine(xp::stringOf(array_keys($children[$key]))); } Console::writeLine('Parent: ' . $this->getName() . '=' . xp::typeOf($this)); } else { $children[$key]->accept($Visitor); } } }
public function afterAction($action, $params, $exitCode = 0) { Console::writeLine('Command ended'); return parent::afterAction($action, $params, $exitCode); }
/** * Entry point * * @param text.doclet.RootDoc root * @return var */ public function start(RootDoc $root) { $this->processor = new MarkupBuilder(); // Option: API (will be used in title, default: none) $this->api = $this->option('api'); // Option: Gen (will be used in footer) $this->gen = $this->option('gen'); // Option: CSS to embed (filename, default: none) if ($css = $this->option('css')) { $this->css = FileUtil::getContents(new File($css)); } // Option: Output folder (default: Current directory, created if non-existant) $target = new Folder($this->option('output', '.')); $target->exists() || $target->create(); // Compute hierarchy Console::write('['); $this->hierarchy = array(); $seen = array(); while ($this->classes->hasNext()) { $class = $this->classes->next(); if (isset($seen[$class->qualifiedName()])) { continue; } $seen[$class->qualifiedName()] = TRUE; $key = $class->containingPackage()->name(); if (!isset($this->hierarchy[$key])) { $sub = new Folder($target, strtr($key, '.', DIRECTORY_SEPARATOR)); $sub->exists() || $sub->create(); $this->hierarchy[$key] = array('target' => $sub, 'doc' => $class->containingPackage(), 'contents' => array(INTERFACE_CLASS => array(), ORDINARY_CLASS => array(), ENUM_CLASS => array(), EXCEPTION_CLASS => array(), ERROR_CLASS => array())); } Console::write('.'); $this->hierarchy[$key]['contents'][$class->classType()][] = $class; } // Generate HTML files Console::write('>'); $this->writeOverview($this->hierarchy, $target)->close(); Console::writeLine($target, ']'); }
public function start() { $this->requests_count = 0; Console::writeTitle('Welcome to Brutor!'); for ($i = 0; $this->opt['times'] === 'forever' ? true : $i < $this->opt['times']; $i++) { $wait_per_ip = false; Console::writeLine("\nProcessing new request (" . ++$this->requests_count . ")", ConsoleColor::purple); try { $this->enableTor(); Console::write("New IP is: "); $this->ip = $this->getIP(); Console::writeLine($this->ip, ConsoleColor::brown); for ($j = 0; $j < $this->opt['times_per_ip']; $j++) { Console::write("Making CURL request... "); $response = $this->curlRequest($this->opt['curl_request']); Console::writeLine("OK!", ConsoleColor::green); $continue = @call_user_func($this->opt['curl_continue'], $response) ?: false; if ($continue == false) { Console::writeLine("Breaking (globally) caused by 'curl_continue' callback.", ConsoleColor::cyan); break 2; } $continue_per_ip = false; $continue_per_ip = @call_user_func($this->opt['curl_continue_per_ip'], $response) ?: false; if ($continue_per_ip == false) { Console::writeLine("Breaking (per IP) caused by 'curl_continue_per_ip' callback.", ConsoleColor::cyan); break 1; } $wait_per_ip = true; sleep($this->opt['sleep_per_ip']); } $this->disableTor(); if ($wait_per_ip) { sleep($this->opt['sleep']); } } catch (Exception $e) { Console::writeLine("\n" . $e->getMessage(), ConsoleColor::red); $this->disableTor(); } } }
<?php require 'lang.base.php'; uses('org.dia.DiaUnmarshaller', 'org.dia.UpdateVisitor'); // TODO: => unittest... Console::writeLine('============= Unmarshaller =========='); $Dia = DiaUnmarshaller::unmarshal('DiaClasses.dia'); $Dia->saveTo('DiaClasses_parsed.dia', FALSE); Console::writeLine('============= Visitor ==============='); $Visitor = new UpdateVisitor(array(), FALSE, TRUE); $Dia->accept($Visitor); $Visitor->finalize(); $Dia->saveTo('DiaClasses_updated.dia', FALSE);
/** * Start server * * @param string[] args */ public static function main(array $args) { $protocol = newinstance('peer.server.ServerProtocol', array(), '{ public function initialize() { } public function handleDisconnect($socket) { } public function handleError($socket, $e) { } public function handleConnect($socket) { } public function handleData($socket) { $cmd= $socket->readLine(); switch (substr($cmd, 0, 4)) { case "ECHO": { $socket->write("+ECHO ".substr($cmd, 5)."\\n"); break; } case "LINE": { sscanf(substr($cmd, 5), "%d %s", $l, $sep); for ($i= 0, $sbytes= urldecode($sep); $i < $l; $i++) { $socket->write("+LINE ".$i.$sbytes); } $socket->write("+LINE .\\n"); break; } case "CLOS": { $socket->close(); break; } case "HALT": { $socket->write("+HALT\\n"); $this->server->terminate= TRUE; break; } } } }'); $s = new Server('127.0.0.1', 0); try { $s->setProtocol($protocol); $s->init(); Console::writeLinef('+ Service %s:%d', $s->socket->host, $s->socket->port); $s->service(); Console::writeLine('+ Done'); } catch (Throwable $e) { Console::writeLine('- ', $e->getMessage()); } }
* $Id$ */ require 'lang.base.php'; uses('util.cmd.ParamString', 'org.dia.DiaUnmarshaller', 'org.dia.UpdateVisitor'); $P = new ParamString(); $diagram = $P->value(1); if (!file_exists($diagram)) { Console::writeLine("You need to specify an existing dia diagram file as first parameter!"); exit(0); } // parse diagram try { $Dia = DiaUnmarshaller::unmarshal($diagram); } catch (Exception $e) { $e->printStackTrace(); exit(-1); } // visitor that updates all existing classes in the diagram try { $V = new UpdateVisitor(array(), FALSE, TRUE); } catch (Exception $e) { $e->printStackTrace(); exit(-1); } $Dia->accept($V); $V->finalize(); // only needed when adding classes... // save back to diagram file (uncompressed) $Dia->saveTo($diagram, FALSE); Console::writeLine("Successfully updated the diagram: '{$diagram}' :)");
* * */ require 'lang.base.php'; uses('util.cmd.Console', 'io.File', 'io.ZipFile', 'xml.dom.Document', 'org.dia.DiaDiagram', 'org.dia.DiaText', 'org.dia.DiaMarshaller', 'org.dia.DiaUnmarshaller'); // create new empty diagram: $Dia = new DiaDiagram(); $BgLayer = $Dia->getChild('Background'); $BgLayer->addObject(new DiaText()); Console::writeLine($Dia->getSource()); exit(0); //$Dia= &DiaMarshaller::marshal(array('object.TdocVertrag'), $recurse= 1, $depend= FALSE); //print($Dia->getSource()); // read an existing diagram $file = getcwd() . '/test-read.dia'; Console::writeLine("Using file: {$file}"); DiaUnmarshaller::unmarshal($file, array('org.dia.DiaDiagram', 'lang.Object')); // try opening (zipped) file // hint: ZipFile also handles unzipped files... /* try (); { $dia_file= &new ZipFile($file) && $dia_file->open(FILE_MODE_READ); } if (catch('Exception', $e)) { $e->printStackTrace(); exit(-1); } // get the encoding from file //$xml_encoding= $dia_file->readLine(); $dia_xml= $dia_file->read($dia_file->size());
/** * Adds the given class to the 'Background' layer of the diagram * * @param &text.doclet.ClassDoc ClassDoc */ protected function _addClass($ClassDoc) { // check for DiaDiagram instance if (!isset($this->Dia)) { Console::writeLine('DiaDiagram object not defined!'); exit(-1); } // get background layer $Layer = $this->Dia->getLayer('Background'); // create new (empty) UMLClass and update it $Class = new DiaUMLClass(); $Class->setName($ClassDoc->qualifiedName()); $this->_updateClass($Class, $ClassDoc); // add the class to the background layer $Layer->addClass($Class); $this->added_classes[] = $ClassDoc->qualifiedName(); }
public function writeLine() { Console::writeLine('.'); $this->assertEquals(".\n", $this->streams[1]->getBytes()); }
/** * Process XML with the annotated methods of the given class * * @param xml.XPath XPath Instance of xml.XPath * @param php.DomNode Context The XML node to recurse from * @param string classname Fully qualified class name */ public static function recurse($XPath, $Context, $classname) { if (DIA_UNM_DEBUG) { Console::writeLine('recurse: ' . $Context->tagname() . "-> {$classname}"); } $Class = XPClass::forName($classname); $Instance = $Class->newInstance(); if (DIA_UNM_DEBUG) { Console::writeLine('Instance: ' . $Instance->getClassName()); } // loop over class methods with annotation 'fromDia' $methods = $Class->getMethods(); foreach (array_keys($methods) as $key) { $Method = $methods[$key]; if (!$Method->hasAnnotation('fromDia', 'xpath')) { continue; } $name = $Method->getName(); $xpath = $Method->getAnnotation('fromDia', 'xpath'); if (DIA_UNM_DEBUG) { Console::writeLine("--> Method: {$name} Xpath: {$xpath}"); } // continue if this fails: some expressions don't work on WRONG nodes... try { $result = $XPath->query($xpath, $Context); } catch (Exception $e) { if (DIA_UNM_DEBUG) { $e->printStackTrace(); } $nodename = $Context->tagname(); if ($Context->has_attribute('type')) { $type = $Context->get_attribute('type'); } else { $type = '<unknown>'; } if (DIA_UNM_DEBUG) { Console::writeLine("Warn: XPath= '{$xpath}' failed on Node= '{$nodename}' Type= '{$type}'"); } // skip this method/expression continue; } if (DIA_UNM_DEBUG) { Console::writeLine(' + Size of nodeset: ' . sizeof($result->nodeset)); } // loop over nodeset foreach (array_keys($result->nodeset) as $key) { $Node = $result->nodeset[$key]; // key 'value' (simple value) if ($Method->hasAnnotation('fromDia', 'value')) { $type = $Method->getAnnotation('fromDia', 'value'); if (DIA_UNM_DEBUG) { Console::writeLine(" + Value-type: '{$type}'"); } // get node value depending on nod type if (is('domattribute', $Node)) { $nodevalue = $Node->value(); } elseif (is('domelement', $Node)) { // remove whitespace and leading/trailing '#' character $content = $Node->get_content(); if (isset($content) and $content !== '') { $nodevalue = substr(trim($Node->get_content()), 1, -1); } else { $nodevalue = ''; } } elseif (is('domnamespace', $Node)) { $nodevalue = array($Node->prefix() => $Node->namespace_uri()); } else { Console::writeLine('Unknown node class: ' . xp::stringOf($Node)); exit(-1); } switch ($type) { case 'namespace': if (!is_array($nodevalue) or empty($nodevalue)) { Console::writeLine("Nodevalue is no array or is empty: {$nodevalue}"); } $value = $nodevalue; break; case 'enum': case 'int': $nodevalue = cast($nodevalue, 'int'); if (!is_int($nodevalue)) { Console::writeLine("Nodevalue is no integer: {$nodevalue}"); } $value = $nodevalue; break; case 'real': $nodevalue = cast($nodevalue, 'float'); if (!is_real($nodevalue) and !is_int($nodevalue)) { Console::writeLine("Nodevalue is no float/integer: {$nodevalue}"); } $value = $nodevalue; break; case 'string': $nodevalue = cast($nodevalue, 'string'); if (!is_string($nodevalue)) { Console::writeLine("Nodevalue is no string: {$nodevalue}"); } $value = $nodevalue; break; case 'boolean': $value = NULL; if ($nodevalue === 'false') { $value = FALSE; } if ($nodevalue === 'true') { $value = TRUE; } if (!is_bool($value)) { Console::writeLine("Nodevalue is no boolean: {$nodevalue}"); } break; case 'point': case 'array': // comma separated list of values $value = explode(',', $nodevalue); break; case 'rectangle': case 'arrayarray': // semicolon and comma separated list of values $points = explode(';', $nodevalue); $value = array(); foreach ($points as $point) { $value[] = explode(',', $point); } break; case 'font': if (is('domelement', $Node)) { $value = array(); $value['family'] = $Node->get_attribute('family'); $value['style'] = $Node->get_attribute('style'); $value['name'] = $Node->get_attribute('name'); } else { Console::writeLine('Wrong font node: ' . xp::stringOf($Node)); exit(-1); } break; default: Console::writeLine("!!!Unknown 'value' type: '{$type}'!"); } $Method->invoke($Instance, array($value)); } // key 'class' if ($Method->hasAnnotation('fromDia', 'class')) { $classname = $Method->getAnnotation('fromDia', 'class'); if (DIA_UNM_DEBUG) { Console::writeLine(" + Class: {$classname}"); } // recurse with given classname $Obj = DiaUnmarshaller::recurse($XPath, $Node, $classname); // hand results over to the method $Method->invoke($Instance, array($Obj)); } } } return $Instance; }