Call custom cjdns admin function
968230
def _callFunc(session, funcName, password, args):
    """"""

    txid = _randomString()
    sock = session.socket
    sock.send(bytearray('d1:q6:cookie4:txid10:%se' % txid, 'utf-8'))
    msg = _getMessage(session, txid)
    cookie = msg['cookie']
    txid = _randomString()
    tohash = (password + cookie).encode('utf-8')
    req = {
        'q': funcName,
        'hash': hashlib.sha256(tohash).hexdigest(),
        'cookie': cookie,
        'args': args,
        'txid': txid
    }

    if password:
        req['aq'] = req['q']
        req['q'] = 'auth'
        reqBenc = bencode(req).encode('utf-8')
        req['hash'] = hashlib.sha256(reqBenc).hexdigest()

    reqBenc = bencode(req)
    sock.send(bytearray(reqBenc, 'utf-8'))
    return _getMessage(session, txid)
597867
private void addAdminObjectService(ServiceReference<AdminObjectService> reference, String id, boolean jndiName) {
        NamedAdminObjectServiceInfo aosInfo = createNamedAdminObjectServiceInfo(id);
        aosInfo.getServices(jndiName).addReference(reference);

        // If the highest reference after updating is the one we just added,
        // then we need to deactivate any endpoints using the old admin object
        // and reactive them using the new admin object.
        ServiceReference<AdminObjectService> oldServiceRef = aosInfo.serviceRef;
        if (aosInfo.updateServiceRef().equals(reference)) {
            if (oldServiceRef != null) {
                deactivateEndpoints(aosInfo.endpointFactories);
            }
            activateDeferredEndpoints(aosInfo.endpointFactories);
        }

        // With a new adminObjectService, there is a possibility that lookups which
        // failed earlier could now succeed, allowing endpoint activation.
        updateSchemeJndiNames(true);
    }
1361406
def call(self, name, *a):
        """"""
        return callJavaFunc(self._sc, getattr(self._java_model, name), *a)
944610
function handleAjax( url, origSettings ) {
		var mockRequest, requestSettings, mockHandler, overrideCallback;

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			origSettings = url;
			url = undefined;
		} else {
			// work around to support 1.5 signature
			origSettings = origSettings || {};
			origSettings.url = url;
		}

		// Extend the original settings for the request
		requestSettings = $.extend(true, {}, $.ajaxSettings, origSettings);

		// Generic function to override callback methods for use with
		// callback options (onAfterSuccess, onAfterError, onAfterComplete)
		overrideCallback = function(action, mockHandler) {
			var origHandler = origSettings[action.toLowerCase()];
			return function() {
				if ( $.isFunction(origHandler) ) {
					origHandler.apply(this, [].slice.call(arguments));
				}
				mockHandler['onAfter' + action]();
			};
		};

		// Iterate over our mock handlers (in registration order) until we find
		// one that is willing to intercept the request
		for(var k = 0; k < mockHandlers.length; k++) {
			if ( !mockHandlers[k] ) {
				continue;
			}

			mockHandler = getMockForRequest( mockHandlers[k], requestSettings );
			if(!mockHandler) {
				// No valid mock found for this request
				continue;
			}

			mockedAjaxCalls.push(requestSettings);

			// If logging is enabled, log the mock to the console
			$.mockjaxSettings.log( mockHandler, requestSettings );


			if ( requestSettings.dataType && requestSettings.dataType.toUpperCase() === 'JSONP' ) {
				if ((mockRequest = processJsonpMock( requestSettings, mockHandler, origSettings ))) {
					// This mock will handle the JSONP request
					return mockRequest;
				}
			}


			// Removed to fix #54 - keep the mocking data object intact
			//mockHandler.data = requestSettings.data;

			mockHandler.cache = requestSettings.cache;
			mockHandler.timeout = requestSettings.timeout;
			mockHandler.global = requestSettings.global;

			// In the case of a timeout, we just need to ensure
			// an actual jQuery timeout (That is, our reponse won't)
			// return faster than the timeout setting.
			if ( mockHandler.isTimeout ) {
				if ( mockHandler.responseTime > 1 ) {
					origSettings.timeout = mockHandler.responseTime - 1;
				} else {
					mockHandler.responseTime = 2;
					origSettings.timeout = 1;
				}
				mockHandler.isTimeout = false;
			}

			// Set up onAfter[X] callback functions
			if ( $.isFunction( mockHandler.onAfterSuccess ) ) {
				origSettings.success = overrideCallback('Success', mockHandler);
			}
			if ( $.isFunction( mockHandler.onAfterError ) ) {
				origSettings.error = overrideCallback('Error', mockHandler);
			}
			if ( $.isFunction( mockHandler.onAfterComplete ) ) {
				origSettings.complete = overrideCallback('Complete', mockHandler);
			}

			copyUrlParameters(mockHandler, origSettings);

			(function(mockHandler, requestSettings, origSettings, origHandler) {

				mockRequest = _ajax.call($, $.extend(true, {}, origSettings, {
					// Mock the XHR object
					xhr: function() { return xhr( mockHandler, requestSettings, origSettings, origHandler ); }
				}));
			})(mockHandler, requestSettings, origSettings, mockHandlers[k]);

			return mockRequest;
		}

		// We don't have a mock request
		unmockedAjaxCalls.push(origSettings);
		if($.mockjaxSettings.throwUnmocked === true) {
			throw new Error('AJAX not mocked: ' + origSettings.url);
		}
		else { // trigger a normal request
			return _ajax.apply($, [origSettings]);
		}
	}
