Example usage for java.util NoSuchElementException getMessage

List of usage examples for java.util NoSuchElementException getMessage

Introduction

In this page you can find the example usage for java.util NoSuchElementException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.qspin.qtaste.ui.reporter.TestCaseReportTable.java

private void init() {
    final String tableLayoutProperty = interactive ? INTERACTIVE_TABLE_LAYOUT_PROPERTY
            : EXECUTION_TABLE_LAYOUT_PROPERTY;
    final String statusColumnProperty = tableLayoutProperty + ".status";
    final String testCaseColumnProperty = tableLayoutProperty + ".test_case";
    final String detailsColumnProperty = tableLayoutProperty + ".details";
    final String testbedColumnProperty = tableLayoutProperty + ".testbed";
    final String resultColumnProperty = tableLayoutProperty + ".result";

    tcModel = new DefaultTableModel(
            new Object[] { "Status", "Test Case", "Details", "Result", "Testbed", "Time", "." }, 0) {

        @Override// w w w. j a va  2 s .c  om
        public Class<?> getColumnClass(int columnIndex) {
            Class<?> dataType = super.getColumnClass(columnIndex);
            if (columnIndex == STATUS) {
                dataType = Icon.class;
            }
            return dataType;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int mColIndex) {
            return false;
        }
    };
    tcTable = new SortableJTable(new TableSorter(tcModel)) {

        public String getToolTipText(MouseEvent e) {
            Point p = e.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            if (colIndex < 0) {
                return null;
            }
            return convertObjectToToolTip(getValueAt(rowIndex, colIndex));
        }
    };
    tcTable.setColumnSelectionAllowed(false);

    int tcWidth = interactive ? 360 : 480;
    int tcStatusWidth = 40;
    int tcTestbedWidth = 100;
    int tcDetailsWidth = 360;
    int tcResultWidth = 150;
    GUIConfiguration guiConfiguration = GUIConfiguration.getInstance();
    List<?> list = guiConfiguration.configurationsAt(tableLayoutProperty);
    if (!list.isEmpty()) {
        try {
            tcWidth = guiConfiguration.getInt(testCaseColumnProperty);
        } catch (NoSuchElementException ex) {
            guiConfiguration.setProperty(testCaseColumnProperty, tcWidth);
        }
        try {
            tcStatusWidth = guiConfiguration.getInt(statusColumnProperty);
        } catch (NoSuchElementException ex) {
            guiConfiguration.setProperty(statusColumnProperty, tcStatusWidth);
        }
        try {
            tcDetailsWidth = guiConfiguration.getInt(detailsColumnProperty);
        } catch (NoSuchElementException ex) {
            guiConfiguration.setProperty(detailsColumnProperty, tcDetailsWidth);
        }
        try {
            tcTestbedWidth = guiConfiguration.getInt(testbedColumnProperty);
        } catch (NoSuchElementException ex) {
            guiConfiguration.setProperty(testbedColumnProperty, tcTestbedWidth);
        }
        if (interactive) {
            try {
                tcResultWidth = guiConfiguration.getInt(resultColumnProperty);
            } catch (NoSuchElementException ex) {
                guiConfiguration.setProperty(resultColumnProperty, tcResultWidth);
            }
        }
    } else {
        tcWidth = interactive ? 360 : 480;

        guiConfiguration.setProperty(testCaseColumnProperty, tcWidth);
        guiConfiguration.setProperty(statusColumnProperty, tcStatusWidth);
        guiConfiguration.setProperty(detailsColumnProperty, tcDetailsWidth);
        guiConfiguration.setProperty(testbedColumnProperty, tcTestbedWidth);
        if (interactive) {
            guiConfiguration.setProperty(resultColumnProperty, tcResultWidth);
        }
        try {
            guiConfiguration.save();
        } catch (ConfigurationException ex) {
            logger.error("Error while saving GUI configuration: " + ex.getMessage());
        }
    }

    TableColumnModel tcTableColumnModel = tcTable.getColumnModel();
    tcTableColumnModel.getColumn(TEST_CASE).setPreferredWidth(tcWidth);
    tcTableColumnModel.getColumn(STATUS).setPreferredWidth(tcStatusWidth);
    tcTableColumnModel.getColumn(STATUS).setMaxWidth(40);
    tcTableColumnModel.getColumn(DETAILS).setPreferredWidth(tcDetailsWidth);
    tcTableColumnModel.getColumn(TESTBED).setPreferredWidth(tcTestbedWidth);
    tcTableColumnModel.getColumn(EXEC_TIME).setPreferredWidth(70);
    tcTableColumnModel.getColumn(EXEC_TIME).setMinWidth(70);
    tcTableColumnModel.getColumn(EXEC_TIME).setMaxWidth(70);
    tcTableColumnModel.removeColumn(tcTableColumnModel.getColumn(TC));
    if (!interactive) {
        tcTable.getSelectionModel().addListSelectionListener(new TCResultsSelectionListeners());
    }
    tcTable.setName("tcTable");
    tcTableColumnModel.addColumnModelListener(new TableColumnModelListener() {

        public void columnAdded(TableColumnModelEvent e) {
        }

        public void columnRemoved(TableColumnModelEvent e) {
        }

        public void columnMoved(TableColumnModelEvent e) {
        }

        public void columnMarginChanged(ChangeEvent e) {
            try {
                // save the current layout
                int tcStatusWidth = tcTable.getColumnModel().getColumn(STATUS).getWidth();
                int tcWidth = tcTable.getColumnModel().getColumn(TEST_CASE).getWidth();
                int tcDetailsWidth = tcTable.getColumnModel().getColumn(DETAILS).getWidth();
                int tcResultWidth = tcTable.getColumnModel().getColumn(RESULT).getWidth();
                int tcTestbedWidth = tcTable.getColumnModel().getColumn(TESTBED).getWidth();
                // save it into the settings
                GUIConfiguration guiConfiguration = GUIConfiguration.getInstance();
                guiConfiguration.setProperty(statusColumnProperty, tcStatusWidth);
                guiConfiguration.setProperty(testCaseColumnProperty, tcWidth);
                guiConfiguration.setProperty(detailsColumnProperty, tcDetailsWidth);
                guiConfiguration.setProperty(testbedColumnProperty, tcTestbedWidth);
                if (interactive) {
                    guiConfiguration.setProperty(resultColumnProperty, tcResultWidth);
                }
                guiConfiguration.save();
            } catch (ConfigurationException ex) {
                logger.error("Error while saving GUI configuration: " + ex.getMessage());
            }
        }

        public void columnSelectionChanged(ListSelectionEvent e) {
        }
    });

    try {
        tcTable.setDefaultRenderer(Class.forName("java.lang.Object"), new TableCellRenderer());
    } catch (ClassNotFoundException ex) {
    }

    if (interactive) {
        displayTableForInteractiveMode();
    } else {
        displayTableForExecutionMode();
    }

    tcTable.addMouseListener(new TableMouseListener());

    // use timer for updating elapsed time every seconds
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            updateRunningTestCaseElapsedTime();
        }
    }, 1000, 1000);
}

From source file:com.eucalyptus.objectstorage.WalrusManager.java

/**
 * Handles a HEAD request to the bucket. Just returns 200ok if bucket exists and user has access. Otherwise returns 404 if not found or 403 if no accesss.
 * //from  www.j a va 2 s.  c om
 * @param request
 * @return
 * @throws EucalyptusCloudException
 */
public HeadBucketResponseType headBucket(HeadBucketType request) throws EucalyptusCloudException {
    HeadBucketResponseType reply = (HeadBucketResponseType) request.getReply();
    Context ctx = Contexts.lookup();
    Account account = ctx.getAccount();
    String bucketName = request.getBucket();
    EntityTransaction db = Entities.get(BucketInfo.class);
    try {
        BucketInfo bucket = Entities.uniqueResult(new BucketInfo(bucketName));
        if (ctx.hasAdministrativePrivileges() || (bucket.canRead(account.getAccountNumber())
                && (bucket.isGlobalRead() || Lookups.checkPrivilege(PolicySpec.S3_LISTBUCKET,
                        PolicySpec.VENDOR_S3, PolicySpec.S3_RESOURCE_BUCKET, bucketName, null)))) {
            return reply;
        } else {
            // Insufficient access, return 403
            throw new HeadAccessDeniedException(bucketName);
        }
    } catch (NoSuchElementException e) {
        // Bucket not found return 404
        throw new HeadNoSuchBucketException(bucketName);
    } catch (TransactionException e) {
        LOG.error("DB transaction error looking up bucket " + bucketName + ": " + e.getMessage());
        LOG.debug("DB tranction exception looking up bucket " + bucketName, e);
        throw new EucalyptusCloudException("Internal error doing db lookup for " + bucketName, e);
    } finally {
        // Nothing to commit, always rollback.
        db.rollback();
    }
}