686679
@SuppressWarnings("unchecked")
        public static void executeCommand(String[] args) throws IOException {

            OptionParser parser = getParser();

            // declare parameters
            String url = null;
            List<Integer> nodeIds = null;
            Boolean allNodes = true;
            Boolean confirm = false;

            // parse command-line input
            OptionSet options = parser.parse(args);
            if(options.has(AdminParserUtils.OPT_HELP)) {
                printHelp(System.out);
                return;
            }

            // check required options and/or conflicting options
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);
            AdminParserUtils.checkOptional(options,
                                           AdminParserUtils.OPT_NODE,
                                           AdminParserUtils.OPT_ALL_NODES);

            // load parameters
            url = (String) options.valueOf(AdminParserUtils.OPT_URL);
            if(options.has(AdminParserUtils.OPT_NODE)) {
                nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);
                allNodes = false;
            }
            if(options.has(AdminParserUtils.OPT_CONFIRM)) {
                confirm = true;
            }

            // print summary
            System.out.println("Remove metadata related to rebalancing");
            System.out.println("Location:");
            System.out.println("  bootstrap url = " + url);
            if(allNodes) {
                System.out.println("  node = all nodes");
            } else {
                System.out.println("  node = " + Joiner.on(", ").join(nodeIds));
            }

            // execute command
            if(!AdminToolUtils.askConfirm(confirm, "remove metadata related to rebalancing")) {
                return;
            }
            AdminClient adminClient = AdminToolUtils.getAdminClient(url);

            if(allNodes) {
                nodeIds = AdminToolUtils.getAllNodeIds(adminClient);
            }

            AdminToolUtils.assertServerNotInRebalancingState(adminClient, nodeIds);

            doMetaClearRebalance(adminClient, nodeIds);
        }
543316
@Override
    public void run(C configuration, Environment environment) {
        checkArgument(environment != null, "Environment is null");
        environment.servlets().addServlet("CXF Servlet " + jaxwsEnvironment.getDefaultPath(),
                jaxwsEnvironment.buildServlet()).addMapping(servletPath);

        environment.lifecycle().addServerLifecycleListener(
                server -> jaxwsEnvironment.logEndpoints());

        String publishedEndpointUrlPrefix = getPublishedEndpointUrlPrefix(configuration);
        if(publishedEndpointUrlPrefix != null) {
            jaxwsEnvironment.setPublishedEndpointUrlPrefix(publishedEndpointUrlPrefix);
        }
    }
846089
private void doUpdateJavaCFX() throws PageException {
	String name = getString("admin", action, "name");
	if (StringUtil.startsWithIgnoreCase(name, "cfx_")) name = name.substring(4);
	lucee.runtime.db.ClassDefinition cd = new ClassDefinitionImpl(getString("admin", action, "class"), getString("bundleName", null), getString("bundleVersion", null),
		config.getIdentification());
	admin.updateJavaCFX(name, cd);
	store();
	adminSync.broadcast(attributes, config);
    }