From source file:com.eucalyptus.walrus.WalrusFSManager.java

/**
 * Handles a HEAD request to the bucket. Just returns 200ok if bucket exists and user has access. Otherwise returns 404 if not found or 403 if no accesss.
 *
 * @param request// www  . j a v a  2 s. com
 * @return
 * @throws EucalyptusCloudException
 */
@Override
public HeadBucketResponseType headBucket(HeadBucketType request) throws WalrusException {
    HeadBucketResponseType reply = (HeadBucketResponseType) request.getReply();
    Context ctx = Contexts.lookup();
    Account account = ctx.getAccount();
    String bucketName = request.getBucket();
    EntityTransaction db = Entities.get(BucketInfo.class);
    try {
        BucketInfo bucket = Entities.uniqueResult(new BucketInfo(bucketName));
        return reply;
    } catch (NoSuchElementException e) {
        // Bucket not found return 404
        throw new HeadNoSuchBucketException(bucketName);
    } catch (TransactionException e) {
        LOG.error("DB transaction error looking up bucket " + bucketName + ": " + e.getMessage());
        LOG.debug("DB tranction exception looking up bucket " + bucketName, e);
        throw new HeadNoSuchBucketException("Internal error doing db lookup for " + bucketName, e);
    } finally {
        // Nothing to commit, always rollback.
        db.rollback();
    }
}

From source file:org.wso2.carbon.ml.core.internal.MLCoreDS.java

protected void activate(ComponentContext context) {

    try {//  w  ww.  j av  a2 s . c o  m
        SparkConfigurationParser mlConfigParser = new SparkConfigurationParser();
        MLCoreServiceValueHolder valueHolder = MLCoreServiceValueHolder.getInstance();
        MLConfiguration mlConfig = valueHolder.getDatabaseService().getMlConfiguration();

        valueHolder.setSummaryStatSettings(mlConfig.getSummaryStatisticsSettings());
        valueHolder.setMlProperties(MLUtils.getProperties(mlConfig.getProperties()));
        valueHolder.setHdfsUrl(mlConfig.getHdfsUrl());
        valueHolder.setAlgorithms(mlConfig.getMlAlgorithms());
        valueHolder.setEmailNotificationEndpoint(mlConfig.getEmailNotificationEndpoint());
        valueHolder.setModelRegistryLocation(mlConfig.getModelRegistryLocation());
        valueHolder.setModelStorage(mlConfig.getModelStorage());
        valueHolder.setDatasetStorage(mlConfig.getDatasetStorage());

        Properties mlProperties = valueHolder.getMlProperties();
        String poolSizeStr = mlProperties
                .getProperty(org.wso2.carbon.ml.core.utils.MLConstants.ML_THREAD_POOL_SIZE);
        String poolQueueSizeStr = mlProperties
                .getProperty(org.wso2.carbon.ml.core.utils.MLConstants.ML_THREAD_POOL_QUEUE_SIZE);
        int poolSize = 50;
        int poolQueueSize = 1000;
        if (poolSizeStr != null) {
            try {
                poolSize = Integer.parseInt(poolSizeStr);
            } catch (Exception ignore) {
                // use the default
            }
        }

        if (poolQueueSizeStr != null) {
            try {
                poolQueueSize = Integer.parseInt(poolQueueSizeStr);
            } catch (Exception ignore) {
                // use the default
            }
        }
        valueHolder.setThreadExecutor(new BlockingExecutor(poolSize, poolQueueSize));

        // Checks whether ML spark context disabling JVM option is set
        if (System.getProperty(MLConstants.DISABLE_ML_SPARK_CONTEXT_JVM_OPT) != null) {
            if (Boolean.parseBoolean(System.getProperty(MLConstants.DISABLE_ML_SPARK_CONTEXT_JVM_OPT))) {
                valueHolder.setSparkContextEnabled(false);
                log.info("ML Spark context will not be initialized.");
            }
        }

        if (valueHolder.isSparkContextEnabled()) {
            SparkConf sparkConf = mlConfigParser.getSparkConf(MLConstants.SPARK_CONFIG_XML);

            // Add extra class paths for DAS Spark cluster
            String sparkClassPath = ComputeClasspath.getSparkClasspath("", CarbonUtils.getCarbonHome());
            try {
                sparkConf.set(MLConstants.SPARK_EXECUTOR_CLASSPATH,
                        sparkConf.get(MLConstants.SPARK_EXECUTOR_CLASSPATH) + ":" + sparkClassPath);
            } catch (NoSuchElementException e) {
                sparkConf.set(MLConstants.SPARK_EXECUTOR_CLASSPATH, "");
            }

            try {
                sparkConf.set(MLConstants.SPARK_DRIVER_CLASSPATH,
                        sparkConf.get(MLConstants.SPARK_DRIVER_CLASSPATH) + ":" + sparkClassPath);
            } catch (NoSuchElementException e) {
                sparkConf.set(MLConstants.SPARK_DRIVER_CLASSPATH, "");
            }

            sparkConf.setAppName("ML-SPARK-APPLICATION-" + Math.random());
            String portOffset = System.getProperty("portOffset",
                    ServerConfiguration.getInstance().getFirstProperty("Ports.Offset"));
            int sparkUIPort = Integer.parseInt(portOffset) + Integer.parseInt(sparkConf.get("spark.ui.port"));
            sparkConf.set("spark.ui.port", String.valueOf(sparkUIPort));
            valueHolder.setSparkConf(sparkConf);

            // create a new java spark context
            JavaSparkContext sparkContext = new JavaSparkContext(sparkConf);
            sparkContext.hadoopConfiguration().set("fs.hdfs.impl",
                    org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
            sparkContext.hadoopConfiguration().set("fs.file.impl",
                    org.apache.hadoop.fs.LocalFileSystem.class.getName());

            valueHolder.setSparkContext(sparkContext);
        }

        // Retrieving H2O configurations
        HashMap<String, String> h2oConf = new H2OConfigurationParser().getH2OConf(MLConstants.H2O_CONFIG_XML);

        // Start H2O server only if it is enabled
        if (h2oConf.get("enabled").equals("true")) {
            if (h2oConf.get("mode").equals("local")) {
                valueHolder.setH2oClientModeEnabled(false);
                log.info("H2O Server will start in local mode.");
            } else if (h2oConf.get("mode").equals("client")) {
                valueHolder.setH2oClientModeEnabled(true);
                log.info("H2O Server will start in client mode.");
            } else {
                log.error(String.format("H2O server failed to start. Unsupported H2O mode: %s",
                        h2oConf.get("mode")));
            }

            if (valueHolder.isH2oClientModeEnabled()) {
                H2OServer.startH2O(h2oConf.get("ip"), h2oConf.get("port"), h2oConf.get("name"));
            } else {
                String portOffset = System.getProperty("portOffset",
                        ServerConfiguration.getInstance().getFirstProperty("Ports.Offset"));
                String port = String.valueOf(54321 + Integer.parseInt(portOffset));
                H2OServer.startH2O(port);
            }
        }

        // Creating an email output adapter
        this.emailAdapterService = valueHolder.getOutputEventAdapterService();
        OutputEventAdapterConfiguration outputAdapterConfig = new OutputEventAdapterConfiguration();
        outputAdapterConfig.setName(MLConstants.ML_EMAIL_ADAPTER);
        outputAdapterConfig.setType(EmailEventAdapterConstants.ADAPTER_TYPE_EMAIL);
        this.emailAdapterService.create(outputAdapterConfig);
        // Hostname
        String hostName = "localhost";
        try {
            hostName = NetworkUtils.getMgtHostName();
        } catch (Exception ignored) {
        }

        // HTTPS port
        String mgtConsoleTransport = CarbonUtils.getManagementTransport();
        ConfigurationContextService configContextService = MLCoreServiceValueHolder.getInstance()
                .getConfigurationContextService();
        int httpsPort = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
        int httpsProxyPort = CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
                mgtConsoleTransport);
        // set the ml.url property which will be used to print in the console by the ML jaggery app.
        configContextService.getServerConfigContext().setProperty("ml.url",
                "https://" + hostName + ":" + (httpsProxyPort != -1 ? httpsProxyPort : httpsPort) + "/ml");

        // ML metrices
        MetricManager.gauge(Level.INFO, "org.wso2.carbon.ml.thread-pool-active-count", activeCountGauge);
        MetricManager.gauge(Level.INFO, "org.wso2.carbon.ml.thread-pool-queue-size", queueSizeGauge);

        log.info("ML core bundle activated successfully.");
    } catch (Throwable e) {
        log.error("Could not create ModelService: " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.analytics.spark.core.internal.SparkAnalyticsExecutor.java

private void setAdditionalConfigs(SparkConf conf) throws AnalyticsException {
    //executor constants for spark env
    String carbonHome = null, carbonConfDir, analyticsSparkConfDir;
    try {//  ww  w.  ja va 2s  .co  m
        carbonHome = conf.get(AnalyticsConstants.CARBON_DAS_SYMBOLIC_LINK);
        logDebug("CARBON HOME set with the symbolic link " + carbonHome);
    } catch (NoSuchElementException e) {
        try {
            carbonHome = CarbonUtils.getCarbonHome();
        } catch (Throwable ex) {
            logDebug("CARBON HOME can not be found. Spark conf in non-carbon environment");
        }
    }
    logDebug("CARBON HOME used for Spark Conf : " + carbonHome);

    if (carbonHome != null) {
        carbonConfDir = carbonHome + File.separator + "repository" + File.separator + "conf";
    } else {
        logDebug("CARBON HOME is NULL. Spark conf in non-carbon environment. Using the custom conf path");
        carbonConfDir = GenericUtils.getAnalyticsConfDirectory();
    }
    analyticsSparkConfDir = carbonConfDir + File.separator + "analytics" + File.separator + "spark";

    conf.setIfMissing(AnalyticsConstants.SPARK_APP_NAME, DEFAULT_SPARK_APP_NAME);
    conf.setIfMissing(AnalyticsConstants.SPARK_DRIVER_CORES, "1");
    conf.setIfMissing(AnalyticsConstants.SPARK_DRIVER_MEMORY, "512m");
    conf.setIfMissing(AnalyticsConstants.SPARK_EXECUTOR_MEMORY, "512m");

    conf.setIfMissing(AnalyticsConstants.SPARK_UI_PORT, "4040");
    conf.setIfMissing(AnalyticsConstants.SPARK_HISTORY_OPTS, "18080");

    conf.setIfMissing(AnalyticsConstants.SPARK_SERIALIZER, KryoSerializer.class.getName());
    conf.setIfMissing(AnalyticsConstants.SPARK_KRYOSERIALIZER_BUFFER, "256k");
    conf.setIfMissing(AnalyticsConstants.SPARK_KRYOSERIALIZER_BUFFER_MAX, "256m");

    conf.setIfMissing("spark.blockManager.port", "12000");
    conf.setIfMissing("spark.broadcast.port", "12500");
    conf.setIfMissing("spark.driver.port", "13000");
    conf.setIfMissing("spark.executor.port", "13500");
    conf.setIfMissing("spark.fileserver.port", "14000");
    conf.setIfMissing("spark.replClassServer.port", "14500");

    conf.setIfMissing(AnalyticsConstants.SPARK_MASTER_PORT, "7077");
    conf.setIfMissing("spark.master.rest.port", "6066");
    conf.setIfMissing(AnalyticsConstants.SPARK_MASTER_WEBUI_PORT, "8081");

    conf.setIfMissing(AnalyticsConstants.SPARK_WORKER_CORES, "1");
    conf.setIfMissing(AnalyticsConstants.SPARK_WORKER_MEMORY, "1g");
    conf.setIfMissing(AnalyticsConstants.SPARK_WORKER_DIR, "work");
    conf.setIfMissing(AnalyticsConstants.SPARK_WORKER_PORT, "11000");
    conf.setIfMissing(AnalyticsConstants.SPARK_WORKER_WEBUI_PORT, "11500");

    conf.setIfMissing(AnalyticsConstants.SPARK_SCHEDULER_MODE, "FAIR");
    conf.setIfMissing(AnalyticsConstants.SPARK_SCHEDULER_ALLOCATION_FILE,
            analyticsSparkConfDir + File.separator + AnalyticsConstants.FAIR_SCHEDULER_XML);
    conf.setIfMissing(AnalyticsConstants.SPARK_RECOVERY_MODE, "CUSTOM");
    conf.setIfMissing(AnalyticsConstants.SPARK_RECOVERY_MODE_FACTORY,
            AnalyticsRecoveryModeFactory.class.getName());

    conf.setIfMissing("spark.executor.extraJavaOptions", "-Dwso2_custom_conf_dir=" + carbonConfDir);
    conf.setIfMissing("spark.driver.extraJavaOptions", "-Dwso2_custom_conf_dir=" + carbonConfDir);

    //setting the default limit for the spark query results
    conf.setIfMissing("carbon.spark.results.limit", "1000");

    String sparkClasspath = (System.getProperty("SPARK_CLASSPATH") == null) ? ""
            : System.getProperty("SPARK_CLASSPATH");

    // if the master url starts with "spark", this means that the cluster would be pointed
    // an external cluster. in an external cluster, having more than one implementations of
    // sl4j is not possible. hence, it would be removed from the executor cp. DAS-199
    if (carbonHome != null) {
        try {
            if (conf.get(AnalyticsConstants.CARBON_SPARK_MASTER).trim().toLowerCase().startsWith("spark")) {
                sparkClasspath = ComputeClasspath.getSparkClasspath(sparkClasspath, carbonHome,
                        new String[] { "slf4j" });
            } else {
                sparkClasspath = ComputeClasspath.getSparkClasspath(sparkClasspath, carbonHome);
            }
        } catch (IOException e) {
            throw new AnalyticsExecutionException("Unable to create the extra spark classpath" + e.getMessage(),
                    e);
        }
    } else {
        logDebug("CARBON HOME is NULL. Spark conf in non-carbon environment");
    }

    try {
        conf.set("spark.executor.extraClassPath",
                conf.get("spark.executor.extraClassPath") + ";" + sparkClasspath);
    } catch (NoSuchElementException e) {
        conf.set("spark.executor.extraClassPath", sparkClasspath);
    }

    try {
        conf.set("spark.driver.extraClassPath", conf.get("spark.driver.extraClassPath") + ";" + sparkClasspath);
    } catch (NoSuchElementException e) {
        conf.set("spark.driver.extraClassPath", sparkClasspath);
    }
}

From source file:com.metaparadigm.jsonrpc.JSONRPCBridge.java

public JSONRPCResult call(Object context[], JSONObject jsonReq) {
    JSONRPCResult result = null;//from www  .j  a  va 2 s. c o  m
    String encodedMethod = null;
    Object requestId = null;
    JSONArray arguments = null;

    try {
        // Get method name, arguments and request id
        encodedMethod = jsonReq.getString("method");
        arguments = jsonReq.getJSONArray("params");
        requestId = jsonReq.opt("id");
    } catch (NoSuchElementException e) {
        log.severe("no method or parameters in request");
        return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, null, JSONRPCResult.MSG_ERR_NOMETHOD);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (isDebug())
        log.fine("call " + encodedMethod + "(" + arguments + ")" + ", requestId=" + requestId);

    String className = null;
    String methodName = null;
    int objectID = 0;

    // Parse the class and methodName
    StringTokenizer t = new StringTokenizer(encodedMethod, ".");
    if (t.hasMoreElements())
        className = t.nextToken();
    if (t.hasMoreElements())
        methodName = t.nextToken();

    // See if we have an object method in the format ".obj#<objectID>"
    if (encodedMethod.startsWith(".obj#")) {
        t = new StringTokenizer(className, "#");
        t.nextToken();
        objectID = Integer.parseInt(t.nextToken());
    }

    ObjectInstance oi = null;
    ClassData cd = null;
    HashMap methodMap = null;
    Method method = null;
    Object itsThis = null;

    if (objectID == 0) {
        // Handle "system.listMethods"
        if (encodedMethod.equals("system.listMethods")) {
            HashSet m = new HashSet();
            globalBridge.allInstanceMethods(m);
            if (globalBridge != this) {
                globalBridge.allStaticMethods(m);
                globalBridge.allInstanceMethods(m);
            }
            allStaticMethods(m);
            allInstanceMethods(m);
            JSONArray methods = new JSONArray();
            Iterator i = m.iterator();
            while (i.hasNext())
                methods.put(i.next());
            return new JSONRPCResult(JSONRPCResult.CODE_SUCCESS, requestId, methods);
        }
        // Look up the class, object instance and method objects
        if (className == null || methodName == null
                || ((oi = resolveObject(className)) == null && (cd = resolveClass(className)) == null))
            return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, requestId,
                    JSONRPCResult.MSG_ERR_NOMETHOD);
        if (oi != null) {
            itsThis = oi.o;
            methodMap = oi.classData().methodMap;
        } else {
            methodMap = cd.staticMethodMap;
        }
    } else {
        if ((oi = resolveObject(new Integer(objectID))) == null)
            return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, requestId,
                    JSONRPCResult.MSG_ERR_NOMETHOD);
        itsThis = oi.o;
        methodMap = oi.classData().methodMap;
        // Handle "system.listMethods"
        if (methodName.equals("listMethods")) {
            HashSet m = new HashSet();
            uniqueMethods(m, "", oi.classData().staticMethodMap);
            uniqueMethods(m, "", oi.classData().methodMap);
            JSONArray methods = new JSONArray();
            Iterator i = m.iterator();
            while (i.hasNext())
                methods.put(i.next());
            return new JSONRPCResult(JSONRPCResult.CODE_SUCCESS, requestId, methods);
        }
    }

    if ((method = resolveMethod(methodMap, methodName, arguments)) == null)
        return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, requestId, JSONRPCResult.MSG_ERR_NOMETHOD);
    // Call the method
    try {
        if (debug)
            log.fine("invoking " + method.getReturnType().getName() + " " + method.getName() + "("
                    + argSignature(method) + ")");
        Object javaArgs[] = unmarshallArgs(context, method, arguments);
        for (int i = 0; i < context.length; i++)
            preInvokeCallback(context[i], itsThis, method, javaArgs);
        Object o = method.invoke(itsThis, javaArgs);
        for (int i = 0; i < context.length; i++)
            postInvokeCallback(context[i], itsThis, method, o);
        SerializerState state = new SerializerState();
        result = new JSONRPCResult(JSONRPCResult.CODE_SUCCESS, requestId, ser.marshall(state, o));
    } catch (UnmarshallException e) {
        for (int i = 0; i < context.length; i++)
            errorCallback(context[i], itsThis, method, e);
        result = new JSONRPCResult(JSONRPCResult.CODE_ERR_UNMARSHALL, requestId, e.getMessage());
    } catch (MarshallException e) {
        for (int i = 0; i < context.length; i++)
            errorCallback(context[i], itsThis, method, e);
        result = new JSONRPCResult(JSONRPCResult.CODE_ERR_MARSHALL, requestId, e.getMessage());
    } catch (Throwable e) {
        if (e instanceof InvocationTargetException)
            e = ((InvocationTargetException) e).getTargetException();
        for (int i = 0; i < context.length; i++)
            errorCallback(context[i], itsThis, method, e);
        result = new JSONRPCResult(JSONRPCResult.CODE_REMOTE_EXCEPTION, requestId, e);
    }

    // Return the results
    return result;
}