982334
static function runTrigger( $name, $moduleName, $function, $parameters, $keys = null )
    {
        $trigger = eZPersistentObject::fetchObject( eZTrigger::definition(),
                                                    null,
                                                    array( 'name' => $name,
                                                           'module_name' => $moduleName,
                                                           'function_name' => $function ),
                                                    true );
        if ( $trigger !== NULL )
        {
            $workflowID = $trigger->attribute( 'workflow_id' );
            $workflow = eZWorkflow::fetch( $workflowID );
            if ( $keys != null )
            {
                $keys[] = 'workflow_id';
            }

            $parameters['workflow_id']     = $workflowID;
            $parameters['trigger_name']    = $name;
            $parameters['module_name']     = $moduleName;
            $parameters['module_function'] = $function;
            // It is very important that the user_id is set correctly.
            // If it was not supplied by the calling code we will use
            // the currently logged in user.
            if ( !isset( $parameters['user_id'] ) or
                 $parameters['user_id'] == 0 )
            {
                $user = eZUser::currentUser();
                $parameters['user_id'] = $user->attribute( 'contentobject_id' );
            }
            $processKey = eZWorkflowProcess::createKey( $parameters, $keys );

//            $searchKey = eZWorkflowProcess::createKey( $keyArray );

            $workflowProcessList = eZWorkflowProcess::fetchListByKey( $processKey );

            if ( count( $workflowProcessList ) > 0 )
            {
                $existingWorkflowProcess = $workflowProcessList[0];
                $existingWorkflowStatus = $existingWorkflowProcess->attribute( 'status' );


                switch( $existingWorkflowStatus )
                {
                    case eZWorkflow::STATUS_FAILED:
                    case eZWorkflow::STATUS_CANCELLED:
                    case eZWorkflow::STATUS_NONE:
                    case eZWorkflow::STATUS_BUSY:
                    {
                        $existingWorkflowProcess->removeThis();
                        return array( 'Status' => eZTrigger::WORKFLOW_CANCELLED,
                                      'Result' => null );
                    } break;
                    case eZWorkflow::STATUS_FETCH_TEMPLATE:
                    case eZWorkflow::STATUS_FETCH_TEMPLATE_REPEAT:
                    case eZWorkflow::STATUS_REDIRECT:
                    case eZWorkflow::STATUS_RESET:
                    {
                        return eZTrigger::runWorkflow( $existingWorkflowProcess );
//                        return eZTrigger::FETCH_TEMPLATE;
                    } break;
                    case eZWorkflow::STATUS_DEFERRED_TO_CRON:
                    {
                        return eZTrigger::runWorkflow( $existingWorkflowProcess );
/*                        return array( 'Status' => eZTrigger::STATUS_CRON_JOB,

                                      'Result' => array( 'content' => 'Operation halted during execution.<br/>Refresh page to continue<br/><br/><b>Note: The halt is just a temporary test</b><br/>',
                                                         'path' => array( array( 'text' => 'Operation halt',
                                                                            'url' => false ) ) ) );
*/                  } break;
                    case eZWorkflow::STATUS_DONE:
                    {
                        $existingWorkflowProcess->removeThis();
                        return array( 'Status' => eZTrigger::WORKFLOW_DONE,
                                      'Result' => null );
                    }
                }
                return array( 'Status' => eZTrigger::WORKFLOW_CANCELLED,
                              'Result' => null );
            }else
            {
//                print( "\n starting new workflow process \n");
//                var_dump( $keyArray );
//                print( " $workflowID, $userID, $objectID, $version, $nodeID, \n ");
            }
            $workflowProcess = eZWorkflowProcess::create( $processKey, $parameters );

            $workflowProcess->store();

            return eZTrigger::runWorkflow( $workflowProcess );

        }
        else
        {
            return array( 'Status' => eZTrigger::NO_CONNECTED_WORKFLOWS,
                          'Result' => null );
        }
    }
124007
function run(brokerOptions) {
    const defaultPort = 1883;
    const options = {
        port: defaultPort,
        logVerbose: false,
        startBonjour: true,
        bonjourHost: undefined,
    };
    Object.assign(options, brokerOptions);

    const port = options.port;
    const wsPort = options.wsPort || options.port + 8000;

    const node = require("../runtime-node");

    const aedes = require("aedes")();
    const tcpServer = require('net').createServer(aedes.handle);
    const wsServer = require('http').createServer();
    const ws = require('websocket-stream');

    ws.createServer({ server: wsServer }, aedes.handle);

    tcpServer.listen(port, () => {
        wsServer.listen(wsPort, () => {
            utils.logInfo(`Coaty MQTT Broker running on TCP port ${port} and websocket port ${wsPort}...`);
            if (options.startBonjour && port === defaultPort) {
                node.MulticastDnsDiscovery.publishMqttBrokerService(
                    port,
                    wsPort,
                    undefined,
                    undefined,
                    options.bonjourHost)
                    .then(srv => utils.logInfo(`Published multicast DNS for host ${srv.host} on FQDN "${srv.fqdn}:${srv.port}"`))
                    .catch(error => utils.logError(`Error while publishing multicast DNS: ${error}`));

                node.NodeUtils.handleProcessTermination(undefined, () => {
                    return node.MulticastDnsDiscovery.unpublishMulticastDnsServices()
                        .then(() => {
                            utils.logInfo(`Unpublished multicast DNS service. Exiting...`);
                        });
                });
            }
            if (options.onReady) {
                options.onReady();
            }
        })
    });

    if (!options.logVerbose) {
        return;
    }

    aedes.on("publish", (packet, client) => {
        utils.logMessage(`PUBLISH by ${client ? client.id : "broker"} on topic ${packet.topic} with payload ${packet.payload.toString()}`);
    });

    aedes.on("subscribe", (subscriptions, client) => {
        utils.logMessage(`SUBSCRIBE by ${client ? client.id : "broker"}: on topic ${subscriptions.map(s => s.topic).join(", ")}`);
    });

    aedes.on("unsubscribe", (unsubscriptions, client) => {
        utils.logMessage(`UNSUBSCRIBE by ${client ? client.id : "broker"} on topic ${unsubscriptions.join(", ")}`);
    });

    aedes.on("client", (client) => {
        utils.logMessage(`CLIENT CONNECT ${client.id}`);
    });

    aedes.on("clientDisconnect", (client) => {
        utils.logMessage(`CLIENT DISCONNECT ${client.id}`);
    });

    aedes.on("clientError", (client, err) => {
        utils.logError(`CLIENT ERROR ${client.id} ${err.message}`);
    });

    aedes.on("connectionError", (client, err) => {
        utils.logError(`CONNECTION ERROR ${client} ${err.message}`);
    });
}
1232704
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the CustomFieldService.
    CustomFieldServiceInterface customFieldService =
        adManagerServices.get(session, CustomFieldServiceInterface.class);

    // Create a number custom field that can be used for an external ID in the
    // API.
    CustomField numberCustomField = new CustomField();
    numberCustomField.setName("External ID #" + new Random().nextInt(Integer.MAX_VALUE));
    numberCustomField.setEntityType(CustomFieldEntityType.LINE_ITEM);
    numberCustomField.setDataType(CustomFieldDataType.NUMBER);
    numberCustomField.setVisibility(CustomFieldVisibility.API_ONLY);

    // Create a drop-down custom field that can be used in the UI.
    CustomField dropDownCustomField = new CustomField();
    dropDownCustomField.setName(
        "Internal approval status #" + new Random().nextInt(Integer.MAX_VALUE));
    dropDownCustomField.setEntityType(CustomFieldEntityType.LINE_ITEM);
    dropDownCustomField.setDataType(CustomFieldDataType.DROP_DOWN);
    dropDownCustomField.setVisibility(CustomFieldVisibility.FULL);

    // Create the custom fields on the server.
    CustomField[] customFields =
        customFieldService.createCustomFields(
            new CustomField[] {numberCustomField, dropDownCustomField});

    for (CustomField createdCustomField : customFields) {
      System.out.printf(
          "A custom field with ID %d and name '%s' was created.%n",
          createdCustomField.getId(), createdCustomField.getName());
    }

    // Set the created drop-down custom field.
    dropDownCustomField = customFields[1];

    // Create approved custom field option.
    CustomFieldOption approvedCustomFieldOption = new CustomFieldOption();
    approvedCustomFieldOption.setDisplayName("APPROVED");
    approvedCustomFieldOption.setCustomFieldId(dropDownCustomField.getId());

    // Create unapproved custom field option.
    CustomFieldOption unapprovedCustomFieldOption = new CustomFieldOption();
    unapprovedCustomFieldOption.setDisplayName("UNAPPROVED");
    unapprovedCustomFieldOption.setCustomFieldId(dropDownCustomField.getId());

    // Create the custom field options on the server.
    CustomFieldOption[] customFieldOptions =
        customFieldService.createCustomFieldOptions(
            new CustomFieldOption[] {approvedCustomFieldOption, unapprovedCustomFieldOption});

    for (CustomFieldOption createdCustomFieldOption : customFieldOptions) {
      System.out.printf(
          "A custom field option with ID %d and display name '%s' was created.%n",
          createdCustomFieldOption.getId(), createdCustomFieldOption.getDisplayName());
    }
  }