From source file:com.meidusa.amoeba.net.poolable.copy.GenericObjectPool.java

public Object borrowObject() throws Exception {
    long starttime = System.currentTimeMillis();
    for (;;) {// w  w  w  .  j a  v  a2  s . c om
        ObjectTimestampPair pair = null;

        lock.lock();
        try {
            assertOpen();
            // if there are any sleeping, just grab one of those
            try {
                pair = (ObjectTimestampPair) (_pool.removeFirst());
            } catch (NoSuchElementException e) {
                ; /* ignored */
            }
        } finally {
            lock.unlock();
        }
        // otherwise
        if (null == pair) {
            // check if we can create one
            // (note we know that the num sleeping is 0, else we wouldn't be here)
            if (_maxActive < 0 || _numActive < _maxActive) {
                // allow new object to be created
            } else {
                // the pool is exhausted
                switch (_whenExhaustedAction) {
                case WHEN_EXHAUSTED_GROW:
                    // allow new object to be created
                    break;
                case WHEN_EXHAUSTED_FAIL:
                    throw new NoSuchElementException("Pool exhausted");
                case WHEN_EXHAUSTED_BLOCK:
                    synchronized (this) {
                        try {
                            if (_maxWait <= 0) {
                                wait();
                            } else {
                                // this code may be executed again after a notify then continue cycle
                                // so, need to calculate the amount of time to wait
                                final long elapsed = (System.currentTimeMillis() - starttime);
                                final long waitTime = _maxWait - elapsed;
                                if (waitTime > 0) {
                                    wait(waitTime);
                                }
                            }
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            throw e;
                        }
                    }
                    if (_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) {
                        throw new NoSuchElementException("Timeout waiting for idle object");
                    } else {
                        continue; // keep looping
                    }
                default:
                    throw new IllegalArgumentException(
                            "WhenExhaustedAction property " + _whenExhaustedAction + " not recognized.");
                }
            }
        }

        // create new object when needed
        boolean newlyCreated = false;
        boolean numIncreased = false;
        if (null == pair) {
            if (_maxActive < 0 || this.getNumActive() < _maxActive
                    || _whenExhaustedAction != WHEN_EXHAUSTED_BLOCK) {
                lock.lock();
                try {
                    if (_numActive < _maxActive) {
                        _numActive++;
                        numIncreased = true;
                    } else {
                        continue;
                    }
                } finally {
                    lock.unlock();
                }
                try {
                    Object obj = _factory.makeObject();
                    pair = new ObjectTimestampPair(obj);
                    newlyCreated = true;
                } catch (Exception e) {
                    lock.lock();
                    try {
                        _numActive--;
                        numIncreased = false;
                    } finally {
                        lock.unlock();
                    }
                    throw e;
                }
            } else {
                continue;
            }
        }

        // activate & validate the object
        try {
            if (_testOnBorrow && !_factory.validateObject(pair.value)) {
                throw new Exception("ValidateObject failed");
            }
            _factory.activateObject(pair.value);
            if (!numIncreased) {
                lock.lock();
                try {
                    _numActive++;
                    numIncreased = true;
                } finally {
                    lock.unlock();
                }
            }
            return pair.value;
        } catch (Throwable e) {
            if (numIncreased) {
                lock.lock();
                try {
                    _numActive--;
                } finally {
                    lock.unlock();
                }
            }
            // object cannot be activated or is invalid
            try {
                _factory.destroyObject(pair.value);
            } catch (Throwable e2) {
                // cannot destroy broken object
            }
            if (newlyCreated) {
                throw new NoSuchElementException(
                        "Could not create a validated object, cause: " + e.getMessage());
            } else {
                continue; // keep looping
            }
        }
    }
}