239451
function ConnectionServer(endpoint, options, connectionListener) {
  events.EventEmitter.call(this);

  if (!(endpoint instanceof Endpoint)) {
    endpoint = new Endpoint(endpoint);
  }
  if (typeof options === 'function') {
    connectionListener = options;
    options = undefined;
  }

  this.endpoint = endpoint;
  this.options = options || {};
  if (typeof connectionListener === 'function') {
    this.on('connection', connectionListener);
  }

  listen.call(this);
}
355164
def method_call(receiver, message, args, pseudo_type=None):
    ''''''

    if not isinstance(receiver, Node):
        receiver = local(receiver)
    return Node('method_call', receiver=receiver, message=message, args=args, pseudo_type=pseudo_type)
272126
private function functionCall(Node $function_reference, $dynamic = FALSE) {
    if ($dynamic) {
      $node = new CallbackCallNode();
      $node->addChild($function_reference, 'callback');
    }
    else {
      if ($function_reference instanceof NameNode && $function_reference->childCount() === 1 && $function_reference == 'define') {
        $node = new DefineNode();
      }
      else {
        $node = new FunctionCallNode();
      }
      $node->addChild($function_reference, 'name');
    }
    $this->functionCallParameterList($node);
    return $this->objectDereference($this->arrayDeference($node));
  }
1138611
private void doUpdateMailSetting() throws PageException {
	// admin.setMailLog(getString("admin",action,"logfile"),getString("loglevel","ERROR"));

	admin.setMailSpoolEnable(getBoolObject("admin", action, "spoolenable"));

	/*
	 * / spool interval String str=getString("admin",action,"maxThreads"); Integer i=null;
	 * if(!StringUtil.isEmpty(str))i=Caster.toInteger(maxThreads);
	 */

	// timeout
	String str = getString("admin", action, "timeout");
	Integer i = null;
	if (!StringUtil.isEmpty(str)) i = Caster.toInteger(str);
	admin.setMailTimeout(i);

	admin.setMailDefaultCharset(getString("admin", action, "defaultencoding"));
	store();
	adminSync.broadcast(attributes, config);
    }
1066056
public void customizeVueObserverPrototype(VueObserver vueObserver) {
    vueObserveArrayFunction = vueObserver.getObserveArray();
    vueWalkFunction = vueObserver.getWalk();

    vueObserver.setWalk(toObserve -> {
      if (observeJavaObject(toObserve)) {
        return;
      }

      vueWalkFunction.call(this, toObserve);
    });
  }
25036
protected Object invokeJavascript(String function, Object... args) {
        Object[] jsArgs = new Object[args.length];
        for (int i = 0; i < jsArgs.length; i++) {
            if (args[i] instanceof JavascriptObject) {
                jsArgs[i] = ((JavascriptObject) args[i]).getJSObject();
            } else if (args[i] instanceof JavascriptEnum) {
                jsArgs[i] = ((JavascriptEnum) args[i]).getEnumValue();
            } else {
                jsArgs[i] = args[i];
            }
        }
        return checkUndefined(jsObject.call(function, (Object[]) jsArgs));
    }
1012610
void doMain(String[] args, boolean throwOnError) throws Exception {
		if (args.length == 0) {
			usage(throwOnError, "no arguments specified");
			return;
		} else if (args.length > 2) {
			usage(throwOnError, "improper number of arguments:" + Arrays.toString(args));
			return;
		}

		// check for --usage or --help
		if (args.length == 1 && ("--usage".equals(args[0]) || "--help".equals(args[0]))) {
			usage(throwOnError, null);
			return;
		}

		CommandLineJmxClient jmxClient;
		if (args[0].indexOf('/') >= 0) {
			jmxClient = new CommandLineJmxClient(args[0]);
		} else {
			String[] parts = args[0].split(":");
			if (parts.length != 2) {
				usage(throwOnError, "argument should be in 'hostname:port' format, not: " + args[0]);
				return;
			}
			String hostName = parts[0];
			int port = 0;
			try {
				port = Integer.parseInt(parts[1]);
			} catch (NumberFormatException e) {
				usage(throwOnError, "port number not in the right format: " + parts[1]);
				return;
			}
			jmxClient = new CommandLineJmxClient(hostName, port);
		}

		if (args.length == 1) {
			jmxClient.runCommandLine();
		} else if (args.length == 2) {
			jmxClient.runBatchFile(new File(args[1]));
		}
	}